feat(admin): 改善工作台和账户消耗的等待、异常与移动体验
This commit is contained in:
@@ -0,0 +1,306 @@
|
||||
"""Offline black-box checks for the native account-cost form. No business writes leave the fixture."""
|
||||
import argparse
|
||||
import json
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
from browser_contract import ACCOUNT, COST, LOGIN, OFFICIAL, PASS, SELF, TOKEN, USER, Fixture, desktop_entry, loopback
|
||||
|
||||
PREFIX = "stats.personal_account_cost/"
|
||||
SOURCE = "线下渠道"
|
||||
PAGE = ".personal-account-cost-page"
|
||||
|
||||
|
||||
class CostFixture(Fixture):
|
||||
def __init__(self, host, role):
|
||||
super().__init__(host, False, False)
|
||||
perms = self.reads[SELF]["permissions"]
|
||||
perms.remove(PREFIX + "add")
|
||||
perms.extend(PREFIX + key for key in {"reader": [], "edit": ["edit"], "delete": ["delete"],
|
||||
"operator": ["add", "edit", "delete"]}[role])
|
||||
self.reads["/dept.dept/all"] = [{"id": 42, "name": "验收部门", "children": []}]
|
||||
self.reads["/stats.self_input/mediaSourceOptions"] = [{"name": SOURCE}]
|
||||
self.pending = []
|
||||
self.queries = []
|
||||
|
||||
def route(self, route):
|
||||
req, url = route.request, urlsplit(route.request.url)
|
||||
if (f"{url.scheme}://{url.netloc}", url.path, req.method) != (OFFICIAL, "/adminapi" + COST, "GET"):
|
||||
return super().route(route)
|
||||
if req.headers.get("token") != TOKEN:
|
||||
self.errors.append("missing fixture session")
|
||||
return route.abort()
|
||||
self.calls.append(["GET", COST])
|
||||
self.pending.append(route)
|
||||
self.queries.append({k: v[0] for k, v in parse_qs(url.query).items()})
|
||||
|
||||
def await_request(self, page, index):
|
||||
for _ in range(150):
|
||||
if len(self.queries) > index:
|
||||
return self.queries[index]
|
||||
page.wait_for_timeout(30)
|
||||
raise AssertionError(f"missing cost query #{index + 1}: {self.queries}")
|
||||
|
||||
def release(self, page, index, *, amount="128.50", days=1, tag="首条记录", count=1, fail=False):
|
||||
params = self.await_request(page, index)
|
||||
route = self.pending[index]
|
||||
self.pending[index] = None
|
||||
row = {"id": 11, "cost_date": params["start_date"], "amount": amount, "media_source": SOURCE,
|
||||
"remark": tag, "creator_name": "验收录入员", "dept_name": "验收部门"}
|
||||
with page.expect_event("requestfinished", predicate=lambda req: req.url == route.request.url):
|
||||
route.fulfill(headers={"Access-Control-Allow-Origin": self.base, "Cache-Control": "no-store"},
|
||||
json={"code": 0 if fail else 1, "msg": "离线失败" if fail else "", "show": 0,
|
||||
"data": None if fail else {"lists": [row] if count else [], "count": count,
|
||||
"extend": {"days_count": days, "total_amount": amount}}})
|
||||
page.evaluate("() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
|
||||
|
||||
|
||||
def permissions(page, ui, role):
|
||||
wanted = {"reader": set(), "edit": {"编辑"}, "delete": {"删除"}, "operator": {"新增", "编辑", "删除"}}[role]
|
||||
for label in ("新增", "编辑", "删除"):
|
||||
expect(ui.get_by_role("button", name=label, exact=True)).to_have_count(int(label in wanted))
|
||||
expect(ui.get_by_role("columnheader", name="操作", exact=True)).to_have_count(int(bool(wanted & {"编辑", "删除"})))
|
||||
if role == "operator":
|
||||
for label, title in (("新增", "新增账户消耗"), ("编辑", "编辑账户消耗"), ("删除", "确定删除该账户消耗记录?")):
|
||||
ui.get_by_role("button", name=label, exact=True).click()
|
||||
dialog = page.get_by_role("dialog")
|
||||
expect(dialog).to_contain_text(title)
|
||||
if label == "编辑":
|
||||
expect(dialog.get_by_placeholder("选填")).to_have_value("首条记录")
|
||||
dialog.get_by_placeholder("选填").fill("不保存此次修改")
|
||||
dialog.get_by_role("button", name="取消", exact=True).click()
|
||||
expect(dialog).not_to_be_visible()
|
||||
|
||||
|
||||
def geometry(ui):
|
||||
return ui.evaluate("""root => {
|
||||
const w = document.documentElement.clientWidth;
|
||||
const shown = [...root.querySelectorAll('.el-radio-button,.el-date-editor,.stats-filter-form .el-select,' +
|
||||
'.cost-remark-filter .el-input, .el-button, .el-pagination .number')].filter(e => e.getClientRects().length);
|
||||
const clipped = shown.filter(e => {
|
||||
const r=e.getBoundingClientRect(); return r.left < -.5 || r.right > w+.5 || r.width < 8;
|
||||
}).map(e => e.className);
|
||||
const label = root.querySelector('.cost-remark-filter input'), table=root.querySelector('.el-table__body-wrapper .el-scrollbar__wrap');
|
||||
const main=root.closest('.el-scrollbar__wrap');
|
||||
return { width:w, root:root.scrollWidth, rootBox:root.clientWidth, doc:document.documentElement.scrollWidth,
|
||||
main:main.scrollWidth, mainBox:main.clientWidth, clipped, keyword:label.getBoundingClientRect().width,
|
||||
table:table.clientWidth, content:table.scrollWidth };
|
||||
}""")
|
||||
|
||||
|
||||
def shot(page, out, name):
|
||||
if out:
|
||||
page.screenshot(path=str(out / f"cost-{name}.png"), animations="disabled")
|
||||
|
||||
|
||||
def reader_checks(page, ui, fx, out, report):
|
||||
summary = ui.locator(".cost-summary")
|
||||
rows = ui.locator("tbody tr.el-table__row")
|
||||
amount, days = summary.locator("dd").first, summary.locator("dd").last
|
||||
submit = ui.get_by_role("button", name="查询", exact=True)
|
||||
detail = ui.locator(".el-table__body")
|
||||
today = date.fromisoformat(fx.await_request(page, 0)["start_date"])
|
||||
assert fx.queries[0]["end_date"] == today.isoformat()
|
||||
expect(summary).to_have_attribute("aria-busy", "true")
|
||||
expect(ui.locator(".cost-skeleton")).to_have_count(2)
|
||||
expect(ui.get_by_role("status").filter(has_text="加载")).to_be_visible()
|
||||
assert not re.search(r"\d", summary.inner_text())
|
||||
assert ui.locator(".cost-skeleton").first.evaluate("e=>getComputedStyle(e).animationName") == "none"
|
||||
shot(page, out, "first-load")
|
||||
fx.release(page, 0)
|
||||
expect(amount).to_have_text("¥128.50")
|
||||
expect(days).to_have_text("1")
|
||||
expect(detail).to_contain_text("¥128.50")
|
||||
permissions(page, ui, "reader")
|
||||
shot(page, out, "desktop-light")
|
||||
report.extend(["pending_has_no_false_zero", "api_precision", "read_only_no_operation_column"])
|
||||
|
||||
ui.get_by_text("最近7天", exact=True).click()
|
||||
assert fx.await_request(page, 1)["start_date"] == (today - timedelta(days=6)).isoformat()
|
||||
ui.get_by_text("昨天", exact=True).click()
|
||||
assert fx.await_request(page, 2)["start_date"] == (today - timedelta(days=1)).isoformat()
|
||||
fx.release(page, 2, tag="昨日记录", amount="42.00")
|
||||
expect(detail).to_contain_text("昨日记录")
|
||||
fx.release(page, 1, tag="不再显示的旧周报", amount="777.00", days=7)
|
||||
expect(amount).to_have_text("¥42.00")
|
||||
expect(detail).to_contain_text("昨日记录")
|
||||
expect(ui).not_to_contain_text("777.00")
|
||||
report.append("late_success_ignored")
|
||||
|
||||
ui.get_by_text("本月", exact=True).click()
|
||||
fx.await_request(page, 3)
|
||||
ui.get_by_text("自定义", exact=True).click()
|
||||
expect(submit).to_be_disabled()
|
||||
fx.release(page, 3, fail=True)
|
||||
expect(rows).to_have_count(0)
|
||||
expect(amount).to_have_text("—")
|
||||
expect(ui.get_by_text("请选择开始和结束日期", exact=True)).to_be_visible()
|
||||
expect(ui.get_by_role("alert")).to_have_count(0)
|
||||
keyword = ui.get_by_placeholder("备注 / 创建人")
|
||||
keyword.fill("测试备注")
|
||||
keyword.press("Enter")
|
||||
assert len(fx.queries) == 4
|
||||
ui.get_by_placeholder("开始日期").click()
|
||||
options = page.locator(".el-date-range-picker__content.is-left:visible td.available")
|
||||
options.nth(2).click()
|
||||
options.nth(4).click()
|
||||
custom = fx.await_request(page, 4)
|
||||
assert custom["start_date"] == ui.get_by_placeholder("开始日期").input_value()
|
||||
assert custom["end_date"] == ui.get_by_placeholder("结束日期").input_value()
|
||||
assert custom["start_date"] < custom["end_date"] and custom["remark"] == "测试备注"
|
||||
fx.release(page, 4, tag="自定义记录", count=32)
|
||||
expect(detail).to_contain_text("自定义记录")
|
||||
report.extend(["incomplete_dates_block_query_and_hide_old_errors", "selected_dates_sent_without_fallback"])
|
||||
|
||||
# Keep the active page on retry (a failed second page must not silently send page one).
|
||||
ui.locator(".cost-pagination .btn-next").click()
|
||||
assert fx.await_request(page, 5)["page_no"] == "2"
|
||||
fx.release(page, 5, fail=True)
|
||||
expect(ui.get_by_role("alert")).to_be_visible()
|
||||
expect(amount).to_have_text("—")
|
||||
expect(rows).to_have_count(0)
|
||||
shot(page, out, "error")
|
||||
ui.get_by_role("button", name="重新加载", exact=True).click()
|
||||
assert fx.await_request(page, 6) == fx.queries[5]
|
||||
fx.release(page, 6, amount="31.10", tag="第二页", count=32)
|
||||
expect(detail).to_contain_text("第二页")
|
||||
expect(amount).to_have_text("¥31.10")
|
||||
report.extend(["failure_no_stale_data", "retry_preserves_page_and_filter"])
|
||||
|
||||
ui.locator(".el-form-item").filter(has_text="部门").locator(".el-select__wrapper").click()
|
||||
page.get_by_role("treeitem").get_by_text("验收部门", exact=True).click()
|
||||
assert fx.await_request(page, 7)["dept_id"] == "42" and fx.queries[7]["page_no"] == "1"
|
||||
fx.release(page, 7)
|
||||
ui.locator(".el-form-item").filter(has_text="自媒体来源").locator(".el-select__wrapper").click()
|
||||
page.get_by_role("option", name=SOURCE, exact=True).click()
|
||||
assert fx.await_request(page, 8)["media_source"] == SOURCE
|
||||
fx.release(page, 8, fail=True)
|
||||
ui.get_by_role("button", name="重置", exact=True).click()
|
||||
q = fx.await_request(page, 9)
|
||||
assert q == fx.queries[0], (q, fx.queries[0])
|
||||
fx.release(page, 9, amount="0.00", days=0, count=0)
|
||||
expect(amount).to_have_text("¥0.00")
|
||||
expect(days).to_have_text("0")
|
||||
expect(ui.get_by_text("当前筛选下没有消耗记录", exact=True)).to_be_visible()
|
||||
report.extend(["department_source_filters", "reset_restores_initial_query", "real_zero_and_empty_distinct"])
|
||||
|
||||
ui.get_by_text("最近7天", exact=True).click()
|
||||
fx.await_request(page, 10)
|
||||
ui.get_by_text("昨天", exact=True).click()
|
||||
fx.release(page, 11, tag="当前结果", amount=None, days=None)
|
||||
fx.release(page, 10, fail=True)
|
||||
expect(detail).to_contain_text("当前结果")
|
||||
expect(ui.get_by_role("alert")).to_have_count(0)
|
||||
expect(amount).to_have_text("—")
|
||||
expect(days).to_have_text("—")
|
||||
report.extend(["late_failure_ignored", "missing_summary_not_zero"])
|
||||
|
||||
light = ui.locator(".cost-results").evaluate("e=>getComputedStyle(e).backgroundColor")
|
||||
page.emulate_media(color_scheme="dark", reduced_motion="reduce")
|
||||
expect(page.locator("html")).to_have_class(re.compile(r"\bdark\b"))
|
||||
dark = ui.locator(".cost-results").evaluate("e=>getComputedStyle(e).backgroundColor")
|
||||
assert light != dark, (light, dark)
|
||||
shot(page, out, "desktop-dark")
|
||||
page.set_viewport_size({"width": 390, "height": 844})
|
||||
expect(page.locator(".app-aside .side")).to_be_hidden()
|
||||
submit.click()
|
||||
fx.release(page, 12, amount="1234567890123456.75", tag="窄屏记录")
|
||||
expect(amount).to_have_text("¥1234567890123456.75")
|
||||
dims = geometry(ui)
|
||||
assert not dims["clipped"] and dims["doc"] <= dims["width"] + 1 and dims["root"] <= dims["rootBox"] + 1, dims
|
||||
assert dims["main"] <= dims["mainBox"] + 1 and dims["content"] > dims["table"] > 0 and dims["keyword"] >= 100, dims
|
||||
assert amount.evaluate("""e=>{const r=document.createRange();r.selectNodeContents(e);const box=e.getBoundingClientRect();
|
||||
return [...r.getClientRects()].every(x=>x.right<=box.right+1 && x.bottom<=box.bottom+1);}""")
|
||||
shot(page, out, "390-dark")
|
||||
report.extend(["desktop_light_and_dark", "390px_fields_visible_only_table_scrolls", "large_amount_wraps"])
|
||||
ui.get_by_text("自定义", exact=True).click()
|
||||
ui.get_by_placeholder("开始日期").click()
|
||||
picker = page.locator(".el-date-range-picker:visible")
|
||||
expect(picker).to_be_visible()
|
||||
picker_box = picker.bounding_box()
|
||||
assert picker_box["x"] >= 0 and picker_box["x"] + picker_box["width"] <= dims["width"], picker_box
|
||||
shot(page, out, "390-calendar")
|
||||
body = picker.locator(".el-picker-panel__body-wrapper")
|
||||
assert body.evaluate("e=>e.scrollWidth <= e.clientWidth + 1")
|
||||
assert page.evaluate("document.documentElement.scrollWidth === document.documentElement.clientWidth")
|
||||
left_dates = picker.locator(".el-date-range-picker__content.is-left td.available")
|
||||
right_dates = picker.locator(".el-date-range-picker__content.is-right td.available")
|
||||
left_dates.nth(1).click()
|
||||
right_dates.nth(3).click()
|
||||
fx.release(page, 13)
|
||||
expect(amount).to_have_text("¥128.50")
|
||||
expect(picker).to_be_hidden()
|
||||
start, end = ui.get_by_placeholder("开始日期"), ui.get_by_placeholder("结束日期")
|
||||
committed = (start.input_value(), end.input_value())
|
||||
assert committed[0][:7] != committed[1][:7] and committed == (fx.queries[13]["start_date"], fx.queries[13]["end_date"])
|
||||
# Cancel a partial edit: the last applied dates and amount must remain intact.
|
||||
start.click()
|
||||
left_dates.nth(2).click()
|
||||
page.keyboard.press("Escape")
|
||||
expect(picker).to_be_hidden()
|
||||
assert committed == (start.input_value(), end.input_value()) and len(fx.queries) == 14
|
||||
expect(amount).to_have_text("¥128.50")
|
||||
report.extend(["390px_custom_calendar_across_months", "cancel_partial_range_keeps_applied_dates"])
|
||||
return dims
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--host", type=loopback, default="127.0.0.1:5181")
|
||||
parser.add_argument("--chrome", required=True)
|
||||
parser.add_argument("--out", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.out:
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
report = {"checks": [], "errors": [], "business_writes": [], "fixtures": {}}
|
||||
with sync_playwright() as pw, pw.chromium.launch(headless=True, 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", "operator"):
|
||||
fx = CostFixture(args.host, role)
|
||||
with browser.new_context(service_workers="block", viewport={"width":1280,"height":900},
|
||||
color_scheme="light", reduced_motion="reduce") as ctx:
|
||||
ctx.set_default_timeout(6000)
|
||||
ctx.route("**/*", fx.route)
|
||||
ctx.route_web_socket("**/*", lambda ws: (fx.errors.append("WebSocket blocked"), ws.close()))
|
||||
page = ctx.new_page()
|
||||
page.on("pageerror", lambda err: fx.errors.append(str(err)))
|
||||
try:
|
||||
page.goto(fx.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)
|
||||
desktop_entry(page, "账户消耗录入").click()
|
||||
ui = page.locator("main " + PAGE)
|
||||
expect(ui).to_be_visible()
|
||||
if role == "reader":
|
||||
report["mobile_geometry"] = reader_checks(page, ui, fx, args.out, report["checks"])
|
||||
else:
|
||||
fx.release(page, 0)
|
||||
expect(ui.locator(".el-table__body")).to_contain_text("首条记录")
|
||||
permissions(page, ui, role)
|
||||
report["checks"].append("permissions_" + role)
|
||||
except Exception as err:
|
||||
report["errors"].append([role, str(err)])
|
||||
shot(page, args.out, role + "-failure")
|
||||
finally:
|
||||
for pending in fx.pending:
|
||||
if pending is not None:
|
||||
pending.abort()
|
||||
report["fixtures"][role] = fx.queries
|
||||
report["errors"].extend(fx.errors)
|
||||
report["business_writes"].extend(p for m, p in fx.calls if m not in {"GET", "OPTIONS"} and p != LOGIN)
|
||||
report["status"] = "FAIL" if report["errors"] or report["business_writes"] else "PASS"
|
||||
if args.out:
|
||||
(args.out / "cost-feedback.json").write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n")
|
||||
print(json.dumps(report, ensure_ascii=False))
|
||||
return int(report["status"] != "PASS")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,176 @@
|
||||
"""Headless native workbench feedback. Only loopback static files may reach the network."""
|
||||
import argparse
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
from browser_contract import ACCOUNT, LOGIN, OFFICIAL, PASS, SELF, TOKEN, Fixture, loopback, menu
|
||||
|
||||
|
||||
ORDER = "/order.order/orderStats"
|
||||
DIAG = "/tcm.diagnosis/assistantDiagnosisStats"
|
||||
TREND = "/workbench/index"
|
||||
|
||||
|
||||
class WorkbenchFixture(Fixture):
|
||||
def __init__(self, host):
|
||||
super().__init__(host, False, False)
|
||||
self.reads[SELF]["menu"] = [menu(911, "工作台", "workbench", component="workbench/index", perm="workbench/index")]
|
||||
self.reads[SELF]["permissions"] = [ORDER[1:], DIAG[1:], TREND[1:]]
|
||||
self.pending = {}
|
||||
|
||||
def route(self, route):
|
||||
req, url = route.request, urlsplit(route.request.url)
|
||||
path = url.path.removeprefix("/adminapi")
|
||||
if f"{url.scheme}://{url.netloc}" != OFFICIAL or not url.path.startswith("/adminapi/") or path not in (ORDER, DIAG, TREND) or req.method != "GET":
|
||||
return super().route(route)
|
||||
q = parse_qs(url.query)
|
||||
if req.headers.get("token") != TOKEN or set(q) != {ORDER: {"order_type", "days"}, DIAG: {"days"}, TREND: set()}[path]:
|
||||
self.errors.append("unexpected workbench query or missing fixture session")
|
||||
return route.abort()
|
||||
if path == ORDER and q["order_type"] != ["-1"]:
|
||||
self.errors.append("unexpected order type")
|
||||
return route.abort()
|
||||
key = (path, q.get("days", [""])[0])
|
||||
if key in self.pending:
|
||||
self.errors.append("duplicate pending workbench request")
|
||||
return route.abort()
|
||||
self.pending[key] = route
|
||||
self.calls.append(["GET", path])
|
||||
|
||||
def release(self, page, key, data=None, *, failure=False):
|
||||
until = time.monotonic() + 5
|
||||
while key not in self.pending and time.monotonic() < until:
|
||||
page.wait_for_timeout(15)
|
||||
assert key in self.pending, (key, self.calls)
|
||||
route = self.pending.pop(key)
|
||||
with page.expect_event("requestfinished", predicate=lambda req: req == route.request):
|
||||
route.fulfill(headers={"Access-Control-Allow-Origin": self.base}, json={
|
||||
"code": 0 if failure else 1, "show": 0, "msg": "离线验收" if failure else "", "data": data})
|
||||
page.evaluate("() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))")
|
||||
|
||||
|
||||
def orders(count, amount, name="全部已支付"):
|
||||
return {"today_total": count, "today_amount": amount, "order_type_name": name,
|
||||
"date_range": ["2026-01-01", "2026-01-07"], "today_ranking": [], "departments": [], "ranking": [],
|
||||
"chart": {"xAxis": [], "series": []}}
|
||||
|
||||
|
||||
def series(values):
|
||||
return {"date": ["01/02", "01/01"], "list": [{"data": values}]}
|
||||
|
||||
|
||||
def run(browser, args, mobile):
|
||||
fixture = WorkbenchFixture(args.host)
|
||||
mode = "dark" if mobile else "light"
|
||||
size = {"width": 390, "height": 844} if mobile else {"width": 1440, "height": 960}
|
||||
with browser.new_context(service_workers="block", color_scheme=mode, viewport=size, reduced_motion="reduce") as ctx:
|
||||
ctx.set_default_timeout(8000)
|
||||
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)))
|
||||
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()
|
||||
page.wait_for_url("**/admin/workbench", timeout=15000)
|
||||
order, diag, trend = [page.locator(".wb-section--" + name) for name in ("order", "diagnosis", "trend")]
|
||||
for section in (order, diag):
|
||||
expect(section).to_have_attribute("data-state", "loading")
|
||||
expect(section.get_by_role("status")).to_contain_text("正在读取")
|
||||
expect(section.locator(".wb-kpi-value, canvas, .el-empty")).to_have_count(0)
|
||||
expect(trend).to_have_attribute("data-state", "collapsed")
|
||||
opener = trend.get_by_role("button", name="查看示例趋势")
|
||||
expect(opener).to_have_attribute("aria-expanded", "false")
|
||||
expect(trend.locator("canvas, .wb-placeholders")).to_have_count(0)
|
||||
assert ["GET", TREND] not in fixture.calls
|
||||
assert order.locator(".wb-placeholders i").first.evaluate("e => getComputedStyle(e).animationName") == "none"
|
||||
assert page.locator("html").evaluate("e => e.classList.contains('dark')") == mobile
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth + 1")
|
||||
if args.out:
|
||||
order.scroll_into_view_if_needed()
|
||||
page.screenshot(path=str(args.out / f"workbench-{mode}-loading.png"))
|
||||
|
||||
# Independent completions: genuine zero, an isolated failure, two explicitly empty plots.
|
||||
fixture.release(page, (ORDER, "0"), orders(0, "0.00"))
|
||||
fixture.release(page, (DIAG, "0"), failure=True)
|
||||
assert ["GET", TREND] not in fixture.calls
|
||||
opener.click()
|
||||
expect(trend.get_by_role("button", name="收起示例趋势")).to_have_attribute("aria-expanded", "true")
|
||||
expect(trend).to_have_attribute("data-state", "loading")
|
||||
fixture.release(page, (TREND, ""), {"visitor": series([]), "sale": series([None, None])})
|
||||
expect(order.locator(".wb-kpi-value")).to_have_text(["0", "¥0.00"])
|
||||
expect(diag.get_by_role("status")).to_contain_text("读取失败")
|
||||
expect(trend.get_by_text("暂无销售额趋势数据")).to_be_visible()
|
||||
expect(trend.locator("canvas")).to_have_count(0)
|
||||
if args.out:
|
||||
diag.scroll_into_view_if_needed()
|
||||
page.screenshot(path=str(args.out / f"workbench-{mode}-error.png"))
|
||||
before = len(fixture.calls)
|
||||
diag.get_by_role("button", name="重试诊单统计").click()
|
||||
expect(diag).to_have_attribute("data-state", "loading")
|
||||
fixture.release(page, (DIAG, "0"), {"today_total": 13, "date_range": ["01/01", "01/02"]})
|
||||
expect(diag.locator(".wb-kpi-value")).to_have_text("13")
|
||||
assert [p for _, p in fixture.calls[before:] if p in (ORDER, DIAG, TREND)] == [DIAG]
|
||||
|
||||
# Switch two filters rapidly: older success may not overwrite the current response.
|
||||
for label in ("最近7天", "最近30天"):
|
||||
order.locator(".el-select").nth(1).click()
|
||||
page.get_by_role("option", name=label, exact=True).click()
|
||||
expect(order).to_have_attribute("data-state", "loading")
|
||||
expect(order.locator(".wb-kpi-value")).to_have_count(0)
|
||||
fixture.release(page, (ORDER, "30"), orders(32, None, "当前筛选"))
|
||||
fixture.release(page, (ORDER, "7"), orders(7, "888.00", "过期结果"))
|
||||
expect(order.locator(".wb-kpi-value")).to_have_text(["32", "—"])
|
||||
expect(order).not_to_contain_text("过期结果")
|
||||
expect(diag.locator(".wb-kpi-value")).to_have_text("13")
|
||||
|
||||
page.get_by_role("button", name="刷新全部").click()
|
||||
for section in (order, diag, trend):
|
||||
expect(section).to_have_attribute("data-state", "loading")
|
||||
fixture.release(page, (ORDER, "30"), failure=True)
|
||||
fixture.release(page, (DIAG, "0"), {"today_total": 0})
|
||||
fixture.release(page, (TREND, ""), failure=True)
|
||||
expect(diag.locator(".wb-kpi-value")).to_have_text("0")
|
||||
order.get_by_role("button", name="重试订单统计").click()
|
||||
fixture.release(page, (ORDER, "30"), orders(26, "416.80"))
|
||||
expect(order.locator(".wb-kpi-value")).to_have_text(["26", "¥416.80"])
|
||||
trend.get_by_role("button", name="重试运营趋势").click()
|
||||
fixture.release(page, (TREND, ""), {"visitor": series([0, 2]), "sale": series([8, 66])})
|
||||
expect(trend.locator("canvas")).to_have_count(2)
|
||||
if args.out:
|
||||
trend.scroll_into_view_if_needed()
|
||||
page.screenshot(path=str(args.out / f"workbench-{mode}-ready.png"))
|
||||
trend.get_by_role("button", name="收起示例趋势").click()
|
||||
expect(trend).to_have_attribute("data-state", "collapsed")
|
||||
expect(trend.locator("canvas")).to_have_count(0)
|
||||
count = fixture.calls.count(["GET", TREND])
|
||||
page.get_by_role("button", name="刷新全部").click()
|
||||
fixture.release(page, (ORDER, "30"), orders(12, "22.00"))
|
||||
fixture.release(page, (DIAG, "0"), {"today_total": 4})
|
||||
expect(order.locator(".wb-kpi-value")).to_have_text(["12", "¥22.00"])
|
||||
expect(diag.locator(".wb-kpi-value")).to_have_text("4")
|
||||
expect(opener).to_have_attribute("aria-expanded", "false")
|
||||
assert fixture.calls.count(["GET", TREND]) == count
|
||||
assert not fixture.pending and not fixture.errors, (fixture.errors, list(fixture.pending))
|
||||
assert [p for method, p in fixture.calls if method == "POST"] == [LOGIN]
|
||||
return {"mode": mode, "width": size["width"], "workbench_reads": sum(path in (ORDER, DIAG, TREND) for _, path in fixture.calls)}
|
||||
|
||||
|
||||
if __name__ == "__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)
|
||||
args = parser.parse_args()
|
||||
if args.out:
|
||||
args.out.mkdir(parents=True, exist_ok=True)
|
||||
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:
|
||||
cases = [run(browser, args, mobile) for mobile in (False, True)]
|
||||
print(json.dumps({"workbench_feedback": "PASS", "real_api_calls": 0, "cases": cases}, ensure_ascii=False))
|
||||
@@ -78,9 +78,11 @@ export function createRouteRecord(route: any, firstRoute: boolean): RouteRecordR
|
||||
export function loadRouteView(component: string) {
|
||||
try {
|
||||
const normalizedComponent = normalizeMenuPath(component)
|
||||
const key = Object.keys(modules).find((key) => {
|
||||
return key.includes(`/${normalizedComponent}.vue`)
|
||||
})
|
||||
// Menus store paths relative to views/. A suffix alone can open a different
|
||||
// authorized page, e.g. assistant_service/workbench/index instead of workbench/index.
|
||||
const exact = `/src/views/${normalizedComponent}.vue`
|
||||
if (Object.hasOwn(modules, exact)) return modules[exact]
|
||||
const key = Object.keys(modules).find(key => key.endsWith(`/${normalizedComponent}.vue`))
|
||||
if (key) {
|
||||
return modules[key]
|
||||
}
|
||||
|
||||
@@ -1,26 +1,16 @@
|
||||
<template>
|
||||
<div class="personal-account-cost-page">
|
||||
<el-card class="!border-none mb-4" shadow="never">
|
||||
<div class="flex flex-wrap">
|
||||
<div class="w-1/2 md:w-1/3">
|
||||
<div class="leading-10">当前筛选天数</div>
|
||||
<div class="text-4xl">{{ pager.extend.days_count ?? 0 }}</div>
|
||||
<el-card shadow="never" class="cost-filter-card">
|
||||
<el-form :model="queryParams" label-position="top" class="stats-filter-form" @submit.prevent="handleQuery">
|
||||
<div class="cost-time-filter">
|
||||
<list-time-filter
|
||||
v-model:time-type="time_type"
|
||||
v-model:date-range="dateRange"
|
||||
variant="inline"
|
||||
@time-type-change="onTimeTypeChange"
|
||||
@custom-change="handleQuery"
|
||||
/>
|
||||
</div>
|
||||
<div class="w-1/2 md:w-1/3">
|
||||
<div class="leading-10">累计账户消耗 (元)</div>
|
||||
<div class="text-4xl">¥{{ pager.extend.total_amount ?? '0.00' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
<el-card class="!border-none" shadow="never">
|
||||
<el-form :inline="true" :model="queryParams" class="stats-filter-form">
|
||||
<list-time-filter
|
||||
v-model:time-type="time_type"
|
||||
v-model:date-range="dateRange"
|
||||
@time-type-change="onTimeTypeChange"
|
||||
@custom-change="onCustomDateChange"
|
||||
/>
|
||||
|
||||
<el-form-item label="部门">
|
||||
<el-tree-select
|
||||
@@ -33,7 +23,7 @@
|
||||
placeholder="全部部门"
|
||||
clearable
|
||||
filterable
|
||||
class="w-[220px]"
|
||||
class="cost-input"
|
||||
@change="handleQuery"
|
||||
/>
|
||||
</el-form-item>
|
||||
@@ -44,42 +34,70 @@
|
||||
:loading="mediaSourceLoading"
|
||||
placeholder="全部来源"
|
||||
:allow-create="false"
|
||||
select-class="w-[220px]"
|
||||
select-class="cost-input"
|
||||
@change="handleQuery"
|
||||
@visible-change="onMediaSourceDropdownVisible"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item class="w-[280px]" label="备注/录入人">
|
||||
<el-form-item class="cost-remark-filter" label="备注/录入人">
|
||||
<el-input
|
||||
v-model="queryParams.remark"
|
||||
placeholder="备注 / 创建人"
|
||||
clearable
|
||||
@keyup.enter="handleQuery"
|
||||
/>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button type="primary" :loading="pager.loading" @click="handleQuery">查询</el-button>
|
||||
<el-form-item class="cost-filter-actions">
|
||||
<el-button type="primary" native-type="submit" :disabled="awaitingDates">查询</el-button>
|
||||
<el-button @click="handleReset">重置</el-button>
|
||||
<el-button v-if="selfInputPath" class="ml-2" @click="goSelfInput">返回统计</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<el-card class="!border-none mt-4" shadow="never">
|
||||
<div>
|
||||
<el-button v-perms="['stats.personal_account_cost/add']" type="primary" @click="handleAdd">
|
||||
<template #icon>
|
||||
<icon name="el-icon-Plus" />
|
||||
</template>
|
||||
新增
|
||||
</el-button>
|
||||
</div>
|
||||
<el-card shadow="never" class="cost-results">
|
||||
<template #header>
|
||||
<div class="cost-heading">
|
||||
<h2>账户消耗明细</h2>
|
||||
<div class="cost-heading-actions">
|
||||
<el-button v-if="selfInputPath" @click="goSelfInput">返回统计</el-button>
|
||||
<el-button v-perms="['stats.personal_account_cost/add']" type="primary" @click="handleAdd">
|
||||
<template #icon><icon name="el-icon-Plus" /></template>
|
||||
新增
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-table class="mt-4" size="large" v-loading="pager.loading" :data="pager.lists">
|
||||
<dl class="cost-summary" aria-label="当前筛选汇总" :aria-busy="state === 'loading'">
|
||||
<div>
|
||||
<dt>累计账户消耗 (元)</dt>
|
||||
<dd>
|
||||
<span v-if="state === 'loading'" class="cost-skeleton" aria-hidden="true"></span>
|
||||
<template v-else>{{ state === 'ready' ? money(pager.extend?.total_amount) : '—' }}</template>
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt title="按有记录的日期去重">当前筛选天数</dt>
|
||||
<dd>
|
||||
<span v-if="state === 'loading'" class="cost-skeleton is-count" aria-hidden="true"></span>
|
||||
<template v-else>{{ state === 'ready' ? (pager.extend?.days_count ?? '—') : '—' }}</template>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<el-table
|
||||
:data="state === 'ready' ? pager.lists : []"
|
||||
size="large"
|
||||
:aria-busy="state === 'loading'"
|
||||
>
|
||||
<template #empty>
|
||||
<span v-if="state === 'error'" role="alert">账户消耗加载失败。</span>
|
||||
<el-button v-if="state === 'error'" type="primary" link @click="loadCosts">重新加载</el-button>
|
||||
<span v-else role="status">{{ emptyText }}</span>
|
||||
</template>
|
||||
<el-table-column label="日期" prop="cost_date" min-width="120" />
|
||||
<el-table-column label="自媒体来源" prop="media_source" min-width="160" show-overflow-tooltip />
|
||||
<el-table-column label="账户消耗" min-width="120">
|
||||
<template #default="{ row }">¥{{ row.amount }}</template>
|
||||
<el-table-column label="账户消耗" min-width="120" align="right">
|
||||
<template #default="{ row }">{{ money(row.amount) }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="备注" prop="remark" min-width="200" show-overflow-tooltip />
|
||||
<el-table-column label="录入人" prop="creator_name" min-width="100" />
|
||||
@@ -99,10 +117,10 @@
|
||||
</el-table-column>
|
||||
<el-table-column label="最后修改人" prop="updater_name" min-width="100" />
|
||||
<el-table-column label="更新时间" prop="update_time" min-width="180" />
|
||||
<el-table-column label="操作" width="160" fixed="right">
|
||||
<el-table-column v-if="canEdit || canDelete" label="操作" :width="canEdit && canDelete ? 120 : 78" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<el-button
|
||||
v-perms="['stats.personal_account_cost/edit']"
|
||||
v-if="canEdit"
|
||||
type="primary"
|
||||
link
|
||||
@click="handleEdit(row)"
|
||||
@@ -110,7 +128,7 @@
|
||||
编辑
|
||||
</el-button>
|
||||
<el-button
|
||||
v-perms="['stats.personal_account_cost/delete']"
|
||||
v-if="canDelete"
|
||||
type="danger"
|
||||
link
|
||||
@click="handleDelete(row.id)"
|
||||
@@ -121,8 +139,8 @@
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
|
||||
<div class="flex justify-end mt-4">
|
||||
<pagination v-model="pager" @change="getLists" />
|
||||
<div v-if="state === 'ready'" class="cost-pagination">
|
||||
<pagination v-model="pager" @change="loadCosts" />
|
||||
</div>
|
||||
</el-card>
|
||||
|
||||
@@ -143,6 +161,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 CostEditPopup from './cost-edit.vue'
|
||||
import MediaSourceSelect from './MediaSourceSelect.vue'
|
||||
@@ -169,6 +188,12 @@ const deptTreeProps = {
|
||||
|
||||
const selfInputPath = computed(() => getRoutePath('stats.self_input/overview') || '')
|
||||
|
||||
const canEdit = computed(() => hasPermission(['stats.personal_account_cost/edit']))
|
||||
const canDelete = computed(() => hasPermission(['stats.personal_account_cost/delete']))
|
||||
|
||||
// Keep the API's decimal representation (including trailing zeros); missing is not zero.
|
||||
const money = (value?: number | string | null) => value == null || value === '' ? '—' : `¥${value}`
|
||||
|
||||
const goSelfInput = () => {
|
||||
if (selfInputPath.value) {
|
||||
router.push(selfInputPath.value)
|
||||
@@ -186,11 +211,12 @@ const {
|
||||
dateRange,
|
||||
resolve,
|
||||
handleTimeTypeChange,
|
||||
handleCustomDateChange,
|
||||
resetTimeFilter,
|
||||
} = useListTimeFilter('today')
|
||||
|
||||
const { pager, getLists, resetPage } = usePaging({
|
||||
const { pager, getLists } = usePaging({
|
||||
firstLoading: true,
|
||||
latestOnly: true,
|
||||
fetchFun: async (params: Record<string, any>) => {
|
||||
const [start_date, end_date] = resolve()
|
||||
return personalAccountCostLists({
|
||||
@@ -202,13 +228,39 @@ const { pager, getLists, resetPage } = usePaging({
|
||||
params: queryParams,
|
||||
})
|
||||
|
||||
const awaitingDates = computed(() => time_type.value === 'custom' &&
|
||||
!(dateRange.value?.[0] && dateRange.value?.[1]))
|
||||
const failed = ref(false)
|
||||
const state = computed(() => awaitingDates.value ? 'dates' : pager.loading ? 'loading' : failed.value ? 'error' : 'ready')
|
||||
const emptyText = computed(() => ({
|
||||
dates: '请选择开始和结束日期',
|
||||
loading: '正在加载账户消耗…',
|
||||
ready: '当前筛选下没有消耗记录',
|
||||
error: '',
|
||||
})[state.value])
|
||||
|
||||
const loadCosts = async () => {
|
||||
if (awaitingDates.value) return
|
||||
failed.value = false
|
||||
try {
|
||||
await getLists()
|
||||
} catch {
|
||||
// latestOnly suppresses superseded failures. Clear the last successful
|
||||
// result only when the current request fails, without changing the page to retry.
|
||||
failed.value = true
|
||||
pager.lists = []
|
||||
pager.extend = {}
|
||||
pager.count = 0
|
||||
}
|
||||
}
|
||||
|
||||
const handleQuery = () => {
|
||||
if (awaitingDates.value) return
|
||||
pager.page = 1
|
||||
getLists()
|
||||
return loadCosts()
|
||||
}
|
||||
|
||||
const onTimeTypeChange = () => handleTimeTypeChange(handleQuery)
|
||||
const onCustomDateChange = () => handleCustomDateChange(handleQuery)
|
||||
|
||||
const handleReset = () => {
|
||||
resetTimeFilter()
|
||||
@@ -217,7 +269,7 @@ const handleReset = () => {
|
||||
queryParams.remark = ''
|
||||
pager.page = 1
|
||||
pager.size = 15
|
||||
getLists()
|
||||
return loadCosts()
|
||||
}
|
||||
|
||||
const onMediaSourceDropdownVisible = (visible: boolean) => {
|
||||
@@ -228,7 +280,7 @@ const onMediaSourceDropdownVisible = (visible: boolean) => {
|
||||
|
||||
const handleCostSuccess = async () => {
|
||||
await refreshMediaSourceOptions()
|
||||
getLists()
|
||||
await loadCosts()
|
||||
}
|
||||
|
||||
const handleAdd = async () => {
|
||||
@@ -246,9 +298,14 @@ const handleEdit = async (row: Record<string, any>) => {
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
await feedback.confirm('确定删除该账户消耗记录?')
|
||||
try {
|
||||
await feedback.confirm('确定删除该账户消耗记录?')
|
||||
} catch (reason) {
|
||||
if (reason === 'cancel' || reason === 'close') return
|
||||
throw reason
|
||||
}
|
||||
await personalAccountCostDelete({ id })
|
||||
getLists()
|
||||
await loadCosts()
|
||||
}
|
||||
|
||||
const loadDeptOptions = async () => {
|
||||
@@ -265,23 +322,99 @@ const loadDeptOptions = async () => {
|
||||
onMounted(async () => {
|
||||
loadDeptOptions()
|
||||
loadMediaSourceOptions()
|
||||
await getLists()
|
||||
await loadCosts()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.personal-account-cost-page {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 16px;
|
||||
padding: 20px;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
:root[data-admin-ui='v2'] .personal-account-cost-page { padding: 0; }
|
||||
|
||||
.cost-filter-card, .cost-results { min-width: 0; }
|
||||
|
||||
.stats-filter-form {
|
||||
:deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
display: grid;
|
||||
grid-template-columns: minmax(125px, 1fr) minmax(125px, 1fr) minmax(155px, 1.4fr) auto;
|
||||
align-items: end;
|
||||
gap: 12px 16px;
|
||||
:deep(.el-form-item) { margin: 0; min-width: 0; }
|
||||
:deep(.el-form-item__label) { margin-bottom: 4px; }
|
||||
:deep(.el-form-item__content), :deep(.el-radio-group) { min-width: 0; }
|
||||
:deep(.cost-input) { width: 100%; }
|
||||
}
|
||||
.cost-time-filter {
|
||||
grid-column: 1 / -1;
|
||||
min-width: 0;
|
||||
:deep(.el-form-item) { display: flex; flex-flow: row wrap; align-items: center; gap: 6px 12px; }
|
||||
:deep(.el-form-item__label) { margin: 0; }
|
||||
:deep(.list-time-filter-inline), :deep(.el-date-editor) { max-width: 100%; }
|
||||
}
|
||||
|
||||
.dept-cell {
|
||||
cursor: help;
|
||||
border-bottom: 1px dashed #c0c4cc;
|
||||
.cost-heading, .cost-heading-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
:deep(.el-button + .el-button) { margin-left: 0; }
|
||||
}
|
||||
.cost-heading { justify-content: space-between; }
|
||||
.cost-heading h2 { margin: 0; font-size: 16px; font-weight: 600; }
|
||||
.cost-summary {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
|
||||
gap: 16px;
|
||||
margin: 0 0 18px;
|
||||
padding: 0;
|
||||
dt { color: var(--el-text-color-regular); font-size: 13px; }
|
||||
dd {
|
||||
margin: 4px 0 0;
|
||||
font-size: clamp(22px, 2.6vw, 32px);
|
||||
font-weight: 600;
|
||||
line-height: 1.22;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
.cost-skeleton {
|
||||
display: inline-block;
|
||||
height: .7em;
|
||||
width: min(5em, 85%);
|
||||
border-radius: 4px;
|
||||
background: var(--el-fill-color);
|
||||
&.is-count { width: min(1.8em, 85%); }
|
||||
}
|
||||
.cost-pagination {
|
||||
margin-top: 16px;
|
||||
:deep(.el-pagination) { justify-content: flex-end; flex-wrap: wrap; row-gap: 6px; }
|
||||
}
|
||||
.dept-cell { cursor: help; border-bottom: 1px dashed var(--el-text-color-secondary); }
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.stats-filter-form { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 640px) {
|
||||
.personal-account-cost-page { gap: 12px; padding: 8px; }
|
||||
.cost-results, .cost-filter-card {
|
||||
:deep(.el-card__header), :deep(.el-card__body) { padding: 12px; }
|
||||
}
|
||||
.stats-filter-form { gap: 8px 10px; }
|
||||
.cost-time-filter {
|
||||
:deep(.el-form-item) { display: block; }
|
||||
:deep(.el-form-item__label) { margin-bottom: 4px; }
|
||||
:deep(.el-radio-group) { flex-wrap: wrap; row-gap: 4px; }
|
||||
:deep(.el-radio-button__inner) { padding-inline: 8px; }
|
||||
}
|
||||
.cost-remark-filter, .cost-filter-actions { grid-column: 1 / -1; }
|
||||
.cost-summary { margin-bottom: 12px; gap: 8px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.personal-account-cost-page :deep(*) { transition-duration: 0s !important; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<template>
|
||||
<div class="wb-section-body wb-feedback">
|
||||
<p role="status" aria-atomic="true">{{ state === 'error' ? label + '读取失败。' : '正在读取' + label + '…' }}</p>
|
||||
<div v-if="state === 'loading'" class="wb-placeholders" aria-hidden="true"><i/><i/><i/></div>
|
||||
<el-button v-else plain size="small" :aria-label="'重试' + label" @click="$emit('retry')">重新加载</el-button>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
defineProps<{ state: 'loading' | 'error'; label: string }>()
|
||||
defineEmits<{ (event: 'retry'): void }>()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.wb-feedback { min-height: 116px; padding: 18px 22px; }
|
||||
.wb-feedback p { margin: 0 0 10px; font-size: 14px; color: var(--zyt-text, var(--el-text-color-regular)); }
|
||||
.wb-placeholders { display: grid; grid-template-columns: 2fr 2fr 3fr; gap: 12px; }
|
||||
.wb-placeholders i { display: block; height: 52px; border-radius: 8px; background: var(--el-fill-color-light); animation: wb-breathe 1.6s ease-in-out infinite alternate; }
|
||||
@keyframes wb-breathe { to { opacity: .55; } }
|
||||
@media (prefers-reduced-motion: reduce) { .wb-placeholders i { animation: none; } }
|
||||
</style>
|
||||
+115
-123
@@ -3,14 +3,14 @@
|
||||
<header class="wb-hero">
|
||||
<div class="wb-hero-text">
|
||||
<h1 class="wb-hero-title">数据工作台</h1>
|
||||
<p class="wb-hero-desc">{{ isLiveReadonly ? '查看订单与诊单统计,仅展示接口返回的实际数据。' : '医助诊单、订单营收与运营趋势一屏掌握' }}</p>
|
||||
<p class="wb-hero-desc">{{ isLiveReadonly ? '查看订单与诊单统计,仅展示接口返回的实际数据。' : '查看订单营收与医助诊单统计。' }}</p>
|
||||
</div>
|
||||
<el-button type="primary" :icon="Refresh" round class="wb-refresh-btn" @click="refreshAll">
|
||||
刷新全部
|
||||
</el-button>
|
||||
</header>
|
||||
<!-- 订单统计 -->
|
||||
<section class="wb-section wb-section--order">
|
||||
<section class="wb-section wb-section--order" :data-state="orderReadState">
|
||||
<div class="wb-section-head">
|
||||
<div class="wb-section-title">
|
||||
<span class="wb-section-icon wb-section-icon--violet">
|
||||
@@ -18,7 +18,7 @@
|
||||
</span>
|
||||
<div>
|
||||
<div class="wb-section-name">订单统计</div>
|
||||
<div v-if="!isLiveReadonly || orderReadState === 'ready'" class="wb-section-sub">{{ orderStatsDateRangeText }} · {{ orderStatsData.order_type_name || '—' }}</div>
|
||||
<div v-if="orderReadState === 'ready'" class="wb-section-sub">{{ orderStatsDateRangeText }} · {{ orderStatsData.order_type_name || '—' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wb-toolbar">
|
||||
@@ -42,21 +42,19 @@
|
||||
<el-button aria-label="刷新订单统计" :icon="Refresh" circle @click="loadOrderStats" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="isLiveReadonly && orderReadState !== 'ready'" class="wb-section-body" role="status">
|
||||
{{ orderReadState === 'error' ? '订单统计读取失败,请重新刷新。' : '正在读取订单统计…' }}
|
||||
</div>
|
||||
<SectionFeedback v-if="orderReadState !== 'ready'" :state="orderReadState" label="订单统计" @retry="loadOrderStats" />
|
||||
<div v-else class="wb-section-body">
|
||||
<el-row :gutter="16" class="wb-kpi-row">
|
||||
<el-col :xs="24" :sm="8">
|
||||
<div class="wb-kpi wb-kpi--violet">
|
||||
<div class="wb-kpi-label">今日单数</div>
|
||||
<div class="wb-kpi-value">{{ orderStatsData.today_total ?? 0 }}</div>
|
||||
<div class="wb-kpi-value">{{ displayMetric(orderStatsData.today_total) }}</div>
|
||||
</div>
|
||||
</el-col>
|
||||
<el-col :xs="24" :sm="8">
|
||||
<div class="wb-kpi wb-kpi--amber">
|
||||
<div class="wb-kpi-label">今日金额</div>
|
||||
<div class="wb-kpi-value wb-kpi-value--sm">¥{{ orderStatsData.today_amount ?? '0.00' }}</div>
|
||||
<div class="wb-kpi-value wb-kpi-value--sm">{{ displayMetric(orderStatsData.today_amount, '¥') }}</div>
|
||||
</div>
|
||||
</el-col>
|
||||
<el-col :xs="24" :sm="8">
|
||||
@@ -103,7 +101,7 @@
|
||||
<span class="wb-chart-hint">{{ isLiveReadonly ? '按开单人排名' : '柱状 + 趋势' }}</span>
|
||||
</div>
|
||||
<v-charts
|
||||
v-if="orderStatsData.chart?.xAxis?.length"
|
||||
v-if="hasBars(orderStatsData.chart)"
|
||||
:key="'order-bar-' + orderStatsType"
|
||||
class="wb-chart"
|
||||
style="height: 300px"
|
||||
@@ -191,7 +189,7 @@
|
||||
</div>
|
||||
</section>
|
||||
<!-- 医助理诊单 -->
|
||||
<section class="wb-section wb-section--diagnosis">
|
||||
<section class="wb-section wb-section--diagnosis" :data-state="diagnosisReadState">
|
||||
<div class="wb-section-head">
|
||||
<div class="wb-section-title">
|
||||
<span class="wb-section-icon wb-section-icon--blue">
|
||||
@@ -199,8 +197,8 @@
|
||||
</span>
|
||||
<div>
|
||||
<div class="wb-section-name">医助理诊单统计</div>
|
||||
<div v-if="!isLiveReadonly || diagnosisReadState === 'ready'" class="wb-section-sub">
|
||||
{{ assistantStats.date_range?.[0] }} 至 {{ assistantStats.date_range?.[1] }}
|
||||
<div v-if="diagnosisReadState === 'ready'" class="wb-section-sub">
|
||||
{{ assistantStats.date_range?.length === 2 ? assistantStats.date_range.join(' 至 ') : '—' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -214,15 +212,13 @@
|
||||
<el-button aria-label="刷新诊单统计" :icon="Refresh" circle @click="loadAssistantStats" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="isLiveReadonly && diagnosisReadState !== 'ready'" class="wb-section-body" role="status">
|
||||
{{ diagnosisReadState === 'error' ? '诊单统计读取失败,请重新刷新。' : '正在读取诊单统计…' }}
|
||||
</div>
|
||||
<SectionFeedback v-if="diagnosisReadState !== 'ready'" :state="diagnosisReadState" label="诊单统计" @retry="loadAssistantStats" />
|
||||
<div v-else class="wb-section-body">
|
||||
<el-row :gutter="16" class="wb-kpi-row">
|
||||
<el-col :xs="24" :sm="8" :lg="6">
|
||||
<div class="wb-kpi wb-kpi--blue">
|
||||
<div class="wb-kpi-label">今日创建诊单</div>
|
||||
<div class="wb-kpi-value">{{ assistantStats.today_total ?? 0 }}</div>
|
||||
<div class="wb-kpi-value">{{ displayMetric(assistantStats.today_total) }}</div>
|
||||
<div class="wb-kpi-hint">当日新增总量</div>
|
||||
</div>
|
||||
</el-col>
|
||||
@@ -253,7 +249,7 @@
|
||||
<span class="wb-chart-hint">{{ isLiveReadonly ? '按医助排名' : '柱状 + 趋势线' }}</span>
|
||||
</div>
|
||||
<v-charts
|
||||
v-if="assistantStats.chart.xAxis?.length"
|
||||
v-if="hasBars(assistantStats.chart)"
|
||||
ref="assistantChart"
|
||||
class="wb-chart"
|
||||
style="height: 340px"
|
||||
@@ -319,19 +315,23 @@
|
||||
|
||||
|
||||
<!-- 访问 & 销售趋势 -->
|
||||
<section v-if="!isLiveReadonly" class="wb-section wb-section--trend">
|
||||
<section v-if="!isLiveReadonly" class="wb-section wb-section--trend" :data-state="trendExpanded ? trendReadState : 'collapsed'">
|
||||
<div class="wb-section-head">
|
||||
<div class="wb-section-title">
|
||||
<span class="wb-section-icon wb-section-icon--teal">
|
||||
<el-icon><TrendCharts /></el-icon>
|
||||
</span>
|
||||
<div>
|
||||
<div class="wb-section-name">运营趋势</div>
|
||||
<div class="wb-section-sub">访问量与销售额走势</div>
|
||||
<div class="wb-section-name">运营趋势示例</div>
|
||||
<div class="wb-section-sub">当前接口返回示例趋势,不计入经营统计。</div>
|
||||
</div>
|
||||
</div>
|
||||
<el-button v-if="!isLocalPreview" plain :aria-expanded="trendExpanded" @click="toggleTrend">
|
||||
{{ trendExpanded ? '收起示例趋势' : '查看示例趋势' }}
|
||||
</el-button>
|
||||
</div>
|
||||
<div class="wb-section-body wb-trend-body">
|
||||
<SectionFeedback v-if="trendExpanded && trendReadState !== 'ready'" :state="trendReadState" label="运营趋势" @retry="getData" />
|
||||
<div v-else-if="trendExpanded" class="wb-section-body wb-trend-body">
|
||||
<el-row :gutter="20">
|
||||
<el-col :xs="24" :lg="14">
|
||||
<div class="wb-chart-card wb-trend-card">
|
||||
@@ -339,6 +339,7 @@
|
||||
<span class="wb-chart-title">访问量趋势</span>
|
||||
</div>
|
||||
<v-charts
|
||||
v-if="hasTrend(workbenchData.visitorOption)"
|
||||
ref="visitorChart"
|
||||
class="wb-chart"
|
||||
style="height: 320px"
|
||||
@@ -346,6 +347,7 @@
|
||||
:theme="chartTheme"
|
||||
:autoresize="true"
|
||||
/>
|
||||
<el-empty v-else class="wb-chart-empty" description="暂无访问量趋势数据" />
|
||||
</div>
|
||||
</el-col>
|
||||
<el-col :xs="24" :lg="10">
|
||||
@@ -355,6 +357,7 @@
|
||||
<span class="wb-chart-hint">单位(万)</span>
|
||||
</div>
|
||||
<v-charts
|
||||
v-if="hasTrend(workbenchData.saleOption)"
|
||||
ref="saleChart"
|
||||
class="wb-chart"
|
||||
style="height: 320px"
|
||||
@@ -362,6 +365,7 @@
|
||||
:theme="chartTheme"
|
||||
:autoresize="true"
|
||||
/>
|
||||
<el-empty v-else class="wb-chart-empty" description="暂无销售额趋势数据" />
|
||||
</div>
|
||||
</el-col>
|
||||
</el-row>
|
||||
@@ -371,7 +375,8 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup name="workbench">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
|
||||
import SectionFeedback from './SectionFeedback.vue'
|
||||
import { useMutationObserver } from '@vueuse/core'
|
||||
import vCharts from 'vue-echarts'
|
||||
import { DataAnalysis, Histogram, Refresh, TrendCharts } from '@element-plus/icons-vue'
|
||||
@@ -384,11 +389,51 @@ import { useComponentRef } from '@/utils/getExposeType'
|
||||
import { calcColor } from '@/utils/util'
|
||||
|
||||
const isLiveReadonly = import.meta.env.MODE === 'live-readonly'
|
||||
const isLocalPreview = import.meta.env.MODE === 'local-preview'
|
||||
// Only the isolated demo opens the example by default. Ordinary business reads are independent.
|
||||
const trendExpanded = ref(isLocalPreview)
|
||||
function toggleTrend() {
|
||||
trendExpanded.value = !trendExpanded.value
|
||||
if (trendExpanded.value) getData()
|
||||
}
|
||||
type ReadState = 'loading' | 'ready' | 'error'
|
||||
const orderReadState = ref<ReadState>('loading')
|
||||
const diagnosisReadState = ref<ReadState>('loading')
|
||||
let orderRequest = 0
|
||||
let diagnosisRequest = 0
|
||||
// Only the latest read for this section owns its result, including rejection.
|
||||
function useSectionRead() {
|
||||
const state = ref<ReadState>('loading')
|
||||
let generation = 0
|
||||
onUnmounted(() => { generation++ })
|
||||
async function run(fetch: () => Promise<any>, apply: (res: any) => void) {
|
||||
const owner = ++generation
|
||||
state.value = 'loading'
|
||||
try {
|
||||
const res = await fetch()
|
||||
if (owner !== generation) return
|
||||
if (!res || typeof res !== 'object' || Array.isArray(res)) throw new Error('无统计结果')
|
||||
apply(res)
|
||||
state.value = 'ready'
|
||||
} catch {
|
||||
if (owner === generation) state.value = 'error'
|
||||
}
|
||||
}
|
||||
return { state, run }
|
||||
}
|
||||
const { state: orderReadState, run: readOrders } = useSectionRead()
|
||||
const { state: diagnosisReadState, run: readDiagnosis } = useSectionRead()
|
||||
const { state: trendReadState, run: readTrends } = useSectionRead()
|
||||
|
||||
function hasMetric(value: unknown) {
|
||||
return (typeof value === 'number' && Number.isFinite(value)) ||
|
||||
(typeof value === 'string' && value.trim() !== '')
|
||||
}
|
||||
function displayMetric(value: unknown, prefix = '') {
|
||||
return hasMetric(value) ? prefix + value : '—'
|
||||
}
|
||||
function hasBars(chart: any) {
|
||||
return chart?.xAxis?.length && chart.series?.some((s: any) => s?.data?.some(hasMetric))
|
||||
}
|
||||
function hasTrend(option: any) {
|
||||
return option.xAxis.data.length && option.series[0].data.some((v: any) => hasMetric(v?.value ?? v))
|
||||
}
|
||||
const settingStore = useSettingStore()
|
||||
const saleChart = useComponentRef(vCharts)
|
||||
const visitorChart = useComponentRef(vCharts)
|
||||
@@ -540,33 +585,26 @@ const assistantChartOption = computed(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const loadAssistantStats = () => {
|
||||
const request = ++diagnosisRequest
|
||||
if (isLiveReadonly) diagnosisReadState.value = 'loading'
|
||||
assistantDiagnosisStats({ days: assistantStats.days })
|
||||
.then((res: any) => {
|
||||
if (isLiveReadonly) {
|
||||
if (request !== diagnosisRequest) return
|
||||
if (res?.today_total == null) throw new Error('缺少诊单统计')
|
||||
diagnosisReadState.value = 'ready'
|
||||
}
|
||||
assistantStats.date_range = res.date_range
|
||||
assistantStats.today_total = res.today_total ?? 0
|
||||
assistantStats.today_ranking = res.today_ranking || []
|
||||
assistantStats.departments = res.departments || []
|
||||
assistantStats.ranking = res.ranking || []
|
||||
assistantStats.chart = res.chart || { xAxis: [], series: [] }
|
||||
})
|
||||
.catch(() => { if (isLiveReadonly && request === diagnosisRequest) diagnosisReadState.value = 'error' })
|
||||
}
|
||||
const loadAssistantStats = () => readDiagnosis(
|
||||
() => assistantDiagnosisStats({ days: assistantStats.days }),
|
||||
res => {
|
||||
if (isLiveReadonly && !hasMetric(res.today_total)) throw new Error('缺少诊单统计')
|
||||
assistantStats.date_range = res.date_range
|
||||
assistantStats.today_total = res.today_total
|
||||
assistantStats.today_ranking = res.today_ranking || []
|
||||
assistantStats.departments = res.departments || []
|
||||
assistantStats.ranking = res.ranking || []
|
||||
assistantStats.chart = res.chart || { xAxis: [], series: [] }
|
||||
}
|
||||
)
|
||||
|
||||
const orderStatsType = ref(-1)
|
||||
const orderStatsDays = ref(0)
|
||||
const orderStatsData = reactive<any>({
|
||||
order_type_name: '',
|
||||
date_range: [] as string[],
|
||||
today_total: 0,
|
||||
today_amount: '0.00',
|
||||
today_total: null,
|
||||
today_amount: null,
|
||||
today_ranking: [],
|
||||
departments: [],
|
||||
ranking: [],
|
||||
@@ -605,7 +643,7 @@ const orderDeptCountPieOption = computed(() => {
|
||||
const orderDeptAmountPieOption = computed(() => {
|
||||
const data = (orderStatsData.departments || [])
|
||||
.map((d: any) => ({ name: d.dept_name || '—', value: parseAmount(d.amount) }))
|
||||
.filter((d) => d.value > 0)
|
||||
.filter((d: { value: number }) => d.value > 0)
|
||||
return {
|
||||
color: skin.value ? artSeriesColors.value : pieColors,
|
||||
tooltip: {
|
||||
@@ -705,29 +743,24 @@ const orderChartOption = computed(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const loadOrderStats = () => {
|
||||
const request = ++orderRequest
|
||||
if (isLiveReadonly) orderReadState.value = 'loading'
|
||||
orderStats({ order_type: orderStatsType.value, days: orderStatsDays.value })
|
||||
.then((res: any) => {
|
||||
if (isLiveReadonly) {
|
||||
if (request !== orderRequest) return
|
||||
if (res?.today_total == null || res?.today_amount == null) throw new Error('缺少订单统计')
|
||||
orderReadState.value = 'ready'
|
||||
}
|
||||
Object.assign(orderStatsData, {
|
||||
order_type_name: res.order_type_name ?? '',
|
||||
date_range: res.date_range || [],
|
||||
today_total: res.today_total ?? 0,
|
||||
today_amount: res.today_amount ?? '0.00',
|
||||
today_ranking: res.today_ranking || [],
|
||||
departments: res.departments || [],
|
||||
ranking: res.ranking || [],
|
||||
chart: res.chart || { xAxis: [], series: [] }
|
||||
})
|
||||
const loadOrderStats = () => readOrders(
|
||||
() => orderStats({ order_type: orderStatsType.value, days: orderStatsDays.value }),
|
||||
res => {
|
||||
if (isLiveReadonly && (!hasMetric(res.today_total) || !hasMetric(res.today_amount))) {
|
||||
throw new Error('缺少订单统计')
|
||||
}
|
||||
Object.assign(orderStatsData, {
|
||||
order_type_name: res.order_type_name ?? '',
|
||||
date_range: res.date_range || [],
|
||||
today_total: res.today_total,
|
||||
today_amount: res.today_amount,
|
||||
today_ranking: res.today_ranking || [],
|
||||
departments: res.departments || [],
|
||||
ranking: res.ranking || [],
|
||||
chart: res.chart || { xAxis: [], series: [] }
|
||||
})
|
||||
.catch(() => { if (isLiveReadonly && request === orderRequest) orderReadState.value = 'error' })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
const refreshAll = () => {
|
||||
getData()
|
||||
@@ -762,17 +795,6 @@ const lowSalesColor = computed(() => skin.value ? artSeriesColors.value[4] : {
|
||||
})
|
||||
|
||||
const workbenchData: any = reactive({
|
||||
version: {
|
||||
version: '',
|
||||
website: '',
|
||||
based: '',
|
||||
channel: { gitee: '', website: '' }
|
||||
},
|
||||
support: [],
|
||||
today: {},
|
||||
menu: [],
|
||||
visitor: [],
|
||||
article: [],
|
||||
visitorOption: {
|
||||
xAxis: { type: 'category', data: [] },
|
||||
yAxis: { type: 'value' },
|
||||
@@ -832,43 +854,16 @@ const workbenchData: any = reactive({
|
||||
|
||||
const getData = () => {
|
||||
// WorkbenchLogic::visitor() and sale() generate random series, not operational figures.
|
||||
if (isLiveReadonly) return
|
||||
getWorkbench()
|
||||
.then((res: any) => {
|
||||
workbenchData.version = res.version
|
||||
workbenchData.today = res.today
|
||||
workbenchData.menu = res.menu
|
||||
workbenchData.visitor = res.visitor
|
||||
workbenchData.support = res.support
|
||||
|
||||
workbenchData.visitorOption.xAxis.data = []
|
||||
workbenchData.visitorOption.series[0].data = []
|
||||
workbenchData.saleOption.xAxis.data = []
|
||||
workbenchData.saleOption.series[0].data = []
|
||||
|
||||
res.visitor?.date?.reverse().forEach((item: any) => {
|
||||
workbenchData.visitorOption.xAxis.data.push(item)
|
||||
})
|
||||
res.visitor?.list?.[0]?.data?.forEach((item: any) => {
|
||||
workbenchData.visitorOption.series[0].data.push(item)
|
||||
})
|
||||
res.sale?.date?.reverse().forEach((item: any) => {
|
||||
workbenchData.saleOption.xAxis.data.push(item)
|
||||
})
|
||||
res.sale?.list?.[0]?.data?.forEach((item: any) => {
|
||||
let v: any = item
|
||||
if (item <= 50) {
|
||||
v = {
|
||||
value: item,
|
||||
itemStyle: { color: lowSalesColor }
|
||||
}
|
||||
}
|
||||
workbenchData.saleOption.series[0].data.push(v)
|
||||
})
|
||||
})
|
||||
.catch((err: any) => {
|
||||
console.log('err', err)
|
||||
})
|
||||
if (isLiveReadonly || !trendExpanded.value) return
|
||||
return readTrends(getWorkbench, res => {
|
||||
// Preserve the API's existing date/value ordering without mutating the response.
|
||||
workbenchData.visitorOption.xAxis.data = [...(res.visitor?.date || [])].reverse()
|
||||
workbenchData.visitorOption.series[0].data = res.visitor?.list?.[0]?.data || []
|
||||
workbenchData.saleOption.xAxis.data = [...(res.sale?.date || [])].reverse()
|
||||
workbenchData.saleOption.series[0].data = (res.sale?.list?.[0]?.data || []).map((item: any) =>
|
||||
!hasMetric(item) ? null : item <= 50 ? { value: item, itemStyle: { color: lowSalesColor.value } } : item
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const updateColor = () => {
|
||||
@@ -885,11 +880,7 @@ const updateColor = () => {
|
||||
visitorChart.value?.setOption(workbenchData.visitorOption)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
getData()
|
||||
loadAssistantStats()
|
||||
loadOrderStats()
|
||||
})
|
||||
onMounted(refreshAll)
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
@@ -1349,6 +1340,7 @@ html[data-admin-ui="v2"] .workbench-page {
|
||||
background: none;
|
||||
border: 0;
|
||||
}
|
||||
.wb-section--trend[data-state="collapsed"] .wb-section-head { padding-bottom: 16px; }
|
||||
.wb-section-title { gap: 10px; }
|
||||
.wb-section-icon {
|
||||
width: 40px; height: 40px; border-radius: 8px; font-size: 20px;
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// Execute the production resolver and route-record factory against the actual Vite glob
|
||||
// inventory. A sentinel importer stands in for each .vue chunk for this Node-only test.
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const { readFileSync, readdirSync } = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const ts = require('typescript')
|
||||
const vueRouter = require('vue-router')
|
||||
|
||||
const admin = path.resolve(__dirname, '..')
|
||||
const keys = readdirSync(path.join(admin, 'src/views'), { recursive: true })
|
||||
.filter(name => name.endsWith('.vue')).map(name => '/src/views/' + name).sort()
|
||||
const views = Object.fromEntries(keys.map(key => [key, async () => key]))
|
||||
const source = readFileSync(path.join(admin, 'src/router/index.ts'), 'utf8')
|
||||
.replace("import.meta.glob('/src/views/**/*.vue')", 'views')
|
||||
.replace('import.meta.env.BASE_URL', "'/admin/'")
|
||||
const js = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS,
|
||||
target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
const api = {}
|
||||
const deps = {
|
||||
'vue-router': { ...vueRouter, createWebHistory: vueRouter.createMemoryHistory },
|
||||
'@/enums/appEnums': { MenuEnum: { MENU: 'C', CATALOGUE: 'M' } },
|
||||
'@/stores/modules/user': {}, '@/utils/validate': { isExternal: () => false },
|
||||
'./routes': { constantRoutes: [] }
|
||||
}
|
||||
new Function('exports', 'require', 'views', js)(api, id => {
|
||||
assert.ok(Object.hasOwn(deps, id), 'unexpected dependency: ' + id)
|
||||
return deps[id]
|
||||
}, views)
|
||||
|
||||
test('native workbench and assistant workbench resolve to their own SFC via real menu records', async () => {
|
||||
for (const component of ['workbench/index', 'assistant_service/workbench/index']) {
|
||||
const record = api.createRouteRecord({ type: 'C', paths: 'workbench', component, name: '工作台' }, true)
|
||||
assert.equal(await record.component(), '/src/views/' + component + '.vue')
|
||||
}
|
||||
})
|
||||
|
||||
test('every complete component path in the actual glob resolves exactly, including slash normalization', () => {
|
||||
assert.ok(keys.length > 0)
|
||||
for (const key of keys) {
|
||||
const relative = key.slice('/src/views/'.length, -'.vue'.length)
|
||||
assert.equal(api.loadRouteView('/' + relative + '/'), views[key], relative)
|
||||
}
|
||||
})
|
||||
|
||||
test('old abbreviated keys still resolve; empty or missing keys retain RouterView fallback', t => {
|
||||
const oldKey = keys.find(key => key.endsWith('/dept-tongji.vue'))
|
||||
assert.ok(oldKey)
|
||||
assert.equal(api.loadRouteView('dept-tongji'), views[oldKey])
|
||||
const errors = t.mock.method(console, 'error', () => {})
|
||||
for (const bad of ['', 'missing/not-a-view']) {
|
||||
assert.equal(api.loadRouteView(bad), vueRouter.RouterView)
|
||||
}
|
||||
assert.equal(errors.mock.callCount(), 2)
|
||||
})
|
||||
Reference in New Issue
Block a user