Commit 7d4cd294 by 黄南光

修改部署

1 parent 5a9c566e
...@@ -7,6 +7,11 @@ ...@@ -7,6 +7,11 @@
# mock-dms [demo] 模拟广汽丰田 DMS # mock-dms [demo] 模拟广汽丰田 DMS
# edge-mock [demo] 模拟门店取数端(连 mock-dms 取数 / 建单 / 截图)。设备令牌由云端自动生成(server/data/demo_edge_token); # edge-mock [demo] 模拟门店取数端(连 mock-dms 取数 / 建单 / 截图)。设备令牌由云端自动生成(server/data/demo_edge_token);
# DMS 账号由云端下发(--demo 时云端设置 DEMO_MOCK_DMS=true,首次启动自动填入模拟 DMS 的账号)。 # DMS 账号由云端下发(--demo 时云端设置 DEMO_MOCK_DMS=true,首次启动自动填入模拟 DMS 的账号)。
# 固定项目名(和 start.sh 里的 PROJECT 保持一致)。不写的话默认取本文件所在目录名 "deploy",
# 和老版本(compose 在仓库根目录,项目名 auto-restock)建的容器对不上,会报 container name already in use。
name: auto-restock
services: services:
restock-cloud: restock-cloud:
build: build:
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
- 远程自检:取数端 →「远程自检」(复用登录态 + 只读查询 + 截图)。 - 远程自检:取数端 →「远程自检」(复用登录态 + 只读查询 + 截图)。
- 取回日志文件:取数端 →「拉取日志文件」,完成后在「任务」里打开下载;实时日志在「日志」标签页。 - 取回日志文件:取数端 →「拉取日志文件」,完成后在「任务」里打开下载;实时日志在「日志」标签页。
- 看 DMS 登录情况:取数端 → 设备与状态,「今日登录 N 次」正常应为 1~2 次。 - 看 DMS 登录情况:取数端 → 设备与状态,「今日登录 N 次」正常应为 1~2 次。
- 临时停掉自动推送:补货规则,关掉「每天定时推送」;试运行不想真建单:取数端 → 运行参数,关掉「允许建单」。 - 临时停掉自动推送:补货规则 → 定时补货,关掉「每天自动执行」(不再预检和到点推送,补货单页仍可「立即执行补货」);整个库存补货停用:系统设置 → 功能开通;试运行不想真建单:取数端 → 运行参数,关掉「允许建单」。
- 助手听不懂某种说法:智能助手 → 试聊,复现后在「提示词与话术 → 工具说明」里补例子。 - 助手听不懂某种说法:智能助手 → 试聊,复现后在「提示词与话术 → 工具说明」里补例子。
- 查谁做了什么:操作日志,按操作人类型 / 时间 / 关键词筛选,点一行看改前改后。 - 查谁做了什么:操作日志,按操作人类型 / 时间 / 关键词筛选,点一行看改前改后。
......
# -*- coding: utf-8 -*-
"""门店电脑上自助更新到云端最新版本(update.bat 调用;tool.bat 菜单 13 也能用)。
python main.py update 查云端最新版本 → 比本机新就更新 → 重启服务 → 等新版本连上云端
python main.py update --check 只查看本机 / 云端版本,不安装
python main.py update --yes 服务正在执行任务时不询问,直接更新(会中断那个任务)
下载 / 校验 sha256 / 解压到 app\\<版本>\\ / 试导入 与后台「版本更新」推送是同一套(core/updater.install),
回滚保护也一样:新版本以服务运行连续 3 次启动都没连上云端,启动器自动回滚到上一个版本。
只更新程序代码(edgeclient/);Python、浏览器运行时变了仍需重新装整包。
退出码:0 已是最新 / 更新成功;2 失败;3 配置错误
"""
import contextlib
import json
import logging
import os
import re
import subprocess
import time
from .. import __version__
from ..core import updater
from ..core.cloud import CloudClient, CloudError
from ..core.tasks import NullSteps, TaskError
log = logging.getLogger("edge")
SERVICE = "StoreEdge"
CONFIRM_WAIT = 120 # 重启服务后最多等多少秒看新版本连上云端
BANNER = "=" * 60
def _say(text=""):
print(text, flush=True)
def ver_tuple(v):
out = []
for p in str(v or "0").split("."):
out.append(int("".join(ch for ch in p if ch.isdigit()) or 0))
return tuple((out + [0, 0, 0])[:3])
class _Steps(NullSteps):
"""把 updater.install 的步骤打到控制台。"""
NAMES = {"download": "下载更新包", "verify": "校验 sha256 和包结构", "install": "解压并试运行新版本"}
@contextlib.contextmanager
def step(self, name, detail="", timeout=None, on_timeout=None, scale=1):
_say(" · %s(%s)……" % (self.NAMES.get(name, name), detail))
t0 = time.time()
yield
_say(" 完成,用时 %.1f 秒" % (time.time() - t0))
# ---------------------------------------------------------------- Windows 服务
def service_state():
"""RUNNING / STOPPED / START_PENDING / STOP_PENDING …;没装服务(或不是 Windows)返回 None。"""
if os.name != "nt":
return None
try:
out = subprocess.run(["sc", "query", SERVICE], capture_output=True, timeout=10).stdout.decode("gbk", "replace")
except Exception: # noqa: BLE001
return None
m = re.search(r"STATE\s*:\s*\d+\s+(\w+)", out)
return m.group(1) if m else None
def _net(action):
r = subprocess.run(["net", action, SERVICE], capture_output=True, timeout=90)
text = (r.stdout + r.stderr).decode("gbk", "replace").strip()
return r.returncode, text
def restart_service():
"""停止再启动服务(net stop / start 会等到完成)。返回 (成功?, 说明)。"""
code, text = _net("stop")
if code != 0 and service_state() != "STOPPED":
return False, "停止服务失败:%s" % (text.splitlines()[-1] if text else "退出码 %d" % code)
code, text = _net("start")
if code != 0 and service_state() not in ("RUNNING", "START_PENDING"):
return False, "启动服务失败:%s" % (text.splitlines()[-1] if text else "退出码 %d" % code)
return True, ""
def _read_status(root):
try:
with open(os.path.join(root, "run", "status.json"), encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError):
return {}
def _busy_task(root):
"""服务正在执行的任务(status.json 2 分钟内更新过且 state=busy);空闲返回 None。"""
st = _read_status(root)
if st.get("state") != "busy":
return None
try:
age = time.time() - time.mktime(time.strptime(st.get("updated") or "", "%Y-%m-%d %H:%M:%S"))
except ValueError:
return None
return st if age < 120 else None
def wait_confirmed(root, version, seconds=CONFIRM_WAIT):
"""等新版本启动并连上云端(version.json 的 pending 清空)。返回 "ok" / "rollback" / "timeout"。"""
deadline = time.time() + seconds
dots = 0
while time.time() < deadline:
st = updater.load_state(root)
if st.get("current") == version and not st.get("pending"):
_say("")
return "ok"
res = updater.read_result(root) or {}
if res.get("ok") is False and res.get("to") == version:
_say("")
return "rollback"
time.sleep(3)
dots += 1
print("." if dots % 20 else ".\n", end="", flush=True)
_say("")
return "timeout"
# ---------------------------------------------------------------- 主流程
def run(local, root, check_only=False, yes=False, ask=input):
_say(BANNER)
_say(" 门店取数端 · 更新到最新版本")
_say(BANNER)
try:
cc = CloudClient(local)
latest = cc.latest_release()
except CloudError as e:
if e.status == 404:
_say("[失败] 云端还不支持查询最新版本(云端版本太旧),请在企业后台「取数端 → 版本更新」推送。")
else:
_say("[失败] %s" % e)
return 3 if e.status == 400 else 2
build = updater.build_info()
_say("本机版本:%s%s" % (__version__, "(%s)" % build if build else ""))
ver = latest.get("version")
if not ver:
_say("云端版本库里还没有任何取数端版本。")
return 0
_say("云端最新:%s%s%s" % (ver, "(%s)" % latest["build"] if latest.get("build") else "",
" 说明:%s" % latest["notes"] if latest.get("notes") else ""))
if ver_tuple(ver) <= ver_tuple(__version__):
_say("[完成] 已经是最新版本,不需要更新。" if ver_tuple(ver) == ver_tuple(__version__) else
"[完成] 本机版本比云端还新,不降级。")
return 0
if check_only:
_say("有新版本 %s,运行 update.bat(不带 --check)即可更新。" % ver)
return 0
state = service_state()
busy = _busy_task(root) if state == "RUNNING" else None
if busy and not yes:
_say("[注意] 服务正在执行任务 %s(步骤 %s),现在更新会中断它。" % (busy.get("task_type"), busy.get("step") or "-"))
try:
if ask("输入 Y 回车继续更新,直接回车取消(可以等任务做完再运行 update.bat):").strip().upper() != "Y":
_say("已取消,没有做任何改动。")
return 0
except EOFError:
return 0
_say("开始更新 %s → %s:" % (__version__, ver))
try:
updater.install(cc, root, ver, latest.get("sha256") or "", _Steps(), size=latest.get("size"))
except (TaskError, CloudError) as e:
_say("[失败] %s(本机版本没有变化)" % e)
return 2
finally:
updater.RESTART["pending"] = False # 本命令自己不重启进程,由下面重启服务
_say("新版本 %s 已装到 %s" % (ver, os.path.join(root, "app", ver)))
if state is None:
_say("[完成] 这台电脑没有装 Windows 服务 StoreEdge:下次打开取数端(tool.bat)就会用新版本。")
return 0
if state != "RUNNING":
_say("[完成] 服务 StoreEdge 当前是停止状态(%s),没有替你启动;下次启动服务时加载新版本。" % state)
return 0
_say("重启服务 StoreEdge 加载新版本……")
ok, why = restart_service()
if not ok:
_say("[注意] %s" % why)
_say("新版本已装好,但服务没能重启:请右键 update.bat「以管理员身份运行」,或在 services.msc 里重启 StoreEdge。")
return 2
_say("等待新版本连上云端(最多 %d 秒)" % CONFIRM_WAIT)
r = wait_confirmed(root, ver)
if r == "ok":
_say("[完成] 已更新到 %s,新版本运行正常、已连上云端。" % ver)
return 0
if r == "rollback":
res = updater.read_result(root) or {}
_say("[失败] 新版本没能正常运行,已自动回滚到 %s:%s" % (res.get("current"), res.get("error")))
return 2
_say("[注意] %d 秒内新版本还没连上云端。服务会继续尝试;连续 3 次启动都连不上会自动回滚。" % CONFIRM_WAIT)
_say("稍后用 status.bat 查看「最近一次远程更新」那一行。")
return 2
@echo off
rem Update StoreEdge to the latest version in the cloud console (program code only: edgeclient\).
rem Double-click it. It asks for administrator rights (needed to restart the service), then:
rem 1. asks the cloud for the latest version and compares it with the version on this computer
rem 2. downloads the update package, checks sha256, unpacks it to app\<version>\ and test-runs it
rem 3. restarts the StoreEdge service and waits until the new version is connected to the cloud
rem If the new version fails to connect 3 starts in a row, the service rolls back to the previous version by itself.
rem update.bat --check only show the versions, install nothing
rem update.bat --yes do not ask when the service is busy with a task (the task is interrupted)
setlocal
net session >nul 2>&1
if not errorlevel 1 goto admin
echo Asking for administrator rights (needed to restart the StoreEdge service) ...
if "%~1"=="" goto elevate_noargs
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -ArgumentList '%*' -Verb RunAs"
goto elevated
:elevate_noargs
powershell -NoProfile -Command "Start-Process -FilePath '%~f0' -Verb RunAs"
:elevated
if not errorlevel 1 exit /b 0
echo [ERROR] Could not get administrator rights. Right-click update.bat and choose "Run as administrator".
pause
exit /b 1
:admin
rem update the installed copy: this folder if the service lives here, otherwise the default install folder
set "EDGE_HOME=%~dp0"
if exist "%EDGE_HOME%StoreEdge.exe" goto home_ok
if exist "C:\autoRestore\StoreEdge\StoreEdge.exe" set "EDGE_HOME=C:\autoRestore\StoreEdge\"
:home_ok
cd /d "%EDGE_HOME%"
if exist "python38\python.exe" goto run
echo [ERROR] python38 folder not found in %EDGE_HOME% . Install StoreEdge first (install.bat).
pause
exit /b 3
:run
if exist config.ini goto cfg_ok
echo [ERROR] config.ini not found in %EDGE_HOME% . Run install.bat first.
pause
exit /b 3
:cfg_ok
set PYTHONNOUSERSITE=1
python38\python.exe main.py update %*
set RC=%errorlevel%
echo.
echo ===== exit code %RC% (0=ok 2=failed 3=config error) folder: %EDGE_HOME% =====
pause
exit /b %RC%
...@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request ...@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import FileResponse from fastapi.responses import FileResponse
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from .. import features
from ..core import db from ..core import db
from ..services import alerts, audit, edge, events, notify, settings, stores from ..services import alerts, audit, edge, events, notify, settings, stores
from .deps import Scope, current_store, current_user from .deps import Scope, current_store, current_user
...@@ -25,6 +26,10 @@ class ResolveIn(BaseModel): ...@@ -25,6 +26,10 @@ class ResolveIn(BaseModel):
note: str = "" note: str = ""
class FeatureToggleIn(BaseModel):
enabled: bool
def _err(e: Exception) -> str: def _err(e: Exception) -> str:
if hasattr(e, "errors"): if hasattr(e, "errors"):
return ";".join(f"{'.'.join(str(x) for x in er['loc'])}:{er['msg']}" for er in e.errors()) # type: ignore return ";".join(f"{'.'.join(str(x) for x in er['loc'])}:{er['msg']}" for er in e.errors()) # type: ignore
...@@ -83,6 +88,22 @@ def put_store(body: StoreIn, s: Scope = Depends(current_store)): ...@@ -83,6 +88,22 @@ def put_store(body: StoreIn, s: Scope = Depends(current_store)):
return {"ok": True} return {"ok": True}
# ====================================================================== 功能开通(门店级:关掉后定时任务、企微指令、功能接口全部停用,数据保留)
@router.get("/system/features")
def list_features(s: Scope = Depends(current_store)):
return features.catalog(s.store_id)
@router.put("/system/features/{key}")
def toggle_feature(key: str, body: FeatureToggleIn, s: Scope = Depends(current_store)):
if key not in features.FEATURES:
raise HTTPException(404, "没有这个功能")
before, after = features.save(s.store_id, key, enabled=body.enabled, by=s.actor.name)
audit.record(s.store_id, s.actor, "feature.toggle", target_type="feature", target_id=key,
before={"enabled": before["enabled"]}, after={"enabled": after["enabled"]})
return {"ok": True, "features": features.catalog(s.store_id)}
# ====================================================================== 告警 / 操作日志 / 运行事件 # ====================================================================== 告警 / 操作日志 / 运行事件
@router.get("/alerts") @router.get("/alerts")
def list_alerts(status: str = "", page: int = 1, size: int = 30, s: Scope = Depends(current_store)): def list_alerts(status: str = "", page: int = 1, size: int = 30, s: Scope = Depends(current_store)):
......
...@@ -161,7 +161,9 @@ def save(store_id: int, key: str, *, enabled: bool | None = None, values: dict | ...@@ -161,7 +161,9 @@ def save(store_id: int, key: str, *, enabled: bool | None = None, values: dict |
cur = _row(store_id, key) cur = _row(store_id, key)
before_cfg = config(store_id, key).model_dump(mode="json") before_cfg = config(store_id, key).model_dump(mode="json")
before = {"enabled": bool(cur and cur["enabled"]), "config": before_cfg} before = {"enabled": bool(cur and cur["enabled"]), "config": before_cfg}
cfg = f.config_model.model_validate(before_cfg | (values or {}), context={"saving": True}).model_dump(mode="json") # 只切换开通(values=None)时沿用已存参数,不做保存校验:旧参数碰上新加的校验规则也不至于开 / 关不了
cfg = before_cfg if values is None else \
f.config_model.model_validate(before_cfg | values, context={"saving": True}).model_dump(mode="json")
en = before["enabled"] if enabled is None else bool(enabled) en = before["enabled"] if enabled is None else bool(enabled)
with db.tx() as c: with db.tx() as c:
if cur: if cur:
......
...@@ -62,7 +62,7 @@ class ExportIn(BaseModel): ...@@ -62,7 +62,7 @@ class ExportIn(BaseModel):
def _feature_on(s: Scope = Depends(current_store)) -> Scope: def _feature_on(s: Scope = Depends(current_store)) -> Scope:
if not features.is_enabled(s.store_id, KEY): if not features.is_enabled(s.store_id, KEY):
raise HTTPException(403, "门店还没有开通「库存补货」(在「补货规则」里打开)") raise HTTPException(403, "门店还没有开通「库存补货」(在「系统设置 → 功能开通」里打开)")
return s return s
...@@ -282,13 +282,15 @@ def today(s: Scope = Depends(current_store)): ...@@ -282,13 +282,15 @@ def today(s: Scope = Depends(current_store)):
enabled = features.is_enabled(sid, KEY) enabled = features.is_enabled(sid, KEY)
cur = svc.current(sid, now.date()) if enabled else None cur = svc.current(sid, now.date()) if enabled else None
ordered = svc.ordered_today(sid, now.date()) if enabled else None ordered = svc.ordered_today(sid, now.date()) if enabled else None
steps = [{"time": t, "title": "预检", "kind": "preflight"} for t in cfg.preflight_times] steps = [{"time": t, "title": "预检", "kind": "preflight"} for t in cfg.preflight_times] if cfg.auto_push else []
if cfg.auto_push: if cfg.auto_push:
steps.append({"time": cfg.push_time, "title": "拉出库明细、推送补货推荐", "kind": "push"}) steps.append({"time": cfg.push_time, "title": "拉出库明细、推送补货推荐", "kind": "push"})
if cfg.urgent_before_min: if cfg.urgent_before_min:
u = at(now.date(), cfg.cutoff) - dt.timedelta(minutes=cfg.urgent_before_min) u = at(now.date(), cfg.cutoff) - dt.timedelta(minutes=cfg.urgent_before_min)
steps.append({"time": u.strftime("%H:%M"), "title": "未下单紧急告警", "kind": "urgent"}) steps.append({"time": u.strftime("%H:%M"), "title": "未下单紧急告警", "kind": "urgent"})
steps.append({"time": cfg.cutoff, "title": "截单收口", "kind": "close"}) steps.append({"time": cfg.cutoff, "title": "截单收口", "kind": "close"})
if cfg.summary_enabled:
steps.append({"time": cfg.summary_time, "title": "发今日补货小结", "kind": "summary"})
if now.weekday() in cfg.so_sync_weekdays: if now.weekday() in cfg.so_sync_weekdays:
steps.append({"time": cfg.so_sync_time, "title": "同步近期 SO 单", "kind": "so_sync"}) steps.append({"time": cfg.so_sync_time, "title": "同步近期 SO 单", "kind": "so_sync"})
for x in steps: for x in steps:
......
...@@ -51,7 +51,8 @@ def _mins(t: str) -> int: ...@@ -51,7 +51,8 @@ def _mins(t: str) -> int:
class RestockConfig(BaseModel): class RestockConfig(BaseModel):
# ---- 时间线 ---- # ---- 时间线 ----
auto_push: bool = Field(True, title="每天定时推送补货清单") auto_push: bool = Field(True, title="每天自动执行定时补货",
description="到点预检 + 定时推送;关闭后仍可在后台「立即执行补货」手动跑,截单 / 提醒 / 重试 / 口径照样生效")
push_time: str = Field("15:00", title="定时推送时间", description="门店本地时间 HH:MM;到点拉出库明细、算补货清单、推链接") push_time: str = Field("15:00", title="定时推送时间", description="门店本地时间 HH:MM;到点拉出库明细、算补货清单、推链接")
cutoff: str = Field("16:00", title="厂家截单时间", description="过了这个时间不再提醒、不再建单,当天流程收口") cutoff: str = Field("16:00", title="厂家截单时间", description="过了这个时间不再提醒、不再建单,当天流程收口")
preflight_times: list[str] = Field(["14:00", "14:45"], title="预检时间", preflight_times: list[str] = Field(["14:00", "14:45"], title="预检时间",
...@@ -79,6 +80,9 @@ class RestockConfig(BaseModel): ...@@ -79,6 +80,9 @@ class RestockConfig(BaseModel):
description="群里发「零件号 数量」→ 查库存 → 回「订」建单截图 → 回「确认」提交") description="群里发「零件号 数量」→ 查库存 → 回「订」建单截图 → 回「确认」提交")
single_max_qty: int = Field(500, title="单次补货最大数量", ge=1, le=10000, single_max_qty: int = Field(500, title="单次补货最大数量", ge=1, le=10000,
description="防群里手滑打错数量(多打一个 0、把零件号当数量)直接在 DMS 建出大单") description="防群里手滑打错数量(多打一个 0、把零件号当数量)直接在 DMS 建出大单")
# ---- 每日小结(定时 + 单次补货一起统计)----
summary_enabled: bool = Field(True, title="发送今日补货小结")
summary_time: str = Field("16:30", title="今日补货小结发送时间", description="门店本地时间 HH:MM,须晚于截单时间")
# ---- 业务口径 ---- # ---- 业务口径 ----
warehouses: list[str] = Field(["GTMC广州", "华南GTMC"], title="关注仓", description="名字须与 DMS 全国仓库查询结果一致") warehouses: list[str] = Field(["GTMC广州", "华南GTMC"], title="关注仓", description="名字须与 DMS 全国仓库查询结果一致")
supplier_code: str = Field("APC40", title="采购单供应商代码", supplier_code: str = Field("APC40", title="采购单供应商代码",
...@@ -90,7 +94,7 @@ class RestockConfig(BaseModel): ...@@ -90,7 +94,7 @@ class RestockConfig(BaseModel):
step_timeouts: StepTimeouts = Field(default_factory=StepTimeouts, title="取数端各步骤超时") step_timeouts: StepTimeouts = Field(default_factory=StepTimeouts, title="取数端各步骤超时")
task_timeouts: TaskTimeouts = Field(default_factory=TaskTimeouts, title="任务整体超时") task_timeouts: TaskTimeouts = Field(default_factory=TaskTimeouts, title="任务整体超时")
@field_validator("push_time", "cutoff", "window_cut", "so_sync_time") @field_validator("push_time", "cutoff", "window_cut", "so_sync_time", "summary_time")
@classmethod @classmethod
def _hhmm(cls, v: str) -> str: def _hhmm(cls, v: str) -> str:
v = v.strip().replace(":", ":") v = v.strip().replace(":", ":")
...@@ -140,9 +144,11 @@ class RestockConfig(BaseModel): ...@@ -140,9 +144,11 @@ class RestockConfig(BaseModel):
cut = _mins(self.cutoff) cut = _mins(self.cutoff)
if self.auto_push and _mins(self.push_time) >= cut: if self.auto_push and _mins(self.push_time) >= cut:
raise ValueError(f"推送时间(push_time){self.push_time} 必须早于截单时间(cutoff){self.cutoff}") raise ValueError(f"推送时间(push_time){self.push_time} 必须早于截单时间(cutoff){self.cutoff}")
late = [t for t in self.preflight_times if _mins(t) >= cut] late = [t for t in self.preflight_times if _mins(t) >= cut] if self.auto_push else []
if late: if late:
raise ValueError(f"预检时间(preflight_times){'、'.join(late)} 必须早于截单时间(cutoff){self.cutoff}") raise ValueError(f"预检时间(preflight_times){'、'.join(late)} 必须早于截单时间(cutoff){self.cutoff}")
if self.summary_enabled and _mins(self.summary_time) <= cut:
raise ValueError(f"小结发送时间(summary_time){self.summary_time} 必须晚于截单时间(cutoff){self.cutoff}")
if self.scan_retry_stop_before_min > cut: if self.scan_retry_stop_before_min > cut:
raise ValueError("停止自动重试(scan_retry_stop_before_min)不能早于当天 00:00") raise ValueError("停止自动重试(scan_retry_stop_before_min)不能早于当天 00:00")
if self.urgent_before_min > cut: if self.urgent_before_min > cut:
......
...@@ -63,10 +63,13 @@ class RestockFeature(Feature): ...@@ -63,10 +63,13 @@ class RestockFeature(Feature):
def jobs(self): def jobs(self):
s = self.svc s = self.svc
return [ return [
JobSpec("preflight", "补货预检", lambda c: list(c.preflight_times), s.preflight, deadline=lambda c: c.cutoff), JobSpec("preflight", "补货预检", lambda c: list(c.preflight_times) if c.auto_push else [], s.preflight,
deadline=lambda c: c.cutoff),
JobSpec("push", "定时推送补货清单", lambda c: [c.push_time] if c.auto_push else [], s.push, JobSpec("push", "定时推送补货清单", lambda c: [c.push_time] if c.auto_push else [], s.push,
deadline=lambda c: c.cutoff), deadline=lambda c: c.cutoff),
JobSpec("close", "截单收口", lambda c: [c.cutoff], s.close, deadline=lambda c: "23:59"), JobSpec("close", "截单收口", lambda c: [c.cutoff], s.close, deadline=lambda c: "23:59"),
JobSpec("summary", "今日补货小结", lambda c: [c.summary_time] if c.summary_enabled else [], s.summary,
deadline=lambda c: "23:59"),
JobSpec("so_sync", "同步近期 SO 单", lambda c: [c.so_sync_time], s.so_sync, deadline=lambda c: "23:59", JobSpec("so_sync", "同步近期 SO 单", lambda c: [c.so_sync_time], s.so_sync, deadline=lambda c: "23:59",
weekdays=lambda c: list(c.so_sync_weekdays)), weekdays=lambda c: list(c.so_sync_weekdays)),
] ]
......
...@@ -1506,6 +1506,8 @@ class RestockService: ...@@ -1506,6 +1506,8 @@ class RestockService:
async def preflight(self, sid: int, now: dt.datetime, slot: str) -> None: async def preflight(self, sid: int, now: dt.datetime, slot: str) -> None:
cfg = self.cfg(sid) cfg = self.cfg(sid)
if not cfg.auto_push: # 预检是为定时推送服务的,关了每天自动执行就不查
return
key = f"day:{now.date()}" key = f"day:{now.date()}"
online, info = await edge.wait_online(sid, 90) # 云端刚重启时取数端可能正在重连 online, info = await edge.wait_online(sid, 90) # 云端刚重启时取数端可能正在重连
title = "补货预检失败:今天的补货可能受影响" title = "补货预检失败:今天的补货可能受影响"
...@@ -1555,9 +1557,9 @@ class RestockService: ...@@ -1555,9 +1557,9 @@ class RestockService:
await history.sync(sid, "schedule", Actor.system("每周 SO 单同步"), now.date()) await history.sync(sid, "schedule", Actor.system("每周 SO 单同步"), now.date())
async def close(self, sid: int, now: dt.datetime, slot: str) -> None: async def close(self, sid: int, now: dt.datetime, slot: str) -> None:
"""截单收口:今天还没完成的定时补货单作废(不顺延到明天)。小结另按「每日小结」时间发(summary)。"""
cfg = self.cfg(sid) cfg = self.cfg(sid)
cur = self.current(sid, now.date()) cur = self.current(sid, now.date())
orders = self.orders_today(sid, now.date())
if cur and cur["status"] in ("awaiting_confirm", "scan_retry", "scanning", "refreshing"): if cur and cur["status"] in ("awaiting_confirm", "scan_retry", "scanning", "refreshing"):
self._set(cur["id"], "expired", message=f"到 {cfg.cutoff} 截单仍未完成") self._set(cur["id"], "expired", message=f"到 {cfg.cutoff} 截单仍未完成")
await self.say(cur, self.t(sid, "msg_closed", cutoff=cfg.cutoff, doc=cur["doc_no"], await self.say(cur, self.t(sid, "msg_closed", cutoff=cfg.cutoff, doc=cur["doc_no"],
...@@ -1566,6 +1568,12 @@ class RestockService: ...@@ -1566,6 +1568,12 @@ class RestockService:
ref=self.ref(cur["id"]), detail={"create_unknown_at": _ts(cur.get("create_unknown_at"))}) ref=self.ref(cur["id"]), detail={"create_unknown_at": _ts(cur.get("create_unknown_at"))})
if cur.get("create_unknown_at"): if cur.get("create_unknown_at"):
await self.say(cur, self.t(sid, "msg_unknown_left", doc=cur["doc_no"])) await self.say(cur, self.t(sid, "msg_unknown_left", doc=cur["doc_no"]))
async def summary(self, sid: int, now: dt.datetime, slot: str) -> None:
"""今日补货小结:定时补货(含手动补充)+ 单次补货,按「每日小结」的时间发(须晚于截单,截单已收口)。"""
cfg = self.cfg(sid)
cur = self.current(sid, now.date())
orders = self.orders_today(sid, now.date())
if orders: if orders:
def po_state(o: dict) -> str: def po_state(o: dict) -> str:
st = (self.po_of(o["id"]) or {}).get("status") or "待提交" st = (self.po_of(o["id"]) or {}).get("status") or "待提交"
...@@ -1579,7 +1587,7 @@ class RestockService: ...@@ -1579,7 +1587,7 @@ class RestockService:
elif cur: elif cur:
text = f"今日未完成下单({STAGE_CN.get(cur['status'], cur['status'])}:{cur['message'] or ''})" text = f"今日未完成下单({STAGE_CN.get(cur['status'], cur['status'])}:{cur['message'] or ''})"
else: else:
text = "今日没有运行定时补货" + ("(定时推送已关闭)" if not cfg.auto_push else "") text = "今日没有运行定时补货" + ("(每天自动执行已关闭)" if not cfg.auto_push else "")
singles = db.rows(select(runs_t.c.doc_no, runs_t.c.order_no, runs_t.c.status, runs_t.c.submitted_at).where( singles = db.rows(select(runs_t.c.doc_no, runs_t.c.order_no, runs_t.c.status, runs_t.c.submitted_at).where(
runs_t.c.store_id == sid, runs_t.c.biz_date == now.date(), runs_t.c.kind == "single")) runs_t.c.store_id == sid, runs_t.c.biz_date == now.date(), runs_t.c.kind == "single"))
if singles: if singles:
......
...@@ -15,7 +15,7 @@ log = logging.getLogger("server.audit") ...@@ -15,7 +15,7 @@ log = logging.getLogger("server.audit")
ACTION_CN = { ACTION_CN = {
"auth.login": "登录", "auth.login_failed": "登录失败", "auth.password_change": "修改密码", "auth.login": "登录", "auth.login_failed": "登录失败", "auth.password_change": "修改密码",
"settings.update": "修改系统设置", "assistant.update": "修改智能助手", "text.save": "修改话术", "settings.update": "修改系统设置", "feature.toggle": "开通 / 关闭功能","assistant.update": "修改智能助手", "text.save": "修改话术",
"text.reset": "恢复默认话术", "dms.account.update": "修改厂商账号", "edge.runtime.update": "修改取数端运行参数", "text.reset": "恢复默认话术", "dms.account.update": "修改厂商账号", "edge.runtime.update": "修改取数端运行参数",
"edge.device.create": "新增取数端", "edge.device.rotate_token": "重置取数端令牌", "edge.device.status": "启停取数端", "edge.device.delete": "删除取数端", "edge.device.create": "新增取数端", "edge.device.rotate_token": "重置取数端令牌", "edge.device.status": "启停取数端", "edge.device.delete": "删除取数端",
"edge.remote_check": "远程自检", "edge.upload_logs": "拉取取数端日志", "edge.collect_diag": "收集取数端诊断", "edge.remote_check": "远程自检", "edge.upload_logs": "拉取取数端日志", "edge.collect_diag": "收集取数端诊断",
......
"""取数端设备表增加 token_enc:令牌明文的加密串,页面上直接展示 / 复制。
老设备该列为空(当时只存了 sha256),重置令牌后补上。
Revision ID: 0002_device_token_enc
Revises: 0001_init
"""
import sqlalchemy as sa
from alembic import op
revision = "0002_device_token_enc"
down_revision = "0001_init"
branch_labels = None
depends_on = None
_T = "atrs_edge_device"
def upgrade() -> None:
cols = {c["name"] for c in sa.inspect(op.get_bind()).get_columns(_T)}
if "token_enc" not in cols:
op.add_column(_T, sa.Column("token_enc", sa.String(255), nullable=True,
comment="设备令牌明文的加密串(Fernet,页面上展示 / 复制用;老设备为空,重置令牌后补上)"))
def downgrade() -> None:
op.drop_column(_T, "token_enc")
...@@ -386,6 +386,8 @@ def test_manual_run_does_not_affect_schedule(client, admin, outbox, fake_edge, m ...@@ -386,6 +386,8 @@ def test_manual_run_does_not_affect_schedule(client, admin, outbox, fake_edge, m
sent.append(text) sent.append(text)
monkeypatch.setattr(restock_service.notify, "send", fake_send) monkeypatch.setattr(restock_service.notify, "send", fake_send)
k.call(k.svc().close, k.store_id, fake_now(hh=16), "16:00") k.call(k.svc().close, k.store_id, fake_now(hh=16), "16:00")
assert sent == [] # 截单只收口,小结按自己的时间发
k.call(k.svc().summary, k.store_id, fake_now(hh=16, mm=30), "16:30")
assert "(手动补充,待提交" in sent[-1] and "(定时推送,已提交)" in sent[-1] assert "(手动补充,待提交" in sent[-1] and "(定时推送,已提交)" in sent[-1]
...@@ -1305,11 +1307,26 @@ def test_config_validation_and_gating(client, admin): ...@@ -1305,11 +1307,26 @@ def test_config_validation_and_gating(client, admin):
assert r.status_code == 400 and "push_time" in r.json()["detail"] assert r.status_code == 400 and "push_time" in r.json()["detail"]
r = client.put("/api/restock/config", json={"values": {"preflight_times": ["14:00", "16:00"]}}, headers=admin) r = client.put("/api/restock/config", json={"values": {"preflight_times": ["14:00", "16:00"]}}, headers=admin)
assert r.status_code == 400 and "preflight_times" in r.json()["detail"] assert r.status_code == 400 and "preflight_times" in r.json()["detail"]
assert client.put("/api/restock/config", json={"values": {"push_time": "16:30", "auto_push": False}}, assert client.put("/api/restock/config", json={"values": {"push_time": "16:30", "auto_push": False,
headers=admin).status_code == 200 # 关了定时推送就不管推送时间 "preflight_times": ["16:00"]}},
assert client.put("/api/restock/config", json={"enabled": False}, headers=admin).status_code == 200 headers=admin).status_code == 200 # 关了每天自动执行就不管推送 / 预检时间
# 每日小结须晚于截单
r = client.put("/api/restock/config", json={"values": {"summary_time": "16:00"}}, headers=admin)
assert r.status_code == 400 and "summary_time" in r.json()["detail"]
assert client.put("/api/restock/config", json={"values": {"summary_time": "16:00", "summary_enabled": False}},
headers=admin).status_code == 200
today = client.get("/api/restock/today", headers=admin).json()
assert [s["kind"] for s in today["timeline"] if s["kind"] in ("preflight", "push", "summary")] == []
# 功能开通在系统设置:只切换开通,不校验参数
assert client.put("/api/system/features/nope", json={"enabled": False}, headers=admin).status_code == 404
r = client.put("/api/system/features/restock", json={"enabled": False}, headers=admin)
assert r.status_code == 200 and r.json()["features"][0]["enabled"] is False
assert client.get("/api/system/features", headers=admin).json()[0]["enabled"] is False
assert client.get("/api/restock/categories", headers=admin).status_code == 403 assert client.get("/api/restock/categories", headers=admin).status_code == 403
assert client.get("/api/restock/today", headers=admin).json()["enabled"] is False assert client.get("/api/restock/today", headers=admin).json()["enabled"] is False
assert features.config(k.store_id, "restock").push_time == "16:30" # 切换开通不动参数
assert client.put("/api/system/features/restock", json={"enabled": True}, headers=admin).status_code == 200
assert client.get("/api/restock/categories", headers=admin).status_code == 200
def test_history_export(client, admin, monkeypatch): def test_history_export(client, admin, monkeypatch):
...@@ -1344,6 +1361,23 @@ def test_scheduler_fires_once_and_respects_feature(client, admin, outbox, fake_e ...@@ -1344,6 +1361,23 @@ def test_scheduler_fires_once_and_respects_feature(client, admin, outbox, fake_e
assert not [x for x in fake_edge.by_store if x[0] == other] assert not [x for x in fake_edge.by_store if x[0] == other]
def test_scheduler_auto_off_skips_preflight_and_push_keeps_close_summary(client, admin, outbox, fake_edge, monkeypatch):
a = setup_store(client, admin, auto_push=False)
sent = []
async def fake_send(sid, kind, severity, title, text, **kw):
sent.append((kind, text))
monkeypatch.setattr(restock_service.notify, "send", fake_send)
a.heartbeat()
for hh, mm in ((14, 0), (15, 0), (16, 0), (16, 30)):
fake_now(hh=hh, mm=mm)
a.call(scheduler.tick, True)
keys = [m["job_key"] for m in db.rows(select(schedule_marks_t).where(schedule_marks_t.c.store_id == a.store_id))]
assert "preflight" not in keys and "push" not in keys and {"close", "summary"} <= set(keys)
assert "sys.check" not in fake_edge.calls and db.rows(select(runs_t)) == []
assert any(k == "restock.daily_summary" and "每天自动执行已关闭" in t for k, t in sent)
def test_scheduler_weekly_so_sync(client, admin, outbox, fake_edge): def test_scheduler_weekly_so_sync(client, admin, outbox, fake_edge):
a = setup_store(client, admin, so=False) a = setup_store(client, admin, so=False)
fake_now(y=2026, m=10, d=27, hh=9, mm=0) # 周二:不同步 fake_now(y=2026, m=10, d=27, hh=9, mm=0) # 周二:不同步
......
...@@ -19,7 +19,10 @@ ...@@ -19,7 +19,10 @@
[ -z "$BASH_VERSION" ] && exec bash "$0" "$@" [ -z "$BASH_VERSION" ] && exec bash "$0" "$@"
cd "$(dirname "$0")" || exit 1 # 仓库根目录 cd "$(dirname "$0")" || exit 1 # 仓库根目录
COMPOSE="docker compose -f deploy/docker-compose.yml" PROJECT=auto-restock # compose 项目名,和 deploy/docker-compose.yml 的 name: 一致
COMPOSE="docker compose -p $PROJECT -f deploy/docker-compose.yml"
# docker-compose.yml 里写死的 container_name;同名容器若不归本项目管(老版本部署留下的),启动前先移除
CONTAINERS=(restock-cloud restock-mock-dms restock-edge-mock)
GREEN='\033[0;32m' GREEN='\033[0;32m'
BLUE='\033[0;34m' BLUE='\033[0;34m'
...@@ -139,8 +142,21 @@ build_images() { ...@@ -139,8 +142,21 @@ build_images() {
ok "✅ 镜像构建完成。" ok "✅ 镜像构建完成。"
} }
# 同名但不属于本 compose 项目的容器(老版本 / 别的目录 / 手动 docker run 建的)会让 up 报
# "container name ... is already in use":先移除它们。只删容器,数据目录是挂载的宿主机目录,不受影响。
remove_foreign_containers() {
local name proj
for name in "${CONTAINERS[@]}"; do
proj=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}' "$name" 2>/dev/null) || continue
[ "$proj" = "$PROJECT" ] && continue
warn " 发现不归本项目管理的旧容器 ${name}(所属:${proj:-非 compose 创建}),先移除再用新镜像启动(数据目录不受影响)"
docker rm -f "$name" >/dev/null || die "❌ 错误: 移除旧容器 ${name} 失败,请手动执行 docker rm -f ${name} 后重试。"
done
}
up_services() { up_services() {
local extra="" local extra=""
remove_foreign_containers
[ "$ACTION" = "restart" ] && extra="--force-recreate" [ "$ACTION" = "restart" ] && extra="--force-recreate"
$COMPOSE $PROFILE_ARGS up -d $extra || die "❌ 错误: 服务启动失败。" $COMPOSE $PROFILE_ARGS up -d $extra || die "❌ 错误: 服务启动失败。"
} }
...@@ -221,6 +237,7 @@ do_stop() { ...@@ -221,6 +237,7 @@ do_stop() {
check_docker check_docker
info "🛑 正在停止全部容器(含演示容器)..." info "🛑 正在停止全部容器(含演示容器)..."
$COMPOSE --profile demo down || die "❌ 停止容器时出现问题。" $COMPOSE --profile demo down || die "❌ 停止容器时出现问题。"
remove_foreign_containers
ok "✅ 已停止。数据保留在 server/data。" ok "✅ 已停止。数据保留在 server/data。"
} }
......
...@@ -45,18 +45,18 @@ const weekday = (s: string) => '日一二三四五六'[new Date(s + 'T00:00:00') ...@@ -45,18 +45,18 @@ const weekday = (s: string) => '日一二三四五六'[new Date(s + 'T00:00:00')
<template> <template>
<div class="page"> <div class="page">
<PageHeader title="工作台" :desc="d ? `今天 ${d.now.slice(0, 10)} · ${d.config.auto_push ? `每天 ${d.config.push_time} 自动推送` : '已关闭定时推送'} · ${d.config.cutoff} 截单` : ''"> <PageHeader title="工作台" :desc="d ? `今天 ${d.now.slice(0, 10)} · ${d.config.auto_push ? `每天 ${d.config.push_time} 自动推送` : '已关闭每天自动执行'} · ${d.config.cutoff} 截单` : ''">
<template #actions> <template #actions>
<el-button :icon="Refresh" @click="load">刷新</el-button> <el-button :icon="Refresh" @click="load">刷新</el-button>
</template> </template>
</PageHeader> </PageHeader>
<template v-if="d"> <template v-if="d">
<div v-if="!d.enabled" class="notice warn mb-3">库存补货功能还没有开通,到「补货规则」里打开。</div> <div v-if="!d.enabled" class="notice warn mb-3">库存补货功能还没有开通,到「系统设置 → 功能开通」里打开。</div>
<div class="grid" :class="session.isAdmin ? 'grid-4' : 'grid-2'"> <div class="grid" :class="session.isAdmin ? 'grid-4' : 'grid-2'">
<StatCard label="今日补货单" :tone="run ? STAGE[run.status]?.tone : 'info'"> <StatCard label="今日补货单" :tone="run ? STAGE[run.status]?.tone : 'info'">
{{ run ? STAGE[run.status]?.text || run.stage_cn : '未开始' }} {{ run ? STAGE[run.status]?.text || run.stage_cn : '未开始' }}
<template #hint>{{ run ? `${run.doc_no} · ${TRIGGER[run.trigger] || run.trigger}` : `${d.config.push_time} 自动推送` }}</template> <template #hint>{{ run ? `${run.doc_no} · ${TRIGGER[run.trigger] || run.trigger}` : (d.config.auto_push ? `${d.config.push_time} 自动推送` : '每天自动执行已关闭') }}</template>
</StatCard> </StatCard>
<StatCard label="可订" :value="run ? `${run.summary.order_count} 项 / ${run.summary.order_qty} 件` : '—'" <StatCard label="可订" :value="run ? `${run.summary.order_count} 项 / ${run.summary.order_qty} 件` : '—'"
:hint="run ? `约 ${fmtMoney(run.summary.amount)} · 出库 ${run.summary.total} 种(常备 ${run.summary.stock_count})` : `分类表 ${d.category_count} 种 · SO 常备 ${d.so_part_count} 种 · 今天单次补货 ${d.single_today} 次`" /> :hint="run ? `约 ${fmtMoney(run.summary.amount)} · 出库 ${run.summary.total} 种(常备 ${run.summary.stock_count})` : `分类表 ${d.category_count} 种 · SO 常备 ${d.so_part_count} 种 · 今天单次补货 ${d.single_today} 次`" />
...@@ -91,7 +91,7 @@ const weekday = (s: string) => '日一二三四五六'[new Date(s + 'T00:00:00') ...@@ -91,7 +91,7 @@ const weekday = (s: string) => '日一二三四五六'[new Date(s + 'T00:00:00')
<div v-if="run.status === 'awaiting_confirm'" class="notice warn">待计划员确认 · <a :href="run.link" target="_blank">打开单据页</a></div> <div v-if="run.status === 'awaiting_confirm'" class="notice warn">待计划员确认 · <a :href="run.link" target="_blank">打开单据页</a></div>
<div v-else-if="run.status === 'awaiting_submit'" class="notice warn">已建单 {{ run.order_no }},待确认提交 · <a :href="run.link" target="_blank">打开单据页</a></div> <div v-else-if="run.status === 'awaiting_submit'" class="notice warn">已建单 {{ run.order_no }},待确认提交 · <a :href="run.link" target="_blank">打开单据页</a></div>
</div> </div>
<EmptyState v-else title="今天还没有补货单" :desc="d.config.auto_push ? `${d.config.push_time} 自动推送` : '定时推送已关闭'"> <EmptyState v-else title="今天还没有补货单" :desc="d.config.auto_push ? `${d.config.push_time} 自动推送` : '每天自动执行已关闭'">
<el-button type="primary" @click="router.push('/runs')">去补货单</el-button> <el-button type="primary" @click="router.push('/runs')">去补货单</el-button>
</EmptyState> </EmptyState>
</Panel> </Panel>
......
<!-- 系统设置:门店信息、大模型、企微网关、通知与访问、取数端监控(值守时段、心跳与离线判定、异常通知谁)、日志保留。 --> <!-- 系统设置:功能开通(即时生效,不走保存栏)、门店信息、大模型、企微网关、通知与访问、取数端监控(值守时段、心跳与离线判定、异常通知谁)、日志保留。 -->
<script setup lang="ts"> <script setup lang="ts">
import { Delete, Plus } from '@element-plus/icons-vue' import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, nextTick, onMounted, ref } from 'vue' import { computed, nextTick, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router' import { useRoute } from 'vue-router'
import { api } from '@/api' import { api } from '@/api'
...@@ -22,10 +22,14 @@ const rtOrig = ref('') ...@@ -22,10 +22,14 @@ const rtOrig = ref('')
const targets = ref<any[]>([]) const targets = ref<any[]>([])
const watch = ref<any>(null) const watch = ref<any>(null)
const saving = ref(false) const saving = ref(false)
const feats = ref<any[]>([])
const toggling = ref('')
async function load() { async function load() {
try { try {
const [s, st, r] = await Promise.all([api.get('/api/system/settings'), api.get('/api/system/store'), api.get('/api/client/runtime')]) const [s, st, r, f] = await Promise.all([api.get('/api/system/settings'), api.get('/api/system/store'), api.get('/api/client/runtime'),
api.get('/api/system/features')])
feats.value = f
v.value = s.values v.value = s.values
targets.value = s.im_targets targets.value = s.im_targets
watch.value = s.watch watch.value = s.watch
...@@ -70,6 +74,22 @@ async function testEdgeAlert() { ...@@ -70,6 +74,22 @@ async function testEdgeAlert() {
if (JSON.stringify(v.value) !== orig.value) return ElMessage.warning('请先保存设置,再发送测试通知') if (JSON.stringify(v.value) !== orig.value) return ElMessage.warning('请先保存设置,再发送测试通知')
try { const r = await api.post('/api/system/test-edge-alert'); r.ok ? ElMessage.success(`测试通知已发出(${r.sent} 个对象)`) : ElMessage.error(r.error) } catch (e: any) { ElMessage.error(e.message) } try { const r = await api.post('/api/system/test-edge-alert'); r.ok ? ElMessage.success(`测试通知已发出(${r.sent} 个对象)`) : ElMessage.error(r.error) } catch (e: any) { ElMessage.error(e.message) }
} }
// 功能开通:即时生效。关闭影响大(定时任务、企微指令、功能接口全停),先确认
async function toggleFeature(f: any, on: boolean) {
if (!on) {
try {
await ElMessageBox.confirm(`关闭后「${f.name}」不再执行定时任务、不响应企业微信里的相关指令,相关页面的操作也用不了;已有数据保留,随时可以重新打开。`,
`关闭「${f.name}」`, { type: 'warning', confirmButtonText: '关闭', cancelButtonText: '取消' })
} catch { return }
}
toggling.value = f.key
try {
const r = await api.put(`/api/system/features/${f.key}`, { enabled: on })
feats.value = r.features
session.features = r.features
ElMessage.success(on ? `已开通「${f.name}」` : `已关闭「${f.name}」`)
} catch (e: any) { ElMessage.error(e.message) } finally { toggling.value = '' }
}
function addWindow() { v.value.edge_watch_windows = [...v.value.edge_watch_windows, { start: '08:30', end: '18:00' }] } function addWindow() { v.value.edge_watch_windows = [...v.value.edge_watch_windows, { start: '08:30', end: '18:00' }] }
function delWindow(i: number) { v.value.edge_watch_windows = v.value.edge_watch_windows.filter((_: any, j: number) => j !== i) } function delWindow(i: number) { v.value.edge_watch_windows = v.value.edge_watch_windows.filter((_: any, j: number) => j !== i) }
const hbWarn = computed(() => rt.value && v.value && rt.value.heartbeat_seconds * 2 > v.value.edge_offline_after) const hbWarn = computed(() => rt.value && v.value && rt.value.heartbeat_seconds * 2 > v.value.edge_offline_after)
...@@ -79,6 +99,19 @@ const hbWarn = computed(() => rt.value && v.value && rt.value.heartbeat_seconds ...@@ -79,6 +99,19 @@ const hbWarn = computed(() => rt.value && v.value && rt.value.heartbeat_seconds
<div class="page narrow"> <div class="page narrow">
<PageHeader title="系统设置" desc="敏感信息(API Key、Token)加密保存,页面上只显示是否已设置;留空表示不修改。" /> <PageHeader title="系统设置" desc="敏感信息(API Key、Token)加密保存,页面上只显示是否已设置;留空表示不修改。" />
<div v-if="v"> <div v-if="v">
<el-form id="features" label-position="top" class="form-card">
<FormSection title="功能开通" desc="门店用哪些功能。关闭后该功能的定时任务、企业微信指令、相关操作全部停用,已有数据保留。切换即时生效,不用点保存。">
<div v-for="f in feats" :key="f.key" class="feat">
<div class="grow">
<b>{{ f.name }}</b>
<div class="muted small">{{ f.description }}</div>
</div>
<el-switch :model-value="f.enabled" :loading="toggling === f.key" size="large" inline-prompt active-text="已开通" inactive-text="已关闭"
@change="(on: any) => toggleFeature(f, !!on)" />
</div>
</FormSection>
</el-form>
<el-form label-position="top" class="form-card"> <el-form label-position="top" class="form-card">
<FormSection title="门店信息" desc="门店名称会出现在企业微信消息和告警里。"> <FormSection title="门店信息" desc="门店名称会出现在企业微信消息和告警里。">
<div class="grid grid-2"> <div class="grid grid-2">
...@@ -170,5 +203,7 @@ const hbWarn = computed(() => rt.value && v.value && rt.value.heartbeat_seconds ...@@ -170,5 +203,7 @@ const hbWarn = computed(() => rt.value && v.value && rt.value.heartbeat_seconds
.windows { display: grid; gap: var(--sp-2); } .windows { display: grid; gap: var(--sp-2); }
.w-time { width: 120px; } .w-time { width: 120px; }
.w-ver { width: 160px; } .w-ver { width: 160px; }
#edge-monitor { scroll-margin-top: calc(var(--topbar-h) + 16px); } .feat { display: flex; align-items: center; gap: var(--sp-3); }
.feat + .feat { margin-top: var(--sp-3); }
#features, #edge-monitor { scroll-margin-top: calc(var(--topbar-h) + 16px); }
</style> </style>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!