Compare commits

...
Author SHA1 Message Date
wuzilongandCursor 233c2c7faa fix(pl): 加油汇总卡片排除报废车辆。
验收反馈:顶部车牌卡片不再展示 vehicle_status=scrapped 的自有车。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:02:11 +08:00
wuzilong a4d747aece Merge branch 'codex/issue-48-fuel-avg-rate-42852718d883' into V3.0
加油汇总顶部近10/20/30次平均油耗(#48),待用户测试。
2026-11-19 18:00:10 +08:00
wuzilongandCursor c658f78329 feat(pl): 加油汇总顶部改为近10/20/30次平均油耗。
按相邻登记的升数与期初公里差计算 L/100km,并恢复汇总页车牌卡片展示。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 18:00:00 +08:00
wuzilongandCursor 90fc25f3fe fix(crm): 被引用合同明细的空品牌与不限品牌视为同一身份。
编辑页会把历史空品牌提交为 any,原先被当成更换产品身份,导致无法同时新增明细。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 20:33:48 +08:00
wuzilongandCursor d333e97bec fix(web): 派车日历在日期旁显示红色星期。
手工日历和普通日历都能直接看出当天是星期几。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:50:41 +08:00
wuzilongandCursor f9d031bacb fix(pl): 未打标计划按生效时间判断是否走客户品类额度规则。
安排前版本为空时不再一律当成旧规则,归档和实际调整与安排判定保持一致。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:50:41 +08:00
wuzilongandCursor 3f62af430f fix(pl): 同市与异地混跑时结转只要求本组来源有实运量。
运输证分组只有部分来源时,忽略实际量里多出来的来源,不再整单报缺实际量。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:50:41 +08:00
wuzilongandCursor 643221c61f feat(crm): 客户增加同市标记,装卸段选客户时默认带入。
同市客户在运输计划装货、卸货段自动带出同市,同市运输只要求购买证。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:50:41 +08:00
wuzilongandCursor a7b9386e79 fix(pl): 报废车和三方车不再生成证件到期提醒。
扫描时跳过这两类车辆,并关闭已经存在的待提醒。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:45:29 +08:00
wuzilongandCursor 9f8dd0590a fix(pl): 购买证和运输证有效期改为按计划日期比对。
安排与归档不再取今天和计划日期的较晚值,历史计划按自身计划日期判断证件是否有效。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:45:28 +08:00
wuzilongandCursor ff2f05c522 fix(pl): 运输归档角标不再统计 2026-09-01 及更早的计划。
菜单数字只计计划日期晚于 2026-09-01、已安排且未归档的计划。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-18 13:45:28 +08:00
wuzilongandCursor 7cef2d0f9d fix(crm): 合同详情基本信息展示合同备注。
表单已可录入备注,详情页此前未展示,补齐查看态。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 17:19:16 +08:00
wuzilongandCursor 9143eb776c fix(crm): 合同 PC 新增/编辑表单补全合同备注字段。
列表与移动端已有合同级备注,PC 弹窗此前仅有产品行备注,导致无法录入。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-17 17:12:27 +08:00
wuzilong 366c69b8a3 merge: issue #45 再安排排除本单一次有效占用。 2026-11-17 12:39:55 +08:00
wuzilong 97d6ec4b8a merge: issue #45 内部站点清合同并隐藏已释放关联证件。 2026-11-17 12:10:48 +08:00
48 changed files with 1038 additions and 337 deletions

No files matched your search

+8 -2
View File
@@ -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):
+8
View File
@@ -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)
+6
View File
@@ -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(
+10
View File
@@ -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")
+15
View File
@@ -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}
+42 -1
View File
@@ -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()
+3 -1
View File
@@ -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:
+6 -4
View File
@@ -121,17 +121,19 @@ def apply_plan_quota(db, user, plan, action, payload=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_applies_customer_category_rule,
plan_skips_archive_cert_quota,
plan_uses_customer_category,
)
tenant_no = getattr(user, 'tenant_no', None) or ''
customer_rule = plan_applies_customer_category_rule(db, tenant_no, plan)
# 新规则:齐备仅放行安排/改派预占;归档与实际调整必须真证结转。
# 切点前首次安排:归档/实调不校证件(无需齐备);齐备仍可跳过安排预占。
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, getattr(user, 'tenant_no', None))
and plan_skips_archive_cert_quota(plan, db, tenant_no)
)
if grandfather_archive_skip:
return {'operationId': ledger_id, 'usageIds': [], 'waived': True, 'skippedCertQuota': True}
@@ -140,7 +142,7 @@ def apply_plan_quota(db, user, plan, action, payload=None):
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 -2
View File
@@ -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 = [], []
@@ -140,7 +147,7 @@ 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,
@@ -187,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 '',
+10 -9
View File
@@ -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]
@@ -416,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
@@ -440,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} 有效次数待确认'
@@ -463,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)
@@ -650,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:
@@ -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)
+175 -21
View File
@@ -125,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)
@@ -346,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
@@ -510,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',
@@ -563,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):
@@ -584,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
@@ -1306,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()],
)
@@ -1324,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, {}, [],
)
@@ -1623,3 +1713,67 @@ def test_arranged_legacy_plan_build_usage_keeps_contract_bind(monkeypatch):
)
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()
+16
View File
@@ -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
+5 -1
View File
@@ -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')]:
@@ -587,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',
+105 -9
View File
@@ -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,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,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;
+1
View File
@@ -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,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 启前后端)
+4
View File
@@ -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;
+4
View File
@@ -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' })
@@ -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(
+5
View File
@@ -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">
+11
View File
@@ -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,
@@ -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),
['客户级别', '客户来源', '客户状态', '成交状态', '成交金额', '负责人', '创建人', '创建时间', '跟进天数', '下次联系时间']
+8 -3
View File
@@ -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;
@@ -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>