feat(admin): 完善自录统计卡片的明暗、移动布局及查询反馈
This commit is contained in:
@@ -0,0 +1,353 @@
|
||||
"""Self-input stats visual/data contract. Only loopback static assets reach the network."""
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from PIL import Image
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
from browser_contract import ACCOUNT, LOGIN, OFFICIAL, OVERVIEW, PASS, SELF, TOKEN, USER, Fixture, loopback, open_group
|
||||
|
||||
|
||||
SOURCE = "离线验收来源"
|
||||
PERMS = {"edit": "stats.personal_yeji/edit", "delete": "stats.personal_yeji/delete"}
|
||||
PAGE = "main .self-input-stats-page"
|
||||
EMPTY = re.compile(r"^(?:[-–—―]+|暂无(?:数据)?|未(?:提供|返回|统计)|无数据|N/A)$", re.I)
|
||||
|
||||
|
||||
class StatsFixture(Fixture):
|
||||
def __init__(self, host, role):
|
||||
super().__init__(host, False, False)
|
||||
if role in PERMS:
|
||||
self.reads[SELF]["permissions"].append(PERMS[role])
|
||||
self.reads["/stats.self_input/mediaSourceOptions"] = [{"name": SOURCE, "value": "native"}]
|
||||
self.reads["/dept.dept/all"] = [{"id": 42, "name": "离线部门", "children": []}]
|
||||
self.hold = {"today"} if role == "reader" else set()
|
||||
self.pending, self.queries = {}, []
|
||||
self.large_amount, self.fail_next = False, False
|
||||
|
||||
def route(self, route):
|
||||
req, url = route.request, urlsplit(route.request.url)
|
||||
if (f"{url.scheme}://{url.netloc}", url.path, req.method) != (OFFICIAL, "/adminapi" + OVERVIEW, "GET"):
|
||||
return super().route(route)
|
||||
if req.headers.get("token") != TOKEN:
|
||||
self.errors.append("overview without fixture session")
|
||||
return route.abort()
|
||||
self.calls.append(["GET", OVERVIEW])
|
||||
query = {k: v[0] for k, v in parse_qs(url.query).items()}
|
||||
self.queries.append(query)
|
||||
period = query.get("time_type")
|
||||
if period not in {"today", "week", "month", "yesterday", "custom"}:
|
||||
self.errors.append("unexpected stats range")
|
||||
return route.abort()
|
||||
if period in self.hold:
|
||||
self.hold.remove(period)
|
||||
self.pending[period] = (route, query)
|
||||
else:
|
||||
self.respond(route, query)
|
||||
|
||||
def release(self, period):
|
||||
self.respond(*self.pending.pop(period))
|
||||
|
||||
def respond(self, route, query):
|
||||
period = query["time_type"]
|
||||
if self.fail_next:
|
||||
self.fail_next = False
|
||||
return route.fulfill(headers={"Access-Control-Allow-Origin": self.base}, json={
|
||||
"code": 0, "show": 0, "msg": "离线查询失败", "data": None})
|
||||
n, date = {"today": (17, "2026-01-30"), "week": (31, "2026-01-24"),
|
||||
"month": (87, "2026-01-01"), "yesterday": (0, "2026-01-29"),
|
||||
"custom": (5, query.get("start_date", ""))}[period]
|
||||
fields = {"add_fans_count": n, "total_open_count": 0, "order_amount": 12.50,
|
||||
"paid_appointment_count": None, "total_open_rate": 0}
|
||||
if self.large_amount:
|
||||
fields["order_amount"] = 12345678901234.50
|
||||
finance = period == "week"
|
||||
if finance:
|
||||
fields.update(account_cost=321.25, roi=1.5, cash_cost=0)
|
||||
empty = period == "yesterday"
|
||||
label = "ROW-" + period + ("-filtered" if "media_source" in query else "")
|
||||
row = dict(fields, id=1, media_source=label, yeji_date=date, creator_name="离线录入员")
|
||||
data = {"lists": [] if empty else [row], "count": 0 if empty else 1,
|
||||
"extend": {"date_range": [date, date if empty else "2026-01-30"], "summary": fields,
|
||||
"can_view_finance": finance}}
|
||||
route.fulfill(headers={"Access-Control-Allow-Origin": self.base, "Cache-Control": "no-store"},
|
||||
json={"code": 1, "show": 0, "msg": "", "data": data})
|
||||
|
||||
|
||||
def check(report, name, result, actual):
|
||||
report["checks"][name] = {"ok": bool(result), "actual": actual}
|
||||
|
||||
|
||||
def shot(page, out, name):
|
||||
if out:
|
||||
page.screenshot(path=str(out / f"stats-{name}.png"), animations="disabled")
|
||||
|
||||
|
||||
def card(stats, label):
|
||||
return stats.locator(".stats-kpi-card").filter(has=stats.page.get_by_text(label, exact=True))
|
||||
|
||||
|
||||
def value(stats, label):
|
||||
return card(stats, label).locator(".stats-kpi-value").inner_text().strip()
|
||||
|
||||
|
||||
def row_visible(stats, period):
|
||||
expect(stats.locator(".el-table__body").get_by_text("ROW-" + period, exact=True)).to_be_visible()
|
||||
|
||||
|
||||
def row_value(stats, label):
|
||||
# Element's column id is shared by the header and the body, even with sticky columns.
|
||||
return stats.locator(".el-table").evaluate("""(table, name) => {
|
||||
const th = [...table.querySelectorAll('thead th')].find(h => h.innerText.trim() === name);
|
||||
const id = th && [...th.classList].find(n => /_column_/.test(n));
|
||||
return id ? table.querySelector('tbody td.' + id)?.textContent.trim() : null;
|
||||
}""", label)
|
||||
|
||||
|
||||
def luminance(rgb):
|
||||
channels = [v / 255 for v in rgb[:3]]
|
||||
linear = [v / 12.92 if v <= .04045 else ((v + .055) / 1.055) ** 2.4 for v in channels]
|
||||
return sum(v * w for v, w in zip(linear, (.2126, .7152, .0722)))
|
||||
|
||||
|
||||
def palette(stats):
|
||||
target = card(stats, "加粉数")
|
||||
# Sample actual rendered pixels, not just backgroundColor (the baseline paints a gradient).
|
||||
im = Image.open(io.BytesIO(target.screenshot(animations="disabled"))).convert("RGB")
|
||||
background = im.getpixel((im.width * 3 // 4, im.height // 2))
|
||||
colors = target.evaluate("""el => ['.stats-kpi-label','.stats-kpi-value'].map(s => {
|
||||
const c = document.createElement('canvas').getContext('2d');
|
||||
c.fillStyle = getComputedStyle(el.querySelector(s)).color; c.fillRect(0,0,1,1);
|
||||
return [...c.getImageData(0,0,1,1).data];
|
||||
})""")
|
||||
bg = luminance(background)
|
||||
ratios = []
|
||||
for rgb in colors:
|
||||
alpha = rgb[3] / 255
|
||||
fg = luminance([v * alpha + b * (1 - alpha) for v, b in zip(rgb, background)])
|
||||
ratios.append(round((max(fg, bg) + .05) / (min(fg, bg) + .05), 2))
|
||||
return {"rgb": background, "luminance": round(bg, 3), "label_contrast": ratios[0], "value_contrast": ratios[1]}
|
||||
|
||||
|
||||
def mobile_geometry(stats):
|
||||
return stats.evaluate("""root => {
|
||||
const visible = e => e.getClientRects().length && getComputedStyle(e).visibility !== 'hidden';
|
||||
const w = document.documentElement.clientWidth, rect = e => e.getBoundingClientRect();
|
||||
const elements = [...root.querySelectorAll('.stats-filter-form .el-radio-button,.stats-filter-form .el-select,' +
|
||||
'.stats-filter-form .el-button,.stats-kpi-card,.stats-detail-card,.el-pagination button,' +
|
||||
'.el-pagination .number,.el-pagination .el-select,.el-pagination .el-input')].filter(visible);
|
||||
const clipped = elements.filter(e => rect(e).x < -1 || rect(e).right > w + 1)
|
||||
.map(e => [e.textContent.trim().slice(0,20) || e.className, Math.round(rect(e).x),Math.round(rect(e).right)]);
|
||||
const table = root.querySelector('.el-table__body-wrapper .el-scrollbar__wrap');
|
||||
const cards = [...root.querySelectorAll('.stats-kpi-card')].filter(visible).map(rect);
|
||||
const firstRow = cards.filter(r => Math.abs(r.top - cards[0].top) < 2);
|
||||
const overlap = firstRow.some((r,i) => i && r.left < firstRow[i - 1].right - 1);
|
||||
return {width:w,clipped,rootWidth:root.clientWidth,contentWidth:root.scrollWidth,
|
||||
cardsPerRow:firstRow.length,cardWidth:Math.round(firstRow[0]?.width || 0),overlap,
|
||||
detailOffset:Math.round(rect(root.querySelector('.stats-detail-card')).top - rect(root).top),
|
||||
tableWidth:table.clientWidth,tableContentWidth:table.scrollWidth};
|
||||
}""")
|
||||
|
||||
|
||||
def wait_query(page, fixture, *, query_count=None, pending=None):
|
||||
# Pump browser events while a routed request is deliberately left unanswered.
|
||||
for _ in range(100):
|
||||
if ((query_count is None or len(fixture.queries) >= query_count) and
|
||||
(pending is None or pending in fixture.pending)):
|
||||
return
|
||||
page.wait_for_timeout(30)
|
||||
raise AssertionError(f"missing fixture query: pending={pending}, queries={fixture.queries}")
|
||||
|
||||
|
||||
def enter(page, fixture):
|
||||
page.goto(fixture.base + "/admin/login")
|
||||
page.get_by_placeholder("请输入账号").fill(ACCOUNT)
|
||||
page.get_by_placeholder("请输入密码").fill(PASS)
|
||||
page.get_by_role("button", name="登录", exact=True).click()
|
||||
expect(page.locator(".app-header").get_by_text(USER, exact=True)).to_be_visible(timeout=15000)
|
||||
expect(page.locator("html")).to_have_attribute("data-admin-ui", "v2")
|
||||
aside = page.locator(".app-aside .menu:visible")
|
||||
open_group(open_group(aside, "数据统计"), "自录数据统计").get_by_text("自录转化统计", exact=True).click()
|
||||
stats = page.locator(PAGE)
|
||||
expect(stats).to_be_visible()
|
||||
return stats
|
||||
|
||||
|
||||
def permission_checks(stats, role, report):
|
||||
table = stats.locator(".el-table")
|
||||
actions = {
|
||||
"column": table.locator("thead th").get_by_text("操作", exact=True).count(),
|
||||
"edit": table.get_by_role("button", name="编辑", exact=True).count(),
|
||||
"delete": table.get_by_role("button", name="删除", exact=True).count(),
|
||||
}
|
||||
wanted = {"column": int(role != "reader"), "edit": int(role == "edit"), "delete": int(role == "delete")}
|
||||
check(report, f"permissions_{role}", actions == wanted, actions)
|
||||
|
||||
|
||||
def reader_checks(page, stats, fx, report, out):
|
||||
wait_query(page, fx, pending="today")
|
||||
loading = card(stats, "加粉数")
|
||||
val = loading.locator(".stats-kpi-value").inner_text().strip() if loading.locator(".stats-kpi-value").count() else ""
|
||||
busy = stats.locator("[aria-busy=true]:visible,.el-skeleton:visible,.el-loading-mask:visible,[role=progressbar]:visible").count()
|
||||
loading_text = bool(re.search(r"加载|读取|统计中", stats.inner_text()))
|
||||
check(report, "initial_loading_not_zero", not re.search(r"\d", val) and (busy or loading_text),
|
||||
{"value": val, "busy": busy, "loading_text": loading_text})
|
||||
shot(page, out, "loading")
|
||||
fx.release("today")
|
||||
row_visible(stats, "today")
|
||||
permission_checks(stats, "reader", report)
|
||||
values = {k: value(stats, k) for k in ("加粉数", "总开口", "未回复", "付费挂号", "订单金额", "总开口率")}
|
||||
cells = {k: row_value(stats, k) for k in ("总开口", "未回复", "付费挂号")}
|
||||
check(report, "known_values_and_real_zero",
|
||||
[values[k] for k in ("加粉数", "总开口", "总开口率")] == ["17", "0", "0.00%"] and
|
||||
values["订单金额"] in {"¥12.50", "¥12.50"} and cells["总开口"] == "0", values)
|
||||
check(report, "missing_and_null_not_zero", all(EMPTY.fullmatch(v or "") for v in
|
||||
(values["未回复"], values["付费挂号"], cells["未回复"], cells["付费挂号"])), cells)
|
||||
light = palette(stats)
|
||||
check(report, "light_cards", light["luminance"] > .5 and min(light["label_contrast"], light["value_contrast"]) >= 4.5, light)
|
||||
shot(page, out, "light")
|
||||
page.emulate_media(color_scheme="dark")
|
||||
expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b"))
|
||||
dark = palette(stats)
|
||||
check(report, "dark_cards", dark["luminance"] < .2 and min(dark["label_contrast"], dark["value_contrast"]) >= 4.5, dark)
|
||||
shot(page, out, "dark")
|
||||
|
||||
# First a normal finance-enabled result. Then the same period is delayed and must lose to month.
|
||||
stats.get_by_text("最近7天", exact=True).click()
|
||||
row_visible(stats, "week")
|
||||
check(report, "finance_granted", card(stats, "账户消耗").count() == 1 and value(stats, "ROI") == "1.50"
|
||||
and row_value(stats, "账户消耗") in {"¥321.25", "¥321.25"},
|
||||
{"finance_cards": card(stats, "账户消耗").count(), "finance_column": row_value(stats, "账户消耗")})
|
||||
stats.get_by_text("今天", exact=True).click()
|
||||
row_visible(stats, "today")
|
||||
fx.hold.add("week")
|
||||
stats.get_by_text("最近7天", exact=True).click()
|
||||
wait_query(page, fx, pending="week")
|
||||
stats.get_by_text("最近30天", exact=True).click()
|
||||
row_visible(stats, "month")
|
||||
# Observe completion of the *older* reply before checking that it did not replace the latest results.
|
||||
with page.expect_event("requestfinished", predicate=lambda r:
|
||||
urlsplit(r.url).path == "/adminapi" + OVERVIEW and parse_qs(urlsplit(r.url).query).get("time_type") == ["week"]):
|
||||
fx.release("week")
|
||||
page.evaluate("() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
|
||||
race = {"value": value(stats, "加粉数"), "month": stats.get_by_text("ROW-month", exact=True).count(),
|
||||
"finance_card": card(stats, "账户消耗").count(), "finance_column": row_value(stats, "账户消耗"),
|
||||
"range": stats.locator(".stats-detail-card .el-card__header").inner_text()}
|
||||
check(report, "latest_response_wins", race["value"] == "87" and race["month"] == 1 and
|
||||
race["finance_card"] == 0 and race["finance_column"] is None and "2026-01-01" in race["range"], race)
|
||||
|
||||
filters = stats.locator(".stats-filter-form")
|
||||
filters.locator(".el-form-item").filter(has_text="部门").locator(".el-select__wrapper").click()
|
||||
page.get_by_role("treeitem").get_by_text("离线部门", exact=True).click()
|
||||
filters.locator(".el-form-item").filter(has_text="自媒体来源").locator(".el-select__wrapper").click()
|
||||
page.get_by_role("option", name=SOURCE, exact=True).click()
|
||||
row_visible(stats, "month-filtered")
|
||||
query = fx.queries[-1]
|
||||
check(report, "filters_keep_real_parameters", all(query.get(k) == v for k, v in
|
||||
{"time_type":"month", "dept_id":"42", "media_source":SOURCE, "page_no":"1", "page_size":"15"}.items()), query)
|
||||
filters.get_by_role("button", name="重置").click()
|
||||
row_visible(stats, "today")
|
||||
query = fx.queries[-1]
|
||||
check(report, "reset_actual_query", query.get("time_type") == "today" and not query.get("media_source")
|
||||
and not query.get("dept_id") and query.get("page_no") == "1", query)
|
||||
page.set_viewport_size({"width":390, "height":844})
|
||||
expect(page.locator(".app-aside .side")).to_be_hidden()
|
||||
dimensions = mobile_geometry(stats)
|
||||
check(report, "390px_two_column_cards", dimensions["cardsPerRow"] == 2, dimensions)
|
||||
check(report, "390px_controls_and_local_table_scroll", not dimensions["clipped"] and not dimensions["overlap"] and
|
||||
dimensions["contentWidth"] <= dimensions["rootWidth"] + 1 and
|
||||
dimensions["tableContentWidth"] > dimensions["tableWidth"] > 0, dimensions)
|
||||
shot(page, out, "mobile")
|
||||
fx.large_amount = True
|
||||
filters.get_by_role("button", name="查询", exact=True).click()
|
||||
amount = card(stats, "订单金额").locator(".stats-kpi-value")
|
||||
expect(amount).to_have_text(re.compile(r"12345678901234\.50"))
|
||||
box = amount.evaluate("""el => {
|
||||
const r = document.createRange(); r.selectNodeContents(el);
|
||||
const card = el.closest('.stats-kpi-card').getBoundingClientRect();
|
||||
const fragments = [...r.getClientRects()].filter(r => r.width && r.height);
|
||||
return {count: fragments.length, fits: fragments.every(r =>
|
||||
r.left >= card.left && r.right <= card.right && r.bottom <= card.bottom)};
|
||||
}""")
|
||||
check(report, "390px_full_amount_fits", box["count"] and box["fits"], box)
|
||||
fx.large_amount = False
|
||||
fx.fail_next = True
|
||||
filters.get_by_text("最近7天", exact=True).click()
|
||||
expect(stats.locator(".el-table__body tbody tr")).to_have_count(0)
|
||||
expect(stats.get_by_role("alert")).to_be_visible()
|
||||
expect(filters.get_by_role("button", name="查询", exact=True)).to_be_enabled()
|
||||
stale = value(stats, "加粉数")
|
||||
check(report, "failed_query_clears_stale_results", EMPTY.fullmatch(stale or ""), stale)
|
||||
filters.get_by_role("button", name="查询", exact=True).click()
|
||||
row_visible(stats, "week")
|
||||
check(report, "retry_succeeds", value(stats, "加粉数") == "31", value(stats, "加粉数"))
|
||||
filters.get_by_text("昨天", exact=True).click()
|
||||
expect(stats.locator(".el-table__body tbody tr")).to_have_count(0)
|
||||
expect(card(stats, "加粉数").locator(".stats-kpi-value")).to_have_text("0")
|
||||
empty_state = stats.locator(".el-table__empty-text").inner_text().strip()
|
||||
check(report, "empty_result_has_true_zero", bool(empty_state) and value(stats, "加粉数") == "0", empty_state)
|
||||
# An incomplete custom range must not replay the preceding period's totals.
|
||||
n = len(fx.queries)
|
||||
filters.get_by_text("自定义", exact=True).click()
|
||||
submit = filters.get_by_role("button", name="查询", exact=True)
|
||||
expect(submit).to_be_disabled()
|
||||
check(report, "incomplete_custom_range", n == len(fx.queries) and
|
||||
EMPTY.fullmatch(value(stats, "加粉数")), {"queries":len(fx.queries)-n})
|
||||
filters.get_by_placeholder("开始日期").click()
|
||||
dates = page.locator(".el-date-range-picker__content.is-left:visible td.available")
|
||||
dates.nth(2).click()
|
||||
dates.nth(4).click()
|
||||
row_visible(stats, "custom")
|
||||
query = fx.queries[-1]
|
||||
check(report, "custom_range_actual_dates", query.get("time_type") == "custom" and
|
||||
re.fullmatch(r"\d{4}-\d\d-\d\d", query.get("start_date","")) and
|
||||
query["start_date"] < query.get("end_date",""), query)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--host", type=loopback, default="127.0.0.1:5179")
|
||||
parser.add_argument("--chrome", required=True)
|
||||
parser.add_argument("--out", type=Path, help="Write JSON and local screenshots to this directory")
|
||||
args = parser.parse_args()
|
||||
if args.out:
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
report = {"checks": {}, "infrastructure_errors": []}
|
||||
with sync_playwright() as pw, pw.chromium.launch(executable_path=args.chrome, args=[
|
||||
"--disable-background-networking", "--disable-quic", "--no-proxy-server",
|
||||
"--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1"]) as browser:
|
||||
for role in ("reader", "edit", "delete"):
|
||||
fixture = StatsFixture(args.host, role)
|
||||
with browser.new_context(service_workers="block", viewport={"width":1440,"height":960}, color_scheme="light") as ctx:
|
||||
ctx.set_default_timeout(6000)
|
||||
ctx.route("**/*", fixture.route)
|
||||
ctx.route_web_socket("**/*", lambda ws: (fixture.errors.append("unexpected WebSocket"), ws.close()))
|
||||
page = ctx.new_page()
|
||||
page.on("pageerror", lambda err: fixture.errors.append(str(err)))
|
||||
try:
|
||||
stats = enter(page, fixture)
|
||||
if role == "reader":
|
||||
reader_checks(page, stats, fixture, report, args.out)
|
||||
else:
|
||||
row_visible(stats, "today")
|
||||
permission_checks(stats, role, report)
|
||||
assert [p for m, p in fixture.calls if m == "POST"] == [LOGIN]
|
||||
except Exception as e:
|
||||
report["infrastructure_errors"].append({"role": role, "error": str(e)})
|
||||
shot(page, args.out, f"failure-{role}")
|
||||
report["infrastructure_errors"].extend(fixture.errors)
|
||||
report["status"] = ("PASS" if report["checks"] and all(c["ok"] for c in report["checks"].values())
|
||||
and not report["infrastructure_errors"] else "FAIL")
|
||||
report["real_api_calls"] = 0
|
||||
if args.out:
|
||||
(args.out / "stats-visual.json").write_text(json.dumps(report, ensure_ascii=False, indent=2)+"\n")
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
return int(report["status"] != "PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -2,7 +2,7 @@
|
||||
<div class="self-input-stats-page">
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :inline="true" :model="queryParams" class="stats-filter-form">
|
||||
<el-form-item label="时间范围">
|
||||
<el-form-item label="时间范围" class="stats-field-wide">
|
||||
<el-radio-group v-model="queryParams.time_type" @change="handleTimeTypeChange">
|
||||
<el-radio-button label="today">今天</el-radio-button>
|
||||
<el-radio-button label="yesterday">昨天</el-radio-button>
|
||||
@@ -12,7 +12,7 @@
|
||||
</el-radio-group>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item v-if="queryParams.time_type === 'custom'">
|
||||
<el-form-item v-if="queryParams.time_type === 'custom'" class="stats-field-wide">
|
||||
<el-date-picker
|
||||
v-model="dateRange"
|
||||
type="daterange"
|
||||
@@ -54,18 +54,18 @@
|
||||
/>
|
||||
</el-form-item>
|
||||
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="pager.loading" @click="handleQuery">查询</el-button>
|
||||
<el-form-item class="stats-field-wide">
|
||||
<el-button type="primary" :loading="pager.loading" :disabled="awaitingDates" @click="handleQuery">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<div class="stats-kpi-grid">
|
||||
<div class="stats-kpi-grid" role="group" aria-label="指标概览" :aria-busy="pager.loading">
|
||||
<div v-for="card in visibleSummaryCards" :key="card.key" class="stats-kpi-card">
|
||||
<div class="stats-kpi-label">{{ card.label }}</div>
|
||||
<div class="stats-kpi-value" :class="{ 'is-money': card.type === 'money' }">
|
||||
{{ renderMetric(card.key, overview.summary, card.type) }}
|
||||
{{ pager.loading && !awaitingDates ? '…' : renderMetric(card.key, overview.summary, card.type) }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -97,11 +97,16 @@
|
||||
|
||||
<el-table
|
||||
v-loading="pager.loading"
|
||||
:data="pager.lists"
|
||||
:data="pager.loading || awaitingDates ? [] : pager.lists"
|
||||
:empty-text="awaitingDates ? '请选择完整的日期范围' : undefined"
|
||||
border
|
||||
size="large"
|
||||
max-height="640"
|
||||
>
|
||||
<template v-if="overviewFailed && !awaitingDates" #empty>
|
||||
<span role="alert">业绩明细加载失败。</span>
|
||||
<el-button type="primary" link @click="fetchOverview">重新加载</el-button>
|
||||
</template>
|
||||
<el-table-column label="日期" prop="yeji_date" min-width="110" fixed="left" />
|
||||
<el-table-column label="自媒体来源" prop="media_source" min-width="140" show-overflow-tooltip />
|
||||
<el-table-column label="录入人" prop="creator_name" min-width="100" />
|
||||
@@ -131,7 +136,7 @@
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="备注" prop="remark" min-width="160" show-overflow-tooltip />
|
||||
<el-table-column label="操作" width="140" fixed="right">
|
||||
<el-table-column v-if="canManageRows" label="操作" width="140" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-perms="['stats.personal_yeji/edit']"
|
||||
@@ -153,7 +158,7 @@
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="flex justify-end mt-4">
|
||||
<div v-if="!overviewFailed && !awaitingDates" class="flex justify-end mt-4">
|
||||
<pagination v-model="pager" @change="fetchOverview" />
|
||||
</div>
|
||||
</el-card>
|
||||
@@ -178,6 +183,7 @@ import { deptAll } from '@/api/org/department'
|
||||
import { usePaging } from '@/hooks/usePaging'
|
||||
import { getRoutePath } from '@/router'
|
||||
import feedback from '@/utils/feedback'
|
||||
import { hasPermission } from '@/utils/perm'
|
||||
|
||||
import MediaSourceSelect from './MediaSourceSelect.vue'
|
||||
import YejiEditPopup from './yeji-edit.vue'
|
||||
@@ -198,10 +204,16 @@ interface MetricColumn {
|
||||
minWidth?: number
|
||||
}
|
||||
|
||||
interface OverviewMeta {
|
||||
date_range?: string[]
|
||||
summary?: Record<string, unknown>
|
||||
can_view_finance?: boolean | number | string
|
||||
}
|
||||
|
||||
const router = useRouter()
|
||||
const yejiEditRef = shallowRef<InstanceType<typeof YejiEditPopup>>()
|
||||
const showYejiEdit = ref(false)
|
||||
const dateRange = ref<string[]>([])
|
||||
const dateRange = ref<string[] | null>([])
|
||||
const deptOptions = ref<any[]>([])
|
||||
const {
|
||||
mediaSourceOptions,
|
||||
@@ -216,14 +228,10 @@ const deptTreeProps = {
|
||||
children: 'children',
|
||||
}
|
||||
|
||||
const overview = reactive<Record<string, any>>({
|
||||
date_range: [],
|
||||
summary: {},
|
||||
can_view_finance: false,
|
||||
})
|
||||
|
||||
const FINANCE_KEYS = new Set(['account_cost', 'cash_cost', 'roi'])
|
||||
const canViewFinance = computed(() => Boolean(overview.can_view_finance))
|
||||
const canManageRows = computed(() =>
|
||||
hasPermission(['stats.personal_yeji/edit']) || hasPermission(['stats.personal_yeji/delete'])
|
||||
)
|
||||
|
||||
const queryParams = reactive({
|
||||
media_source: '',
|
||||
@@ -234,6 +242,8 @@ const queryParams = reactive({
|
||||
})
|
||||
|
||||
const accountCostEntryPath = computed(() => getRoutePath('stats.personal_account_cost/lists') || '')
|
||||
const awaitingDates = computed(() => queryParams.time_type === 'custom' && dateRange.value?.length !== 2)
|
||||
const overviewFailed = ref(false)
|
||||
|
||||
const goAccountCostEntry = () => {
|
||||
if (accountCostEntryPath.value) {
|
||||
@@ -241,14 +251,12 @@ const goAccountCostEntry = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const fetchOverviewList = async (params: Record<string, any>) => {
|
||||
if (queryParams.time_type === 'custom') {
|
||||
params.start_date = dateRange.value[0] || ''
|
||||
params.end_date = dateRange.value[1] || ''
|
||||
const fetchOverviewList = (params: Record<string, any>) => {
|
||||
if (params.time_type === 'custom') {
|
||||
params.start_date = dateRange.value?.[0] || ''
|
||||
params.end_date = dateRange.value?.[1] || ''
|
||||
}
|
||||
const res = await getSelfInputOverview(params)
|
||||
Object.assign(overview, res?.extend || {})
|
||||
return res
|
||||
return getSelfInputOverview(params)
|
||||
}
|
||||
|
||||
const loadDeptOptions = async () => {
|
||||
@@ -282,6 +290,13 @@ const { pager, getLists } = usePaging({
|
||||
fetchFun: fetchOverviewList,
|
||||
params: queryParams,
|
||||
firstLoading: true,
|
||||
latestOnly: true,
|
||||
})
|
||||
// usePaging commits the rows, count and extend of the latest request together.
|
||||
const overview = computed<OverviewMeta>(() => pager.loading || awaitingDates.value ? {} : pager.extend || {})
|
||||
const canViewFinance = computed(() => {
|
||||
const allowed = overview.value.can_view_finance
|
||||
return allowed === true || allowed === 1 || allowed === '1'
|
||||
})
|
||||
|
||||
const summaryCards: MetricCard[] = [
|
||||
@@ -341,14 +356,25 @@ const visibleTableColumns = computed(() =>
|
||||
)
|
||||
|
||||
const dateRangeText = computed(() => {
|
||||
if (!overview.date_range?.length) return '未选择'
|
||||
return `${overview.date_range[0]} 至 ${overview.date_range[1]}`
|
||||
if (awaitingDates.value) return '请选择完整的日期范围'
|
||||
if (pager.loading) return '正在加载…'
|
||||
if (overviewFailed.value) return '统计数据未加载'
|
||||
const range = overview.value.date_range
|
||||
return Array.isArray(range) && range.length === 2 ? `${range[0]} 至 ${range[1]}` : '日期未提供'
|
||||
})
|
||||
|
||||
const fetchOverview = async () => {
|
||||
if (awaitingDates.value) return
|
||||
overviewFailed.value = false
|
||||
try {
|
||||
await getLists()
|
||||
} catch (error: any) {
|
||||
// latestOnly ignores superseded errors; a failed current query must not
|
||||
// leave the previous filter's rows, metrics or finance access on screen.
|
||||
overviewFailed.value = true
|
||||
pager.extend = {}
|
||||
pager.lists = []
|
||||
pager.count = 0
|
||||
console.error('获取自录转化统计失败:', error)
|
||||
ElMessage.error(error?.msg || '获取统计数据失败')
|
||||
}
|
||||
@@ -363,7 +389,7 @@ const handleTimeTypeChange = () => {
|
||||
}
|
||||
|
||||
const handleCustomDateChange = () => {
|
||||
if (dateRange.value.length === 2) {
|
||||
if (dateRange.value?.length === 2) {
|
||||
pager.page = 1
|
||||
fetchOverview()
|
||||
}
|
||||
@@ -384,12 +410,15 @@ const handleReset = () => {
|
||||
fetchOverview()
|
||||
}
|
||||
|
||||
const renderMetric = (key: string, source: Record<string, any>, type = 'count') => {
|
||||
const value = source?.[key] ?? 0
|
||||
if (type === 'money') return `¥${Number(value || 0).toFixed(2)}`
|
||||
if (type === 'percent') return `${Number(value || 0).toFixed(2)}%`
|
||||
if (type === 'ratio') return Number(value || 0).toFixed(2)
|
||||
return String(value ?? 0)
|
||||
const renderMetric = (key: string, source?: Record<string, unknown>, type: MetricType = 'count') => {
|
||||
const value = source?.[key]
|
||||
if (typeof value !== 'number' && (typeof value !== 'string' || !value.trim())) return '—'
|
||||
const numeric = Number(value)
|
||||
if (!Number.isFinite(numeric)) return '—'
|
||||
if (type === 'money') return `¥${numeric.toFixed(2)}`
|
||||
if (type === 'percent') return `${numeric.toFixed(2)}%`
|
||||
if (type === 'ratio') return numeric.toFixed(2)
|
||||
return String(value)
|
||||
}
|
||||
|
||||
const handleAddYeji = async () => {
|
||||
@@ -500,4 +529,64 @@ onMounted(async () => {
|
||||
.stats-detail-card :deep(.el-card__body) {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
// Art's border-mode cards use a plain surface, a thin outline and no shadow.
|
||||
// The surrounding native layout already provides the page gutter.
|
||||
:root[data-admin-ui='v2'] .self-input-stats-page {
|
||||
padding: 0;
|
||||
|
||||
.stats-filter-form {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-end;
|
||||
gap: 10px 16px;
|
||||
:deep(.el-form-item) { max-width: 100%; margin: 0; }
|
||||
}
|
||||
|
||||
.stats-kpi-grid {
|
||||
grid-template-columns: repeat(auto-fill, minmax(min(100%, 160px), 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.stats-kpi-card {
|
||||
min-width: 0;
|
||||
padding: 14px 16px;
|
||||
border: 1px solid var(--zyt-card-border);
|
||||
border-radius: var(--zyt-radius);
|
||||
background: var(--zyt-surface);
|
||||
box-shadow: var(--zyt-shadow);
|
||||
}
|
||||
.stats-kpi-label, .card-hint { color: var(--zyt-text); }
|
||||
.stats-kpi-value, .card-title { color: var(--zyt-ink); }
|
||||
.stats-kpi-value {
|
||||
margin-top: 8px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dept-cell { border-color: var(--zyt-primary); }
|
||||
.card-header-main { flex-wrap: wrap; }
|
||||
|
||||
@media (max-width: 640px) {
|
||||
:deep(.el-card__body), :deep(.el-card__header) { padding-inline: 12px; }
|
||||
.stats-filter-form {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
.stats-field-wide { grid-column: 1 / -1; }
|
||||
:deep(.el-form-item) { flex-direction: column; align-items: stretch; min-width: 0; }
|
||||
:deep(.el-form-item__label) { justify-content: flex-start; line-height: 22px; height: auto; }
|
||||
:deep(.el-form-item__content) { min-width: 0; }
|
||||
:deep(.el-select), :deep(.el-date-editor) { max-width: 100%; }
|
||||
:deep(.el-radio-group) { max-width: 100%; row-gap: 4px; }
|
||||
:deep(.el-radio-button__inner) { padding-inline: 8px; }
|
||||
}
|
||||
.stats-kpi-grid {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
.stats-kpi-card { padding: 12px; }
|
||||
.stats-kpi-value { font-size: 23px; }
|
||||
.stats-kpi-value.is-money { font-size: 20px; }
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user