Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
233c2c7faa | ||
|
|
a4d747aece | ||
|
|
c658f78329 | ||
|
|
90fc25f3fe | ||
|
|
d333e97bec | ||
|
|
f9d031bacb | ||
|
|
3f62af430f | ||
|
|
643221c61f | ||
|
|
a7b9386e79 | ||
|
|
9f8dd0590a | ||
|
|
ff2f05c522 | ||
|
|
7cef2d0f9d | ||
|
|
9143eb776c | ||
|
|
366c69b8a3 | ||
|
|
4f24fd9658 | ||
|
|
97d6ec4b8a | ||
|
|
2045e7de89 | ||
|
|
eab882f92c | ||
|
|
04450fff88 | ||
|
|
82c21262ed | ||
|
|
8ac835fa96 | ||
|
|
e9f3602459 | ||
|
|
d2b8a573a1 | ||
|
|
79d1242d25 | ||
|
|
12652b826d | ||
|
|
be0ba622a0 |
No files matched your search
@@ -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)
|
||||
|
||||
# 查询合同产品明细
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -447,8 +447,14 @@ def _assert_contract_line_unreferenced(db, tenant_no, line_id):
|
||||
|
||||
|
||||
def _referenced_line_identity(data: dict):
|
||||
"""产品、品牌、型号、单位决定被引用明细的身份;包装规格单独校验。"""
|
||||
return _product_identity(data)[:-1]
|
||||
"""产品、品牌、型号、单位决定被引用明细的身份;包装规格单独校验。
|
||||
|
||||
未指定具体品牌时,历史空值和编辑页提交的 any(不限品牌)是同一身份。
|
||||
"""
|
||||
product_id, brand_mode, brand_id, model, unit = _product_identity(data)[:-1]
|
||||
if not brand_id and brand_mode in ("", "any"):
|
||||
brand_mode = ""
|
||||
return (product_id, brand_mode, brand_id, model, unit)
|
||||
|
||||
|
||||
def _package_specs_used_by_active_plans(db, tenant_no, line_id):
|
||||
|
||||
@@ -129,6 +129,7 @@ def _row_to_dict(row: CrmCustomer) -> Dict[str, Any]:
|
||||
"city": row.city or "",
|
||||
"district": row.district or "",
|
||||
"address": row.address or "",
|
||||
"sameCity": 1 if int(getattr(row, "same_city", 0) or 0) == 1 else 0,
|
||||
"status": row.status or "",
|
||||
"dealStatus": row.deal_status or "",
|
||||
"ownerUserId": row.owner_user_id or "",
|
||||
@@ -206,6 +207,7 @@ def list_customer_options(
|
||||
"id": r.id,
|
||||
"customerName": r.customer_name,
|
||||
"customerNo": r.customer_no,
|
||||
"sameCity": 1 if int(getattr(r, "same_city", 0) or 0) == 1 else 0,
|
||||
"label": r.customer_name,
|
||||
"value": r.id,
|
||||
}
|
||||
@@ -569,6 +571,7 @@ def create_customer(
|
||||
city=kwargs.get("city"),
|
||||
district=kwargs.get("district"),
|
||||
address=kwargs.get("address"),
|
||||
same_city=1 if int(kwargs.get("same_city") or 0) == 1 else 0,
|
||||
status="normal",
|
||||
deal_status="not_deal",
|
||||
owner_user_id=owner_id,
|
||||
@@ -626,18 +629,23 @@ def update_customer(
|
||||
"customer_name", "short_name", "customer_type", "mobile", "telephone",
|
||||
"email", "website", "level", "source", "industry", "park_area",
|
||||
"payment_terms", "scale", "province", "city", "district", "address",
|
||||
"same_city",
|
||||
"business_license_img",
|
||||
"business_permit_images", "other_cert_images",
|
||||
"clue_id", "order_num", "remark",
|
||||
"next_time",
|
||||
)
|
||||
_datetime_fields = {"next_time"}
|
||||
_flag_fields = {"same_city"}
|
||||
for field in _updatable:
|
||||
if field not in kwargs:
|
||||
continue
|
||||
val = kwargs[field]
|
||||
if field in _datetime_fields:
|
||||
setattr(obj, field, _parse_optional_datetime(val))
|
||||
elif field in _flag_fields:
|
||||
if val is not None:
|
||||
setattr(obj, field, 1 if int(val or 0) == 1 else 0)
|
||||
elif val is not None:
|
||||
setattr(obj, field, val)
|
||||
|
||||
|
||||
@@ -177,6 +177,12 @@ class CrmCustomer(Base):
|
||||
city = Column(String(50), nullable=True, comment="市")
|
||||
district = Column(String(50), nullable=True, comment="区")
|
||||
address = Column(String(255), nullable=True, comment="详细地址")
|
||||
same_city = Column(
|
||||
SmallInteger,
|
||||
nullable=False,
|
||||
default=0,
|
||||
comment="是否同市 0-否 1-是;相对本公司业务所在市,运输计划段次默认带入",
|
||||
)
|
||||
|
||||
# 状态与归属
|
||||
status = Column(
|
||||
|
||||
@@ -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="作废原因")
|
||||
|
||||
@@ -263,6 +263,11 @@ class CustomerCreateBody(BaseModel):
|
||||
city: Optional[str] = Field(default=None, description="市")
|
||||
district: Optional[str] = Field(default=None, description="区")
|
||||
address: Optional[str] = Field(default=None, description="详细地址")
|
||||
same_city: int = Field(
|
||||
default=0,
|
||||
alias="sameCity",
|
||||
description="是否同市 0-否 1-是;相对本公司业务所在市,运输计划段次默认带入",
|
||||
)
|
||||
next_time: Optional[str] = Field(default=None, alias="nextTime", description="下次联系时间")
|
||||
remark: Optional[str] = Field(default=None, description="备注")
|
||||
owner_user_id: Optional[str] = Field(default=None, alias="ownerUserId", description="负责人ID")
|
||||
@@ -330,6 +335,11 @@ class CustomerUpdateBody(BaseModel):
|
||||
city: Optional[str] = Field(default=None, description="市")
|
||||
district: Optional[str] = Field(default=None, description="区")
|
||||
address: Optional[str] = Field(default=None, description="详细地址")
|
||||
same_city: Optional[int] = Field(
|
||||
default=None,
|
||||
alias="sameCity",
|
||||
description="是否同市 0-否 1-是;相对本公司业务所在市,运输计划段次默认带入",
|
||||
)
|
||||
next_time: Optional[str] = Field(default=None, alias="nextTime", description="下次联系时间")
|
||||
remark: Optional[str] = Field(default=None, description="备注")
|
||||
owner_user_id: Optional[str] = Field(default=None, alias="ownerUserId", description="负责人ID")
|
||||
|
||||
@@ -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="作废原因")
|
||||
|
||||
@@ -130,6 +130,21 @@ class VehicleFuelPlateMonthItem(BaseModel):
|
||||
alias="last3MonthsRateL100",
|
||||
description="近三个月百公里油耗 L/100km,不足则为 null",
|
||||
)
|
||||
avg_rate_last10_l100: Optional[Decimal] = Field(
|
||||
default=None,
|
||||
alias="avgRateLast10L100",
|
||||
description="近10次有效加油段平均百公里油耗 L/100km,不足则为 null",
|
||||
)
|
||||
avg_rate_last20_l100: Optional[Decimal] = Field(
|
||||
default=None,
|
||||
alias="avgRateLast20L100",
|
||||
description="近20次有效加油段平均百公里油耗 L/100km,不足则为 null",
|
||||
)
|
||||
avg_rate_last30_l100: Optional[Decimal] = Field(
|
||||
default=None,
|
||||
alias="avgRateLast30L100",
|
||||
description="近30次有效加油段平均百公里油耗 L/100km,不足则为 null",
|
||||
)
|
||||
|
||||
model_config = {"populate_by_name": True}
|
||||
|
||||
|
||||
@@ -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)
|
||||
@@ -252,8 +252,35 @@ def _resolve_pending_reminder(
|
||||
reminder.document_no = document_no
|
||||
|
||||
|
||||
def _vehicle_reminder_skip_reason(
|
||||
db: Session, cert: PlCert
|
||||
) -> Optional[str]:
|
||||
"""报废车、三方(承运商)车不做人车证件到期提醒;返回关闭 remark。"""
|
||||
if cert.owner_type != "vehicle" or not cert.owner_id:
|
||||
return None
|
||||
vehicle = (
|
||||
db.query(PlVehicle)
|
||||
.filter(
|
||||
PlVehicle.id == cert.owner_id,
|
||||
PlVehicle.tenant_no == cert.tenant_no,
|
||||
PlVehicle.del_flag == 0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if not vehicle:
|
||||
return None
|
||||
if vehicle.vehicle_status == "scrapped":
|
||||
return "系统自动关闭:车辆已报废,不再提醒"
|
||||
if vehicle.vehicle_type == "carrier":
|
||||
return "系统自动关闭:三方/承运商车辆不提醒"
|
||||
return None
|
||||
|
||||
|
||||
def scan_cert_expiry(db: Session, tenant_no: Optional[str] = None, *, today: Optional[date] = None) -> int:
|
||||
"""扫描 pl_cert 生成到期提醒;退出提醒窗口或证件失效时关闭旧 pending。"""
|
||||
"""扫描 pl_cert 生成到期提醒;退出提醒窗口或证件失效时关闭旧 pending。
|
||||
|
||||
报废车辆、三方(承运商)车辆的证件不提醒,并关闭已有 pending。
|
||||
"""
|
||||
today = today or date.today()
|
||||
query = db.query(PlCert).filter(
|
||||
PlCert.del_flag == 0,
|
||||
@@ -266,6 +293,20 @@ def scan_cert_expiry(db: Session, tenant_no: Optional[str] = None, *, today: Opt
|
||||
active_cert_ids: set[str] = set()
|
||||
created_count = 0
|
||||
for cert in query.all():
|
||||
skip_reason = _vehicle_reminder_skip_reason(db, cert)
|
||||
if skip_reason:
|
||||
existing = _pending_reminder_for_cert(db, cert.id)
|
||||
if existing:
|
||||
_resolve_pending_reminder(
|
||||
existing,
|
||||
remark=skip_reason,
|
||||
expire_date=cert.expire_date,
|
||||
days_remaining=(cert.expire_date - today).days,
|
||||
document_type=cert.cert_name,
|
||||
document_no=cert.cert_no,
|
||||
)
|
||||
continue
|
||||
|
||||
active_cert_ids.add(cert.id)
|
||||
days_remaining = (cert.expire_date - today).days
|
||||
existing = _pending_reminder_for_cert(db, cert.id)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""运输管理 - 侧栏菜单角标统计"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
@@ -115,14 +116,19 @@ def count_legal_use_document_pending(db: Session, tenant_no: str, user) -> int:
|
||||
return apply_pl_scope(query, PlPlan, user, db, tenant_no).count()
|
||||
|
||||
|
||||
# 运输归档角标从该日之后起算,当天及更早的计划不计入。
|
||||
ARCHIVE_BADGE_PLAN_DATE_AFTER = date(2026, 9, 1)
|
||||
|
||||
|
||||
def count_plan_archive_pending(db: Session, tenant_no: str, user) -> int:
|
||||
"""待归档角标:与归档列表一致,仅统计已安排运输且未归档的计划。"""
|
||||
"""待归档角标:已安排运输、未归档,且计划日期晚于 2026-09-01。"""
|
||||
query = db.query(PlPlan).filter(
|
||||
PlPlan.tenant_no == tenant_no,
|
||||
PlPlan.del_flag == 0,
|
||||
PlPlan.archive_status == "unarchived",
|
||||
PlPlan.follow_status != "cancelled",
|
||||
PlPlan.transport_status == "arranged",
|
||||
PlPlan.plan_date > ARCHIVE_BADGE_PLAN_DATE_AFTER,
|
||||
)
|
||||
query = apply_pl_scope(query, PlPlan, user, db, tenant_no)
|
||||
return query.count()
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -339,6 +339,8 @@ def settle_allocations(reserved: Sequence[Allocation], actual_by_source: Mapping
|
||||
超来源量或超任一证件预占量均要求先补充分配。
|
||||
同市等仅购买证场景下,调用方仍可能对本函数传入空的运输证分组与全量实运量;
|
||||
无预占行时直接空结转,不把「缺实际量」套到另一类证件上。
|
||||
同市装货 + 异地卸货混跑时,运输证分组往往只有卸货来源,而 actual 含全部来源;
|
||||
只要求本组预占来源都有实运量,多出来源忽略。
|
||||
"""
|
||||
if not reserved:
|
||||
return ()
|
||||
@@ -357,7 +359,7 @@ def settle_allocations(reserved: Sequence[Allocation], actual_by_source: Mapping
|
||||
keys.add(key)
|
||||
seqs.add(seq)
|
||||
grouped.setdefault(row.source_id, []).append(row)
|
||||
if set(actual_by_source) != set(grouped):
|
||||
if not set(grouped) <= set(actual_by_source):
|
||||
raise AllocationInputError('必须明确提交每个来源的实际量')
|
||||
manual = {}
|
||||
for row in manual_actuals:
|
||||
|
||||
@@ -120,18 +120,29 @@ 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_applies_customer_category_rule,
|
||||
plan_skips_archive_cert_quota,
|
||||
)
|
||||
tenant_no = getattr(user, 'tenant_no', None) or ''
|
||||
customer_rule = plan_applies_customer_category_rule(db, tenant_no, plan)
|
||||
# 新规则:齐备仅放行安排/改派预占;归档与实际调整必须真证结转。
|
||||
# 旧规则(legacy):齐备仍跳过安排与归档(祖父兼容)。
|
||||
# 切点前首次安排:归档/实调不校证件(无需齐备);齐备仍可跳过安排预占。
|
||||
skip_actions = ('reserve', 'resize')
|
||||
if not plan_uses_customer_category(plan):
|
||||
if not customer_rule:
|
||||
skip_actions = ('reserve', 'resize', 'settle', 'actual_adjust')
|
||||
grandfather_archive_skip = (
|
||||
action in ('settle', 'actual_adjust')
|
||||
and plan_skips_archive_cert_quota(plan, db, tenant_no)
|
||||
)
|
||||
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)
|
||||
return {'operationId': ledger_id, 'usageIds': [], 'waived': True}
|
||||
if (
|
||||
plan_uses_customer_category(plan)
|
||||
customer_rule
|
||||
and action in ('settle', 'actual_adjust')
|
||||
and int(getattr(plan, 'quota_cert_pending_fulfill', 0) or 0) == 1
|
||||
):
|
||||
|
||||
@@ -9,6 +9,7 @@ from app.models.pl_quota_models import (
|
||||
PlTransportCert,
|
||||
PlTransportCertPurchaseRef,
|
||||
PlCertQtyLog,
|
||||
PlPlanCertUsage,
|
||||
)
|
||||
from app.schemas.pl.quota_planning import ManualQuantity
|
||||
from app.services.pl_cert_category_service import category_ids_for_product
|
||||
@@ -16,8 +17,29 @@ from app.services.pl_quota_cert_service import is_single_use_consumed
|
||||
from app.services.pl_quota_units import same_quantity_unit, standard_conversion_ratio
|
||||
|
||||
|
||||
def _available(cert):
|
||||
return Decimal(cert.total_qty) - Decimal(cert.used_qty) - Decimal(cert.reserved_qty)
|
||||
def _plan_own_reserved(db, user, plan_id, cert_type, cert_id) -> Decimal:
|
||||
"""本计划对该证的预占量;再安排时加回余量,避免把本单占用当成他人占用。"""
|
||||
if not plan_id:
|
||||
return Decimal('0')
|
||||
row = (
|
||||
db.query(PlPlanCertUsage)
|
||||
.filter_by(
|
||||
tenant_no=user.tenant_no,
|
||||
plan_id=plan_id,
|
||||
cert_type=cert_type,
|
||||
cert_id=cert_id,
|
||||
del_flag=0,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
return Decimal('0')
|
||||
return Decimal(row.reserved_qty or 0)
|
||||
|
||||
|
||||
def _available(cert, *, own_reserved=None):
|
||||
own = Decimal(own_reserved if own_reserved is not None else 0)
|
||||
return Decimal(cert.total_qty) - Decimal(cert.used_qty) - Decimal(cert.reserved_qty) + own
|
||||
|
||||
|
||||
def _in_force(cert, on_date: date) -> bool:
|
||||
@@ -226,6 +248,7 @@ def _linked_transports(db, user, customer_id, purchase_id):
|
||||
|
||||
def _diagnose_select_failure(
|
||||
db, user, source, *, vehicle_no: str, on_date: date, candidates, manual_allocations=(),
|
||||
plan_id=None,
|
||||
):
|
||||
"""选证失败时按证据优先给出单一可执行原因,避免笼统兜底句。"""
|
||||
place = '同市' if not source.requires_transport else '异地'
|
||||
@@ -269,7 +292,7 @@ def _diagnose_select_failure(
|
||||
if not _in_force(purchase, on_date):
|
||||
expired_buy.append(purchase)
|
||||
continue
|
||||
if is_single_use_consumed(db, user, 'purchase', purchase):
|
||||
if is_single_use_consumed(db, user, 'purchase', purchase, exclude_plan_id=plan_id):
|
||||
consumed_buy.append(purchase)
|
||||
continue
|
||||
try:
|
||||
@@ -280,7 +303,8 @@ def _diagnose_select_failure(
|
||||
except HTTPException:
|
||||
unit_buy.append(purchase)
|
||||
continue
|
||||
if _available(purchase) < need:
|
||||
buy_own = _plan_own_reserved(db, user, plan_id, 'purchase', purchase.id)
|
||||
if _available(purchase, own_reserved=buy_own) < need:
|
||||
short_buy.append((purchase, need))
|
||||
continue
|
||||
|
||||
@@ -305,7 +329,7 @@ def _diagnose_select_failure(
|
||||
if not _in_force(transport, on_date):
|
||||
expired_move.append(transport)
|
||||
continue
|
||||
if is_single_use_consumed(db, user, 'transport', transport):
|
||||
if is_single_use_consumed(db, user, 'transport', transport, exclude_plan_id=plan_id):
|
||||
consumed_move.append(transport)
|
||||
continue
|
||||
if not _vehicle_ok(transport, vehicle_no):
|
||||
@@ -319,7 +343,8 @@ def _diagnose_select_failure(
|
||||
except HTTPException:
|
||||
unit_move.append(transport)
|
||||
continue
|
||||
if _available(transport) < t_need:
|
||||
move_own = _plan_own_reserved(db, user, plan_id, 'transport', transport.id)
|
||||
if _available(transport, own_reserved=move_own) < t_need:
|
||||
short_move.append((transport, t_need))
|
||||
continue
|
||||
purchase_had_ready_transport = True
|
||||
@@ -428,11 +453,13 @@ def _diagnose_select_failure(
|
||||
|
||||
def select_whole_cover_certs(
|
||||
db, user, sources, *, vehicle_no: str, on_date: date, manual_allocations=(),
|
||||
plan_id=None,
|
||||
):
|
||||
"""返回 purchase_cert_ids, transport_cert_ids, manual_allocations。
|
||||
|
||||
每个来源必须由一张购买证整笔覆盖;异地再配一张关联且车号/余量够的运输证。
|
||||
单位无法自动换算时,使用计划段次用证已保存的人工换算量。
|
||||
plan_id:再安排时排除本计划已占用的一次有效证,并把本单预占加回可选余量。
|
||||
"""
|
||||
if not sources:
|
||||
return [], [], []
|
||||
@@ -467,7 +494,7 @@ def select_whole_cover_certs(
|
||||
continue
|
||||
if not _in_force(purchase, on_date):
|
||||
continue
|
||||
if is_single_use_consumed(db, user, 'purchase', purchase):
|
||||
if is_single_use_consumed(db, user, 'purchase', purchase, exclude_plan_id=plan_id):
|
||||
continue
|
||||
try:
|
||||
need = _need_permit_qty(
|
||||
@@ -476,7 +503,8 @@ def select_whole_cover_certs(
|
||||
)
|
||||
except HTTPException:
|
||||
continue
|
||||
if _available(purchase) < need:
|
||||
buy_own = _plan_own_reserved(db, user, plan_id, 'purchase', purchase.id)
|
||||
if _available(purchase, own_reserved=buy_own) < need:
|
||||
continue
|
||||
|
||||
if not source.requires_transport:
|
||||
@@ -495,7 +523,7 @@ def select_whole_cover_certs(
|
||||
continue
|
||||
if not _in_force(transport, on_date):
|
||||
continue
|
||||
if is_single_use_consumed(db, user, 'transport', transport):
|
||||
if is_single_use_consumed(db, user, 'transport', transport, exclude_plan_id=plan_id):
|
||||
continue
|
||||
if not _vehicle_ok(transport, vehicle_no):
|
||||
continue
|
||||
@@ -506,7 +534,8 @@ def select_whole_cover_certs(
|
||||
)
|
||||
except HTTPException:
|
||||
continue
|
||||
if _available(transport) < t_need:
|
||||
move_own = _plan_own_reserved(db, user, plan_id, 'transport', transport.id)
|
||||
if _available(transport, own_reserved=move_own) < t_need:
|
||||
continue
|
||||
chosen_purchase = purchase
|
||||
chosen_transport = transport
|
||||
@@ -522,6 +551,7 @@ def select_whole_cover_certs(
|
||||
_diagnose_select_failure(
|
||||
db, user, source, vehicle_no=vehicle_no, on_date=on_date,
|
||||
candidates=candidates, manual_allocations=saved_manuals,
|
||||
plan_id=plan_id,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@@ -34,6 +34,13 @@ def plan_fingerprint(sources):
|
||||
return hashlib.sha256(json.dumps(sorted((s.source_id, s.fingerprint) for s in sources)).encode()).hexdigest()
|
||||
|
||||
|
||||
def plan_cert_on_date(plan) -> date:
|
||||
"""购买证、运输证有效期只按计划日期比对。"""
|
||||
if getattr(plan, "plan_date", None) is None:
|
||||
raise HTTPException(409, "请先填写计划日期")
|
||||
return plan.plan_date
|
||||
|
||||
|
||||
def classify_contract_cert_bindings(sources, bindings_by_contract, contract_labels):
|
||||
"""按合同产品的可用绑定选出购买证、运输证。同市段只要求购买证。"""
|
||||
purchase_ids, transport_ids = [], []
|
||||
@@ -131,8 +138,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:
|
||||
# 新规则:禁止手工选证;按客户+品类整笔自动选证
|
||||
@@ -140,10 +147,11 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
|
||||
vehicle = str(
|
||||
(preview_vehicle or {}).get('licensePlate', plan.license_plate) or ''
|
||||
).strip()
|
||||
on_date = max(date.today(), plan.plan_date or date.today())
|
||||
on_date = plan_cert_on_date(plan)
|
||||
purchase_ids, transport_ids, manuals = select_whole_cover_certs(
|
||||
db, user, sources, vehicle_no=vehicle, on_date=on_date,
|
||||
manual_allocations=config.manual_allocations,
|
||||
plan_id=plan.id,
|
||||
)
|
||||
config = config.model_copy(update={
|
||||
'purchase_cert_ids': purchase_ids,
|
||||
@@ -186,7 +194,7 @@ def build_usage_request(db, user, plan_id, operation, action, *, lock=False, che
|
||||
operation_id=op.operation_id, action=action, plan_id=plan_id, sources=sources,
|
||||
allow_supplement=op.allow_supplement,
|
||||
purchase_cert_ids=config.purchase_cert_ids, transport_cert_ids=config.transport_cert_ids,
|
||||
vehicle_no=str((preview_vehicle or {}).get('licensePlate', plan.license_plate) or '').strip(), on_date=max(date.today(), plan.plan_date or date.today()),
|
||||
vehicle_no=str((preview_vehicle or {}).get('licensePlate', plan.license_plate) or '').strip(), on_date=plan_cert_on_date(plan),
|
||||
executed=executed, manual_allocations=[UsageManual(**r.model_dump()) for r in config.manual_allocations],
|
||||
actual_by_source=actuals, manual_actuals=[UsageManual(**r.model_dump()) for r in op.manual_actuals],
|
||||
reason=op.reason, evidence_urls=op.evidence_urls or '', source_note=op.source_note or '',
|
||||
@@ -228,10 +236,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, '已安排计划请通过调整运输在同一事务重算用证')
|
||||
@@ -336,13 +344,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,
|
||||
|
||||
@@ -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():
|
||||
@@ -217,8 +217,9 @@ def _candidate_context(db,user,r,plan,certs,usages,items,selected,preview=False,
|
||||
if product is None or product.product_id!=s.product_id: raise ValueError('合同产品归属不符')
|
||||
scopes={}; candidates={'purchase':[],'transport':[]}
|
||||
skipped_for_vehicle=False
|
||||
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
|
||||
# 安排前 version 常为空;须按 effective_at 前瞻,不能把空当 legacy(否则人工行会报「不适用」)。
|
||||
customer_rule = plan_applies_customer_category_rule(db, getattr(user, 'tenant_no', None) or '', plan)
|
||||
from app.services.pl_quota_cert_service import ensure_zero_opening
|
||||
for k in sorted(selected):
|
||||
kind,pid=k; c=certs[k]
|
||||
@@ -343,7 +344,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')}
|
||||
@@ -411,8 +417,8 @@ 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_cert_quota_rule_config_service import plan_applies_customer_category_rule
|
||||
if plan_applies_customer_category_rule(db, getattr(user, 'tenant_no', None) or '', 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
|
||||
@@ -435,7 +441,7 @@ def _settlement_cover_reject_reason(db, user, r, plan, kind, cert):
|
||||
if cert.status != 'active' or not cert.verified_time or not cert.verified_by:
|
||||
return f'{label} {no} 未启用或未复核'
|
||||
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 f'{label} {no} 不在计划日期 {r.on_date.isoformat()} 的有效期内'
|
||||
policy = usage_policy(cert.valid_use_text)
|
||||
if policy == 'needs_confirmation':
|
||||
return f'{label} {no} 有效次数待确认'
|
||||
@@ -458,8 +464,8 @@ def _settlement_cover_reject_reason(db, user, r, plan, kind, cert):
|
||||
|
||||
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)
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule
|
||||
customer_rule = plan_applies_customer_category_rule(db, getattr(user, 'tenant_no', None) or '', plan)
|
||||
reasons = []
|
||||
for kind, cid in candidate_keys:
|
||||
key = (kind, cid)
|
||||
@@ -645,8 +651,8 @@ def _settle(db,user,r,certs,usages,items,plan):
|
||||
supplemental=[]
|
||||
if excess:
|
||||
if auto_cover:
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_uses_customer_category
|
||||
customer_rule = plan_uses_customer_category(plan)
|
||||
from app.services.pl_cert_quota_rule_config_service import plan_applies_customer_category_rule
|
||||
customer_rule = plan_applies_customer_category_rule(db, getattr(user, 'tenant_no', None) or '', plan)
|
||||
try:
|
||||
purchase_ids, transport_ids = _settle_cover_cert_ids(db, user, plan, r.sources)
|
||||
except HTTPException as exc:
|
||||
|
||||
@@ -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, '该计划不在证书齐备待完善列表中')
|
||||
|
||||
@@ -479,6 +479,41 @@ def rate_l100(liters: Decimal, run_km: Optional[Decimal]) -> Optional[Decimal]:
|
||||
)
|
||||
|
||||
|
||||
def trip_rate_l100(
|
||||
prev_liters: Optional[Decimal],
|
||||
prev_odometer: Optional[Decimal],
|
||||
curr_odometer: Optional[Decimal],
|
||||
) -> Optional[Decimal]:
|
||||
"""相邻两次登记的单次油耗:上次升数 × 100 / (本次期初 − 上次期初)。"""
|
||||
if prev_liters is None or prev_odometer is None or curr_odometer is None:
|
||||
return None
|
||||
liters = Decimal(prev_liters)
|
||||
if liters <= 0:
|
||||
return None
|
||||
return rate_l100(liters, Decimal(curr_odometer) - Decimal(prev_odometer))
|
||||
|
||||
|
||||
def avg_recent_trip_rates_l100(
|
||||
rows: Sequence[Tuple[Optional[Decimal], Optional[Decimal]]],
|
||||
n: int,
|
||||
) -> Optional[Decimal]:
|
||||
"""rows 为按时间升序的 (期初公里, 加油升数);取最近 n 个有效单次油耗算术平均。"""
|
||||
if n <= 0:
|
||||
return None
|
||||
rates: list[Decimal] = []
|
||||
for i in range(1, len(rows)):
|
||||
prev_odo, prev_liters = rows[i - 1]
|
||||
curr_odo, _ = rows[i]
|
||||
rate = trip_rate_l100(prev_liters, prev_odo, curr_odo)
|
||||
if rate is not None:
|
||||
rates.append(rate)
|
||||
if not rates:
|
||||
return None
|
||||
selected = rates[-n:]
|
||||
total = sum(selected, Decimal("0"))
|
||||
return (total / Decimal(len(selected))).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def _odo_pairs(
|
||||
rows: Sequence[PlVehicleFuelRegister],
|
||||
) -> list[Tuple[date, Optional[Decimal]]]:
|
||||
@@ -526,8 +561,6 @@ def list_plate_month_summary(
|
||||
q_start, q_end = quarter_bounds(anchor)
|
||||
prev_q_start, _ = _ym_bounds(ym_shift(f"{q_start:%Y-%m}", -3))
|
||||
_, next_q_end = quarter_bounds(q_end)
|
||||
range_start = min(prev_q_start, last3_start, prev_start)
|
||||
range_end = max(next_end, next_q_end)
|
||||
|
||||
vehicle_query = (
|
||||
db.query(PlVehicle)
|
||||
@@ -535,6 +568,7 @@ def list_plate_month_summary(
|
||||
PlVehicle.tenant_no == tenant_no,
|
||||
PlVehicle.vehicle_type == "self",
|
||||
PlVehicle.del_flag == 0,
|
||||
PlVehicle.vehicle_status != "scrapped",
|
||||
# 历史档案将叉车、油桶也归为 self;车辆统计卡片不展示这两类用油对象。
|
||||
func.trim(PlVehicle.license_plate).notin_(("叉车", "油桶")),
|
||||
)
|
||||
@@ -547,12 +581,11 @@ def list_plate_month_summary(
|
||||
vehicles = apply_pl_scope(vehicle_query, PlVehicle, user, db, tenant_no).all()
|
||||
personnel_summaries = load_vehicle_personnel_summaries(db, tenant_no, [v.id for v in vehicles])
|
||||
|
||||
# 近 N 次平均需要完整历史;月/季指标仍从同批记录按区间切片。
|
||||
query = db.query(PlVehicleFuelRegister).filter(
|
||||
PlVehicleFuelRegister.tenant_no == tenant_no,
|
||||
PlVehicleFuelRegister.del_flag == 0,
|
||||
PlVehicleFuelRegister.status == "normal",
|
||||
PlVehicleFuelRegister.register_date >= range_start,
|
||||
PlVehicleFuelRegister.register_date < range_end,
|
||||
)
|
||||
query = apply_pl_scope(query, PlVehicleFuelRegister, user, db, tenant_no)
|
||||
registers = query.order_by(
|
||||
@@ -575,6 +608,7 @@ def list_plate_month_summary(
|
||||
next_q_rows = [r for r in rows if q_end <= r.register_date < next_q_end]
|
||||
prev_q_rows = [r for r in rows if prev_q_start <= r.register_date < q_start]
|
||||
last3_rows = [r for r in rows if last3_start <= r.register_date < cur_end]
|
||||
odo_liter_rows = [(r.odometer_km, r.fuel_liters) for r in rows]
|
||||
|
||||
month_km, month_status = period_run_km(_odo_pairs(cur_rows), _odo_pairs(next_rows))
|
||||
prev_month_km, prev_month_status = period_run_km(_odo_pairs(prev_rows), _odo_pairs(cur_rows))
|
||||
@@ -606,6 +640,9 @@ def list_plate_month_summary(
|
||||
prevQuarterRateL100=prev_quarter_rate,
|
||||
prevMonthRateL100=prev_month_rate,
|
||||
last3MonthsRateL100=last3_rate,
|
||||
avgRateLast10L100=avg_recent_trip_rates_l100(odo_liter_rows, 10),
|
||||
avgRateLast20L100=avg_recent_trip_rates_l100(odo_liter_rows, 20),
|
||||
avgRateLast30L100=avg_recent_trip_rates_l100(odo_liter_rows, 30),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -309,6 +309,34 @@ def test_referenced_line_still_cannot_change_product_identity_or_be_removed(db):
|
||||
assert old.del_flag == 0
|
||||
|
||||
|
||||
def test_referenced_blank_brand_can_save_as_unrestricted_and_add_line(db):
|
||||
"""编辑页把历史空品牌提交为不限品牌时,不算更换身份,可以同时新增明细。"""
|
||||
old = _referenced_contract(db)
|
||||
old.brand_mode = None
|
||||
old.brand_id = None
|
||||
old.brand_name = None
|
||||
db.flush()
|
||||
sync(db, 'contract', [
|
||||
{'id': 'old', 'brandMode': 'any', 'brandId': None, 'brandName': None},
|
||||
{'productId': 'lye30', 'productName': '30%液碱', 'model': '30%', 'unit': '吨', 'quantity': 0, 'packageSpec': '槽罐车'},
|
||||
])
|
||||
assert old.del_flag == 0 and old.id == 'old' and old.product_id == 'sku'
|
||||
assert old.brand_mode == 'any' and old.brand_id is None
|
||||
added = db.query(CrmContractProduct).filter_by(product_id='lye30', del_flag=0).one()
|
||||
assert added.model == '30%' and added.unit == '吨'
|
||||
|
||||
|
||||
def test_referenced_blank_brand_still_cannot_become_specific_brand(db):
|
||||
old = _referenced_contract(db)
|
||||
old.brand_mode = None
|
||||
old.brand_id = None
|
||||
old.brand_name = None
|
||||
db.flush()
|
||||
with pytest.raises(ValueError, match='不能删除或更换产品身份'):
|
||||
sync(db, 'contract', [{'id': 'old', 'brandMode': 'required', 'brandId': 'hong', 'brandName': '红四方'}])
|
||||
assert old.brand_mode is None and old.brand_id is None and old.del_flag == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('follow_status,delivery_flag', [('cancelled', 0), ('arranged', 1)])
|
||||
def test_inactive_plan_reference_does_not_lock_package_spec(db, follow_status, delivery_flag):
|
||||
old = _referenced_contract(db, follow_status=follow_status, delivery_flag=delivery_flag)
|
||||
|
||||
@@ -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):
|
||||
@@ -47,17 +125,13 @@ def test_apply_plan_quota_new_rule_waive_skips_reserve_not_settle(monkeypatch):
|
||||
called['assert'] = True
|
||||
|
||||
monkeypatch.setattr('app.services.pl_quota_waiver.assert_waived_sources', fake_assert)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category',
|
||||
lambda p: True,
|
||||
)
|
||||
|
||||
result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u'), plan, 'reserve', None)
|
||||
result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u', tenant_no='t'), plan, 'reserve', None)
|
||||
assert result.get('waived') is True
|
||||
assert called.get('assert') is True
|
||||
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u'), plan, 'settle', None)
|
||||
biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u', tenant_no='t'), plan, 'settle', None)
|
||||
assert '待完善' in str(exc.value.detail)
|
||||
|
||||
|
||||
@@ -268,14 +342,15 @@ def test_legacy_waive_still_skips_settle(monkeypatch):
|
||||
quota_cert_waived=1,
|
||||
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_uses_customer_category',
|
||||
lambda p: False,
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_skips_archive_cert_quota',
|
||||
lambda p, db=None, tenant_no=None: False,
|
||||
)
|
||||
monkeypatch.setattr('app.services.pl_quota_waiver.assert_waived_sources', lambda *a, **k: None)
|
||||
result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u'), plan, 'settle', None)
|
||||
result = biz.apply_plan_quota(MagicMock(), SimpleNamespace(id='u', tenant_no='t'), plan, 'settle', None)
|
||||
assert result.get('waived') is True
|
||||
|
||||
|
||||
@@ -432,7 +507,13 @@ def test_candidate_context_customer_rule_skips_contract_scope(monkeypatch):
|
||||
from app.services import pl_quota_usage_service as usage
|
||||
from app.schemas.pl.quota_usage import UsageSource
|
||||
|
||||
plan = SimpleNamespace(id='plan', cert_quota_rule_version='customer_category', plan_no='P1')
|
||||
# 安排前 version/arranged_at 均为空;必须按前瞻新规则,不能查合同 scope。
|
||||
plan = SimpleNamespace(
|
||||
id='plan',
|
||||
cert_quota_rule_version=None,
|
||||
cert_quota_arranged_at=None,
|
||||
plan_no='P1',
|
||||
)
|
||||
source = UsageSource(
|
||||
source_stop_type='delivery',
|
||||
source_stop_id='s1',
|
||||
@@ -485,8 +566,8 @@ def test_candidate_context_customer_rule_skips_contract_scope(monkeypatch):
|
||||
monkeypatch.setattr(usage, '_query', fake_query)
|
||||
monkeypatch.setattr(usage, '_contract', lambda *a, **k: SimpleNamespace(status='executing', contract_type='sale'))
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category',
|
||||
lambda p: True,
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_applies_customer_category_rule',
|
||||
lambda db, tenant_no, p: True,
|
||||
)
|
||||
# product ownership check uses _query for CrmContractProduct
|
||||
def fake_query2(db, user, model, lock=False, **filters):
|
||||
@@ -506,6 +587,102 @@ def test_candidate_context_customer_rule_skips_contract_scope(monkeypatch):
|
||||
assert candidates['purchase'][0].product_ids == frozenset({'delivery:sp1'})
|
||||
|
||||
|
||||
def test_candidate_context_unstamped_with_manual_allocates(monkeypatch):
|
||||
"""未打戳计划 + 新规则人工行:候选 product_ids 须含 source_id,allocate 才不会报人工分配不适用。"""
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from types import SimpleNamespace
|
||||
from app.services import pl_quota_usage_service as usage
|
||||
from app.services.pl_quota_allocation import allocate_plan, SourceDemand
|
||||
from app.schemas.pl.quota_usage import UsageSource, UsageManual
|
||||
|
||||
plan = SimpleNamespace(
|
||||
id='plan',
|
||||
cert_quota_rule_version=None,
|
||||
cert_quota_arranged_at=None,
|
||||
plan_no='PO20261113031',
|
||||
)
|
||||
source = UsageSource(
|
||||
source_stop_type='delivery',
|
||||
source_stop_id='s1',
|
||||
source_stop_product_id='sp1',
|
||||
plan_product_id='pp1',
|
||||
contract_id='c1',
|
||||
contract_product_id='cp1',
|
||||
product_id='prod1',
|
||||
quantity=Decimal('33'),
|
||||
unit='dun',
|
||||
fingerprint='f' * 64,
|
||||
snapshot={'customerId': 'cust1'},
|
||||
requires_transport=False,
|
||||
)
|
||||
request = SimpleNamespace(
|
||||
sources=[source],
|
||||
on_date=date(2026, 11, 15),
|
||||
vehicle_no='皖A9TEST1',
|
||||
manual_allocations=[
|
||||
UsageManual(
|
||||
permit_kind='purchase',
|
||||
source_id='delivery:sp1',
|
||||
permit_id='buy1',
|
||||
source_quantity=Decimal('33'),
|
||||
permit_quantity=Decimal('33'),
|
||||
),
|
||||
],
|
||||
)
|
||||
cert = SimpleNamespace(
|
||||
id='buy1', status='active', verified_time=date(2026, 11, 1), verified_by='u',
|
||||
valid_from=date(2026, 11, 1), valid_to=date(2027, 1, 1), valid_use_text='多次有效',
|
||||
total_qty=Decimal('100'), used_qty=Decimal('0'), reserved_qty=Decimal('0'),
|
||||
quantity_unit='dun', vehicle_numbers_json=['皖A9TEST1'], opening_single_use_consumed=0,
|
||||
revision=1, cert_no='G1',
|
||||
)
|
||||
|
||||
class Q:
|
||||
def __init__(self, row=None, rows=None):
|
||||
self._row = row
|
||||
self._rows = rows or ([] if row is None else [row])
|
||||
|
||||
def first(self):
|
||||
return self._row
|
||||
|
||||
def all(self):
|
||||
return self._rows
|
||||
|
||||
def fake_query(db, user, model, lock=False, **filters):
|
||||
name = getattr(model, '__name__', '')
|
||||
if name == 'CrmContractProduct':
|
||||
return Q(SimpleNamespace(product_id='prod1'))
|
||||
if name == 'PlCertQtyLog':
|
||||
return Q(SimpleNamespace(id='opening'))
|
||||
if name == 'PlTransportCertPurchaseRef':
|
||||
return Q(rows=[])
|
||||
if name in ('PlContractCertLink', 'PlContractCertProduct'):
|
||||
raise AssertionError('未打戳新规则不应查合同绑证 scope')
|
||||
return Q()
|
||||
|
||||
monkeypatch.setattr(usage, '_query', fake_query)
|
||||
monkeypatch.setattr(usage, '_contract', lambda *a, **k: SimpleNamespace(status='executing', contract_type='sale'))
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_applies_customer_category_rule',
|
||||
lambda db, tenant_no, p: True,
|
||||
)
|
||||
|
||||
sources, scopes, candidates = usage._candidate_context(
|
||||
MagicMock(), SimpleNamespace(tenant_no='t', id='u'), request, plan,
|
||||
{('purchase', 'buy1'): cert}, {}, {}, {('purchase', 'buy1')},
|
||||
)
|
||||
assert 'delivery:sp1' in candidates['purchase'][0].product_ids
|
||||
demands = [
|
||||
SourceDemand(s.source_id, s.source_id, s.quantity, s.unit, s.requires_transport)
|
||||
for s in sources.values()
|
||||
]
|
||||
manuals = usage._manual(request.manual_allocations)
|
||||
allocation = allocate_plan(demands, candidates['purchase'], candidates['transport'], manual_allocations=manuals)
|
||||
assert allocation.purchase_allocations
|
||||
assert allocation.purchase_allocations[0].permit_id == 'buy1'
|
||||
|
||||
|
||||
def test_list_certs_filters_by_customer_id(monkeypatch):
|
||||
from app.services import pl_quota_cert_service as svc
|
||||
|
||||
@@ -663,6 +840,107 @@ def test_whole_cover_skips_once_used_purchase_with_remaining(monkeypatch):
|
||||
assert manuals[0].permit_id == 'buy-fresh'
|
||||
|
||||
|
||||
def test_whole_cover_rearrange_reuses_once_cert_reserved_by_same_plan(monkeypatch):
|
||||
"""已安排计划再次选证:本单已预占的一次有效证不得误判为已使用,并归还本单预占余量。"""
|
||||
from app.services import pl_quota_customer_select as sel
|
||||
from app.schemas.pl.quota_usage import UsageSource
|
||||
from app.models.pl_quota_models import PlPurchaseCert, PlCertQtyLog, PlPlanCertUsage
|
||||
|
||||
source = UsageSource(
|
||||
source_stop_type='delivery',
|
||||
source_stop_id='s1',
|
||||
source_stop_product_id='sp1',
|
||||
plan_product_id='pp1',
|
||||
contract_id='c1',
|
||||
contract_product_id='cp1',
|
||||
product_id='prod1',
|
||||
quantity=Decimal('5'),
|
||||
unit='吨',
|
||||
fingerprint='y' * 64,
|
||||
snapshot={'customerId': 'cust1'},
|
||||
requires_transport=False,
|
||||
)
|
||||
# 与 PO20261116021 现场一致:证面一次有效、本单已预占满额
|
||||
own_cert = SimpleNamespace(
|
||||
id='buy-own', cert_no='G-OWN', customer_id='cust1', category_id='cat1', status='active',
|
||||
verified_by='u', verified_time=datetime.now(), valid_from=None, valid_to=date(2026, 12, 31),
|
||||
total_qty=Decimal('5'), used_qty=Decimal('0'), reserved_qty=Decimal('5'),
|
||||
quantity_unit='吨', opening_single_use_consumed=0, valid_use_text='一次有效',
|
||||
)
|
||||
own_usage = SimpleNamespace(
|
||||
plan_id='plan-self', cert_id='buy-own', usage_status='reserved',
|
||||
reserved_qty=Decimal('5'), confirmation_snapshot=None, del_flag=0,
|
||||
)
|
||||
|
||||
class PurchaseQuery:
|
||||
def filter(self, *a, **k):
|
||||
return self
|
||||
|
||||
def order_by(self, *a, **k):
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
return [own_cert]
|
||||
|
||||
class LogQuery:
|
||||
def filter_by(self, **k):
|
||||
return self
|
||||
|
||||
def first(self):
|
||||
return SimpleNamespace(id='opening')
|
||||
|
||||
class UsageQuery:
|
||||
def __init__(self):
|
||||
self._filters = {}
|
||||
|
||||
def filter_by(self, **k):
|
||||
self._filters.update(k)
|
||||
return self
|
||||
|
||||
def all(self):
|
||||
# is_single_use_consumed 查全部用量
|
||||
return [own_usage]
|
||||
|
||||
def first(self):
|
||||
# _plan_own_reserved 按 plan+cert 查本单预占
|
||||
if self._filters.get('plan_id') == 'plan-self' and self._filters.get('cert_id') == 'buy-own':
|
||||
return own_usage
|
||||
return None
|
||||
|
||||
db = MagicMock()
|
||||
|
||||
def q_side(model):
|
||||
if model is PlPurchaseCert:
|
||||
return PurchaseQuery()
|
||||
if model is PlCertQtyLog:
|
||||
return LogQuery()
|
||||
if model is PlPlanCertUsage:
|
||||
return UsageQuery()
|
||||
return MagicMock()
|
||||
|
||||
db.query.side_effect = q_side
|
||||
user = SimpleNamespace(tenant_no='t')
|
||||
monkeypatch.setattr(sel, 'category_ids_for_product', lambda db, tenant, pid: {'cat1'})
|
||||
# 使用真实占用判定,验证必须传 exclude_plan_id
|
||||
monkeypatch.setattr(sel, 'is_single_use_consumed', __import__(
|
||||
'app.services.pl_quota_cert_service', fromlist=['is_single_use_consumed']
|
||||
).is_single_use_consumed)
|
||||
|
||||
with pytest.raises(HTTPException) as blocked:
|
||||
sel.select_whole_cover_certs(
|
||||
db, user, [source], vehicle_no='皖A12345', on_date=date(2026, 11, 17),
|
||||
)
|
||||
assert '一次有效且已使用' in str(blocked.value.detail)
|
||||
|
||||
purchase_ids, transport_ids, manuals = sel.select_whole_cover_certs(
|
||||
db, user, [source], vehicle_no='皖A12345', on_date=date(2026, 11, 17),
|
||||
plan_id='plan-self',
|
||||
)
|
||||
assert purchase_ids == ['buy-own']
|
||||
assert transport_ids == []
|
||||
assert manuals[0].permit_quantity == Decimal('5')
|
||||
|
||||
|
||||
def test_list_customers_requires_customer_cert_counts(monkeypatch):
|
||||
from app.services import pl_quota_statistics as stats
|
||||
|
||||
@@ -1127,11 +1405,6 @@ def test_settle_cover_cert_ids_customer_rule_skips_contract_bindings(monkeypatch
|
||||
'app.services.pl_quota_planning.resolve_contract_bound_certs',
|
||||
fake_contract,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category',
|
||||
lambda p: True,
|
||||
)
|
||||
|
||||
purchase_ids, transport_ids = usage._settle_cover_cert_ids(
|
||||
MagicMock(), SimpleNamespace(tenant_no='t'), plan, [_remote_source()],
|
||||
)
|
||||
@@ -1145,10 +1418,6 @@ def test_archive_cover_block_message_customer_rule_wording(monkeypatch):
|
||||
|
||||
plan = SimpleNamespace(id='plan', cert_quota_rule_version='customer_category')
|
||||
r = SimpleNamespace(vehicle_no='皖A1', on_date=date(2026, 11, 15))
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_uses_customer_category',
|
||||
lambda p: True,
|
||||
)
|
||||
message = svc._archive_cover_block_message(
|
||||
MagicMock(), SimpleNamespace(tenant_no='t'), r, plan, {}, [],
|
||||
)
|
||||
@@ -1265,8 +1534,9 @@ def test_build_usage_request_passes_saved_manuals_to_customer_select(monkeypatch
|
||||
)
|
||||
captured = {}
|
||||
|
||||
def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=()):
|
||||
def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=(), plan_id=None):
|
||||
captured['manual_allocations'] = list(manual_allocations)
|
||||
captured['plan_id'] = plan_id
|
||||
return ['buy1'], [], list(manual_allocations)
|
||||
|
||||
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
|
||||
@@ -1293,5 +1563,217 @@ def test_build_usage_request_passes_saved_manuals_to_customer_select(monkeypatch
|
||||
)
|
||||
assert captured['manual_allocations']
|
||||
assert captured['manual_allocations'][0].permit_id == 'buy1'
|
||||
assert captured['plan_id'] == 'p1'
|
||||
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
|
||||
|
||||
|
||||
def _past_plan_usage_source():
|
||||
from app.schemas.pl.quota_usage import UsageSource
|
||||
|
||||
return 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('1'),
|
||||
unit='dun',
|
||||
fingerprint='f' * 64,
|
||||
snapshot={'customerId': 'cust1'},
|
||||
requires_transport=False,
|
||||
)
|
||||
|
||||
|
||||
def test_purchase_and_transport_certs_use_plan_date_even_when_it_is_past(monkeypatch):
|
||||
"""安排选证和归档扣证都按计划日期比对,计划日期早于今天时不改用当天。"""
|
||||
from app.services import pl_quota_planning as planning
|
||||
from app.schemas.pl.quota_planning import PlanQuotaOperation
|
||||
|
||||
plan = SimpleNamespace(
|
||||
id='p1',
|
||||
plan_date=date(2026, 9, 2),
|
||||
license_plate='客户自提',
|
||||
transport_status='pending',
|
||||
archive_status='unarchived',
|
||||
cert_quota_rule_version='customer_category',
|
||||
cert_configuration={'measurementVersion': 'per_stop_v2'},
|
||||
tenant_no='t',
|
||||
)
|
||||
captured = {}
|
||||
|
||||
def fake_select(db, user, sources, *, vehicle_no, on_date, manual_allocations=(), plan_id=None):
|
||||
captured['on_date'] = on_date
|
||||
return ['buy1'], [], []
|
||||
|
||||
monkeypatch.setattr(planning, '_plan', lambda *a, **k: plan)
|
||||
monkeypatch.setattr(planning, 'extract_sources', lambda *a, **k: ([_past_plan_usage_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))
|
||||
user = SimpleNamespace(id='u', tenant_no='t', dept_id='')
|
||||
|
||||
request, _ = planning.build_usage_request(
|
||||
MagicMock(), user, 'p1', PlanQuotaOperation(operationId='arrange'), 'reserve', check_conditions=False,
|
||||
)
|
||||
archived, _ = planning.build_usage_request(
|
||||
MagicMock(), user, 'p1', PlanQuotaOperation(operationId='archive'), 'settle', check_conditions=False,
|
||||
)
|
||||
|
||||
assert captured['on_date'] == date(2026, 9, 2)
|
||||
assert request.on_date == date(2026, 9, 2)
|
||||
assert archived.on_date == date(2026, 9, 2)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""运输归档角标:计划日期在 2026-09-01 及以前的不计数。"""
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.pl_models import PlPlan
|
||||
from app.services.pl_menu_badge_service import count_plan_archive_pending
|
||||
|
||||
|
||||
def test_archive_badge_skips_plans_on_or_before_2026_09_01():
|
||||
engine = create_engine("sqlite://")
|
||||
PlPlan.__table__.create(engine)
|
||||
db = Session(engine)
|
||||
|
||||
def add(plan_id, plan_date, **extra):
|
||||
fields = dict(
|
||||
id=plan_id,
|
||||
plan_no=plan_id,
|
||||
create_date=date(2026, 9, 2),
|
||||
plan_date=plan_date,
|
||||
belongs_company="shanxia",
|
||||
plan_type="direct",
|
||||
tenant_no="t",
|
||||
transport_status="arranged",
|
||||
archive_status="unarchived",
|
||||
follow_status="arranged",
|
||||
)
|
||||
fields.update(extra)
|
||||
db.add(PlPlan(**fields))
|
||||
|
||||
add("before", date(2026, 8, 31))
|
||||
add("on-cutoff", date(2026, 9, 1))
|
||||
add("after", date(2026, 9, 2))
|
||||
add("blank", None)
|
||||
add("archived", date(2026, 9, 2), archive_status="archived")
|
||||
add("pending", date(2026, 9, 2), transport_status="pending")
|
||||
add("cancelled", date(2026, 9, 2), follow_status="cancelled")
|
||||
db.commit()
|
||||
|
||||
user = SimpleNamespace()
|
||||
with patch(
|
||||
"app.services.pl_menu_badge_service.apply_pl_scope",
|
||||
side_effect=lambda query, *args, **kwargs: query,
|
||||
):
|
||||
total = count_plan_archive_pending(db, "t", user)
|
||||
|
||||
assert total == 1
|
||||
db.close()
|
||||
engine.dispose()
|
||||
@@ -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="请先选择归属公司")
|
||||
|
||||
@@ -254,6 +254,22 @@ def test_empty_transport_kind_settle_ignores_source_actuals():
|
||||
assert settle_allocations([], {'city': D(10)}) == ()
|
||||
|
||||
|
||||
def test_partial_transport_settle_ignores_sources_without_reservation():
|
||||
"""同市装货无运输预占、异地卸货有运输预占时,运输结转不得因多出来源实运量报缺实际量。"""
|
||||
from app.services.pl_quota_allocation import Allocation
|
||||
|
||||
transport_rows = [
|
||||
Allocation('transport', 'delivery:sp', 't1', D(33), D(33), 'dun', 'dun', 1),
|
||||
]
|
||||
actuals = {'load:sp': D(33), 'delivery:sp': D(33)}
|
||||
settled = settle_allocations(transport_rows, actuals)
|
||||
assert len(settled) == 1
|
||||
assert settled[0].actual_source_quantity == D(33)
|
||||
|
||||
with pytest.raises(AllocationInputError, match='实际量'):
|
||||
settle_allocations(transport_rows, {'load:sp': D(33)})
|
||||
|
||||
|
||||
@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
|
||||
|
||||
@@ -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']
|
||||
@@ -17,7 +17,7 @@ def case(request):
|
||||
db = Session(engine, autoflush=request.param)
|
||||
user = SimpleNamespace(id='u',dept_id='d',tenant_no='t',to_user_info=lambda: {'role':'super_admin','user_id':'u'})
|
||||
for pid in ['plan','other']:
|
||||
db.add(PlPlan(id=pid,plan_no=pid,create_date=date.today(),belongs_company='shanxia',plan_type='direct',tenant_no='t'))
|
||||
db.add(PlPlan(id=pid,plan_no=pid,create_date=date.today(),plan_date=date.today(),belongs_company='shanxia',plan_type='direct',tenant_no='t'))
|
||||
db.add(CrmContract(id='c',contract_no='c',contract_name='c',customer_id='customer',contract_type='sale',status='approved',tenant_no='t'))
|
||||
db.add(CrmContractProduct(id='cp',contract_id='c',product_id='product',product_name='酸',quantity=100,tenant_no='t'))
|
||||
for kind,model,pid in [('purchase',m.PlPurchaseCert,'p'),('transport',m.PlTransportCert,'t')]:
|
||||
@@ -330,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)]:
|
||||
@@ -582,6 +587,10 @@ def test_archive_cover_block_message_names_vehicle(monkeypatch):
|
||||
return SimpleNamespace(id='opening')
|
||||
|
||||
db = SimpleNamespace()
|
||||
monkeypatch.setattr(
|
||||
'app.services.pl_cert_quota_rule_config_service.plan_applies_customer_category_rule',
|
||||
lambda db, tenant_no, plan: False,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
svc,
|
||||
'_query',
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -10,31 +10,43 @@ from app.models.pl_models import PlCert, PlDocumentReminder, PlVehicle
|
||||
from app.services.pl_cert_service import scan_cert_expiry
|
||||
|
||||
|
||||
def _session():
|
||||
def _session(*, vehicles=None):
|
||||
engine = create_engine("sqlite://")
|
||||
PlCert.__table__.create(engine)
|
||||
PlDocumentReminder.__table__.create(engine)
|
||||
PlVehicle.__table__.create(engine)
|
||||
db = sessionmaker(bind=engine)()
|
||||
db.add(
|
||||
PlVehicle(
|
||||
rows = vehicles or [
|
||||
dict(
|
||||
id="veh-1",
|
||||
vehicle_type="self",
|
||||
vehicle_status="available",
|
||||
license_plate="皖LB1283",
|
||||
tenant_no="t1",
|
||||
create_dept_id="d1",
|
||||
)
|
||||
)
|
||||
]
|
||||
for row in rows:
|
||||
db.add(PlVehicle(**row))
|
||||
db.commit()
|
||||
return db
|
||||
|
||||
|
||||
def _add_cert(db, *, cert_id: str, expire_date: date, remind_days: int = 30, del_flag: int = 0, status: str = "valid"):
|
||||
def _add_cert(
|
||||
db,
|
||||
*,
|
||||
cert_id: str,
|
||||
expire_date: date,
|
||||
remind_days: int = 30,
|
||||
del_flag: int = 0,
|
||||
status: str = "valid",
|
||||
owner_id: str = "veh-1",
|
||||
):
|
||||
db.add(
|
||||
PlCert(
|
||||
id=cert_id,
|
||||
owner_type="vehicle",
|
||||
owner_id="veh-1",
|
||||
owner_id=owner_id,
|
||||
cert_name="罐检报告",
|
||||
cert_no="皖R8440挂",
|
||||
expire_date=expire_date,
|
||||
@@ -47,14 +59,23 @@ def _add_cert(db, *, cert_id: str, expire_date: date, remind_days: int = 30, del
|
||||
)
|
||||
|
||||
|
||||
def _add_pending_reminder(db, *, rem_id: str, cert_id: str, expire_date: date, days_remaining: int):
|
||||
def _add_pending_reminder(
|
||||
db,
|
||||
*,
|
||||
rem_id: str,
|
||||
cert_id: str,
|
||||
expire_date: date,
|
||||
days_remaining: int,
|
||||
owner_id: str = "veh-1",
|
||||
owner_label: str = "皖LB1283",
|
||||
):
|
||||
db.add(
|
||||
PlDocumentReminder(
|
||||
id=rem_id,
|
||||
cert_id=cert_id,
|
||||
owner_type="vehicle",
|
||||
owner_id="veh-1",
|
||||
owner_label="皖LB1283",
|
||||
owner_id=owner_id,
|
||||
owner_label=owner_label,
|
||||
document_type="罐检报告",
|
||||
document_no="皖R8440挂",
|
||||
expire_date=expire_date,
|
||||
@@ -161,3 +182,78 @@ def test_scan_resolves_pending_when_cert_soft_deleted():
|
||||
rem = db.query(PlDocumentReminder).filter_by(id="rem-gone").one()
|
||||
assert rem.status == "resolved"
|
||||
assert rem.remark and "失效" in rem.remark
|
||||
|
||||
|
||||
def test_scan_skips_scrapped_vehicle_and_resolves_pending():
|
||||
db = _session(
|
||||
vehicles=[
|
||||
dict(
|
||||
id="veh-scrap",
|
||||
vehicle_type="self",
|
||||
vehicle_status="scrapped",
|
||||
license_plate="皖H57837",
|
||||
trailer_no="皖HE155挂",
|
||||
tenant_no="t1",
|
||||
create_dept_id="d1",
|
||||
)
|
||||
]
|
||||
)
|
||||
today = date.today()
|
||||
expire = today + timedelta(days=5)
|
||||
_add_cert(db, cert_id="cert-scrap", expire_date=expire, owner_id="veh-scrap")
|
||||
_add_pending_reminder(
|
||||
db,
|
||||
rem_id="rem-scrap",
|
||||
cert_id="cert-scrap",
|
||||
expire_date=expire,
|
||||
days_remaining=5,
|
||||
owner_id="veh-scrap",
|
||||
owner_label="皖H57837",
|
||||
)
|
||||
db.commit()
|
||||
|
||||
created = scan_cert_expiry(db, tenant_no="t1")
|
||||
db.commit()
|
||||
|
||||
assert created == 0
|
||||
assert db.query(PlDocumentReminder).filter_by(cert_id="cert-scrap", status="pending").count() == 0
|
||||
rem = db.query(PlDocumentReminder).filter_by(id="rem-scrap").one()
|
||||
assert rem.status == "resolved"
|
||||
assert rem.remark and "报废" in rem.remark
|
||||
|
||||
|
||||
def test_scan_skips_carrier_vehicle_and_resolves_pending():
|
||||
db = _session(
|
||||
vehicles=[
|
||||
dict(
|
||||
id="veh-carrier",
|
||||
vehicle_type="carrier",
|
||||
vehicle_status="available",
|
||||
license_plate="皖HA1082",
|
||||
tenant_no="t1",
|
||||
create_dept_id="d1",
|
||||
)
|
||||
]
|
||||
)
|
||||
today = date.today()
|
||||
expire = today + timedelta(days=5)
|
||||
_add_cert(db, cert_id="cert-carrier", expire_date=expire, owner_id="veh-carrier")
|
||||
_add_pending_reminder(
|
||||
db,
|
||||
rem_id="rem-carrier",
|
||||
cert_id="cert-carrier",
|
||||
expire_date=expire,
|
||||
days_remaining=5,
|
||||
owner_id="veh-carrier",
|
||||
owner_label="皖HA1082",
|
||||
)
|
||||
db.commit()
|
||||
|
||||
created = scan_cert_expiry(db, tenant_no="t1")
|
||||
db.commit()
|
||||
|
||||
assert created == 0
|
||||
assert db.query(PlDocumentReminder).filter_by(cert_id="cert-carrier", status="pending").count() == 0
|
||||
rem = db.query(PlDocumentReminder).filter_by(id="rem-carrier").one()
|
||||
assert rem.status == "resolved"
|
||||
assert rem.remark and ("三方" in rem.remark or "承运" in rem.remark)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""近 N 次加油段平均百公里油耗(L/100km)算法。"""
|
||||
from decimal import Decimal
|
||||
|
||||
from app.services.pl_vehicle_fuel_service import avg_recent_trip_rates_l100, trip_rate_l100
|
||||
|
||||
|
||||
def test_trip_rate_uses_previous_liters_over_odometer_delta():
|
||||
# (本次期初 - 上次期初) = 200km,上次加油 50L → 25 L/100km
|
||||
assert trip_rate_l100(
|
||||
prev_liters=Decimal("50"),
|
||||
prev_odometer=Decimal("1000"),
|
||||
curr_odometer=Decimal("1200"),
|
||||
) == Decimal("25.00")
|
||||
|
||||
|
||||
def test_trip_rate_rejects_non_positive_delta_or_liters():
|
||||
assert trip_rate_l100(Decimal("50"), Decimal("1200"), Decimal("1000")) is None
|
||||
assert trip_rate_l100(Decimal("0"), Decimal("1000"), Decimal("1200")) is None
|
||||
assert trip_rate_l100(Decimal("-1"), Decimal("1000"), Decimal("1200")) is None
|
||||
assert trip_rate_l100(Decimal("50"), None, Decimal("1200")) is None
|
||||
assert trip_rate_l100(Decimal("50"), Decimal("1000"), None) is None
|
||||
|
||||
|
||||
def test_avg_recent_takes_last_n_valid_segments_only():
|
||||
# 段1: 1000→1100 / 40L = 40
|
||||
# 段2: 1100→1300 / 50L = 25
|
||||
# 段3: 无效(里程倒退)
|
||||
# 段4: 1200→1500 / 60L = 20
|
||||
rows = [
|
||||
(Decimal("1000"), Decimal("40")),
|
||||
(Decimal("1100"), Decimal("50")),
|
||||
(Decimal("1300"), Decimal("30")),
|
||||
(Decimal("1200"), Decimal("60")), # 倒退后的上一笔,下一段用其升数
|
||||
(Decimal("1500"), Decimal("10")),
|
||||
]
|
||||
assert avg_recent_trip_rates_l100(rows, 2) == Decimal("22.50") # (25+20)/2
|
||||
assert avg_recent_trip_rates_l100(rows, 10) == Decimal("28.33") # (40+25+20)/3
|
||||
assert avg_recent_trip_rates_l100(rows[:1], 10) is None
|
||||
assert avg_recent_trip_rates_l100([], 10) is None
|
||||
@@ -73,6 +73,10 @@ def test_summary_includes_html_metrics_and_previous_quarter_across_year(summary_
|
||||
assert item["quarterRateL100"] == Decimal("50")
|
||||
assert item["prevMonthRateL100"] == Decimal("50")
|
||||
assert item["prevQuarterRateL100"] == Decimal("21.05")
|
||||
# 五段有效:2、20、10、50、20 → 平均 20.40
|
||||
assert item["avgRateLast10L100"] == Decimal("20.40")
|
||||
assert item["avgRateLast20L100"] == Decimal("20.40")
|
||||
assert item["avgRateLast30L100"] == Decimal("20.40")
|
||||
|
||||
|
||||
def test_summary_follows_requested_month_instead_of_today(summary_db):
|
||||
@@ -105,6 +109,7 @@ def test_all_self_vehicles_visible_even_without_calculable_rate(summary_db):
|
||||
db = summary_db
|
||||
vehicle(db)
|
||||
vehicle(db, "无记录车辆", vehicle_status="maintaining")
|
||||
vehicle(db, "报废车辆", vehicle_status="scrapped")
|
||||
vehicle(db, "承运商车辆", vehicle_type="carrier")
|
||||
vehicle(db, "其他租户", tenant_no="t2")
|
||||
vehicle(db, "删除车辆", del_flag=1)
|
||||
@@ -113,6 +118,7 @@ def test_all_self_vehicles_visible_even_without_calculable_rate(summary_db):
|
||||
fuel(db, "2026-01-10", 120, 3400)
|
||||
items = {item.license_plate: item.model_dump(by_alias=True) for item in summary(db).items}
|
||||
assert set(items) == {"皖H57837", "无记录车辆"}
|
||||
assert "报废车辆" not in items
|
||||
assert items["皖H57837"]["liters"] == 120
|
||||
assert items["皖H57837"]["monthRateL100"] is None
|
||||
assert items["无记录车辆"]["liters"] == 0
|
||||
|
||||
@@ -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,18 @@
|
||||
-- 客户主数据增加「是否同市」,运输计划装/送段选客户时默认带入段次勾选。
|
||||
-- MySQL 5.7。可重复执行。存量客户默认 0。
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
SET @schema_name = DATABASE();
|
||||
|
||||
SET @col_exists = (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @schema_name AND TABLE_NAME = 'crm_customer' AND COLUMN_NAME = 'same_city'
|
||||
);
|
||||
SET @alter_sql = IF(
|
||||
@col_exists = 0,
|
||||
'ALTER TABLE crm_customer ADD COLUMN same_city tinyint NOT NULL DEFAULT 0 COMMENT ''是否同市 0-否 1-是;相对本公司业务所在市,运输计划段次默认带入'' AFTER address',
|
||||
'SELECT 1'
|
||||
);
|
||||
PREPARE alter_stmt FROM @alter_sql;
|
||||
EXECUTE alter_stmt;
|
||||
DEALLOCATE PREPARE alter_stmt;
|
||||
@@ -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,18 @@
|
||||
-- 客户主数据增加「是否同市」,运输计划装/送段选客户时默认带入段次勾选。
|
||||
-- MySQL 5.7。可重复执行。存量客户默认 0。
|
||||
SET NAMES utf8mb4;
|
||||
|
||||
SET @schema_name = DATABASE();
|
||||
|
||||
SET @col_exists = (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @schema_name AND TABLE_NAME = 'crm_customer' AND COLUMN_NAME = 'same_city'
|
||||
);
|
||||
SET @alter_sql = IF(
|
||||
@col_exists = 0,
|
||||
'ALTER TABLE crm_customer ADD COLUMN same_city tinyint NOT NULL DEFAULT 0 COMMENT ''是否同市 0-否 1-是;相对本公司业务所在市,运输计划段次默认带入'' AFTER address',
|
||||
'SELECT 1'
|
||||
);
|
||||
PREPARE alter_stmt FROM @alter_sql;
|
||||
EXECUTE alter_stmt;
|
||||
DEALLOCATE PREPARE alter_stmt;
|
||||
@@ -9792,6 +9792,7 @@ CREATE TABLE `crm_customer` (
|
||||
`city` varchar(50) DEFAULT NULL COMMENT '市',
|
||||
`district` varchar(50) DEFAULT NULL COMMENT '区',
|
||||
`address` varchar(255) DEFAULT NULL COMMENT '详细地址',
|
||||
`same_city` tinyint NOT NULL DEFAULT 0 COMMENT '是否同市 0-否 1-是;相对本公司业务所在市,运输计划段次默认带入',
|
||||
`status` varchar(20) DEFAULT 'normal' COMMENT '客户状态(字典 crm_customer_status: normal/pool/invalid)',
|
||||
`deal_status` varchar(20) DEFAULT 'not_deal' COMMENT '成交状态(字典 crm_deal_status: not_deal/dealed/lost)',
|
||||
`owner_user_id` varchar(64) DEFAULT NULL COMMENT '负责人ID',
|
||||
|
||||
@@ -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`
|
||||
- 不改选证算法本身
|
||||
@@ -0,0 +1,3 @@
|
||||
schema: spec-driven
|
||||
created: 2026-11-19
|
||||
issue: 48
|
||||
@@ -0,0 +1,14 @@
|
||||
## Context
|
||||
|
||||
汇总页与本人登记页共用 `FuelRegisterListPage`;仅 `mode=summary` 显示顶部卡片。原月度指标 API 仍保留字段,前端改为展示近 N 次平均。
|
||||
|
||||
## Decision
|
||||
|
||||
1. **计算放后端**:租户隔离、数据范围与作废过滤与列表一致;前端只展示。
|
||||
2. **复用 `plate-month-summary`**:增加 `avgRateLast10/20/30L100`,拉取该车全部正常未删登记再切片,避免新路由。
|
||||
3. **单位 L/100km**:与既有 `rate_l100` 一致;升数≤0 或里程差≤0 的段不计入平均。
|
||||
4. **UI**:去掉月份条;三项指标;点击车牌仍写列头车牌过滤。
|
||||
|
||||
## Risks
|
||||
|
||||
- 全量历史登记加载:自有车加油量通常可控;若日后变大再按车牌限窗。
|
||||
@@ -0,0 +1,26 @@
|
||||
## Why
|
||||
|
||||
加油登记汇总页顶部曾改为「待开发」。业务需要按车牌展示近 10/20/30 次平均油耗(L/100km),替代原按月加油量/里程/月季油耗卡片内容。
|
||||
|
||||
## What Changes
|
||||
|
||||
- 恢复汇总页顶部车牌卡片(复用既有卡片布局,去掉月份选择)
|
||||
- `plate-month-summary` 增加近 10/20/30 次平均百公里油耗字段
|
||||
- 单次油耗:`(上次加油升数 × 100) / (本次期初公里 − 上次期初公里)`
|
||||
- 近 N 次:同一车牌时间升序中,最近 N 个有效单次的算术平均;无效段跳过
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
- (无)
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `pl-vehicle-fuel-summary`: 汇总顶部统计口径改为近 N 次平均 L/100km
|
||||
|
||||
## Impact
|
||||
|
||||
- 后端 `pl_vehicle_fuel_service` / `vehicle_fuel` schema
|
||||
- Web `FuelPlateMonthCards`、`FuelRegisterListPage`、API 类型
|
||||
- 工单:https://gitea.aichengyan.com/cykj/shanxia2.0/issues/48
|
||||
@@ -0,0 +1,25 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: 近 N 次平均百公里油耗
|
||||
|
||||
系统 SHALL 在加油登记汇总顶部按自有车牌展示近 10、20、30 次平均油耗,单位为 L/100km。
|
||||
|
||||
#### Scenario: 单次油耗计算
|
||||
|
||||
- **WHEN** 同一车牌存在相邻两次正常未删除登记,且上次加油升数 > 0、本次期初公里 > 上次期初公里
|
||||
- **THEN** 该段油耗为 `上次加油升数 × 100 / (本次期初公里 − 上次期初公里)`,保留两位小数
|
||||
|
||||
#### Scenario: 近 N 次平均
|
||||
|
||||
- **WHEN** 某车牌存在至少一段有效单次油耗
|
||||
- **THEN** 近 N 次平均为时间升序下最近 min(N, 有效段数) 个单次油耗的算术平均;无效段(缺期初、升数≤0、里程未增加)不计入
|
||||
|
||||
#### Scenario: 数据不足
|
||||
|
||||
- **WHEN** 某车牌没有有效单次油耗段
|
||||
- **THEN** 对应近 N 次平均字段为 null,界面显示 —
|
||||
|
||||
#### Scenario: 点击筛选
|
||||
|
||||
- **WHEN** 用户点击某车牌卡片
|
||||
- **THEN** 下方列表按该车牌过滤;再次点击同一车牌取消过滤
|
||||
@@ -0,0 +1,15 @@
|
||||
## 1. 后端
|
||||
|
||||
- [x] 单次/近 N 次平均算法与单测
|
||||
- [x] schema 增加 avgRateLast10/20/30L100
|
||||
- [x] `list_plate_month_summary` 填充新字段;汇总回归断言
|
||||
|
||||
## 2. Web
|
||||
|
||||
- [x] 恢复汇总顶部卡片,展示近 10/20/30 次平均
|
||||
- [x] API 类型字段对齐
|
||||
|
||||
## 3. 验证
|
||||
|
||||
- [x] `pytest` 加油汇总相关:21 passed
|
||||
- [ ] 本机打开汇总页目视验收(需在任务 worktree 启前后端)
|
||||
@@ -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)'
|
||||
)
|
||||
})
|
||||
@@ -95,6 +95,8 @@ export interface CustomerForm {
|
||||
district?: string;
|
||||
/** 详细地址 */
|
||||
address?: string;
|
||||
/** 是否同市 0-否 1-是 */
|
||||
sameCity?: number;
|
||||
/** 负责人ID */
|
||||
ownerUserId?: number;
|
||||
/** 下次联系时间 */
|
||||
@@ -133,6 +135,8 @@ export interface CustomerVO {
|
||||
city?: string;
|
||||
district?: string;
|
||||
address?: string;
|
||||
/** 是否同市 0-否 1-是 */
|
||||
sameCity?: number;
|
||||
status: string;
|
||||
dealStatus: string;
|
||||
ownerUserId?: number;
|
||||
|
||||
@@ -2262,6 +2262,10 @@ export interface VehicleFuelPlateMonthItem {
|
||||
prevMonthRateL100?: number | string | null
|
||||
/** 近三个月百公里油耗 L/100km;里程不足时为 null */
|
||||
last3MonthsRateL100?: number | string | null
|
||||
/** 近 10/20/30 次有效加油段平均百公里油耗 L/100km */
|
||||
avgRateLast10L100?: number | string | null
|
||||
avgRateLast20L100?: number | string | null
|
||||
avgRateLast30L100?: number | string | null
|
||||
}
|
||||
|
||||
export interface VehicleFuelPlateMonthSummaryResponse {
|
||||
|
||||
@@ -245,7 +245,7 @@
|
||||
import { mobileStopIdentity } from '@/views/m/pl/plan/mobileStopIdentity'
|
||||
import MobilePlanDeliverySection from '@/views/m/pl/plan/MobilePlanDeliverySection.vue'
|
||||
import { Bottom, Delete, Plus, Search, Top } from '@element-plus/icons-vue'
|
||||
import { fetchCustomerOptions } from '@/api/crm/customer'
|
||||
import { fetchCustomerDetail, fetchCustomerOptions } from '@/api/crm/customer'
|
||||
import { customerStopPrefApi, type CustomerStopPref } from '@/api/pl/index'
|
||||
import PlAddressWithLibrary, {
|
||||
type PlAddressApplyPayload
|
||||
@@ -256,6 +256,7 @@
|
||||
import {
|
||||
canManualToggleStopDibang,
|
||||
createEmptyDeliveryForm,
|
||||
resolveCustomerSameCityFlag,
|
||||
resolveStopDibangDefaults,
|
||||
sumStopProductsPlanQty,
|
||||
type PlanDeliveryForm,
|
||||
@@ -331,6 +332,7 @@
|
||||
id: string
|
||||
customerName: string
|
||||
customerNo?: string
|
||||
sameCity?: number
|
||||
}
|
||||
|
||||
const activeIndex = ref(0)
|
||||
@@ -579,6 +581,7 @@
|
||||
products: [],
|
||||
generateDibang: 0,
|
||||
dibangDirection: 'none',
|
||||
sameCity: 0,
|
||||
address: '',
|
||||
lng: null,
|
||||
lat: null,
|
||||
@@ -604,15 +607,34 @@
|
||||
products: [],
|
||||
generateDibang: defaults.generateDibang,
|
||||
dibangDirection: defaults.dibangDirection,
|
||||
sameCity: resolveCustomerSameCityFlag(customer?.sameCity),
|
||||
address: '',
|
||||
lng: null,
|
||||
lat: null,
|
||||
contact: '',
|
||||
notes: ''
|
||||
})
|
||||
void applySameCityFromCustomer(index, String(customerId))
|
||||
void applyDeliveryStopPref(index, String(customerId))
|
||||
}
|
||||
|
||||
async function applySameCityFromCustomer(index: number, customerId: string) {
|
||||
const identity = props.mobileSheet ? mobileStopIdentity(props.modelValue[index]) : undefined
|
||||
try {
|
||||
const res = await fetchCustomerDetail({ id: customerId })
|
||||
const data = pickBxData<{ sameCity?: number }>(res)
|
||||
if (!data) return
|
||||
if (props.mobileSheet) {
|
||||
index = props.modelValue.findIndex((row) => mobileStopIdentity(row) === identity)
|
||||
}
|
||||
const current = props.modelValue[index]
|
||||
if (!current || String(current.customerId) !== String(customerId)) return
|
||||
patchDelivery(index, { sameCity: resolveCustomerSameCityFlag(data.sameCity) })
|
||||
} catch {
|
||||
// 静默:不阻断选客户
|
||||
}
|
||||
}
|
||||
|
||||
async function applyDeliveryStopPref(index: number, customerId: string) {
|
||||
const identity = props.mobileSheet ? mobileStopIdentity(props.modelValue[index]) : undefined
|
||||
try {
|
||||
|
||||
@@ -175,7 +175,7 @@
|
||||
<script setup lang="ts">
|
||||
import MobilePlanLoadSection from '@/views/m/pl/plan/MobilePlanLoadSection.vue'
|
||||
import { Plus, Search } from '@element-plus/icons-vue'
|
||||
import { fetchCustomerOptions } from '@/api/crm/customer'
|
||||
import { fetchCustomerDetail, fetchCustomerOptions } from '@/api/crm/customer'
|
||||
import { customerStopPrefApi, type CustomerStopPref } from '@/api/pl/index'
|
||||
import PlAddressWithLibrary, {
|
||||
type PlAddressApplyPayload
|
||||
@@ -189,6 +189,7 @@
|
||||
} from '@/utils/pl-plan-contract-product'
|
||||
import {
|
||||
canManualToggleStopDibang,
|
||||
resolveCustomerSameCityFlag,
|
||||
resolveStopDibangDefaults,
|
||||
type PlanLoadForm
|
||||
} from '@/utils/pl-plan-stop-form'
|
||||
@@ -232,6 +233,7 @@
|
||||
id: string
|
||||
customerName: string
|
||||
customerNo?: string
|
||||
sameCity?: number
|
||||
}
|
||||
|
||||
const customerOptions = ref<CustomerOptionRow[]>([])
|
||||
@@ -402,6 +404,7 @@
|
||||
products: [],
|
||||
generateDibang: 0,
|
||||
dibangDirection: 'none',
|
||||
sameCity: 0,
|
||||
address: '',
|
||||
lng: null,
|
||||
lat: null,
|
||||
@@ -427,15 +430,29 @@
|
||||
products: [],
|
||||
generateDibang: defaults.generateDibang,
|
||||
dibangDirection: defaults.dibangDirection,
|
||||
sameCity: resolveCustomerSameCityFlag(customer?.sameCity),
|
||||
address: '',
|
||||
lng: null,
|
||||
lat: null,
|
||||
contact: '',
|
||||
notes: ''
|
||||
})
|
||||
void applySameCityFromCustomer(String(customerId))
|
||||
void applyStopPrefFromCustomer(String(customerId))
|
||||
}
|
||||
|
||||
async function applySameCityFromCustomer(customerId: string) {
|
||||
try {
|
||||
const res = await fetchCustomerDetail({ id: customerId })
|
||||
const data = pickBxData<{ sameCity?: number }>(res)
|
||||
if (!data) return
|
||||
if (String(props.modelValue.customerId) !== String(customerId)) return
|
||||
patch({ sameCity: resolveCustomerSameCityFlag(data.sameCity) })
|
||||
} catch {
|
||||
// 静默:不阻断选客户
|
||||
}
|
||||
}
|
||||
|
||||
async function applyStopPrefFromCustomer(customerId: string) {
|
||||
try {
|
||||
const res = await customerStopPrefApi.get({ customerId, stopType: 'load' })
|
||||
|
||||
@@ -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;
|
||||
|
||||
+1
-7
@@ -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'),
|
||||
|
||||
+1
-1
@@ -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()
|
||||
)
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import {
|
||||
canManualToggleStopDibang,
|
||||
resolveCustomerSameCityFlag,
|
||||
resolveStopDibangDefaults,
|
||||
toxicStopCertBindingMessage
|
||||
} from './pl-plan-stop-form'
|
||||
@@ -24,6 +25,18 @@ describe('isPlDibangOptionalVehiclePlate', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveCustomerSameCityFlag', () => {
|
||||
it('normalizes customer master sameCity to 0/1', () => {
|
||||
assert.equal(resolveCustomerSameCityFlag(1), 1)
|
||||
assert.equal(resolveCustomerSameCityFlag(true), 1)
|
||||
assert.equal(resolveCustomerSameCityFlag('1' as unknown as number), 1)
|
||||
assert.equal(resolveCustomerSameCityFlag(0), 0)
|
||||
assert.equal(resolveCustomerSameCityFlag(false), 0)
|
||||
assert.equal(resolveCustomerSameCityFlag(null), 0)
|
||||
assert.equal(resolveCustomerSameCityFlag(undefined), 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('toxicStopCertBindingMessage', () => {
|
||||
it('same-city stop only requires the purchase certificate', () => {
|
||||
assert.equal(
|
||||
|
||||
@@ -468,6 +468,11 @@ export function resolveStopProductsForView(
|
||||
return enrichStopProductsDisplayFromPlan(rows, planProducts)
|
||||
}
|
||||
|
||||
/** 客户主数据 / options 的同市标记 → 段次 sameCity(0/1) */
|
||||
export function resolveCustomerSameCityFlag(value?: boolean | number | null): number {
|
||||
return value === true || Number(value) === 1 ? 1 : 0
|
||||
}
|
||||
|
||||
export function createEmptyLoadForm(): PlanLoadForm {
|
||||
return {
|
||||
customerId: '',
|
||||
|
||||
@@ -1768,6 +1768,13 @@ const detailBasicViewFields = computed<ViewField[]>(() => {
|
||||
label: '结算方式',
|
||||
value: c.settlementMethod ? dictStore.getLabel('crm_settlement_method', c.settlementMethod) : '—',
|
||||
danger: true
|
||||
},
|
||||
{
|
||||
label: '备注',
|
||||
value: c.remark || '—',
|
||||
long: true,
|
||||
span: 'full',
|
||||
fullSpan: true
|
||||
}
|
||||
];
|
||||
});
|
||||
|
||||
@@ -705,6 +705,17 @@
|
||||
:biz-type="CRM_UPLOAD_BIZ_TYPE.CONTRACT_ATTACHMENT"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="备注" prop="remark" class="form-col-span-2">
|
||||
<el-input
|
||||
v-model="form.remark"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
placeholder="请输入备注"
|
||||
maxlength="500"
|
||||
show-word-limit
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -198,6 +198,19 @@
|
||||
</el-col>
|
||||
</el-row>
|
||||
|
||||
<el-row :gutter="20">
|
||||
<el-col :span="24">
|
||||
<el-form-item label="备注">
|
||||
<el-input
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
:model-value="contract.remark || '-'"
|
||||
readonly
|
||||
/>
|
||||
</el-form-item>
|
||||
</el-col>
|
||||
</el-row>
|
||||
|
||||
<!-- 供方信息 -->
|
||||
<el-divider content-position="left">供方信息</el-divider>
|
||||
<el-row :gutter="20">
|
||||
|
||||
@@ -480,6 +480,17 @@
|
||||
:biz-type="CRM_UPLOAD_BIZ_TYPE.CONTRACT_ATTACHMENT"
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item label="备注" prop="remark" class="form-col-span-2">
|
||||
<el-input
|
||||
v-model="form.remark"
|
||||
type="textarea"
|
||||
:rows="2"
|
||||
placeholder="请输入备注"
|
||||
maxlength="500"
|
||||
show-word-limit
|
||||
/>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<!-- 底部操作按钮 -->
|
||||
|
||||
@@ -841,7 +841,11 @@ const viewSections = computed<ViewSection[]>(() => {
|
||||
tagField('所属行业', 'crm_customer_industry', c.industry),
|
||||
tagField('企业规模', 'crm_company_scale', c.scale),
|
||||
tagField('所在园区', 'crm_customer_park', c.parkArea),
|
||||
{ label: '地址', value: address, span: true }
|
||||
{ label: '地址', value: address, span: true },
|
||||
{
|
||||
label: '是否同市',
|
||||
value: Number(c.sameCity) === 1 ? '是(同市运输只需购买证)' : '否'
|
||||
}
|
||||
]
|
||||
|
||||
const bizFields: ViewField[] = [
|
||||
|
||||
@@ -132,6 +132,15 @@
|
||||
<el-form-item label="详细地址" class="form-field-span-2">
|
||||
<el-input v-model="form.address" placeholder="请输入详细地址" maxlength="255" />
|
||||
</el-form-item>
|
||||
<el-form-item class="form-field-span-2">
|
||||
<template #label>
|
||||
是否同市<span class="form-label-tip">同市运输只需购买证</span>
|
||||
</template>
|
||||
<el-switch
|
||||
:model-value="Number(form.sameCity) === 1"
|
||||
@update:model-value="(checked) => (form.sameCity = checked ? 1 : 0)"
|
||||
/>
|
||||
</el-form-item>
|
||||
</div>
|
||||
|
||||
<el-divider content-position="left">分配信息</el-divider>
|
||||
@@ -361,6 +370,7 @@ const form = ref<CustomerFormType>({
|
||||
city: undefined,
|
||||
district: undefined,
|
||||
address: undefined,
|
||||
sameCity: 0,
|
||||
ownerUserId: undefined,
|
||||
nextTime: undefined,
|
||||
clueId: undefined,
|
||||
@@ -601,6 +611,7 @@ const open = async (id?: number | string) => {
|
||||
const res = await fetchCustomerDetail({ id: String(id) })
|
||||
const data = unwrapApiData(res as Record<string, unknown> | { data?: Record<string, unknown> })
|
||||
Object.assign(form.value, data)
|
||||
form.value.sameCity = Number((data as any)?.sameCity) === 1 ? 1 : 0
|
||||
form.value.businessLicenseImages =
|
||||
(data as any)?.businessLicenseImages || (data as any)?.businessLicenseImg || undefined
|
||||
delete (form.value as Record<string, unknown>).businessLicenseImg
|
||||
@@ -626,6 +637,7 @@ function buildSubmitPayload() {
|
||||
// 显式传空串:后端按「重新生成」处理;有值则手改入库
|
||||
payload.namePinyinAbbr = (form.value.namePinyinAbbr || '').trim()
|
||||
payload.customerName = (form.value.customerName || '').trim()
|
||||
payload.sameCity = Number(form.value.sameCity) === 1 ? 1 : 0
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -699,6 +711,7 @@ const reset = () => {
|
||||
city: undefined,
|
||||
district: undefined,
|
||||
address: undefined,
|
||||
sameCity: 0,
|
||||
ownerUserId: undefined,
|
||||
nextTime: undefined,
|
||||
clueId: undefined,
|
||||
|
||||
@@ -75,6 +75,8 @@
|
||||
if (!settingStore.showCrumbs) {
|
||||
settingStore.setCrumbs()
|
||||
}
|
||||
// 纠正版本化 localStorage 中 showMenuButton:false,保证折叠钮始终可见
|
||||
settingStore.ensureMenuButtonVisible()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -120,6 +120,9 @@
|
||||
}}</span></span
|
||||
>
|
||||
</div>
|
||||
<div class="mp-wv-kv mp-contract-kv-wide"
|
||||
><span>备注</span><span class="mp-wv-pre">{{ contract.remark || '—' }}</span></div
|
||||
>
|
||||
<div v-if="contract.invalidReason" class="mp-wv-kv mp-contract-kv-wide">
|
||||
<span>作废原因</span><span class="mp-wv-pre">{{ contract.invalidReason }}</span>
|
||||
</div>
|
||||
|
||||
@@ -121,7 +121,8 @@ test('客户详情资料分组与 Web 查看弹窗一致', () => {
|
||||
['基本信息', '业务信息', '备注']
|
||||
)
|
||||
assert.equal(sections[0].model.addressLine, '安徽 安庆 大观 某路')
|
||||
assert.equal(sections[0].fields.at(-1)?.label, '地址')
|
||||
assert.equal(sections[0].fields.at(-1)?.label, '是否同市')
|
||||
assert.equal(sections[0].fields.at(-2)?.label, '地址')
|
||||
assert.deepEqual(
|
||||
sections[1].fields.map((field) => field.label),
|
||||
['客户级别', '客户来源', '客户状态', '成交状态', '成交金额', '负责人', '创建人', '创建时间', '跟进天数', '下次联系时间']
|
||||
|
||||
@@ -49,7 +49,8 @@ export const customerGroups: { title: string; fields: Field[] }[] = [
|
||||
{ key: 'province', label: '省份', required: true, max: 50 },
|
||||
{ key: 'city', label: '城市', required: true, max: 50 },
|
||||
{ key: 'district', label: '区县', required: true, max: 50 },
|
||||
{ key: 'address', label: '详细地址', max: 255 }
|
||||
{ key: 'address', label: '详细地址', max: 255 },
|
||||
{ key: 'sameCity', label: '是否同市', type: 'switch' }
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -166,7 +167,8 @@ export function customerDetailSections(customer: Row = {}): CustomerDetailSectio
|
||||
{ key: 'industry', label: '所属行业', dict: 'crm_customer_industry' },
|
||||
{ key: 'scale', label: '企业规模', dict: 'crm_company_scale' },
|
||||
{ key: 'parkArea', label: '所在园区', dict: 'crm_customer_park' },
|
||||
{ key: 'addressLine', label: '地址' }
|
||||
{ key: 'addressLine', label: '地址' },
|
||||
{ key: 'sameCity', label: '是否同市', type: 'switch' }
|
||||
]
|
||||
const bizFields: Field[] = [
|
||||
{ key: 'level', label: '客户级别', dict: 'crm_customer_level' },
|
||||
@@ -346,7 +348,7 @@ export function stageSuggestion(stage: string): Row {
|
||||
return pair ? { stagePercent: pair[0], winRate: pair[1] } : {}
|
||||
}
|
||||
export function customerForm(row: Row = {}): Row {
|
||||
return {
|
||||
const form = {
|
||||
...Object.fromEntries(customerGroups.flatMap((g) => g.fields).map((f) => [f.key, ''])),
|
||||
customerType: '未分类',
|
||||
level: 'normal',
|
||||
@@ -357,6 +359,8 @@ export function customerForm(row: Row = {}): Row {
|
||||
businessPermitImages: row.businessPermitImages ?? '',
|
||||
otherCertImages: row.otherCertImages ?? ''
|
||||
}
|
||||
form.sameCity = Number(row.sameCity ?? form.sameCity) === 1 ? 1 : 0
|
||||
return form
|
||||
}
|
||||
export function customerPayload(form: Row): Row {
|
||||
const keys = [
|
||||
@@ -371,6 +375,7 @@ export function customerPayload(form: Row): Row {
|
||||
data.namePinyinAbbr = String(data.namePinyinAbbr).trim()
|
||||
data.ownerUserId = String(data.ownerUserId || '')
|
||||
data.nextTime = apiTime(data.nextTime)
|
||||
data.sameCity = Number(data.sameCity) === 1 ? 1 : 0
|
||||
return data
|
||||
}
|
||||
export async function saveCustomerAndInvoice(
|
||||
|
||||
@@ -84,6 +84,7 @@
|
||||
<div class="manual-day-heading">
|
||||
<div class="manual-day-title">
|
||||
<strong>{{ Number(day.date.slice(-2)) }}</strong>
|
||||
<span class="manual-day-weekday">{{ weekdayLabel(day.date) }}</span>
|
||||
</div>
|
||||
<div v-if="day.inMonth" class="manual-day-actions">
|
||||
<el-button
|
||||
@@ -301,6 +302,11 @@
|
||||
} = useManualCalendar(undefined, props.calendarKind)
|
||||
const calendarEl = ref<HTMLElement>()
|
||||
const weekdays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
|
||||
function weekdayLabel(date: string) {
|
||||
return ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][
|
||||
new Date(`${date}T12:00:00`).getDay()
|
||||
]
|
||||
}
|
||||
const viewRow = ref<DispatchCalendarRecord>()
|
||||
const viewOpen = computed({
|
||||
get: () => !!viewRow.value,
|
||||
|
||||
@@ -321,14 +321,15 @@
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.day-weekday,
|
||||
.empty-day {
|
||||
.day-weekday {
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.empty-day {
|
||||
padding: 6px 0;
|
||||
font-size: 12px;
|
||||
color: #64748b;
|
||||
}
|
||||
|
||||
.day-content {
|
||||
|
||||
@@ -181,6 +181,16 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.manual-day-weekday {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.manual-day.outside .manual-day-weekday {
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
.manual-day-actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,89 +1,41 @@
|
||||
<!-- 自有车辆加油量、里程、月度/季度油耗,与 index(7).html 对齐 -->
|
||||
<!-- 自有车辆近 10/20/30 次平均油耗(L/100km) -->
|
||||
<template>
|
||||
<div class="fuel-plate-cards-wrap">
|
||||
<div class="fuel-month-bar">
|
||||
<span class="fuel-month-label">统计月份</span>
|
||||
<div class="fuel-month-control">
|
||||
<el-button
|
||||
class="fuel-month-step"
|
||||
:disabled="month <= '1900-01'"
|
||||
aria-label="上个月"
|
||||
@click="shiftMonth(-1)"
|
||||
>
|
||||
<el-icon><ArrowLeft /></el-icon>
|
||||
</el-button>
|
||||
<el-date-picker
|
||||
:model-value="month"
|
||||
type="month"
|
||||
value-format="YYYY-MM"
|
||||
format="YYYY年MM月"
|
||||
:clearable="false"
|
||||
aria-label="统计月份"
|
||||
@update:model-value="handleMonthChange"
|
||||
/>
|
||||
<el-button
|
||||
class="fuel-month-step"
|
||||
:disabled="month >= '2100-12'"
|
||||
aria-label="下个月"
|
||||
@click="shiftMonth(1)"
|
||||
>
|
||||
<el-icon><ArrowRight /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-loading="loading" class="fuel-plate-body">
|
||||
<div v-if="error" class="fuel-plate-error">{{ error }}</div>
|
||||
<div v-else-if="!loading && !items.length" class="fuel-plate-empty">暂无自有车辆</div>
|
||||
<div v-else class="fuel-plate-grid">
|
||||
<article
|
||||
v-for="item in cards"
|
||||
:key="`${item.licensePlate}-${item.trailerNo || ''}`"
|
||||
class="fuel-plate-card"
|
||||
:class="{ 'is-selected': selectedPlate === item.licensePlate }"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:aria-pressed="selectedPlate === item.licensePlate"
|
||||
:aria-label="`筛选 ${item.licensePlate} 的加油记录`"
|
||||
@click="handleClick(item.licensePlate)"
|
||||
@keydown.enter.prevent="handleClick(item.licensePlate)"
|
||||
@keydown.space.prevent="handleClick(item.licensePlate)"
|
||||
>
|
||||
<div class="plate" :title="formatPlVehiclePlateDisplay(item.licensePlate, item.trailerNo)">
|
||||
{{ formatPlVehiclePlateDisplay(item.licensePlate, item.trailerNo) }}
|
||||
</div>
|
||||
<div class="meta">
|
||||
<span>{{ item.defaultDriverName || '—' }}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<el-tag :type="vehicleStatus(item.vehicleStatus).type" size="small">
|
||||
{{ vehicleStatus(item.vehicleStatus).label }}
|
||||
</el-tag>
|
||||
</div>
|
||||
<div class="nums">
|
||||
<div v-for="metric in item.metrics" :key="metric.label">
|
||||
<b>{{ metric.value }}</b>
|
||||
<span class="label" :title="metric.description">{{ metric.label }}</span>
|
||||
<div v-if="metric.notices.length" class="metric-notices">
|
||||
<el-tag
|
||||
v-for="notice in metric.notices"
|
||||
:key="notice.text"
|
||||
:type="notice.type"
|
||||
size="small"
|
||||
>
|
||||
{{ notice.text }}
|
||||
</el-tag>
|
||||
</div>
|
||||
<em
|
||||
v-for="comparison in metric.comparisons"
|
||||
:key="comparison.text"
|
||||
class="mom"
|
||||
:class="comparison.trend"
|
||||
>
|
||||
{{ comparison.text }}
|
||||
</em>
|
||||
<div v-if="error" class="fuel-plate-error">{{ error }}</div>
|
||||
<div v-else-if="!loading && !items.length" class="fuel-plate-empty">暂无自有车辆</div>
|
||||
<div v-else class="fuel-plate-grid">
|
||||
<article
|
||||
v-for="item in cards"
|
||||
:key="`${item.licensePlate}-${item.trailerNo || ''}`"
|
||||
class="fuel-plate-card"
|
||||
:class="{ 'is-selected': selectedPlate === item.licensePlate }"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
:aria-pressed="selectedPlate === item.licensePlate"
|
||||
:aria-label="`筛选 ${item.licensePlate} 的加油记录`"
|
||||
@click="handleClick(item.licensePlate)"
|
||||
@keydown.enter.prevent="handleClick(item.licensePlate)"
|
||||
@keydown.space.prevent="handleClick(item.licensePlate)"
|
||||
>
|
||||
<div class="plate" :title="formatPlVehiclePlateDisplay(item.licensePlate, item.trailerNo)">
|
||||
{{ formatPlVehiclePlateDisplay(item.licensePlate, item.trailerNo) }}
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<span>{{ item.defaultDriverName || '—' }}</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<el-tag :type="vehicleStatus(item.vehicleStatus).type" size="small">
|
||||
{{ vehicleStatus(item.vehicleStatus).label }}
|
||||
</el-tag>
|
||||
</div>
|
||||
<div class="nums">
|
||||
<div v-for="metric in item.metrics" :key="metric.label">
|
||||
<b>{{ metric.value }}</b>
|
||||
<span class="label" :title="metric.description">{{ metric.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -91,20 +43,13 @@
|
||||
<script setup lang="ts">
|
||||
import type { VehicleFuelPlateMonthItem } from '@/api/pl'
|
||||
import { formatPlVehiclePlateDisplay } from '@/utils/pl-display'
|
||||
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
|
||||
import {
|
||||
fuelComparison,
|
||||
formatFuelRate,
|
||||
formatFuelLiters,
|
||||
fuelMileageNotice
|
||||
} from '@/utils/pl-fuel-summary'
|
||||
import { formatFuelRate } from '@/utils/pl-fuel-summary'
|
||||
|
||||
defineOptions({ name: 'FuelPlateMonthCards' })
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
items: VehicleFuelPlateMonthItem[]
|
||||
month: string
|
||||
loading?: boolean
|
||||
error?: string
|
||||
selectedPlate?: string
|
||||
@@ -114,65 +59,34 @@
|
||||
|
||||
const emit = defineEmits<{
|
||||
select: [plate: string | null]
|
||||
'update:month': [month: string]
|
||||
}>()
|
||||
|
||||
function handleMonthChange(value: string | null) {
|
||||
if (!value || value === props.month) return
|
||||
emit('update:month', value)
|
||||
}
|
||||
|
||||
function shiftMonth(offset: number) {
|
||||
const match = /^(\d{4})-(\d{2})$/.exec(props.month)
|
||||
if (!match) return
|
||||
const index = Number(match[1]) * 12 + (Number(match[2]) - 1) + offset
|
||||
const year = Math.floor(index / 12)
|
||||
const month = index - year * 12 + 1
|
||||
if (year < 1900 || year > 2100) return
|
||||
handleMonthChange(`${year}-${String(month).padStart(2, '0')}`)
|
||||
}
|
||||
const RATE_DESC =
|
||||
'单次:上次加油升数 × 100 ÷(本次期初公里 − 上次期初公里)。近 N 次为最近 N 个有效单次油耗的算术平均;缺里程、升数≤0 或里程未增加时跳过该段。'
|
||||
|
||||
const cards = computed(() =>
|
||||
props.items.map((item) => ({
|
||||
...item,
|
||||
metrics: [
|
||||
{
|
||||
value: formatFuelLiters(item.liters),
|
||||
label: '当月加油量/升',
|
||||
description: '按登记日期汇总当月正常、未删除且有权限查看的加油记录。',
|
||||
notices: [],
|
||||
comparisons: [fuelComparison(item.liters, item.prevLiters)]
|
||||
value: formatFuelRate(item.avgRateLast10L100),
|
||||
label: '近10次平均(L/100km)',
|
||||
description: RATE_DESC
|
||||
},
|
||||
{
|
||||
value: formatNumber(item.runKm, 0),
|
||||
label: '当月里程数',
|
||||
description: '下月首笔有效里程减本月首笔;下月无读数时,使用本月最新读数减首笔暂估。',
|
||||
notices: [fuelMileageNotice(item.monthMileageStatus)].filter((notice) => notice !== null),
|
||||
comparisons: [fuelComparison(item.runKm, item.prevRunKm)]
|
||||
value: formatFuelRate(item.avgRateLast20L100),
|
||||
label: '近20次平均(L/100km)',
|
||||
description: RATE_DESC
|
||||
},
|
||||
{
|
||||
value: `${formatFuelRate(item.monthRateL100)} / ${formatFuelRate(item.quarterRateL100)}`,
|
||||
label: '当月/季度油耗(L/100km)',
|
||||
description:
|
||||
'参考估算:本周期加油量 ÷ 本周期里程 × 100。季度里程为下季首笔减本季首笔;尚无下季读数时使用本季首末差暂估。加油量不等同于实际耗油量。',
|
||||
notices: [
|
||||
fuelMileageNotice(item.monthMileageStatus, '当月'),
|
||||
fuelMileageNotice(item.quarterMileageStatus, '季度')
|
||||
].filter((notice) => notice !== null),
|
||||
comparisons: [
|
||||
fuelComparison(item.monthRateL100, item.prevMonthRateL100),
|
||||
fuelComparison(item.quarterRateL100, item.prevQuarterRateL100, '环比上个季度')
|
||||
]
|
||||
value: formatFuelRate(item.avgRateLast30L100),
|
||||
label: '近30次平均(L/100km)',
|
||||
description: RATE_DESC
|
||||
}
|
||||
]
|
||||
}))
|
||||
)
|
||||
|
||||
function formatNumber(value: number | string | null | undefined, digits: number) {
|
||||
if (value == null || value === '' || !Number.isFinite(Number(value))) return '—'
|
||||
return Number(value).toLocaleString('zh-CN', { maximumFractionDigits: digits })
|
||||
}
|
||||
|
||||
function vehicleStatus(status: string): {
|
||||
label: string
|
||||
type: 'success' | 'warning' | 'danger' | 'info'
|
||||
@@ -195,37 +109,6 @@
|
||||
margin: 16px 16px 16px;
|
||||
}
|
||||
|
||||
.fuel-month-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.fuel-month-label {
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
color: var(--el-text-color-regular);
|
||||
}
|
||||
|
||||
.fuel-month-control {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.fuel-month-step {
|
||||
width: 36px;
|
||||
min-width: 36px;
|
||||
height: 36px;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.fuel-month-bar :deep(.el-date-editor) {
|
||||
width: 160px;
|
||||
}
|
||||
|
||||
.fuel-plate-body {
|
||||
min-height: 48px;
|
||||
}
|
||||
@@ -247,111 +130,88 @@
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.fuel-plate-card {
|
||||
min-width: 0;
|
||||
padding: 14px 16px;
|
||||
cursor: pointer;
|
||||
background: var(--el-bg-color, #fff);
|
||||
border: 1px solid var(--el-border-color, #e2e8f0);
|
||||
border-radius: 12px;
|
||||
box-shadow:
|
||||
0 1px 2px rgb(28 36 48 / 4%),
|
||||
0 8px 24px rgb(28 36 48 / 4%);
|
||||
|
||||
&.is-selected {
|
||||
background: var(--el-color-primary-light-9, #ecfdf5);
|
||||
border-color: var(--el-color-primary, #10b981);
|
||||
}
|
||||
|
||||
&:hover,
|
||||
&:focus-visible {
|
||||
border-color: var(--el-color-primary, #10b981);
|
||||
}
|
||||
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--el-color-primary, #10b981);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.plate {
|
||||
overflow: hidden;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
color: var(--el-text-color-primary);
|
||||
text-overflow: ellipsis;
|
||||
letter-spacing: 0.01em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin: 6px 0 10px;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
|
||||
.nums {
|
||||
display: grid;
|
||||
@media (max-width: 1400px) {
|
||||
.fuel-plate-grid {
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
|
||||
b {
|
||||
display: block;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.03em;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.label {
|
||||
display: block;
|
||||
font-size: 11px;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.mom {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
font-weight: 650;
|
||||
overflow-wrap: anywhere;
|
||||
|
||||
&.up {
|
||||
color: #c2410c;
|
||||
}
|
||||
|
||||
&.down {
|
||||
color: var(--primary-dark, #059669);
|
||||
}
|
||||
|
||||
&.flat {
|
||||
font-weight: 500;
|
||||
color: var(--el-text-color-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.metric-notices {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (width <= 1200px) {
|
||||
@media (max-width: 1100px) {
|
||||
.fuel-plate-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
}
|
||||
|
||||
@media (width <= 640px) {
|
||||
@media (max-width: 720px) {
|
||||
.fuel-plate-grid {
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
.fuel-plate-card {
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--mint-border, #e2e8f0);
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color 0.15s ease,
|
||||
box-shadow 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
border-color: #a7f3d0;
|
||||
}
|
||||
|
||||
&.is-selected {
|
||||
border-color: #10b981;
|
||||
box-shadow: 0 0 0 1px #10b981;
|
||||
}
|
||||
}
|
||||
|
||||
.plate {
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
line-height: 24px;
|
||||
color: var(--mint-text, #0f172a);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 4px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
color: var(--mint-text-muted, #64748b);
|
||||
}
|
||||
|
||||
.nums {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
margin-top: 10px;
|
||||
|
||||
> div {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
b {
|
||||
display: block;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
line-height: 26px;
|
||||
color: var(--mint-text, #0f172a);
|
||||
}
|
||||
|
||||
.label {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
font-size: 11px;
|
||||
line-height: 16px;
|
||||
color: var(--mint-text-muted, #64748b);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -2,7 +2,14 @@
|
||||
<template>
|
||||
<div class="page-container">
|
||||
<section class="panel">
|
||||
<div v-if="!isMineMode" class="fuel-summary-pending">待开发</div>
|
||||
<FuelPlateMonthCards
|
||||
v-if="!isMineMode"
|
||||
:items="plateSummaryItems"
|
||||
:loading="plateSummaryLoading"
|
||||
:error="plateSummaryError"
|
||||
:selected-plate="selectedPlateFromFilter"
|
||||
@select="handlePlateCardSelect"
|
||||
/>
|
||||
|
||||
<div class="list-toolbar">
|
||||
<div class="list-toolbar-row">
|
||||
@@ -527,8 +534,10 @@ import {
|
||||
vehicleFuelRegisterApi,
|
||||
type PlanDocumentAttachmentItem,
|
||||
type Vehicle,
|
||||
type VehicleFuelPlateMonthItem,
|
||||
type VehicleFuelRegister
|
||||
} from '@/api/pl'
|
||||
import FuelPlateMonthCards from '@/views/pl/vehicle-fuel-register/FuelPlateMonthCards.vue'
|
||||
import { pickBxData, pickBxPageResult } from '@/utils/http/bx'
|
||||
import { fetchAllPagedRecords } from '@/utils/fetch-paged-list'
|
||||
import { fetchUserOptions } from '@/api/admin'
|
||||
@@ -663,6 +672,42 @@ const vehicleOptions = ref<Vehicle[]>([])
|
||||
const vehicleTrailerLookup = computed(() => buildVehicleTrailerLookup(vehicleOptions.value))
|
||||
const quickSearchKeyword = ref('')
|
||||
|
||||
const plateSummaryItems = ref<VehicleFuelPlateMonthItem[]>([])
|
||||
const plateSummaryLoading = ref(false)
|
||||
const plateSummaryError = ref('')
|
||||
|
||||
const selectedPlateFromFilter = computed(() => {
|
||||
const s = filters.licensePlate as { text?: string } | undefined
|
||||
return String(s?.text || '').trim()
|
||||
})
|
||||
|
||||
async function fetchPlateSummary() {
|
||||
if (isMineMode.value) return
|
||||
plateSummaryLoading.value = true
|
||||
plateSummaryError.value = ''
|
||||
try {
|
||||
const res = await vehicleFuelRegisterApi.plateMonthSummary()
|
||||
const data = (res as { data?: { items?: VehicleFuelPlateMonthItem[] } }).data ?? res
|
||||
plateSummaryItems.value = (data as { items?: VehicleFuelPlateMonthItem[] }).items || []
|
||||
} catch (e: unknown) {
|
||||
plateSummaryItems.value = []
|
||||
plateSummaryError.value =
|
||||
e && typeof e === 'object' && 'message' in e
|
||||
? String((e as { message?: string }).message || '加载车辆汇总失败')
|
||||
: '加载车辆汇总失败'
|
||||
} finally {
|
||||
plateSummaryLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function handlePlateCardSelect(plate: string | null) {
|
||||
if (!plate) {
|
||||
setFilterState('licensePlate', null)
|
||||
return
|
||||
}
|
||||
setFilterState('licensePlate', { text: plate, selected: [] })
|
||||
}
|
||||
|
||||
const fuelTableWrapRef = ref<HTMLElement | null>(null)
|
||||
const fuelBelowRef = ref<HTMLElement | null>(null)
|
||||
const fuelTableRef = ref<any>(null)
|
||||
@@ -1089,6 +1134,7 @@ async function handleSubmit() {
|
||||
}
|
||||
dialogVisible.value = false
|
||||
await fetchData()
|
||||
await fetchPlateSummary()
|
||||
if (editing) await refreshViewIfOpen(formData.id)
|
||||
await promptCopyAfterSave(saved, editing)
|
||||
} finally {
|
||||
@@ -1112,6 +1158,7 @@ async function handleCancel(row: VehicleFuelRegister) {
|
||||
)
|
||||
ElMessage.success('已作废')
|
||||
fetchData()
|
||||
fetchPlateSummary()
|
||||
} finally {
|
||||
cancelLoadingMap[row.id] = false
|
||||
}
|
||||
@@ -1149,6 +1196,7 @@ async function handleRestoreMany(rows: VehicleFuelRegister[]) {
|
||||
ElMessage.warning(`成功恢复 ${successCount} 条,${failedCount} 条失败`)
|
||||
}
|
||||
await fetchData()
|
||||
await fetchPlateSummary()
|
||||
} finally {
|
||||
restoreLoading.value = false
|
||||
for (const row of targets) restoreLoadingMap[row.id] = false
|
||||
@@ -1158,19 +1206,6 @@ async function handleRestoreMany(rows: VehicleFuelRegister[]) {
|
||||
onMounted(async () => {
|
||||
await Promise.all([loadVehicleOptions(), loadUserOptions()])
|
||||
fetchData()
|
||||
fetchPlateSummary()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.fuel-summary-pending {
|
||||
margin: 16px 16px 0;
|
||||
padding: 28px 16px;
|
||||
border: 1px dashed var(--mint-border, #e2e8f0);
|
||||
border-radius: 10px;
|
||||
background: #fff;
|
||||
color: var(--mint-text-muted, #64748b);
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
@@ -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="客户品类额度生效时间">
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user