Compare commits

..
Author SHA1 Message Date
wuzilongandCursor 2045e7de89 fix(pl): 内部站点清空合同,并隐藏已释放关联证件。
避免山峡/云栋装送段残留外部合同选证,以及 released 用量行仍出现在计划详情关联证件中。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 12:09:06 +08:00
wuzilongandCursor eab882f92c fix(deploy): nginx 隐藏 MinIO 上游 CORS 头避免双 Origin。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 15:42:03 +08:00
wuzilongandCursor 04450fff88 fix(web-admin): 运输归档合计行与可见表头列对齐。
planNo 可隐藏后不再硬编码插入,避免统计行按索引错位。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 15:42:03 +08:00
wuzilongandCursor 82c21262ed fix(web-admin): 顶栏菜单折叠按钮改为内联 SVG 并始终可见。
避免 Iconify/el-icon 在部分浏览器不绘制,并去掉可关闭开关以免按钮被关掉。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 15:42:03 +08:00
wuzilongandCursor 8ac835fa96 fix(pl): 未安排计划按生效时间走新规则选证。
安排预检不再把空版本当成 legacy 去查合同绑证,与证书齐备待完善判定一致。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 15:26:12 +08:00
wuzilong e9f3602459 Merge branch 'codex/issue-43-cert-ready-pending-a8f3c1d9e2b4' into V3.0 2026-11-16 15:03:00 +08:00
wuzilong d2b8a573a1 Merge remote-tracking branch 'origin/V3.0' into V3.0 2026-11-16 15:02:57 +08:00
wuzilongandCursor 79d1242d25 fix(pl): 安排前证书齐备按生效时间写入待完善。
避免版本未打标时被当成 legacy,导致待完善列表漏单;安排打成新规则时回补 pending。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 15:02:45 +08:00
wuzilongandCursor 7e515d9ccd fix(pl): 客户品类安排运输时采用已保存单位换算。
安排自动选证不再忽略计划段次用证中的 manualAllocations,避免瓶升等异单位已填换算仍无法安排。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-16 10:56:29 +08:00
wuzilong 12652b826d merge: issue #40 证件额度切点改为按首次安排时间并冻结版本。 2026-11-15 19:47:58 +08:00
wuzilongandCursor be0ba622a0 fix(pl): 证件额度切点改为按首次安排时间并冻结版本。
切点前已安排的计划归档跳过购买证/运输证校验;创建较早但安排在生效后的计划走客户+品类新规则。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 19:11:02 +08:00
wuzilongandCursor f865d8ed99 fix(pl): 证用品类差量复用软删关联,并修正归档用证结转与证面品类展示。
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-15 18:52:33 +08:00
wuzilong 6f20c0ff8a merge: issue #39 安排运输购买证失败提示补全客户与产品。 2026-11-15 16:57:52 +08:00
48 changed files with 1650 additions and 159 deletions

No files matched your search

+3 -6
View File
@@ -2206,8 +2206,7 @@ def create_plan(
create_by=user.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)
# 添加产品明细
@@ -2379,8 +2378,7 @@ def create_plan_full(
create_by=user.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.flush()
@@ -2531,8 +2529,7 @@ def create_from_contract(
create_by=user.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)
# 查询合同产品明细
+5
View File
@@ -888,7 +888,10 @@ def arrange_transport(
)
apply_resource_snapshot_json(plan=plan, transport=transport, snapshot=snapshot)
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)
# 首次安排按生效时间打标并冻结;改派不重打。
stamp_plan_rule_on_arrange(db, user, plan)
plan.transport_status = "arranged"
plan.follow_status = "arranged"
plan.freight_amount = freight_amount or 0
@@ -1304,11 +1307,13 @@ def process_approval(
transport.carrier_name = vehicle_info['carrier_name']
snapshot = build_transport_resource_snapshot(db, tenant_no, transport.vehicle_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:
assert_pl_row_in_scope(db, plan, PlPlan, user, tenant_no)
plan.vehicle_id = transport.vehicle_id
plan.license_plate = transport.license_plate
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)
plan.transport_status = "arranged"
plan.follow_status = "arranged"
+2 -1
View File
@@ -370,7 +370,8 @@ class PlPlan(Base):
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_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-是")
erp_entered = Column(SmallInteger, nullable=False, default=0, comment="是否已录入ERP 0-否 1-是")
cancel_reason = Column(String(500), nullable=True, comment="作废原因")
+2 -1
View File
@@ -417,7 +417,8 @@ class PlanRead(PlanBase, PlanResourceSnapshotMixin):
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_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是")
erp_entered: int = Field(default=0, alias="erpEntered", description="是否已录入ERP 0-否 1-是")
cancel_reason: Optional[str] = Field(default=None, alias="cancelReason", description="作废原因")
@@ -127,12 +127,16 @@ def save_category(db: Session, user, data: dict, category_id=None):
submitted = data['products']
if submitted is None:
raise HTTPException(400, '产品关联集合不可为 null;清空请提交 []')
existing = {
r.id: r
for r in db.query(PlCertCategoryProduct).filter_by(
tenant_no=user.tenant_no, category_id=row.id, del_flag=0,
).with_for_update().populate_existing().all()
}
# uk_cert_category_product 不含 del_flag,软删行仍占唯一键;无 id 再加须复用。
all_links = (
db.query(PlCertCategoryProduct)
.filter_by(tenant_no=user.tenant_no, category_id=row.id)
.with_for_update()
.populate_existing()
.all()
)
existing = {r.id: r for r in all_links if r.del_flag == 0}
by_product = {r.product_id: r for r in all_links}
seen = set()
product_ids = set()
for item in submitted:
@@ -150,20 +154,46 @@ def save_category(db: Session, user, data: dict, category_id=None):
raise HTTPException(400, '产品关联明细不属于当前品类')
if rid in seen:
raise HTTPException(400, '产品关联明细 ID 重复')
if pid != link.product_id:
conflict = by_product.get(pid)
if conflict is not None and conflict.id != link.id:
if conflict.del_flag == 0:
raise HTTPException(400, '同一品类不能重复关联同一产品')
# 目标 product_id 被软删行占用:恢复该行并软删当前行
conflict.del_flag = 0
conflict.scope_status = scope
conflict.update_by = user.id
link.del_flag = 1
link.update_by = user.id
seen.add(conflict.id)
continue
if by_product.get(link.product_id) is link:
del by_product[link.product_id]
link.product_id = pid
by_product[pid] = link
seen.add(rid)
link.product_id = pid
link.scope_status = scope
link.update_by = user.id
else:
link = PlCertCategoryProduct(
**_audit(user),
category_id=row.id,
product_id=pid,
scope_status=scope,
)
db.add(link)
# 关联表业务键 (category_id, product_id):复用有效或软删行,避免 uk 冲突
link = by_product.get(pid)
if link is not None:
if link.del_flag == 0:
seen.add(link.id)
link.del_flag = 0
link.scope_status = scope
link.update_by = user.id
else:
link = PlCertCategoryProduct(
**_audit(user),
category_id=row.id,
product_id=pid,
scope_status=scope,
)
db.add(link)
by_product[pid] = link
for rid, link in existing.items():
if rid not in seen:
if rid not in seen and link.del_flag == 0:
link.del_flag = 1
link.update_by = user.id
db.flush()
@@ -1,4 +1,4 @@
"""客户品类额度规则切点:系统信息配置;未配置则拦住安排。"""
"""客户品类额度规则切点:按首次安排时间打标;切点前已安排归档跳过校证。"""
from datetime import datetime
from typing import Optional
from uuid import uuid4
@@ -58,20 +58,103 @@ def assert_cert_quota_rule_configured(db: Session, tenant_no: str) -> datetime:
return effective_at
def resolve_rule_version_for_create(db: Session, tenant_no: str, create_time: Optional[datetime] = None) -> str:
"""计划创建时打标;未配置生效时间时仍标 legacy(安排会被拦住)。"""
def resolve_rule_version_for_arrange(
db: Session, tenant_no: str, arrange_time: Optional[datetime] = None
) -> str:
"""首次安排时打标:安排时刻 >= 生效时间 → 新规则,否则祖父 legacy。"""
effective_at = get_effective_at(db, tenant_no)
when = create_time or datetime.now()
when = arrange_time or datetime.now()
if effective_at is not None and when >= effective_at:
return VERSION_CUSTOMER_CATEGORY
return VERSION_LEGACY
def stamp_plan_rule_version(db: Session, user, plan) -> str:
version = resolve_rule_version_for_create(db, user.tenant_no, getattr(plan, 'create_time', None) or datetime.now())
# 兼容旧测试/调用名;语义已改为安排时刻。
resolve_rule_version_for_create = resolve_rule_version_for_arrange
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
# 安排前已按旧判定齐备时,打成新规则后回补待完善,避免待完善列表漏单。
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
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:
"""仅看已落库版本;空版本视为 legacy。安排前请用 plan_applies_customer_category_rule。"""
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,7 +1166,9 @@ def create_transport_for_plan(
escort_id=escort_id,
)
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)
stamp_plan_rule_on_arrange(db, user, plan)
plan.transport_status = "arranged"
plan.follow_status = "arranged"
plan.freight_amount = freight_amount or 0
@@ -831,6 +831,15 @@ def assert_stop_contract_required(
raise HTTPException(status_code=422, detail=f"请为{side_label}选择合同")
def _clear_internal_stop_product_contracts(stop) -> None:
"""山峡/云栋段不占用外部合同;客户端若仍回传产品行合同字段,保存前强制清空。"""
if stop is None or not is_internal_customer_name(getattr(stop, 'customer_name', None)):
return
for prod in getattr(stop, 'products', None) or []:
prod.contract_id = None
prod.contract_product_id = None
def _resolve_stop_contracts(
db: Session,
tenant_no: str,
@@ -975,6 +984,7 @@ def validate_plan_stops_write(
"装货合同",
expected_supplier_name=entity_name,
)
_clear_internal_stop_product_contracts(load)
resolved_deliveries: list[PlanDeliveryBody] = []
for idx, delivery in enumerate(deliveries, start=1):
@@ -990,6 +1000,7 @@ def validate_plan_stops_write(
f"送货段#{idx}合同",
expected_supplier_name=entity_name,
)
_clear_internal_stop_product_contracts(delivery)
resolved_deliveries.append(delivery)
enrich_stop_addresses_from_library(db, tenant_no, load, resolved_deliveries)
@@ -1443,6 +1454,7 @@ def replace_plan_stops(
stop.customer_name, kind, body.generate_dibang, body.dibang_direction)
stop.same_city = 1 if int(getattr(body, "same_city", 0) or 0) == 1 else 0
stop.del_flag, stop.update_by, stop.update_time = 0, user_id, now
internal_stop = is_internal_customer_name(body.customer_name)
model = PlPlanLoadProduct if kind == 'load' else PlPlanDeliveryProduct
for idx, (row, product, linked) in enumerate(product_jobs or []):
if row is None:
@@ -1453,6 +1465,10 @@ def replace_plan_stops(
for field in product_fields:
if field in product.model_fields_set or row.id is None:
setattr(row, field, getattr(product, field))
if internal_stop:
# 内部客户段即使客户端漏清/省略合同字段,落库也不得保留外部合同绑定。
row.contract_id = None
row.contract_product_id = None
row.plan_product_id = linked
row.order_num, row.update_by, row.update_time = idx, user_id, now
for row in removed:
@@ -337,7 +337,11 @@ def settle_allocations(reserved: Sequence[Allocation], actual_by_source: Mapping
异单位来源须逐行重新确认全部实际量(含零量行),不按预占比例推算。
超来源量或超任一证件预占量均要求先补充分配。
同市等仅购买证场景下,调用方仍可能对本函数传入空的运输证分组与全量实运量;
无预占行时直接空结转,不把「缺实际量」套到另一类证件上。
"""
if not reserved:
return ()
keys, seqs, grouped = set(), set(), {}
kinds = {r.permit_kind for r in reserved}
if len(kinds) > 1 or kinds - {'purchase', 'transport'}:
+11 -2
View File
@@ -120,12 +120,21 @@ def apply_plan_quota(db, user, plan, action, payload=None):
evidenceUrls=getattr(payload, 'quota_evidence_urls', 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_cert_quota_rule_config_service import plan_uses_customer_category
from app.services.pl_cert_quota_rule_config_service import (
plan_skips_archive_cert_quota,
plan_uses_customer_category,
)
# 新规则:齐备仅放行安排/改派预占;归档与实际调整必须真证结转。
# 旧规则(legacy):齐备仍跳过安排与归档(祖父兼容)。
# 切点前首次安排:归档/实调不校证件(无需齐备);齐备仍可跳过安排预占。
skip_actions = ('reserve', 'resize')
if not plan_uses_customer_category(plan):
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 action in ('reserve', 'resize'):
assert_waived_sources(db, user, plan, lock=True)
+29 -2
View File
@@ -136,6 +136,26 @@ def _customer_display_name(db, user, customer_id):
return (row[0] if row else None) or None
def _category_display_names(db, user, category_ids):
"""按证用品类 ID 顺序返回启用中的品类名称;未知 ID 跳过。"""
from app.models.pl_quota_models import PlCertCategory
ids = [str(item or '').strip() for item in (category_ids or []) if str(item or '').strip()]
if not ids:
return []
rows = (
db.query(PlCertCategory.id, PlCertCategory.category_name)
.filter(
PlCertCategory.tenant_no == user.tenant_no,
PlCertCategory.del_flag == 0,
PlCertCategory.id.in_(ids),
)
.all()
)
names = {row.id: (row.category_name or '').strip() for row in rows}
return [names[item] for item in ids if names.get(item)]
def get_cert(db, user, cert_type, cert_id, current=False):
row = _get_row(db, user, cert_type, cert_id, lock=current)
# 只读列表/详情不得在未提交事务里改状态,否则会出现「页面已启用、库仍 draft」。
@@ -151,12 +171,17 @@ def get_cert(db, user, cert_type, cert_id, current=False):
result['availableQty'] = row.total_qty - row.used_qty - row.reserved_qty
result['singleUseConsumed'] = is_single_use_consumed(db, user, cert_type, row)
result['customerName'] = _customer_display_name(db, user, getattr(row, 'customer_id', None))
if cert_type == 'purchase':
names = _category_display_names(db, user, [getattr(row, 'category_id', None)])
result['categoryName'] = names[0] if names else None
if cert_type == 'transport':
result['purchaseRefs'] = [_row_to_dict(r) for r in _refs(db, user, cert_id, lock=current)]
result['referencesEditable'] = not _has_usage_beyond_zero_opening(
db, user, cert_type, cert_id, lock=current
)
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
@@ -182,7 +207,9 @@ def list_certs(db, user, cert_type, keyword=None, status=None, customer_id=None)
result = [get_cert(db, user, cert_type, r.id) for r in query.order_by(model.create_time.desc()).all()]
if cert_type == 'transport':
for item in result:
item['derivedCategoryIds'] = _transport_derived_categories(db, user, item['id'])
derived_ids = _transport_derived_categories(db, user, item['id'])
item['derivedCategoryIds'] = derived_ids
item['derivedCategoryNames'] = _category_display_names(db, user, derived_ids)
return result
@@ -80,6 +80,49 @@ def _permit_qty_for(source_qty: Decimal, source_unit: str, cert_unit: str) -> De
return (source_qty * Decimal(str(ratio))).quantize(Decimal('0.000001'))
def _manual_field(row, *names):
if isinstance(row, dict):
for name in names:
if name in row and row[name] is not None:
return row[name]
return None
for name in names:
value = getattr(row, name, None)
if value is not None:
return value
return None
def _saved_permit_qty(manuals, kind, source_id, permit_id, source_qty: Decimal):
"""计划段次用证已保存的人工换算;来源量变化时按原比例缩放。"""
for row in manuals or ():
if (
str(_manual_field(row, 'permit_kind', 'permitKind') or '') != kind
or str(_manual_field(row, 'source_id', 'sourceId') or '') != str(source_id)
or str(_manual_field(row, 'permit_id', 'permitId') or '') != str(permit_id)
):
continue
saved_src = Decimal(str(_manual_field(row, 'source_quantity', 'sourceQuantity') or '0'))
saved_permit = Decimal(str(_manual_field(row, 'permit_quantity', 'permitQuantity') or '0'))
if saved_src <= 0 or saved_permit <= 0:
return None
current = Decimal(source_qty)
if saved_src == current:
return saved_permit
return (saved_permit * current / saved_src).quantize(Decimal('0.000001'))
return None
def _need_permit_qty(source_qty, source_unit, cert_unit, manuals, kind, source_id, permit_id):
try:
return _permit_qty_for(Decimal(source_qty), source_unit, cert_unit)
except HTTPException:
manual_qty = _saved_permit_qty(manuals, kind, source_id, permit_id, Decimal(source_qty))
if manual_qty is None:
raise
return manual_qty
def _customer_id_from_source(source) -> str:
snap = source.snapshot or {}
cid = snap.get('customerId') or snap.get('customer_id')
@@ -181,13 +224,16 @@ def _linked_transports(db, user, customer_id, purchase_id):
)
def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date, candidates):
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 '该产品'
@@ -227,7 +273,10 @@ def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date
consumed_buy.append(purchase)
continue
try:
need = _permit_qty_for(need_qty, source.unit, purchase.quantity_unit)
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
@@ -263,7 +312,10 @@ def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date
vehicle_miss.append(transport)
continue
try:
t_need = _permit_qty_for(need_qty, source.unit, transport.quantity_unit)
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
@@ -374,10 +426,13 @@ def _diagnose_select_failure(db, user, source, *, vehicle_no: str, on_date: date
)
def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: date):
def select_whole_cover_certs(
db, user, sources, *, vehicle_no: str, on_date: date, manual_allocations=(),
):
"""返回 purchase_cert_ids, transport_cert_ids, manual_allocations。
每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。
单位无法自动换算时,使用计划段次用证已保存的人工换算量。
"""
if not sources:
return [], [], []
@@ -385,6 +440,7 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
purchase_ids = []
transport_ids = []
manuals = []
saved_manuals = manual_allocations or ()
for source in sources:
customer_id = _customer_id_from_source(source)
@@ -414,7 +470,10 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
if is_single_use_consumed(db, user, 'purchase', purchase):
continue
try:
need = _permit_qty_for(Decimal(source.quantity), source.unit, purchase.quantity_unit)
need = _need_permit_qty(
source.quantity, source.unit, purchase.quantity_unit,
saved_manuals, 'purchase', source.source_id, purchase.id,
)
except HTTPException:
continue
if _available(purchase) < need:
@@ -441,7 +500,10 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
if not _vehicle_ok(transport, vehicle_no):
continue
try:
t_need = _permit_qty_for(Decimal(source.quantity), source.unit, transport.quantity_unit)
t_need = _need_permit_qty(
source.quantity, source.unit, transport.quantity_unit,
saved_manuals, 'transport', source.source_id, transport.id,
)
except HTTPException:
continue
if _available(transport) < t_need:
@@ -458,7 +520,8 @@ def select_whole_cover_certs(db, user, sources, *, vehicle_no: str, on_date: dat
raise HTTPException(
409,
_diagnose_select_failure(
db, user, source, vehicle_no=vehicle_no, on_date=on_date, candidates=candidates,
db, user, source, vehicle_no=vehicle_no, on_date=on_date,
candidates=candidates, manual_allocations=saved_manuals,
),
)
+31 -8
View File
@@ -131,8 +131,8 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
sources, actuals = [], {}
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)
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
customer_rule = plan_uses_customer_category(plan)
from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule
customer_rule = plan_applies_customer_category_rule(db, user.tenant_no, plan)
if action in ('reserve', 'resize') and not explicit and sources:
if customer_rule:
# 新规则:禁止手工选证;按客户+品类整笔自动选证
@@ -143,6 +143,7 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
on_date = max(date.today(), plan.plan_date or date.today())
purchase_ids, transport_ids, manuals = select_whole_cover_certs(
db, user, sources, vehicle_no=vehicle, on_date=on_date,
manual_allocations=config.manual_allocations,
)
config = config.model_copy(update={
'purchase_cert_ids': purchase_ids,
@@ -227,10 +228,10 @@ def preview_plan(db, user, plan_id, config, preview_vehicle=None):
def save_configuration(db, user, plan_id, config):
from app.services.pl_plan_service import record_plan_change
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_applies_customer_category_rule
config = config if isinstance(config, PlanQuotaConfiguration) else PlanQuotaConfiguration.model_validate(config)
plan = _plan(db, user, plan_id, lock=True)
if plan_uses_customer_category(plan):
if plan_applies_customer_category_rule(db, user.tenant_no, plan):
raise HTTPException(409, '新规则下安排仅自动选证,不支持手工保存用证配置')
if plan.transport_status == 'arranged' or plan.archive_status == 'archived':
raise HTTPException(409, '已安排计划请通过调整运输在同一事务重算用证')
@@ -335,13 +336,35 @@ def get_plan_quota(db, user, plan_id):
if row.contract_product_id in cert['productIds']]})
if product.is_toxic == 1:
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()
# 关联证件展示只含仍占用/结转中的用量;released 已从配置摘除,不再算作当前关联。
usages = (
db.query(PlPlanCertUsage)
.filter(
PlPlanCertUsage.tenant_no == user.tenant_no,
PlPlanCertUsage.plan_id == plan_id,
PlPlanCertUsage.del_flag == 0,
PlPlanCertUsage.usage_status != 'released',
)
.order_by(PlPlanCertUsage.create_time.desc())
.all()
)
version = resolve_measurement_version(db, user, plan)
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
customer_rule = plan_uses_customer_category(plan)
from app.services.pl_cert_quota_rule_config_service import (
VERSION_LEGACY,
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,
'quotaCertWaived': int(getattr(plan, 'quota_cert_waived', 0) or 0) == 1,
'certQuotaRuleVersion': getattr(plan, 'cert_quota_rule_version', None) or 'legacy',
'certQuotaRuleVersion': rule_version or VERSION_LEGACY,
'measurementVersion': version,
'configuration': {**(plan.cert_configuration or {}), 'measurementVersion': version}, 'sourceOptions': options,
'stopProducts': stop_products,
+19 -4
View File
@@ -185,9 +185,9 @@ def _execute(db,user,r,digest,plan):
raise ValueError('已执行用证不得释放预占,请先结转实际量')
for k,u in usages.items():
certs[k].reserved_qty-=u.reserved_qty; u.reserved_qty=ZERO
u.usage_status='released'
u.usage_status='released'; u.del_flag=1
for item in items[k]:
item.reserved_qty=ZERO; item.item_status='released'
item.reserved_qty=ZERO; item.item_status='released'; item.del_flag=1
else:
supplement=_settle(db,user,r,certs,usages,items,plan)
for k,u in usages.items():
@@ -343,7 +343,12 @@ def _reserve(db,user,r,plan,certs,usages,items,selected,preview=False,lock_previ
if item.actual_cert_qty is not None or item.item_status in ('in_transit','settled'): raise ValueError('已执行明细不能移除')
item.del_flag=1; item.reserved_qty=ZERO; item.item_status='released'
new_qty=sum((a.permit_quantity for a in allocations),ZERO)
c.reserved_qty+=new_qty-u.reserved_qty; u.reserved_qty=new_qty; u.usage_status='reserved' if allocations else 'released'
c.reserved_qty+=new_qty-u.reserved_qty; u.reserved_qty=new_qty
# 无分配时标记释放并软删,详情「关联证件」不再展示;再预占同证时复用本行并恢复 del_flag。
if allocations:
u.usage_status='reserved'; u.del_flag=0
else:
u.usage_status='released'; u.del_flag=1
u.cert_revision=c.revision; u.confirmed_by=user.id; u.confirmed_time=datetime.now()
u.confirmation_snapshot={'executed':False,'vehicleNo':r.vehicle_no,
'measurementVersion': next((s.snapshot.get('measurementVersion', 'legacy_single_side') for s in r.sources), 'legacy_single_side')}
@@ -675,7 +680,17 @@ def _settle(db,user,r,certs,usages,items,plan):
for kind,rows in settled.items():
for row in rows: base_totals[(kind,row.allocation.permit_id)]+=row.actual_permit_quantity
credits={k:SimpleNamespace(reserved_qty=u.reserved_qty+u.used_qty-base_totals[k]) for k,u in usages.items()}
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]})
# 超额补扣需求仅为超出预占的部分。安排/完善并关闭写入的 manual_allocations
# 是整笔计划量,若原样带入会与超额需求冲突(证件明明够却报额度不足)。
extra_update = {
'sources': [
source.model_copy(update={'quantity': excess[source.source_id]})
for source in r.sources if source.source_id in excess
],
}
if auto_cover:
extra_update['manual_allocations'] = []
extra_request = r.model_copy(update=extra_update)
try:
result=_reserve(db,user,extra_request,plan,certs,credits,{},selected,preview=True,lock_preview=True)
except InsufficientQuota as exc:
+16 -7
View File
@@ -269,7 +269,17 @@ def mark_ready(db, user, plan_id):
plan = _plan(db, user, plan_id, lock=True)
if plan.follow_status == "cancelled" or plan.archive_status == "cancelled":
raise HTTPException(409, "已作废的计划不能标记证书齐备")
from app.services.pl_cert_quota_rule_config_service import plan_requires_cert_fulfill
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])
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():
@@ -290,8 +300,7 @@ def mark_ready(db, user, plan_id):
plan.quota_cert_waived_by = user.id
plan.quota_cert_waived_by_name = name[:100] if name else None
plan.quota_cert_waived_time = datetime.now()
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
if plan_uses_customer_category(plan):
if plan_requires_cert_fulfill(db, user.tenant_no, plan):
plan.quota_cert_pending_fulfill = 1
change_content = "标记证书齐备:可安排运输;归档前须在证书齐备中完善并关闭"
else:
@@ -313,15 +322,15 @@ def mark_ready(db, user, plan_id):
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(
PlPlan.tenant_no == user.tenant_no,
PlPlan.del_flag == 0,
PlPlan.follow_status != "cancelled",
PlPlan.archive_status != "cancelled",
PlPlan.cert_quota_rule_version == VERSION_CUSTOMER_CATEGORY,
PlPlan.quota_cert_pending_fulfill == 1,
PlPlan.quota_cert_waived == 1,
)
@@ -345,14 +354,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):
"""完善并关闭:按安排同款自动选证并 reserve,成功后出队。"""
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_requires_cert_fulfill
from app.services.pl_plan_service import record_plan_change
from app.services.pl_quota_business import apply_plan_quota
from app.services.pl_quota_planning import _plan
from types import SimpleNamespace
plan = _plan(db, user, plan_id, lock=True)
if not plan_uses_customer_category(plan):
if not plan_requires_cert_fulfill(db, user.tenant_no, plan):
raise HTTPException(409, '仅新规则计划支持完善并关闭')
if int(getattr(plan, 'quota_cert_pending_fulfill', 0) or 0) != 1:
raise HTTPException(409, '该计划不在证书齐备待完善列表中')
@@ -0,0 +1,117 @@
"""证用品类产品关联差量保存:软删后再加回须复用唯一键行。"""
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
+464 -4
View File
@@ -19,16 +19,94 @@ def test_assert_rule_not_configured_blocks_arrange():
assert '系统信息' in str(exc.value.detail)
def test_resolve_rule_version_by_effective_at():
def test_resolve_rule_version_by_arrange_effective_at():
from app.services import pl_cert_quota_rule_config_service as cfg
db = MagicMock()
row = SimpleNamespace(effective_at=datetime(2026, 11, 14, 0, 0, 0))
db.query.return_value.filter_by.return_value.first.return_value = row
assert cfg.resolve_rule_version_for_create(db, 't', datetime(2026, 11, 13)) == 'legacy'
assert cfg.resolve_rule_version_for_create(db, 't', datetime(2026, 11, 14)) == 'customer_category'
assert cfg.resolve_rule_version_for_arrange(db, 't', datetime(2026, 11, 13)) == 'legacy'
assert cfg.resolve_rule_version_for_arrange(db, 't', datetime(2026, 11, 14)) == 'customer_category'
db.query.return_value.filter_by.return_value.first.return_value = None
assert cfg.resolve_rule_version_for_create(db, 't', datetime(2026, 11, 20)) == 'legacy'
assert cfg.resolve_rule_version_for_arrange(db, 't', datetime(2026, 11, 20)) == 'legacy'
def test_stamp_plan_rule_version_freezes_first_arrange():
from app.services import pl_cert_quota_rule_config_service as cfg
db = MagicMock()
row = SimpleNamespace(effective_at=datetime(2026, 11, 14, 0, 0, 0))
db.query.return_value.filter_by.return_value.first.return_value = row
user = SimpleNamespace(tenant_no='t', id='u')
plan = SimpleNamespace(cert_quota_rule_version=None, cert_quota_arranged_at=None)
first = cfg.stamp_plan_rule_on_arrange(db, user, plan, arrange_time=datetime(2026, 11, 13, 10, 0, 0))
assert first == 'legacy'
assert plan.cert_quota_rule_version == 'legacy'
assert plan.cert_quota_arranged_at == datetime(2026, 11, 13, 10, 0, 0)
second = cfg.stamp_plan_rule_on_arrange(db, user, plan, arrange_time=datetime(2026, 11, 20, 10, 0, 0))
assert second == 'legacy'
assert plan.cert_quota_rule_version == 'legacy'
assert plan.cert_quota_arranged_at == datetime(2026, 11, 13, 10, 0, 0)
def test_stamp_after_cutoff_uses_customer_category_even_if_created_earlier():
from app.services import pl_cert_quota_rule_config_service as cfg
db = MagicMock()
row = SimpleNamespace(effective_at=datetime(2026, 11, 14, 0, 0, 0))
db.query.return_value.filter_by.return_value.first.return_value = row
user = SimpleNamespace(tenant_no='t', id='u')
plan = SimpleNamespace(
create_time=datetime(2026, 11, 1),
cert_quota_rule_version=None,
cert_quota_arranged_at=None,
)
version = cfg.stamp_plan_rule_on_arrange(db, user, plan, arrange_time=datetime(2026, 11, 15))
assert version == 'customer_category'
assert plan.cert_quota_rule_version == 'customer_category'
def test_plan_skips_archive_when_arranged_before_effective_at():
from app.services import pl_cert_quota_rule_config_service as cfg
db = MagicMock()
db.query.return_value.filter_by.return_value.first.return_value = SimpleNamespace(
effective_at=datetime(2026, 11, 14, 0, 0, 0)
)
before = SimpleNamespace(
tenant_no='t',
cert_quota_arranged_at=datetime(2026, 11, 10),
cert_quota_rule_version='legacy',
transport_id=None,
)
after = SimpleNamespace(
tenant_no='t',
cert_quota_arranged_at=datetime(2026, 11, 15),
cert_quota_rule_version='customer_category',
transport_id=None,
)
assert cfg.plan_skips_archive_cert_quota(before, db, 't') is True
assert cfg.plan_skips_archive_cert_quota(after, db, 't') is False
def test_legacy_arranged_before_cutoff_skips_archive_cert_without_waive(monkeypatch):
"""切点前首次安排的计划:归档不校证件,无需证书齐备。"""
from app.services import pl_quota_business as biz
plan = SimpleNamespace(
id='p1',
quota_cert_waived=0,
quota_cert_pending_fulfill=0,
cert_quota_rule_version='legacy',
cert_quota_arranged_at=datetime(2026, 11, 10),
cert_configuration={},
)
monkeypatch.setattr(
'app.services.pl_cert_quota_rule_config_service.plan_skips_archive_cert_quota',
lambda p, db=None, tenant_no=None: True,
)
result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u', tenant_no='t'), plan, 'settle', None)
assert result.get('waived') is True or result.get('skippedCertQuota') is True
def test_apply_plan_quota_new_rule_waive_skips_reserve_not_settle(monkeypatch):
@@ -754,6 +832,100 @@ def test_get_cert_customer_name_from_crm_not_consignee(monkeypatch):
assert result['customerId'] == 'cust-kanghua'
def test_get_cert_purchase_category_name(monkeypatch):
"""购买证详情回填证用品类名称,便于 H5/Web 只读展示。"""
from app.services import pl_quota_cert_service as svc
class Col:
def __init__(self, name):
self.name = name
row = SimpleNamespace(
id='p1',
cert_no='G1',
customer_id='cust1',
category_id='cat-hcl',
buyer_name='安庆市山峡化工有限公司',
valid_use_text='多次有效',
total_qty=Decimal('100'),
used_qty=Decimal('0'),
reserved_qty=Decimal('0'),
__table__=SimpleNamespace(
columns=[
Col('id'),
Col('cert_no'),
Col('customer_id'),
Col('category_id'),
Col('buyer_name'),
Col('valid_use_text'),
Col('total_qty'),
Col('used_qty'),
Col('reserved_qty'),
]
),
)
monkeypatch.setattr(svc, '_get_row', lambda *a, **k: row)
monkeypatch.setattr(svc, 'is_single_use_consumed', lambda *a, **k: False)
monkeypatch.setattr(svc, '_customer_display_name', lambda *a, **k: '甲客户')
monkeypatch.setattr(svc, '_category_display_names', lambda *a, **k: ['盐酸'])
opening = MagicMock()
opening.filter_by.return_value.first.return_value = None
db = MagicMock()
db.query.return_value = opening
result = svc.get_cert(db, SimpleNamespace(tenant_no='t'), 'purchase', 'p1')
assert result['customerName'] == '甲客户'
assert result['categoryName'] == '盐酸'
assert result['categoryId'] == 'cat-hcl'
def test_get_cert_transport_derived_category_names(monkeypatch):
"""运输证详情回填引用购买证品类名称并集。"""
from app.services import pl_quota_cert_service as svc
class Col:
def __init__(self, name):
self.name = name
row = SimpleNamespace(
id='t1',
cert_no='Y1',
customer_id='cust1',
valid_use_text='多次有效',
total_qty=Decimal('10'),
used_qty=Decimal('0'),
reserved_qty=Decimal('0'),
__table__=SimpleNamespace(
columns=[
Col('id'),
Col('cert_no'),
Col('customer_id'),
Col('valid_use_text'),
Col('total_qty'),
Col('used_qty'),
Col('reserved_qty'),
]
),
)
monkeypatch.setattr(svc, '_get_row', lambda *a, **k: row)
monkeypatch.setattr(svc, 'is_single_use_consumed', lambda *a, **k: False)
monkeypatch.setattr(svc, '_customer_display_name', lambda *a, **k: '甲客户')
monkeypatch.setattr(svc, '_refs', lambda *a, **k: [])
monkeypatch.setattr(svc, '_has_usage_beyond_zero_opening', lambda *a, **k: False)
monkeypatch.setattr(svc, '_transport_derived_categories', lambda *a, **k: ['c1', 'c2'])
monkeypatch.setattr(svc, '_category_display_names', lambda *a, **k: ['硫酸', '盐酸'])
opening = MagicMock()
opening.filter_by.return_value.first.return_value = None
db = MagicMock()
db.query.return_value = opening
result = svc.get_cert(db, SimpleNamespace(tenant_no='t'), 'transport', 't1')
assert result['derivedCategoryIds'] == ['c1', 'c2']
assert result['derivedCategoryNames'] == ['硫酸', '盐酸']
def _remote_source(**kw):
from app.schemas.pl.quota_usage import UsageSource
@@ -1060,3 +1232,291 @@ def test_archive_cover_block_message_customer_rule_wording(monkeypatch):
)
assert '客户名下' in message
assert '合同' not in message
def test_whole_cover_uses_saved_manual_when_units_need_conversion(monkeypatch):
"""计划段次用证已填瓶→升换算时,同市自动选证应采用该证面量,不能因无法自动换算失败。"""
from app.services import pl_quota_customer_select as sel
from app.schemas.pl.quota_planning import ManualQuantity
purchase = _ok_purchase(
id='78bde6ea',
cert_no='G34280697302194',
quantity_unit='sheng',
total_qty=Decimal('2.5'),
)
db = _mock_select_db([purchase], [], [])
monkeypatch.setattr(sel, 'category_ids_for_product', lambda *a, **k: {'cat1'})
source = _remote_source(
requires_transport=False,
quantity=Decimal('5'),
unit='ping',
source_stop_type='delivery',
source_stop_id='d1',
source_stop_product_id='012423E0',
)
saved = [
ManualQuantity(
permit_kind='purchase',
source_id=source.source_id,
permit_id='78bde6ea',
source_quantity=Decimal('5'),
permit_quantity=Decimal('2.5'),
)
]
purchase_ids, transport_ids, manuals = sel.select_whole_cover_certs(
db,
SimpleNamespace(tenant_no='t'),
[source],
vehicle_no='皖H21522',
on_date=date(2026, 11, 16),
manual_allocations=saved,
)
assert purchase_ids == ['78bde6ea']
assert transport_ids == []
assert len(manuals) == 1
assert manuals[0].permit_id == '78bde6ea'
assert manuals[0].permit_quantity == Decimal('2.5')
assert manuals[0].source_quantity == Decimal('5')
def test_whole_cover_hetero_unit_without_manual_still_blocks(monkeypatch):
from app.services import pl_quota_customer_select as sel
purchase = _ok_purchase(quantity_unit='sheng', total_qty=Decimal('2.5'))
db = _mock_select_db([purchase], [], [])
monkeypatch.setattr(sel, 'category_ids_for_product', lambda *a, **k: {'cat1'})
with pytest.raises(HTTPException) as exc:
sel.select_whole_cover_certs(
db,
SimpleNamespace(tenant_no='t'),
[_remote_source(requires_transport=False, quantity=Decimal('5'), unit='ping')],
vehicle_no='皖H21522',
on_date=date(2026, 11, 16),
)
assert exc.value.status_code == 409
assert '无法自动换算' in str(exc.value.detail)
def test_build_usage_request_passes_saved_manuals_to_customer_select(monkeypatch):
"""安排预占在客户品类规则下应把已保存换算传给自动选证。"""
from app.services import pl_quota_planning as planning
from app.schemas.pl.quota_planning import ManualQuantity, PlanQuotaOperation
from app.schemas.pl.quota_usage import UsageSource
source = UsageSource(
source_stop_type='delivery',
source_stop_id='d1',
source_stop_product_id='sp1',
plan_product_id='pp1',
contract_id='c1',
contract_product_id='cp1',
product_id='prod1',
quantity=Decimal('5'),
unit='ping',
fingerprint='f' * 64,
snapshot={'customerId': 'cust1'},
requires_transport=False,
)
saved = [
ManualQuantity(
permit_kind='purchase',
source_id=source.source_id,
permit_id='buy1',
source_quantity=Decimal('5'),
permit_quantity=Decimal('2.5'),
)
]
plan = SimpleNamespace(
id='p1',
plan_date=date(2026, 11, 16),
license_plate='皖H21522',
transport_status='pending',
archive_status='unarchived',
cert_quota_rule_version='customer_category',
cert_configuration={
'measurementVersion': 'per_stop_v2',
'manualAllocations': [row.model_dump(by_alias=True) for row in saved],
},
)
captured = {}
def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=()):
captured['manual_allocations'] = list(manual_allocations)
return ['buy1'], [], list(manual_allocations)
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([source], {}))
monkeypatch.setattr(planning, 'resolve_measurement_version', lambda *a, **k: 'per_stop_v2')
monkeypatch.setattr(planning, 'plan_execution_lock_reason', lambda *a, **k: None)
monkeypatch.setattr(
'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category',
lambda p: True,
)
monkeypatch.setattr(
'app.services.pl_quota_customer_select.select_whole_cover_certs',
fake_select,
)
monkeypatch.setattr(planning, '_get_row', lambda *a, **k: SimpleNamespace(id='buy1', revision=1))
request, config = planning.build_usage_request(
MagicMock(),
SimpleNamespace(id='u', tenant_no='t', dept_id=''),
'p1',
PlanQuotaOperation(operationId='op1'),
'reserve',
check_conditions=False,
)
assert captured['manual_allocations']
assert captured['manual_allocations'][0].permit_id == 'buy1'
assert config.purchase_cert_ids == ['buy1']
assert request.manual_allocations[0].permit_quantity == Decimal('2.5')
def test_unarranged_plan_build_usage_uses_customer_rule_by_effective_at(monkeypatch):
"""尚未安排且版本为空时,按生效时间走新规则自动选证,不查合同绑证。"""
from app.services import pl_quota_planning as planning
from app.schemas.pl.quota_planning import PlanQuotaOperation
from app.schemas.pl.quota_usage import UsageSource
source = UsageSource(
source_stop_type='delivery',
source_stop_id='d1',
source_stop_product_id='sp1',
plan_product_id='pp1',
contract_id='c1',
contract_product_id='cp1',
product_id='prod1',
quantity=Decimal('33'),
unit='dun',
fingerprint='f' * 64,
snapshot={'customerId': 'cust1'},
requires_transport=True,
)
plan = SimpleNamespace(
id='p1',
plan_date=date(2026, 11, 14),
license_plate='皖R48299',
transport_status='pending',
archive_status='unarchived',
cert_quota_rule_version=None,
cert_quota_arranged_at=None,
cert_configuration={'measurementVersion': 'per_stop_v2'},
tenant_no='t',
)
called = {'customer_select': 0, 'contract_bind': 0}
def fake_select(*args, **kwargs):
called['customer_select'] += 1
return ['buy1'], ['move1'], []
def fake_contract_bind(*args, **kwargs):
called['contract_bind'] += 1
raise AssertionError('未安排计划不应再走合同绑证')
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([source], {}))
monkeypatch.setattr(planning, 'resolve_measurement_version', lambda *a, **k: 'per_stop_v2')
monkeypatch.setattr(planning, 'plan_execution_lock_reason', lambda *a, **k: None)
monkeypatch.setattr(
'app.services.pl_cert_quota_rule_config_service.get_effective_at',
lambda *a, **k: datetime(2026, 11, 15, 20, 0, 0),
)
monkeypatch.setattr(
'app.services.pl_quota_customer_select.select_whole_cover_certs',
fake_select,
)
monkeypatch.setattr(planning, 'resolve_contract_bound_certs', fake_contract_bind)
monkeypatch.setattr(
planning,
'_get_row',
lambda *a, **k: SimpleNamespace(id='x', revision=1),
)
request, config = planning.build_usage_request(
MagicMock(),
SimpleNamespace(id='u', tenant_no='t', dept_id=''),
'p1',
PlanQuotaOperation(operationId='arrange-check'),
'reserve',
check_conditions=False,
)
assert called['customer_select'] == 1
assert called['contract_bind'] == 0
assert config.purchase_cert_ids == ['buy1']
assert config.transport_cert_ids == ['move1']
assert request.purchase_cert_ids == ['buy1']
def test_arranged_legacy_plan_build_usage_keeps_contract_bind(monkeypatch):
"""已首次安排并打成 legacy 的计划,安排/改派预占仍走合同绑证。"""
from app.services import pl_quota_planning as planning
from app.schemas.pl.quota_planning import PlanQuotaOperation
from app.schemas.pl.quota_usage import UsageSource
source = UsageSource(
source_stop_type='delivery',
source_stop_id='d1',
source_stop_product_id='sp1',
plan_product_id='pp1',
contract_id='c1',
contract_product_id='cp1',
product_id='prod1',
quantity=Decimal('33'),
unit='dun',
fingerprint='f' * 64,
snapshot={'customerId': 'cust1'},
requires_transport=True,
)
plan = SimpleNamespace(
id='p1',
plan_date=date(2026, 11, 14),
license_plate='皖R48299',
transport_status='arranged',
archive_status='unarchived',
cert_quota_rule_version='legacy',
cert_quota_arranged_at=datetime(2026, 11, 14, 10, 0, 0),
cert_configuration={'measurementVersion': 'per_stop_v2'},
tenant_no='t',
)
called = {'customer_select': 0, 'contract_bind': 0}
def fake_select(*args, **kwargs):
called['customer_select'] += 1
return ['buy1'], ['move1'], []
def fake_contract_bind(*args, **kwargs):
called['contract_bind'] += 1
return ['buy1'], ['move1']
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([source], {}))
monkeypatch.setattr(planning, 'resolve_measurement_version', lambda *a, **k: 'per_stop_v2')
monkeypatch.setattr(planning, 'plan_execution_lock_reason', lambda *a, **k: None)
monkeypatch.setattr(
'app.services.pl_cert_quota_rule_config_service.get_effective_at',
lambda *a, **k: datetime(2026, 11, 15, 20, 0, 0),
)
monkeypatch.setattr(
'app.services.pl_quota_customer_select.select_whole_cover_certs',
fake_select,
)
monkeypatch.setattr(planning, 'resolve_contract_bound_certs', fake_contract_bind)
monkeypatch.setattr(
planning,
'_get_row',
lambda *a, **k: SimpleNamespace(id='x', revision=1),
)
planning.build_usage_request(
MagicMock(),
SimpleNamespace(id='u', tenant_no='t', dept_id=''),
'p1',
PlanQuotaOperation(operationId='arrange-check'),
'resize',
check_conditions=False,
)
assert called['contract_bind'] == 1
assert called['customer_select'] == 0
@@ -42,6 +42,28 @@ def test_internal_stop_skips_belongs_company_contract_check():
assert links == []
def test_internal_stop_clears_product_contract_fields():
from types import SimpleNamespace
from app.services.pl_plan_stop_service import _clear_internal_stop_product_contracts
stop = SimpleNamespace(
customer_name="安庆市山峡化工有限公司",
products=[
SimpleNamespace(contract_id="c-dongheng", contract_product_id="line-1"),
SimpleNamespace(contract_id="c-2", contract_product_id="line-2"),
],
)
_clear_internal_stop_product_contracts(stop)
assert all(p.contract_id is None and p.contract_product_id is None for p in stop.products)
external = SimpleNamespace(
customer_name="安庆市鑫富化工有限责任公司",
products=[SimpleNamespace(contract_id="keep", contract_product_id="line")],
)
_clear_internal_stop_product_contracts(external)
assert external.products[0].contract_id == "keep"
def test_belongs_company_contract_error_is_not_swallowed():
mismatch = HTTPException(status_code=422, detail="装货合同的交易主体与归属公司不一致")
empty = HTTPException(status_code=422, detail="请先选择归属公司")
@@ -249,6 +249,11 @@ def test_same_city_settlement_does_not_require_transport_pairing():
assert validate_allocation_pairing([demand], [purchase], [], []) is None
def test_empty_transport_kind_settle_ignores_source_actuals():
"""同市只结转购买证时,空的运输证分组对实运量应直接空结果,不报缺实际量。"""
assert settle_allocations([], {'city': D(10)}) == ()
@pytest.mark.parametrize('manual_values', [(8,10,0),(18,0,0)])
def test_zero_capacity_foreign_row_cannot_unlock_manual_reordering(manual_values):
from app.services.pl_quota_allocation import Allocation
+46
View File
@@ -353,3 +353,49 @@ def test_plan_quota_usages_include_cert_attachment_urls(case):
assert usages['p1']['attachmentUrls'] == 'https://example.com/buy.jpg'
assert usages['p1']['certNo'] == 'G-BUY'
assert usages['t1']['attachmentUrls'] in ('', None)
def test_plan_quota_usages_hide_released_rows(case, monkeypatch):
"""详情关联证件不展示已释放用量,避免改客户后仍显示旧购买证。"""
from app.models.crm_models import CrmContract
from app.models.pl_quota_models import (
PlCertQuotaRuleConfig, PlPlanCertUsage, PlPlanCertUsageItem, PlPurchaseCert,
)
from app.services.pl_quota_planning import get_plan_quota
c = case
for model in (CrmContract, PlCertQuotaRuleConfig, PlPlanCertUsage, PlPlanCertUsageItem, PlPurchaseCert):
model.__table__.create(c.db.bind, checkfirst=True)
monkeypatch.setattr(
'app.services.pl_cert_quota_rule_config_service.plan_applies_customer_category_rule',
lambda *a, **k: False,
)
monkeypatch.setattr(
'app.services.pl_cert_quota_rule_config_service.resolve_rule_version_for_arrange',
lambda *a, **k: 'legacy',
)
# 本用例只断言 usages 过滤;清空站点合同避免 get_plan_quota 拉合同表
c.db.get(c.m.PlPlanLoadProduct, 'lp').contract_id = None
c.db.get(c.m.PlPlanDeliveryProduct, 'dp').contract_id = None
c.db.add(PlPurchaseCert(
id='p-keep', cert_no='G-KEEP', product_name_on_cert='硫酸', valid_use_text='多次有效',
buyer_name='买方', seller_name='卖方', total_qty=33, quantity_unit='吨',
tenant_no='t', status='active',
))
c.db.add(PlPurchaseCert(
id='p-old', cert_no='G-OLD', product_name_on_cert='硫酸', valid_use_text='多次有效',
buyer_name='买方', seller_name='卖方', total_qty=33, quantity_unit='吨',
tenant_no='t', status='active',
))
c.db.add(PlPlanCertUsage(
id='u-keep', tenant_no='t', plan_id='plan', plan_no_snapshot='PLAN',
cert_type='purchase', cert_id='p-keep', cert_no_snapshot='G-KEEP', cert_revision=1,
quantity_unit='吨', reserved_qty=5, used_qty=0, usage_status='reserved', del_flag=0,
))
c.db.add(PlPlanCertUsage(
id='u-released', tenant_no='t', plan_id='plan', plan_no_snapshot='PLAN',
cert_type='purchase', cert_id='p-old', cert_no_snapshot='G-OLD', cert_revision=1,
quantity_unit='吨', reserved_qty=0, used_qty=0, usage_status='released', del_flag=0,
))
c.db.flush()
cert_nos = [u['certNo'] for u in get_plan_quota(c.db, c.user, 'plan')['usages']]
assert cert_nos == ['G-KEEP']
+51
View File
@@ -98,6 +98,31 @@ def test_zero_reservation_consumes_once_slot(case):
assert c.db.query(c.m.PlPlanCertUsage).count()==2
with pytest.raises(ValueError): run(c,operation_id='other',plan_id='other',sources=sources)
def test_same_city_purchase_only_settle_without_transport(case):
"""同市段只预占购买证时,归档结转不得因空运输证分组误报缺实际量。"""
c = case
sources = [dict(
source_stop_type='delivery', source_stop_id='stop', source_stop_product_id='sp',
plan_product_id='pp', contract_id='c', contract_product_id='cp', product_id='product',
quantity='1', unit='吨', fingerprint='fp', requires_transport=False,
)]
run(c, purchase_cert_ids=['p'], transport_cert_ids=[], sources=sources)
assert c.db.query(c.m.PlPlanCertUsage).count() == 1
assert c.db.get(c.m.PlPurchaseCert, 'p').reserved_qty == 1
run(
c,
operation_id='settle-same-city',
action='settle',
purchase_cert_ids=['p'],
transport_cert_ids=[],
sources=sources,
actual_by_source={'delivery:sp': '1'},
)
assert c.db.get(c.m.PlPurchaseCert, 'p').used_qty == 1
assert c.db.get(c.m.PlPurchaseCert, 'p').reserved_qty == 0
assert c.db.query(c.m.PlTransportCert).filter_by(id='t').one().used_qty == 0
def test_same_cert_balance_covers_actual_above_reservation(case):
c = case
run(c)
@@ -108,6 +133,27 @@ def test_same_cert_balance_covers_actual_above_reservation(case):
assert c.db.query(c.m.PlPlanCertUsage).count() == 2
def test_auto_cover_ignores_arrangement_manuals_when_actual_exceeds_reservation(case):
"""安排/完善并关闭写入的整笔 manual_allocations 不得挡住归档超额补扣。"""
c = case
manuals = [
dict(permit_kind='purchase', source_id='load:sp', permit_id='p', source_quantity='29', permit_quantity='29'),
dict(permit_kind='transport', source_id='load:sp', permit_id='t', source_quantity='29', permit_quantity='29'),
]
run(c, manual_allocations=manuals)
# 归档请求仍带着计划量人工行(与完善并关闭后 cert_configuration 回灌一致)
run(
c,
operation_id='settle-with-stale-manuals',
action='settle',
actual_by_source={'load:sp': '35'},
manual_allocations=manuals,
)
assert c.db.get(c.m.PlPurchaseCert, 'p').used_qty == 35
assert c.db.get(c.m.PlPurchaseCert, 'p').reserved_qty == 0
assert c.db.get(c.m.PlTransportCert, 't').used_qty == 35
def test_same_cert_without_enough_balance_asks_for_another_certificate(case):
c = case
c.db.get(c.m.PlPurchaseCert, 'p').total_qty = 30
@@ -284,11 +330,16 @@ def test_no_cert_operation_is_still_idempotent(case):
def test_removal_and_restore_preserve_item_id(case):
c=case; run(c)
ids={i.id for i in c.db.query(c.m.PlPlanCertUsageItem).all()}
usage_ids={u.id for u in c.db.query(c.m.PlPlanCertUsage).all()}
run(c,action='resize',operation_id='clear',sources=[],purchase_cert_ids=[],transport_cert_ids=[])
assert all(i.del_flag==1 for i in c.db.query(c.m.PlPlanCertUsageItem).all())
# 清空分配后用量行标记 released 并软删,详情关联证件不再展示
assert all(u.usage_status=='released' and u.del_flag==1 for u in c.db.query(c.m.PlPlanCertUsage).all())
run(c,action='resize',operation_id='restore')
assert {i.id for i in c.db.query(c.m.PlPlanCertUsageItem).all()}==ids
assert {u.id for u in c.db.query(c.m.PlPlanCertUsage).all()}==usage_ids
assert all(i.del_flag==0 for i in c.db.query(c.m.PlPlanCertUsageItem).all())
assert all(u.usage_status=='reserved' and u.del_flag==0 for u in c.db.query(c.m.PlPlanCertUsage).all())
def _second_pair(c, cross=False):
for kind,model,old_id,new_id,total in [('purchase',c.m.PlPurchaseCert,'p','p2',100),('transport',c.m.PlTransportCert,'t','t2',100)]:
+170
View File
@@ -113,6 +113,9 @@ def test_mark_ready_allows_weighed_plan_until_quota_is_posted(monkeypatch):
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=__import__("datetime").datetime(2026, 11, 1, 10, 0, 0),
update_by=None,
plan_no="PO1",
plan_date=None,
@@ -173,6 +176,173 @@ def test_mark_ready_allows_weighed_plan_until_quota_is_posted(monkeypatch):
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):
from app.services.pl_quota_planning import contract_cert_arrange_block
@@ -0,0 +1,28 @@
-- 证件额度切点改为首次安排时间:补 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';
@@ -0,0 +1,28 @@
-- 证件额度切点改为首次安排时间:补 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';
@@ -0,0 +1,30 @@
# 证件额度切点:按首次安排时间(设计)
工单:[#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
es5-ext: false
esbuild: true
protobufjs: false
protobufjs: true
vue-demi: true
@@ -31,17 +31,24 @@ test('pending keywords still force alert mode without plan flags', () => {
)
})
test('unmarked legacy quota block still offers certificate ready', () => {
test('unmarked quota block only alerts, never offers certificate ready', () => {
assert.equal(
resolveArchiveQuotaBlockMode(
'实际数量已保存,证件没有扣减。请把实际数量改小,或先补充购买证和运输证,再重新归档。',
'用证没有完成',
{ quotaCertPendingFulfill: 0, quotaCertWaived: 0 }
),
'confirm-ready'
'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'
)
})
@@ -0,0 +1,46 @@
/**
* 顶栏侧栏收起按钮必须始终可见:
* - 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,18 +12,36 @@ import { parse } from '@vue/compiler-sfc'
const root = join(dirname(fileURLToPath(import.meta.url)), '..')
test('ArtSvgIcon: el-icon branch must not use Tailwind inline class', () => {
test('ArtSvgIcon: icon roots must not use Tailwind inline class', () => {
const src = readFileSync(join(root, 'src/components/core/base/art-svg-icon/index.vue'), 'utf8')
const { descriptor } = parse(src)
const template = descriptor.template?.content || ''
assert.match(template, /<el-icon\b[^>]*class="[^"]*art-svg-icon/)
assert.doesNotMatch(
template,
/<el-icon\b[^>]*class="[^"]*\binline\b/,
'el-icon must not include Tailwind inline (breaks display:inline-flex in prod CSS order)'
/<(?:el-icon|Icon)\b[^>]*class="[^"]*\binline\b/,
'icon roots must not include Tailwind inline (breaks display 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', () => {
const src = readFileSync(join(root, 'src/views/pl/plan-archive/index.vue'), 'utf8')
assert.match(src, /prop:\s*'planNo',\s*label:\s*'计划编号'/)
@@ -0,0 +1,66 @@
/**
* #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)'
)
})
@@ -39,6 +39,34 @@ test('H5 客户用证按客户列表展示证件', () => {
assert.match(contractTab, /\/m\/pl\/plan-cert\/customer\//)
assert.match(contractTab, /暂无客户用证数据/)
assert.match(planCertIndex, /title: '客户用证'/)
assert.match(planCertIndex, /客户名称 \/ 编号/)
assert.doesNotMatch(planCertIndex, /合同编号 \/ 名称 \/ 销售或购买单位/)
})
test('H5 客户用证详情显式导入 WebView 壳,避免空白页', () => {
const customerDetail = readFileSync(
new URL('../src/views/m/pl/plan-cert/customer-detail.vue', import.meta.url),
'utf8'
)
assert.match(customerDetail, /import MpWebviewShell from '@\/layouts\/MpWebviewShell\.vue'/)
assert.match(customerDetail, /import MpBusinessHeader from '@\/components\/mp\/MpBusinessHeader\.vue'/)
assert.match(customerDetail, /@ready="onShellReady"/)
})
test('H5 证件详情与建档列表展示系统客户和证用品类', () => {
const faceModel = readFileSync(
new URL('../src/views/m/pl/plan-cert/face-model.ts', import.meta.url),
'utf8'
)
const archiveTab = readFileSync(
new URL('../src/views/m/pl/plan-cert/ArchiveTab.vue', import.meta.url),
'utf8'
)
assert.match(faceModel, /label: '证用品类'/)
assert.match(faceModel, /certCategoryLabel/)
assert.match(archiveTab, /系统客户/)
assert.match(archiveTab, /证用品类/)
assert.match(archiveTab, /certCategoryLabel/)
})
test('H5 建档页使用关联购买证且无证面引用残留', () => {
+2
View File
@@ -65,7 +65,9 @@ export interface QuotaCert extends Omit<CertBody, 'status'> {
createTime?: string
certType?: CertType
derivedCategoryIds?: string[]
derivedCategoryNames?: string[]
customerName?: string | null
categoryName?: string | null
}
export interface ScopeProduct {
id?: string
@@ -1604,36 +1604,17 @@
async function showArchiveQuotaBlockDialog(message: string, title = '不能归档') {
const html = `<p class="pl-arrange-block-text">${escapeArchiveBlockText(message)}</p>`
const mode = resolveArchiveQuotaBlockMode(message, title, plan.value)
if (mode !== 'confirm-ready') {
const guide =
mode === 'alert-pending'
? `${html}<p class="pl-arrange-block-text">该运输计划已走证书齐备,归档前须完善证件。请到「证书齐备 → 已标记待完善证书」上传购买证/运输证并执行完善并关闭后再归档。</p>`
: html
await ElMessageBox.alert(guide, title, {
type: 'warning',
confirmButtonText: '知道了',
dangerouslyUseHTMLString: true,
customClass: 'pl-arrange-block-msgbox',
closeOnClickModal: false
}).catch(() => undefined)
return undefined
}
// 仅旧规则(legacy)允许在归档时标记证书齐备以跳过额度
const readyHtml = `${html}<p class="pl-arrange-block-text">如果购买证、运输证还没上传,可以标记证书齐备。仅旧规则计划标记后这次归档不再校验、不扣这两证额度;新规则计划请走「证书齐备 → 已标记待完善证书」。</p>`
try {
await ElMessageBox.confirm(readyHtml, title, {
type: 'warning',
confirmButtonText: '证书齐备',
cancelButtonText: '知道了',
dangerouslyUseHTMLString: true,
customClass: 'pl-arrange-block-msgbox',
closeOnClickModal: false,
distinguishCancelAndClose: true
})
return 'ready' as const
} catch {
return undefined
}
const guide =
mode === 'alert-pending'
? `${html}<p class="pl-arrange-block-text">该运输计划已走证书齐备,归档前须完善证件。请到「证书齐备 → 已标记待完善证书」上传购买证/运输证并执行完善并关闭后再归档。</p>`
: html
await ElMessageBox.alert(guide, title, {
type: 'warning',
confirmButtonText: '知道了',
dangerouslyUseHTMLString: true,
customClass: 'pl-arrange-block-msgbox',
closeOnClickModal: false
}).catch(() => undefined)
}
function applyArchiveOverageHighlight(items: Array<Record<string, unknown>>) {
@@ -1668,13 +1649,7 @@
// 业务异常已作为一次请求提交;补齐条件后允许新尝试,不回放旧异常。
quotaArchiveAttempt = { signature: '', id: '' }
const message = saved.quotaSettlementError
const choice = await showArchiveQuotaBlockDialog(message, '用证没有完成')
if (choice === 'ready' && current()) {
await planApi.markQuotaCertReady(targetId)
if (!current()) return
await submitArchiveWithOverageConfirm(targetId, frozenBody, current, confirmOverage)
return
}
await showArchiveQuotaBlockDialog(message, '用证没有完成')
const error = new Error(message) as Error & { cancelled?: boolean }
error.cancelled = true
throw error
@@ -1,11 +1,11 @@
<!-- 图标组件:支持 Element Plus 图标(无 : 前缀)与 Iconify 图标(含 : 前缀) -->
<template>
<!-- el-icon 勿加 Tailwind `inline`:生产 CSS 中 `.inline{display:inline}` 会覆盖
`.el-icon{display:inline-flex}`,导致 Fold 等图标在打包后不可见 -->
<!-- 勿给图标根节点加 Tailwind `inline`:生产 CSS 中 `.inline{display:inline}`
会覆盖 flex/尺寸,部分 Chrome 下 Fold 等图标不可见 -->
<el-icon v-if="epIcon" v-bind="iconAttrs" class="art-svg-icon">
<component :is="epIcon" />
</el-icon>
<Icon v-else-if="icon" :icon="icon" v-bind="iconAttrs" class="art-svg-icon inline" />
<Icon v-else-if="icon" :icon="icon" v-bind="iconAttrs" class="art-svg-icon" />
</template>
<script setup lang="ts">
@@ -21,17 +21,31 @@
@click="toHome"
/>
<!-- 菜单按钮 -->
<ArtIconButton
<!-- 菜单按钮:内联 SVG,避开 Chrome 下 el-icon / Iconify 偶发不绘制 -->
<button
v-if="isLeftMenu && shouldShowMenuButton"
icon="fold"
class="ml-3 max-sm:ml-[7px] menu-fold-btn"
type="button"
class="menu-fold-btn"
:class="{ 'is-menu-collapsed': !menuOpen }"
:title="menuOpen ? '收起菜单' : '展开菜单'"
:aria-label="menuOpen ? '收起菜单' : '展开菜单'"
:aria-expanded="menuOpen"
@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
@@ -388,14 +402,49 @@
}
}
.menu-fold-btn :deep(.art-svg-icon) {
transition: transform 0.3s ease;
/* 顶栏折叠按钮:原生 button + 内联 SVG,保证 Chrome/Safari 一致可见 */
.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;
}
.menu-fold-btn.is-menu-collapsed :deep(.art-svg-icon) {
@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;
/* 展开态默认旋转,与收起态对调 */
transform: rotate(180deg);
}
.menu-fold-btn.is-menu-collapsed .menu-fold-btn__icon {
transform: rotate(0deg);
}
/* Hover animation classes */
.refresh-btn:hover :deep(.art-svg-icon) {
animation: rotate180 0.5s;
@@ -119,13 +119,7 @@ export function useSettingsConfig() {
handler: 'uniqueOpened',
headerBarKey: null // 不依赖headerBar配置
},
{
key: 'showMenuButton',
label: t('setting.basics.list.collapseSidebar'),
type: 'switch' as const,
handler: 'menuButton',
headerBarKey: 'menuButton' as const
},
// showMenuButton 不提供开关:顶栏收起侧栏按钮为产品必显能力
{
key: 'showFastEnter',
label: t('setting.basics.list.fastEnter'),
@@ -67,7 +67,7 @@ export function useSettingsHandlers() {
uniqueOpened: createToggleHandler(() => settingStore.setUniqueOpened()),
// 显示菜单按钮
menuButton: createToggleHandler(() => settingStore.setButton()),
menuButton: createToggleHandler(() => settingStore.ensureMenuButtonVisible()),
// 显示快速入口
fastEnter: createToggleHandler(() => settingStore.setFastEnter()),
@@ -185,9 +185,8 @@
settingStore.setElementTheme(config.systemThemeColor)
// 界面显示(切换类方法)
toggleIfDifferent(settingStore.showMenuButton, config.showMenuButton, () =>
settingStore.setButton()
)
// 顶栏收起按钮为必显,导入配置时也强制打开
settingStore.ensureMenuButtonVisible()
toggleIfDifferent(settingStore.showFastEnter, config.showFastEnter, () =>
settingStore.setFastEnter()
)
+10 -6
View File
@@ -227,10 +227,15 @@ export const useSettingStore = defineStore(
}
/**
* 切换菜单按钮显示
* 切换菜单按钮显示(产品要求顶栏始终可收起侧栏,禁止关闭)
*/
const setButton = () => {
showMenuButton.value = !showMenuButton.value
showMenuButton.value = true
}
/** 强制显示顶栏侧栏收起按钮,修复旧 localStorage 中 false 残留 */
const ensureMenuButtonVisible = () => {
showMenuButton.value = true
}
/**
@@ -423,6 +428,7 @@ export const useSettingStore = defineStore(
setContainerWidth,
setUniqueOpened,
setButton,
ensureMenuButtonVisible,
setFastEnter,
setAutoClose,
setShowRefreshButton,
@@ -458,10 +464,8 @@ export const useSettingStore = defineStore(
} else if (width === 290) {
ctx.store.setMenuOpenWidth(270)
}
// 旧本地配置把收起按钮关掉了;产品需要顶栏始终能收起侧栏
if (!ctx.store.showMenuButton) {
ctx.store.setButton()
}
// 旧本地配置(sys-v*-setting)可能残留 showMenuButton:false;必须赋值 true,禁止用 toggle
ctx.store.ensureMenuButtonVisible()
}
}
}
@@ -1,6 +1,6 @@
/** 归档用证拦截弹窗:已齐备/待完善只提醒,未齐备旧规则才可再点证书齐备。 */
/** 归档用证拦截弹窗:只提醒,不在归档界面提供「证书齐备」操作。 */
export type ArchiveQuotaBlockMode = 'alert-pending' | 'alert-plain' | 'confirm-ready'
export type ArchiveQuotaBlockMode = 'alert-pending' | 'alert-plain'
export type ArchiveQuotaBlockPlanFlags = {
quotaCertPendingFulfill?: number | boolean | null
@@ -23,5 +23,5 @@ export function resolveArchiveQuotaBlockMode(
const pendingByPlan = flagOn(plan?.quotaCertPendingFulfill) || flagOn(plan?.quotaCertWaived)
if (title !== '用证没有完成') return 'alert-plain'
if (pendingByPlan || pendingByMessage) return 'alert-pending'
return 'confirm-ready'
return 'alert-plain'
}
+2
View File
@@ -75,6 +75,8 @@
if (!settingStore.showCrumbs) {
settingStore.setCrumbs()
}
// 纠正版本化 localStorage 中 showMenuButton:false,保证折叠钮始终可见
settingStore.ensureMenuButtonVisible()
})
</script>
@@ -25,6 +25,12 @@
}}</span>
</div>
<div class="mp-wv-card__kv">
<div class="mp-wv-card__kv-row"
><span>系统客户</span><span>{{ row.customerName || '—' }}</span></div
>
<div class="mp-wv-card__kv-row"
><span>证用品类</span><span>{{ certCategoryLabel(row) }}</span></div
>
<div class="mp-wv-card__kv-row"
><span>销售单位</span><span>{{ salePartyName(row) || '—' }}</span></div
>
@@ -119,7 +125,7 @@
} from '@/views/pl/quota-cert/cert-list-face'
import { useDictStore } from '@/store/modules/dict'
import { getProductUnitLabel } from '@/utils/crm-product-display'
import { certStatusLabels } from './face-model'
import { certCategoryLabel, certStatusLabels } from './face-model'
const props = defineProps<{
keyword: string
@@ -1,5 +1,5 @@
<template>
<MpWebviewShell @ready="ready = true">
<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">
@@ -34,11 +34,19 @@
import { useRoute, useRouter } from 'vue-router'
import { fetchGetMenuCodes } from '@/api/auth'
import { quotaStatisticsApi, type CustomerStatistics } from '@/api/pl/quota-cert'
import MpWebviewShell from '@/layouts/MpWebviewShell.vue'
import MpBusinessHeader from '@/components/mp/MpBusinessHeader.vue'
import CustomerCertQuotaTab from '@/views/m/crm/contract/CustomerCertQuotaTab.vue'
import '@/styles/mp-webview.scss'
import './cert-mobile.scss'
const route = useRoute()
const router = useRouter()
const ready = ref(false)
function onShellReady() {
ready.value = true
}
const authReady = ref(false)
const allowed = ref(false)
const loading = ref(true)
@@ -30,6 +30,22 @@ const longFaceKeys = new Set([
export type FaceField = { label: string; value: string; wide?: boolean }
export type FaceGroup = { title: string; fields: FaceField[] }
export function certCategoryLabel(
cert: Pick<QuotaCert, 'certType' | 'categoryName' | 'derivedCategoryNames'> & {
certType?: CertType | null
},
kind?: CertType
) {
const certKind = kind || cert.certType
if (certKind === 'transport') {
const names = (cert.derivedCategoryNames || [])
.map((item) => String(item || '').trim())
.filter(Boolean)
return names.join('、') || '—'
}
return String(cert.categoryName || '').trim() || '—'
}
export function certFaceGroups(
cert: QuotaCert,
kind: CertType,
@@ -51,6 +67,11 @@ export function certFaceGroups(
label: '系统客户',
value: String(cert.customerName || '').trim() || '—',
wide: true
},
{
label: '证用品类',
value: certCategoryLabel(cert, kind),
wide: true
}
)
}
+1 -1
View File
@@ -361,7 +361,7 @@
]
const placeholder = computed(() =>
tab.value === 'contract'
? '合同编号 / 名称 / 销售或购买单位'
? '客户名称 / 编号'
: tab.value === 'plan' || tab.value === 'ready'
? '计划编号 / 供方 / 需方'
: '证件编号 / 品名 / 销售或购买单位'
+11 -18
View File
@@ -970,7 +970,7 @@ import {
overflowExportPlaceholder
} from '@/utils/list-toolbar-overflow-items'
import ListColumnStatsRow from '@/components/business/list-column-stats-row/index.vue'
import type { StatsRowColumn } from '@/utils/list-column-stats'
import { buildStatsRowColumns, type StatsRowColumn } from '@/utils/list-column-stats'
import { useContractDetailDialog } from '@/composables/useContractDetailDialog'
import { usePersistedListColumns } from '@/composables/usePersistedListColumns'
import { useListTableViewportHeight } from '@/composables/useListTableViewportHeight'
@@ -1287,22 +1287,15 @@ const {
const archiveStatsRowRef = ref<{ resync?: () => void } | null>(null)
const archiveStatsRowColumns = computed((): StatsRowColumn[] => {
const cols: StatsRowColumn[] = [
{ key: '__selection', interactive: false },
{ key: '__index', interactive: false },
{ key: 'planNo', interactive: true, prop: 'planNo' }
]
for (const def of listColumnDefs.value) {
if (!isArchiveColumnVisible(def.prop)) continue
cols.push({
key: def.prop,
interactive: true,
prop: def.prop
})
}
return cols
})
/** 与表头可见列一一对应:勾选/序号占位 + 可见业务列(含可隐藏的 planNo) */
const archiveStatsRowColumns = computed((): StatsRowColumn[] =>
buildStatsRowColumns({
leadingSpacers: 2,
optionalDefs: listColumnDefs.value,
isColumnVisible: isArchiveColumnVisible,
moneyProps: PRICE_COLUMN_PROPS
})
)
function getArchiveStatCellValue(row: PlPlanListDisplayRow, prop: string): unknown {
const plan = row.plan
@@ -1656,7 +1649,7 @@ async function handleArchive(row: Plan) {
ElMessage.warning('无运输计划归档操作权限')
return
}
// 打开归档弹窗:已归档走调整;未归档/已暂存可直接打开(证书齐备仅在「确认归档」时校验,以便支持暂存)
// 打开归档弹窗:已归档走调整;未归档/已暂存可直接打开(用证校验在「确认归档」时执行,以便支持暂存)
archivePlanId.value = row.id
archiveDialogVisible.value = true
}
@@ -7,7 +7,7 @@
</div>
<div class="p-6 max-w-xl">
<p class="text-sm text-slate-500 mb-4">
配置「客户+品类」额度生效时间。未配置时无法安排运输。计划创建时按该时间打规则版本;修改后只影响之后新建的计划。
配置「客户+品类」额度生效时间。未配置时无法安排运输。以计划首次安排时刻与该时间比较:之前已安排的归档不再校验购买证/运输证;之后安排的走客户+品类最新规则。首次安排后版本冻结,改派不重打;修改生效时间只影响尚未安排的计划。
</p>
<el-form label-position="top" class="dialog-form-layout">
<el-form-item label="客户品类额度生效时间">
+31
View File
@@ -84,6 +84,7 @@ server {
}
# MinIO(bucket=ruoyi);兼容旧链接,推荐逐步切到 res.shanxiachem.com
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000;
@@ -96,8 +97,15 @@ server {
proxy_send_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-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') {
return 204;
@@ -224,6 +232,7 @@ server {
}
}
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000;
@@ -236,8 +245,15 @@ server {
proxy_send_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-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') {
return 204;
@@ -364,6 +380,7 @@ server {
}
}
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000;
@@ -376,8 +393,15 @@ server {
proxy_send_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-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') {
return 204;
@@ -477,6 +501,7 @@ server {
add_header X-Content-Type-Options "nosniff" always;
# 必须 proxy_hide_header 上游 CORS,否则 MinIO 的 Origin 与 nginx 的 * 叠成非法双头
location ^~ /ruoyi/ {
proxy_pass http://127.0.0.1:9000;
@@ -489,6 +514,12 @@ server {
proxy_send_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-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;