Commit 5e6dc8cd by 黄南光

修复日志处理,增加@功能

1 parent 232862cd
...@@ -25,6 +25,15 @@ ...@@ -25,6 +25,15 @@
"port": 58000 "port": 58000
}, },
{ {
"name": "web-dev",
"runtimeExecutable": "cmd",
"runtimeArgs": [
"/c",
"cd /d D:\\code\\auto-restock\\web && set API_TARGET=http://127.0.0.1:58000&& npx vite --port 5173 --strictPort"
],
"port": 5173
},
{
"name": "cloud-preview", "name": "cloud-preview",
"runtimeExecutable": "cmd", "runtimeExecutable": "cmd",
"runtimeArgs": [ "runtimeArgs": [
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
测试群(库存补货助手群_Test)17:18–17:20 的 5 条消息,是**有人用测试机器人把生产群的消息重新发了一遍**,链接随原文带了过来。不是补货系统发错链接。 测试群(库存补货助手群_Test)17:18–17:20 的 5 条消息,是**有人用测试机器人把生产群的消息重新发了一遍**,链接随原文带了过来。不是补货系统发错链接。
- 「被人工重发」证据充分;**具体是谁、用什么工具,没有查到**。 - 「被人工重发」证据充分;**具体是谁、用什么工具,没有查到**。
- 当天生产多出一张补货单 RP-20261126-1-02(DMS 单 S20261126012),是另一个独立的代码 bug,**尚未修复**,见「遗留事项」。 - 当天生产多出一张补货单 RP-20261126-1-02(DMS 单 S20261126012),是另一个独立的代码 bug,v3.3.0 已修复(发布前生产仍受影响),见「遗留事项」。
## 时间线 ## 时间线
...@@ -46,14 +46,14 @@ imhub 网页端共用一个管理员账号;发送和上传日志不记来源 I ...@@ -46,14 +46,14 @@ imhub 网页端共用一个管理员账号;发送和上传日志不记来源 I
- 群里的机器人消息和本系统发出记录一对一核对,对不上的记成「非本系统发送」(消息通道 → 消息记录)。 - 群里的机器人消息和本系统发出记录一对一核对,对不上的记成「非本系统发送」(消息通道 → 消息记录)。
- 发送写日志文件;消息记录加机器人、图片地址、网关消息号;写库失败时日志里有整条内容。 - 发送写日志文件;消息记录加机器人、图片地址、网关消息号;写库失败时日志里有整条内容。
- 启动时记实例信息(主机、库、对外地址、imhub、机器人和群)。 - 启动时记实例信息(主机、库、对外地址、imhub、机器人和群)。
- 定时触发写明晚了多久、今天是否已触发过。 - 定时触发写明今天是否已触发过。
- 写操作和出错的请求记日志;删除机器人 / 接收对象的操作日志带删前内容。 - 写操作和出错的请求记日志;删除机器人 / 接收对象的操作日志带删前内容。
排查步骤见 [值班手册](../runbook.md)「群里出现不该有的消息」。 排查步骤见 [值班手册](../runbook.md)「群里出现不该有的消息」。
## 遗留事项 ## 遗留事项
- [ ] 修复改推送时间导致当天重复推送:`server/app/services/scheduler.py` 按「门店 + 任务 + 日期 + 时刻」去重,改了时间就成了新时刻。close、summary、so_sync 同样受影响。 - [x] (v3.3.0,代码已改,发布后生效)修复改推送时间导致当天重复推送:原来 `server/app/services/scheduler.py` 按「门店 + 任务 + 日期 + 时刻」去重,改了时间就成了新时刻。close、summary、so_sync 同样受影响。现在只有真的走到那个时刻才触发,改配置和重启都不补。
- [ ] 确认生产 DMS 的 S20261126012 已作废。 - [ ] 确认生产 DMS 的 S20261126012 已作废。
- [ ] 核实生产 `.env` 的 `APP_ENV`(排查时看到一份写的是 test)。 - [ ] 核实生产 `.env` 的 `APP_ENV`(排查时看到一份写的是 test)。
- [ ] 请 imhub 维护方: - [ ] 请 imhub 维护方:
......
...@@ -6,10 +6,14 @@ ...@@ -6,10 +6,14 @@
|---|---|---| |---|---|---|
| 14:00 / 14:45 | 预检通过(工作台「实时动态」) | 「补货预检失败:今天的补货可能受影响」 | | 14:00 / 14:45 | 预检通过(工作台「实时动态」) | 「补货预检失败:今天的补货可能受影响」 |
| 15:00 | 群里推「开始查询」→ 几分钟后推补货清单 | 「补货查询失败(自动重试中)」,最后「补货查询失败,今天可能无法按时下单」(紧急) | | 15:00 | 群里推「开始查询」→ 几分钟后推补货清单 | 「补货查询失败(自动重试中)」,最后「补货查询失败,今天可能无法按时下单」(紧急) |
| 15:05 起 | 未确认每 5 分钟 @ 计划员,最多 3 次 | — | | 15:05 起 | 未确认每 5 分钟提醒,最多 3 次(默认 @ 配置的人) | — |
| 15:45 | — | 「距截单还剩 15 分钟,今天还没有下单」(紧急) | | 15:45 | — | 「距截单还剩 15 分钟,今天还没有下单」(紧急) |
| 16:00 | 每日补货小结 | — | | 16:00 | 每日补货小结 | — |
定时任务只在真的走到那个时刻时触发:把时间改成今天已经过去的时刻不会触发;服务停着 / 重启错过的时刻一律不补,
只在实时动态里留一条「已错过」警告,需要的话到「补货单」点「立即执行补货」。**15:00 前后不要发版**,会漏掉当天的补货。
改成今天还没到的时刻,到点照常触发(即使今天已经推过一次)。
告警发给企业微信里用途含「告警通知」的接收对象(按级别),异常及以上同时发「系统设置」里的告警邮箱。 告警发给企业微信里用途含「告警通知」的接收对象(按级别),异常及以上同时发「系统设置」里的告警邮箱。
## 收到告警怎么办 ## 收到告警怎么办
...@@ -31,6 +35,8 @@ ...@@ -31,6 +35,8 @@
- 看 DMS 登录情况:取数端 → 设备与状态,「今日登录 N 次」正常应为 1~2 次。 - 看 DMS 登录情况:取数端 → 设备与状态,「今日登录 N 次」正常应为 1~2 次。
- 临时停掉自动推送:补货规则 → 定时补货,关掉「每天自动执行」(不再预检和到点推送,补货单页仍可「立即执行补货」);整个库存补货停用:系统设置 → 功能开通;试运行不想真建单:取数端 → 运行参数,关掉「允许建单」。 - 临时停掉自动推送:补货规则 → 定时补货,关掉「每天自动执行」(不再预检和到点推送,补货单页仍可「立即执行补货」);整个库存补货停用:系统设置 → 功能开通;试运行不想真建单:取数端 → 运行参数,关掉「允许建单」。
- 助手听不懂某种说法:智能助手 → 试聊,复现后在「提示词与话术 → 工具说明」里补例子。 - 助手听不懂某种说法:智能助手 → 试聊,复现后在「提示词与话术 → 工具说明」里补例子。
- 群里 @ 谁、什么时候 @:消息通道 → 接收对象 → 编辑,从群成员里选人(按用户 ID @,不是昵称),勾选哪些定时补货消息要 @;
保存后点「发送测试消息」看效果。单次 / 批量补货、对话回复、告警都不 @。
- 查谁做了什么:操作日志,按操作人类型 / 时间 / 关键词筛选,点一行看改前改后。 - 查谁做了什么:操作日志,按操作人类型 / 时间 / 关键词筛选,点一行看改前改后。
## 群里出现不该有的消息 ## 群里出现不该有的消息
...@@ -42,7 +48,7 @@ ...@@ -42,7 +48,7 @@
这两个目录挂在宿主机上,imhub 容器重建也还在(`docker logs` 会丢)。 这两个目录挂在宿主机上,imhub 容器重建也还在(`docker logs` 会丢)。
3. imhub 日志没有来源 IP 时,按时间查入口 nginx 的 `yjy/send`、`common/upload`、`webim`。 3. imhub 日志没有来源 IP 时,按时间查入口 nginx 的 `yjy/send`、`common/upload`、`webim`。
4. 怀疑有多个实例:各实例的 `server_<日期>.log` 搜「实例信息」,看主机、库、对外地址、机器人和群;链接域名不对也先看这里的「对外地址」。 4. 怀疑有多个实例:各实例的 `server_<日期>.log` 搜「实例信息」,看主机、库、对外地址、机器人和群;链接域名不对也先看这里的「对外地址」。
5. 怀疑是定时任务重复触发:搜「定时触发」,晚触发或当天再次触发的是 WARNING,并写明原因。 5. 怀疑是定时任务重复触发:搜「定时触发」,当天再次触发的是 WARNING,并写明原因;没有触发的会写「今天已经过了」或「已错过」。
6. 要查谁在后台 / 单据页做的:操作日志(有 IP 和 UA);请求有没有被拒看日志里的 `server.request`。 6. 要查谁在后台 / 单据页做的:操作日志(有 IP 和 UA);请求有没有被拒看日志里的 `server.request`。
例子:[2026-11-26 测试群出现生产链接](incidents/2026-11-26-测试群出现生产链接.md)。 例子:[2026-11-26 测试群出现生产链接](incidents/2026-11-26-测试群出现生产链接.md)。
......
__version__ = "3.2.0" __version__ = "3.3.0"
...@@ -27,7 +27,9 @@ class TargetIn(BaseModel): ...@@ -27,7 +27,9 @@ class TargetIn(BaseModel):
contact_id: str contact_id: str
# 单人对象库里这几项存的是 NULL,编辑时前端会原样带回来:允许 None,按空串处理(im.save_target 里统一清洗) # 单人对象库里这几项存的是 NULL,编辑时前端会原样带回来:允许 None,按空串处理(im.save_target 里统一清洗)
contact_name: str | None = "" contact_name: str | None = ""
at_ids: str | None = "" at_ids: str | None = "" # 要 @ 的人的 user id,逗号分隔(不是昵称)
at_names: dict[str, str] | None = None # {user id: 姓名},只用于显示
at_scenes: list[str] | None = None # 哪些场景 @(im.AT_SCENES);None = 默认场景
bot_names: str | None = "" bot_names: str | None = ""
purposes: list[str] = ["chat"] purposes: list[str] = ["chat"]
alert_min: str = "warn" alert_min: str = "warn"
...@@ -38,15 +40,27 @@ class TargetIn(BaseModel): ...@@ -38,15 +40,27 @@ class TargetIn(BaseModel):
def overview(s: Scope = Depends(current_store)): def overview(s: Scope = Depends(current_store)):
ts = [t | {"sync": im.sync_status(t["id"]) if "chat" in t["purposes"] else None} for t in im.targets(s.store_id)] ts = [t | {"sync": im.sync_status(t["id"]) if "chat" in t["purposes"] else None} for t in im.targets(s.store_id)]
return {"bots": im.bots(), "targets": ts, "purposes": im.PURPOSES, return {"bots": im.bots(), "targets": ts, "purposes": im.PURPOSES,
"contact_types": im.CONTACT_TYPES, "gateway": settings.get().im_api_base} "contact_types": im.CONTACT_TYPES, "at_scenes": im.AT_SCENES, "at_max": im.AT_MAX,
"gateway": settings.get().im_api_base}
@router.get("/contacts") @router.get("/contacts")
def contacts(bot_ref: int, type: str = "", keyword: str = "", page: int = 1, size: int = 20, def contacts(bot_ref: int, type: str = "", keyword: str = "", page: int = 1, size: int = 20, kind: str = "",
s: Scope = Depends(current_store)): s: Scope = Depends(current_store)):
"""从网关通讯录选群 / 选人(只开放企微外部群、内部群、同事、客户四种)。""" """从网关通讯录选群 / 选人(只开放企微外部群、内部群、同事、客户四种);kind = group / single 只查群 / 只查人。"""
try: try:
return im.contacts(s.store_id, bot_ref, type, keyword.strip(), page, size) return im.contacts(s.store_id, bot_ref, type, keyword.strip(), page, size, kind)
except ValueError as e:
raise HTTPException(400, str(e))
except RuntimeError as e:
raise HTTPException(502, str(e))
@router.get("/members")
def members(bot_ref: int, group_id: str, s: Scope = Depends(current_store)):
"""群成员:配置「@ 谁」时从里面选。"""
try:
return {"rows": im.group_members(bot_ref, group_id.strip())}
except ValueError as e: except ValueError as e:
raise HTTPException(400, str(e)) raise HTTPException(400, str(e))
except RuntimeError as e: except RuntimeError as e:
...@@ -109,8 +123,8 @@ def update_target(tid: int, body: TargetIn, s: Scope = Depends(current_store)): ...@@ -109,8 +123,8 @@ def update_target(tid: int, body: TargetIn, s: Scope = Depends(current_store)):
except ValueError as e: except ValueError as e:
raise HTTPException(400, str(e)) raise HTTPException(400, str(e))
audit.record(s.store_id, s.actor, "im.target.save", target_type="im_target", target_id=str(tid), audit.record(s.store_id, s.actor, "im.target.save", target_type="im_target", target_id=str(tid),
before={k: before[k] for k in ("name", "bot_ref", "kind", "contact_id", "at_ids", "bot_names", "purposes", before={k: before[k] for k in ("name", "bot_ref", "kind", "contact_id", "at_ids", "at_names", "at_scenes",
"alert_min", "enabled")}, after=body.model_dump()) "bot_names", "purposes", "alert_min", "enabled")}, after=body.model_dump())
return {"ok": True} return {"ok": True}
......
...@@ -110,7 +110,7 @@ def plain(row: dict | None) -> dict | None: ...@@ -110,7 +110,7 @@ def plain(row: dict | None) -> dict | None:
# 改了 app/models.py:用 `python -m app.cli schema-sql` 打印差异 DDL(只打印不执行),整理进新的 sql_script 版本目录。 # 改了 app/models.py:用 `python -m app.cli schema-sql` 打印差异 DDL(只打印不执行),整理进新的 sql_script 版本目录。
TABLE_PREFIX = "atrs_" TABLE_PREFIX = "atrs_"
SCHEMA_MARK = "db_schema" # atrs_sys_config 里的一行:{"version": "x.y.z"},由各版本 sql_script 的 999 脚本写入 SCHEMA_MARK = "db_schema" # atrs_sys_config 里的一行:{"version": "x.y.z"},由各版本 sql_script 的 999 脚本写入
REQUIRED_SCHEMA = "3.2.0" # 本程序要求的最低表结构版本(与 sql_script/v<版本> 目录对应) REQUIRED_SCHEMA = "3.3.0" # 本程序要求的最低表结构版本(与 sql_script/v<版本> 目录对应)
class SchemaError(RuntimeError): class SchemaError(RuntimeError):
......
...@@ -63,6 +63,7 @@ class SandboxBox: ...@@ -63,6 +63,7 @@ class SandboxBox:
@dataclass(frozen=True) @dataclass(frozen=True)
class JobSpec: class JobSpec:
"""在门店本地时间的某些时刻执行一次的定时任务;同一门店同一天同一时刻只触发一次(跨重启)。 """在门店本地时间的某些时刻执行一次的定时任务;同一门店同一天同一时刻只触发一次(跨重启)。
只在真的走到那个时刻时触发:改成今天已过去的时刻、服务停着错过的时刻都不补。deadline = 到这个时间就不再触发。
weekdays 返回 None = 每天;返回 [0, 3] = 只在周一、周四(0 = 周一 … 6 = 周日)。""" weekdays 返回 None = 每天;返回 [0, 3] = 只在周一、周四(0 = 周一 … 6 = 周日)。"""
key: str key: str
title: str title: str
...@@ -153,6 +154,12 @@ def config(store_id: int, key: str): ...@@ -153,6 +154,12 @@ def config(store_id: int, key: str):
return f.config_model() return f.config_model()
def saved_at(store_id: int, key: str) -> dt.datetime | None:
"""开通状态 / 参数最后一次保存的时间(调度器用:晚于某个时刻保存的配置,不触发那个时刻)。"""
r = _row(store_id, key)
return r["updated_at"] if r else None
def save(store_id: int, key: str, *, enabled: bool | None = None, values: dict | None = None, def save(store_id: int, key: str, *, enabled: bool | None = None, values: dict | None = None,
by: str = "") -> tuple[dict, dict]: by: str = "") -> tuple[dict, dict]:
"""保存开通状态与参数(values 合并到现有参数后整体校验)。返回 (改前, 改后)。""" """保存开通状态与参数(values 合并到现有参数后整体校验)。返回 (改前, 改后)。"""
......
...@@ -48,7 +48,7 @@ class RestockFeature(Feature): ...@@ -48,7 +48,7 @@ class RestockFeature(Feature):
return [ return [
JobSpec("preflight", "补货预检", lambda c: list(c.preflight_times) if c.auto_push else [], s.preflight, JobSpec("preflight", "补货预检", lambda c: list(c.preflight_times) if c.auto_push else [], s.preflight,
deadline=lambda c: c.cutoff), deadline=lambda c: c.cutoff),
# 截单只提示风险(cutoff_hard 关):云端重启后晚到的推送当天照样补发;旧规则下过了截单就不推 # 错过推送时刻一律不补(调度器统一处理),要补由人点「立即执行补货」;旧规则下过了截单不推
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 if c.cutoff_hard else "23:59"), deadline=lambda c: c.cutoff if c.cutoff_hard else "23:59"),
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"),
......
...@@ -309,7 +309,9 @@ im_targets_t = Table( ...@@ -309,7 +309,9 @@ im_targets_t = Table(
Column("kind", String(10), nullable=False, default="group", comment="类型:group 群聊 / single 单人"), Column("kind", String(10), nullable=False, default="group", comment="类型:group 群聊 / single 单人"),
Column("contact_id", String(80), nullable=False, comment="会话 ID:群 id 或联系人 id"), Column("contact_id", String(80), nullable=False, comment="会话 ID:群 id 或联系人 id"),
Column("contact_name", String(120), comment="通讯录里的群名 / 联系人名(从通讯录选择时一并保存,手填 ID 时为空)"), Column("contact_name", String(120), comment="通讯录里的群名 / 联系人名(从通讯录选择时一并保存,手填 ID 时为空)"),
Column("at_ids", String(300), comment="群里推清单 / 提醒时要 @ 的人(企微 user id,逗号分隔)"), Column("at_ids", String(300), comment="群里要 @ 的人(企微 user id,逗号分隔;不是昵称)"),
Column("at_names", JSON, comment="@ 的人的姓名 JSON:{user id: 群里的姓名},只用于显示和核对群消息"),
Column("at_scenes", JSON, comment="哪些场景要 @ 人 JSON 列表(im.AT_SCENES);空 = 默认场景,[] = 都不 @"),
Column("bot_names", String(200), comment="机器人在这个群里的昵称(逗号分隔可写多个别名),用来判断消息是否 @ 了机器人"), Column("bot_names", String(200), comment="机器人在这个群里的昵称(逗号分隔可写多个别名),用来判断消息是否 @ 了机器人"),
Column("purposes", JSON, comment="用途 JSON 列表:chat 补货对话(推清单、收回复、回执、提醒)/ alert 告警通知"), Column("purposes", JSON, comment="用途 JSON 列表:chat 补货对话(推清单、收回复、回执、提醒)/ alert 告警通知"),
Column("alert_min", String(10), nullable=False, default="warn", comment="告警通知的最低级别:info / warn / error / critical"), Column("alert_min", String(10), nullable=False, default="warn", comment="告警通知的最低级别:info / warn / error / critical"),
......
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
拉消息 GET {api}/core/msgs?channel=&bot_id=&contact_id=&start_time=&end_time=&limit=50&offset=0 拉消息 GET {api}/core/msgs?channel=&bot_id=&contact_id=&start_time=&end_time=&limit=50&offset=0
发文字 POST {api}/yjy/send/text {robot_key: bot_id, friends: [contact_id|群id], content, at_user_list: [user id…]} 发文字 POST {api}/yjy/send/text {robot_key: bot_id, friends: [contact_id|群id], content, at_user_list: [user id…]}
at_user_list 认的是用户 ID(网关文档:yjy_ww 传 wxid / VID),和群成员接口的 userId 是同一个,不是昵称
群成员 GET {api}/yjy/group/members?robot_key=&conversation_id=&page=&page_size= → {code, total, data: [{userId, name, …}]}
传图片 POST {api}/common/upload multipart file → {"url": OSS 公网地址} 传图片 POST {api}/common/upload multipart file → {"url": OSS 公网地址}
发图片 POST {api}/yjy/send/image {robot_key, friends, pic_url} 发图片 POST {api}/yjy/send/image {robot_key, friends, pic_url}
同一个机器人两条消息之间至少间隔 1.2 秒(避免网关频控、保证顺序)。bot = {"bot_id", "channel"}。 同一个机器人两条消息之间至少间隔 1.2 秒(避免网关频控、保证顺序)。bot = {"bot_id", "channel"}。
...@@ -21,6 +23,8 @@ from . import settings ...@@ -21,6 +23,8 @@ from . import settings
log = logging.getLogger("server.imhub") log = logging.getLogger("server.imhub")
TIMEOUT = 30 TIMEOUT = 30
SEND_GAP = 1.2 SEND_GAP = 1.2
MEMBER_PAGE_SIZE = 50
MEMBER_PAGES = 20 # 群成员最多取这么多页(1000 人)
_locks: dict[str, threading.Lock] = {} _locks: dict[str, threading.Lock] = {}
_last: dict[str, float] = {} _last: dict[str, float] = {}
_glock = threading.Lock() _glock = threading.Lock()
...@@ -123,6 +127,38 @@ def fetch_contacts(bot: dict, contact_type: str, name: str = "", limit: int = 20 ...@@ -123,6 +127,38 @@ def fetch_contacts(bot: dict, contact_type: str, name: str = "", limit: int = 20
return None, f"网关不可达:{e}" return None, f"网关不可达:{e}"
def fetch_self_id(bot: dict) -> str:
"""机器人自己的 user id(GET {api}/core/bot/{bot_id} 的 wxid);查不到返回空串。"""
try:
r = requests.get(f"{_api()}/core/bot/{bot.get('bot_id')}", headers=_headers(), timeout=TIMEOUT)
res = r.json() if r.status_code == 200 else {}
return str((res if isinstance(res, dict) else {}).get("wxid") or "")
except Exception as e: # noqa: BLE001
log.warning("查询机器人自己的 user id 失败:%s: %s", type(e).__name__, e)
return ""
def fetch_group_members(bot: dict, group_id: str) -> tuple[list[dict] | None, str]:
"""群成员(只读,翻页取全)。返回 (网关原始成员列表, 错误);失败时列表为 None。"""
out: list[dict] = []
for page in range(1, MEMBER_PAGES + 1):
try:
r = requests.get(_api() + "/yjy/group/members", headers=_headers(), timeout=TIMEOUT, params={
"robot_key": bot.get("bot_id"), "conversation_id": group_id, "page": page, "page_size": MEMBER_PAGE_SIZE})
res = r.json() if r.status_code == 200 else None
except Exception as e: # noqa: BLE001
log.warning("查询群成员失败:%s: %s", type(e).__name__, e)
return None, f"网关不可达:{e}"
if not isinstance(res, dict) or str(res.get("code", "")).strip() not in ("0", "200", ""):
log.warning("查询群成员失败:%s", _brief(r))
return None, f"网关返回 HTTP {r.status_code}" + (f":{res.get('msg')}" if isinstance(res, dict) else "")
rows = res.get("data") or []
out += rows
if len(rows) < MEMBER_PAGE_SIZE or len(out) >= int(res.get("total") or 0):
break
return out, ""
def fetch_msgs(bot: dict, contact_id: str, start: str, end: str) -> list[dict] | None: def fetch_msgs(bot: dict, contact_id: str, start: str, end: str) -> list[dict] | None:
"""失败返回 None,原因记在 LAST_ERROR[contact_id](这里不打日志:每 3 秒轮询一次,由收消息线程按次数节流记录)。""" """失败返回 None,原因记在 LAST_ERROR[contact_id](这里不打日志:每 3 秒轮询一次,由收消息线程按次数节流记录)。"""
url = (f"{_api()}/core/msgs?channel={bot.get('channel') or 'yjy_ww'}&bot_id={bot.get('bot_id')}" url = (f"{_api()}/core/msgs?channel={bot.get('channel') or 'yjy_ww'}&bot_id={bot.get('bot_id')}"
......
...@@ -2,8 +2,9 @@ ...@@ -2,8 +2,9 @@
每轮: 每轮:
1. 系统巡检:取数端在线 / 版本 / 磁盘,任务步骤超时与无进度,过期任务清理,旧日志清理; 1. 系统巡检:取数端在线 / 版本 / 磁盘,任务步骤超时与无进度,过期任务清理,旧日志清理;
2. 各业务功能的定时任务(JobSpec):门店本地时间到点且没过截止时间 → 写 schedule_marks(唯一键)抢到才执行, 2. 各业务功能的定时任务(JobSpec):配置始终只是配置,只有真的走到那个时刻才触发 ——
所以同一门店同一天同一时刻只触发一次,服务在 15:00 前后重启也会在截止前补触发; 到点时服务在运行、且那一刻这个配置已经生效 → 写 schedule_marks(唯一键)抢到才执行,同一天同一时刻只触发一次。
把时间改成今天已经过去的时刻不会触发;服务停着 / 重启错过的时刻一律不补,需要的话由人手动执行;
3. 各业务功能的 on_tick:提醒、截单收口等动态逻辑。 3. 各业务功能的 on_tick:提醒、截单收口等动态逻辑。
""" """
from __future__ import annotations from __future__ import annotations
...@@ -23,7 +24,7 @@ from . import aitrace, edge, events, msglog, settings ...@@ -23,7 +24,7 @@ from . import aitrace, edge, events, msglog, settings
log = logging.getLogger("server.scheduler") log = logging.getLogger("server.scheduler")
TICK = 15 TICK = 15
LATE_MIN = 5 # 比计划时刻晚这么多分钟以上才触发,按补触发记(warn) LATE_S = 120 # 到点后这么多秒内触发都算准时(只容忍轮询间隔和偶发卡顿),更晚就是错过,不补
def _mark(store_id: int, feature: str, job_key: str, day: dt.date, slot: str) -> bool: def _mark(store_id: int, feature: str, job_key: str, day: dt.date, slot: str) -> bool:
...@@ -35,20 +36,22 @@ def _mark(store_id: int, feature: str, job_key: str, day: dt.date, slot: str) -> ...@@ -35,20 +36,22 @@ def _mark(store_id: int, feature: str, job_key: str, day: dt.date, slot: str) ->
return False return False
def _marked(store_id: int, feature: str, job_key: str, day: dt.date, slot: str) -> bool:
c = schedule_marks_t.c
return bool(db.one(select(c.id).where(c.store_id == store_id, c.feature == feature, c.job_key == job_key,
c.biz_date == day, c.slot == slot).limit(1)))
def _fired_note(store_id: int, feature: str, job_key: str, now: dt.datetime, slot: str, def _fired_note(store_id: int, feature: str, job_key: str, now: dt.datetime, slot: str,
times: list[str]) -> tuple[str, str]: times: list[str]) -> tuple[str, str]:
"""定时触发的说明和级别:晚了多少、今天是不是已经按别的时刻触发过(改了时间会这样)。只是留痕,不影响执行。""" """定时触发的说明和级别:今天是不是已经按别的时刻触发过(改成了更晚的时间会这样)。只是留痕,不影响执行。"""
late = int((now - clock.at(now.date(), slot)).total_seconds() // 60)
c = schedule_marks_t.c c = schedule_marks_t.c
done = [r["slot"] for r in db.rows(select(c.slot).where( done = [r["slot"] for r in db.rows(select(c.slot).where(
c.store_id == store_id, c.feature == feature, c.job_key == job_key, c.biz_date == now.date(), c.slot != slot) c.store_id == store_id, c.feature == feature, c.job_key == job_key, c.biz_date == now.date(), c.slot != slot)
.order_by(c.id)) if r["slot"] not in times] # 一天本来就有多个时刻的任务(预检)不算重复 .order_by(c.id)) if r["slot"] not in times] # 一天本来就有多个时刻的任务(预检)不算重复
note = slot
if late >= LATE_MIN:
note += f",实际 {now:%H:%M},晚 {late} 分钟"
if done: if done:
note += f";今天已在 {'、'.join(done)} 触发过,这是改时间后的再次触发" return f"{slot};今天已在 {'、'.join(done)} 触发过,这是改时间后的再次触发", "warn"
return note, "warn" if late >= LATE_MIN or done else "info" return slot, "info"
class Scheduler: class Scheduler:
...@@ -59,8 +62,12 @@ class Scheduler: ...@@ -59,8 +62,12 @@ class Scheduler:
self._last_purge = 0.0 self._last_purge = 0.0
self.status = {"last_tick": "", "last_error": ""} self.status = {"last_tick": "", "last_error": ""}
self._failing: set[str] = set() # 出过错、还没恢复的 system.job_failed 告警 key(恢复时才查库) self._failing: set[str] = set() # 出过错、还没恢复的 system.job_failed 告警 key(恢复时才查库)
self._started: dt.datetime | None = None # 本进程的调度从什么时候开始运行:更早的时刻一律不补
self._planned: dict[tuple, set[str]] = {} # (门店, 功能, 任务) → 上一轮看到的时刻:到点前就排上了的
self._passed: set[tuple] = set() # 今天已经过去、不再触发的时刻(只说明一次)
def start(self) -> None: def start(self) -> None:
self._started = clock.now()
self._task = asyncio.create_task(self._loop(), name="scheduler") self._task = asyncio.create_task(self._loop(), name="scheduler")
async def stop(self) -> None: async def stop(self) -> None:
...@@ -116,8 +123,38 @@ class Scheduler: ...@@ -116,8 +123,38 @@ class Scheduler:
else: else:
await self._job_ok(store_id, name) await self._job_ok(store_id, name)
async def _due(self, sid: int, key: str, job, cfg, now: dt.datetime, slot: str, saved: dt.datetime | None,
planned: bool) -> bool:
"""这个时刻现在该不该触发(抢到触发记录才返回 True)。已经过去、不会再触发的时刻只留一条说明。
planned = 上一轮就排着这个时刻:到点后几秒内保存了别的参数(saved 变新),不影响它准时触发。"""
t = clock.at(now.date(), slot)
if now < t:
return False
gone = (sid, key, job.key, now.date(), slot)
if gone in self._passed:
return False
dl = job.deadline(cfg)
running = self._started is not None and self._started <= t
# 晚于 t 保存的配置:只有 t 之前就排着的时刻才算数(改成已过去的时刻、晚打开自动执行都不触发)
in_effect = saved is None or saved < t or planned
on_time = now < t + dt.timedelta(seconds=LATE_S) and not (dl and now >= clock.at(now.date(), dl))
if running and in_effect and on_time:
return await asyncio.to_thread(_mark, sid, key, job.key, now.date(), slot)
self._passed = {x for x in self._passed if x[3] == now.date()} | {gone}
if await asyncio.to_thread(_marked, sid, key, job.key, now.date(), slot):
return False
if not in_effect:
events.emit(f"{job.title}:{slot} 今天已经过了({saved:%H:%M} 才保存),今天不执行,需要的话请手动执行",
store_id=sid, source="system")
else:
events.emit(f"{job.title}:{slot} 到点时服务没有正常运行,已错过,不会自动补,需要的话请手动执行", "warn",
store_id=sid, source="system")
return False
async def tick(self, wait_jobs: bool = False) -> None: async def tick(self, wait_jobs: bool = False) -> None:
self.status["last_tick"] = time.strftime("%H:%M:%S") self.status["last_tick"] = time.strftime("%H:%M:%S")
if self._started is None:
self._started = clock.now()
await edge.presence_tick() await edge.presence_tick()
await edge.step_monitor_tick() await edge.step_monitor_tick()
if time.time() - self._last_sweep > 300: if time.time() - self._last_sweep > 300:
...@@ -130,22 +167,22 @@ class Scheduler: ...@@ -130,22 +167,22 @@ class Scheduler:
await asyncio.to_thread(events.purge, ps.edge_log_retention_days) await asyncio.to_thread(events.purge, ps.edge_log_retention_days)
await asyncio.to_thread(msglog.purge, ps.msg_log_retention_days) await asyncio.to_thread(msglog.purge, ps.msg_log_retention_days)
await asyncio.to_thread(aitrace.purge, ps.ai_trace_retention_days) await asyncio.to_thread(aitrace.purge, ps.ai_trace_retention_days)
last, self._planned = self._planned, {} # 没轮到的门店(功能关着)不保留:重新打开不会沿用关之前的排期
for key, f in features.FEATURES.items(): for key, f in features.FEATURES.items():
jobs = f.jobs() jobs = f.jobs()
for sid in features.enabled_stores(key): for sid in features.enabled_stores(key):
try: try:
now = clock.now() # 和写库的 db.now() 同一个时钟(门店时区字段不再参与计算) now = clock.now() # 和写库的 db.now() 同一个时钟(门店时区字段不再参与计算)
cfg = features.config(sid, key) cfg = features.config(sid, key)
saved = features.saved_at(sid, key)
for job in jobs: for job in jobs:
wd = job.weekdays(cfg) wd = job.weekdays(cfg)
if wd is not None and now.weekday() not in wd: off = wd is not None and now.weekday() not in wd
continue times = [] if off else list(job.times(cfg) or [])
times = list(job.times(cfg) or []) seen = last.get((sid, key, job.key), set())
self._planned[(sid, key, job.key)] = set(times)
for slot in times: for slot in times:
t = clock.at(now.date(), slot) if await self._due(sid, key, job, cfg, now, slot, saved, slot in seen):
dl = job.deadline(cfg)
end = clock.at(now.date(), dl) if dl else t + dt.timedelta(minutes=30)
if t <= now < end and await asyncio.to_thread(_mark, sid, key, job.key, now.date(), slot):
try: try:
note, level = await asyncio.to_thread(_fired_note, sid, key, job.key, now, slot, times) note, level = await asyncio.to_thread(_fired_note, sid, key, job.key, now, slot, times)
except Exception: # noqa: BLE001 说明拼不出来不能影响任务执行 except Exception: # noqa: BLE001 说明拼不出来不能影响任务执行
......
...@@ -194,7 +194,7 @@ class StoreKit: ...@@ -194,7 +194,7 @@ class StoreKit:
self.group = "group-1" self.group = "group-1"
self.contact = self.group self.contact = self.group
r = client.post("/api/wecom/targets", json={"name": "配件计划群", "bot_ref": bot, "kind": "group", r = client.post("/api/wecom/targets", json={"name": "配件计划群", "bot_ref": bot, "kind": "group",
"contact_id": self.group, "at_ids": "zhangsan", "contact_id": self.group, "at_ids": "1688001", "at_names": {"1688001": "张 三"},
"bot_names": "补货助手", "bot_names": "补货助手",
"purposes": ["chat", "alert"], "alert_min": "warn"}, headers=admin) "purposes": ["chat", "alert"], "alert_min": "warn"}, headers=admin)
assert r.status_code == 200, r.text assert r.status_code == 200, r.text
......
...@@ -9,13 +9,14 @@ from pathlib import Path ...@@ -9,13 +9,14 @@ from pathlib import Path
import pytest import pytest
from sqlalchemy import select from sqlalchemy import select
from app import features
from app import main as app_main from app import main as app_main
from app.core import db from app.core import db
from app.core.config import C from app.core.config import C
from app.core.request_log import mask_path from app.core.request_log import mask_path
from app.models import alerts_t, audit_t, events_t, im_targets_t, notify_logs_t from app.models import alerts_t, audit_t, events_t, im_targets_t, notify_logs_t
from app.services import events, im, msglog from app.services import events, im, msglog
from app.services.scheduler import _fired_note, _mark, scheduler from app.services.scheduler import Scheduler, _fired_note, _mark
from tests.conftest import fake_now from tests.conftest import fake_now
TOKEN = "8a0GvzC3AwtZbkxE" TOKEN = "8a0GvzC3AwtZbkxE"
...@@ -66,6 +67,18 @@ def test_own_text_and_image_are_matched(t, kit, outbox): ...@@ -66,6 +67,18 @@ def test_own_text_and_image_are_matched(t, kit, outbox):
assert not foreign() assert not foreign()
@pytest.mark.parametrize("echo", ["@张 三 {}", "@张 三\u2005@Li Lei\u2005{}", "{} @张 三", "{}\n@张 三 @Li Lei"])
def test_at_prefix_with_spaced_names_is_ours(t, kit, outbox, echo):
"""@ 的人姓名带空格、消息又短:网关在前后加上「@姓名」也认得出是自己发的;@ 了别人的不算。"""
db.q(im_targets_t.update().where(im_targets_t.c.id == kit.target_id).values(
at_ids="1,2", at_names={"1": "张 三", "2": "Li Lei"}))
t = im.target(kit.target_id)
im.send_to(t, "单建好了", at=["1", "2"])
age_sent()
assert run(t, [own("s1", echo.format("单建好了"))]) == 0 and not foreign()
assert run(t, [own("s2", "@王 五 单建好了")]) == 1
def test_failed_send_that_was_actually_delivered_is_ours(t, kit, outbox): def test_failed_send_that_was_actually_delivered_is_ours(t, kit, outbox):
outbox.wecom_ok = False # 接口超时报失败,其实发出去了 outbox.wecom_ok = False # 接口超时报失败,其实发出去了
im.send_to(t, REMIND) im.send_to(t, REMIND)
...@@ -211,18 +224,29 @@ def _fired() -> list[tuple[str, str]]: ...@@ -211,18 +224,29 @@ def _fired() -> list[tuple[str, str]]:
def test_fired_note_text(kit): def test_fired_note_text(kit):
"""改推送时间后当天再次触发:说明里写清晚了多久、今天已经触发过。一天多个时刻的任务(预检)不算重复。""" """推送时间改晚、当天再次触发:说明里写清今天已经触发过。一天多个时刻的任务(预检)不算重复。"""
day = dt.date(2026, 10, 22) day = dt.date(2026, 10, 22)
_mark(kit.store_id, "restock", "push", day, "15:00") _mark(kit.store_id, "restock", "push", day, "15:00")
_mark(kit.store_id, "restock", "push", day, "14:30") _mark(kit.store_id, "restock", "push", day, "17:00")
at = lambda h, m: dt.datetime(2026, 10, 22, h, m) # noqa: E731 at = lambda h, m: dt.datetime(2026, 10, 22, h, m) # noqa: E731
note, level = _fired_note(kit.store_id, "restock", "push", at(17, 2), "14:30", ["14:30"]) note, level = _fired_note(kit.store_id, "restock", "push", at(17, 0), "17:00", ["17:00"])
assert level == "warn" and "实际 17:02,晚 152 分钟" in note and "今天已在 15:00 触发过" in note assert level == "warn" and "今天已在 15:00 触发过" in note
for slot in ("14:00", "14:45"): for slot in ("14:00", "14:45"):
_mark(kit.store_id, "restock", "preflight", day, slot) _mark(kit.store_id, "restock", "preflight", day, slot)
assert _fired_note(kit.store_id, "restock", "preflight", at(14, 45), "14:45", ["14:00", "14:45"]) == ("14:45", "info") assert _fired_note(kit.store_id, "restock", "preflight", at(14, 45), "14:45", ["14:00", "14:45"]) == ("14:45", "info")
def _at_1500(kit) -> None:
"""8 点存好参数、14:59 服务在运行,走到 15:00 跑一轮调度。"""
fake_now(hh=8)
features.save(kit.store_id, "restock", values={}, by="test")
s = Scheduler()
for hh, mm in ((14, 59), (15, 0)):
fake_now(hh=hh, mm=mm)
kit.heartbeat()
kit.call(s.tick, True)
def test_tick_emits_note(client, admin, kit, outbox, monkeypatch): def test_tick_emits_note(client, admin, kit, outbox, monkeypatch):
from app.features.restock.service import svc from app.features.restock.service import svc
...@@ -231,11 +255,9 @@ def test_tick_emits_note(client, admin, kit, outbox, monkeypatch): ...@@ -231,11 +255,9 @@ def test_tick_emits_note(client, admin, kit, outbox, monkeypatch):
for name in ("push", "close", "summary", "preflight"): for name in ("push", "close", "summary", "preflight"):
monkeypatch.setattr(svc, name, noop) monkeypatch.setattr(svc, name, noop)
db.q(events_t.delete()) db.q(events_t.delete())
fake_now(hh=15, mm=20) # 服务停到 15:20 才起来:补触发 _at_1500(kit)
kit.heartbeat()
kit.call(scheduler.tick, True)
push = [x for x in _fired() if "定时推送" in x[1]] push = [x for x in _fired() if "定时推送" in x[1]]
assert len(push) == 1 and push[0][0] == "warn" and "15:00,实际 15:20,晚 20 分钟" in push[0][1] assert len(push) == 1 and push[0] == ("info", "定时触发:定时推送补货清单(15:00)")
def test_tick_still_fires_when_note_breaks(client, admin, kit, outbox, monkeypatch): def test_tick_still_fires_when_note_breaks(client, admin, kit, outbox, monkeypatch):
...@@ -252,7 +274,5 @@ def test_tick_still_fires_when_note_breaks(client, admin, kit, outbox, monkeypat ...@@ -252,7 +274,5 @@ def test_tick_still_fires_when_note_breaks(client, admin, kit, outbox, monkeypat
for name in ("close", "summary", "preflight"): for name in ("close", "summary", "preflight"):
monkeypatch.setattr(svc, name, noop) monkeypatch.setattr(svc, name, noop)
monkeypatch.setattr(mod, "_fired_note", lambda *a: 1 / 0) monkeypatch.setattr(mod, "_fired_note", lambda *a: 1 / 0)
fake_now(hh=15) _at_1500(kit)
kit.heartbeat()
kit.call(scheduler.tick, True)
assert ran == ["15:00"] assert ran == ["15:00"]
...@@ -309,6 +309,15 @@ def test_wecom_contacts_picker(client, admin, kit, monkeypatch): ...@@ -309,6 +309,15 @@ def test_wecom_contacts_picker(client, admin, kit, monkeypatch):
r = client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&page=2&size=2", headers=admin).json() r = client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&page=2&size=2", headers=admin).json()
assert r["total"] == 5 and [x["contact_id"] for x in r["rows"]] == ["R:3", "1688"] assert r["total"] == 5 and [x["contact_id"] for x in r["rows"]] == ["R:3", "1688"]
assert [x["kind"] for x in r["rows"]] == ["group", "single"] and r["rows"][1]["type_text"] == "企微同事" assert [x["kind"] for x in r["rows"]] == ["group", "single"] and r["rows"][1]["type_text"] == "企微同事"
# 接收对象选了群聊 / 单人:只查对应的两种;类型和它冲突就拒绝
r = client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&kind=group", headers=admin).json()
assert r["total"] == 3 and {x["kind"] for x in r["rows"]} == {"group"}
calls.clear()
r = client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&kind=single&page=2&size=1", headers=admin).json()
assert r["total"] == 2 and [x["contact_id"] for x in r["rows"]] == ["7881"]
assert {c[1] for c in calls} == {"ww_colleague", "ww_customer"}
for bad in ("kind=group&type=ww_customer", "kind=single&type=ww_group_internal", "kind=x"):
assert client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&{bad}", headers=admin).status_code == 400
# 白名单外的类型、未知机器人都拒绝 # 白名单外的类型、未知机器人都拒绝
assert client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&type=group_member", headers=admin).status_code == 400 assert client.get(f"/api/wecom/contacts?bot_ref={bot_ref}&type=group_member", headers=admin).status_code == 400
assert client.get("/api/wecom/contacts?bot_ref=99999", headers=admin).status_code == 400 assert client.get("/api/wecom/contacts?bot_ref=99999", headers=admin).status_code == 400
...@@ -316,6 +325,63 @@ def test_wecom_contacts_picker(client, admin, kit, monkeypatch): ...@@ -316,6 +325,63 @@ def test_wecom_contacts_picker(client, admin, kit, monkeypatch):
assert client.get(f"/api/wecom/contacts?bot_ref={bot_ref}", headers=admin).status_code == 502 assert client.get(f"/api/wecom/contacts?bot_ref={bot_ref}", headers=admin).status_code == 502
def test_wecom_group_members(client, admin, kit, monkeypatch):
"""群成员:翻页取全、去掉已退群的、去重;网关报错返回 502。"""
from app.services import imhub
rows = [{"userId": 1000 + i, "name": f"成员{i}", "status": 1, "isExternalUser": i % 2} for i in range(60)]
rows[3]["status"] = 0
pages = []
class R:
status_code, text = 200, ""
def __init__(self, body):
self.body = body
def json(self):
return self.body
def fake_get(url, params=None, **kw):
if "/core/bot/" in url:
return R({"bot_id": "bot-1", "wxid": "1005"})
pages.append(params)
st = (params["page"] - 1) * params["page_size"]
return R({"code": "0", "msg": "OK", "total": 60, "data": rows[st:st + params["page_size"]]})
monkeypatch.setattr(imhub.requests, "get", fake_get)
bot_ref = kit.target()["bot_ref"]
r = client.get(f"/api/wecom/members?bot_ref={bot_ref}&group_id=R:1", headers=admin).json()["rows"]
assert len(r) == 59 and r[0] == {"user_id": "1000", "name": "成员0", "external": False, "self": False} and r[1]["external"]
assert [m["user_id"] for m in r if m["self"]] == ["1005"] # 机器人自己:按 user id 认,不看昵称
assert [p["page"] for p in pages] == [1, 2] and pages[0]["robot_key"] == "bot-1" and pages[0]["conversation_id"] == "R:1"
assert client.get("/api/wecom/members?bot_ref=99999&group_id=R:1", headers=admin).status_code == 400
assert client.get(f"/api/wecom/members?bot_ref={bot_ref}&group_id=", headers=admin).status_code == 400
monkeypatch.setattr(imhub.requests, "get", lambda *a, **k: R({"code": "500", "msg": "机器人不在线"}))
r = client.get(f"/api/wecom/members?bot_ref={bot_ref}&group_id=R:1", headers=admin)
assert r.status_code == 502 and "机器人不在线" in r.json()["detail"]
def test_wecom_target_at_people(client, admin, kit, outbox):
"""@ 的人只能是用户 ID;昵称、超过上限都拒绝;姓名只留选中的人;测试消息带上 @。"""
url = f"/api/wecom/targets/{kit.target_id}"
t = kit.target()
body = {k: t[k] for k in ("name", "bot_ref", "kind", "contact_id", "contact_name", "bot_names", "purposes", "alert_min",
"enabled")}
r = client.put(url, json=body | {"at_ids": "1688001,张三"}, headers=admin)
assert r.status_code == 400 and "张三" in r.json()["detail"] and "用户 ID" in r.json()["detail"]
ids = [str(7881300000000000 + i) for i in range(16)]
assert client.put(url, json=body | {"at_ids": ",".join(ids)}, headers=admin).status_code == 400
assert client.put(url, json=body | {"at_ids": ",".join(ids[:15])}, headers=admin).status_code == 200
assert kit.target()["at_ids"].split(",") == ids[:15] # 不截断
r = client.put(url, json=body | {"at_ids": "11, 22,11", "at_names": {"11": "甲", "33": "不在名单"}}, headers=admin)
assert r.status_code == 200
t = kit.target()
assert t["at_ids"] == "11,22" and t["at_names"] == {"11": "甲"}
assert client.post(url + "/test", headers=admin).json()["ok"] and outbox.texts[-1]["at"] == ["11", "22"]
# 改成单人:@ 的人清掉
assert client.put(url, json=body | {"kind": "single", "at_ids": "11"}, headers=admin).status_code == 200
assert kit.target()["at_ids"] is None
# ====================================================================== 助手设置 / 提示词 / 试聊 # ====================================================================== 助手设置 / 提示词 / 试聊
def test_assistant_settings_prompt(client, admin, kit): def test_assistant_settings_prompt(client, admin, kit):
"""后台能改的只有提示词:保存 / 预览 / 恢复默认;话术只用代码版本,库里旧的覆盖行不再生效。""" """后台能改的只有提示词:保存 / 预览 / 恢复默认;话术只用代码版本,库里旧的覆盖行不再生效。"""
......
...@@ -24,7 +24,7 @@ sql_script/ ...@@ -24,7 +24,7 @@ sql_script/
## 部署怎么执行 ## 部署怎么执行
1. **先**执行脚本,**再**发布程序(新程序启动时会检查表结构)。 1. **先**执行脚本,**再**发布程序(新程序启动时会检查表结构)。
2. 全新安装:DBA 建库(`utf8mb4` / `utf8mb4_unicode_ci`)→ 依次执行 `v3.1.0/`、`v3.2.0/` …… 全部目录。 2. 全新安装:DBA 建库(`utf8mb4` / `utf8mb4_unicode_ci`)→ 依次执行 `v3.1.0/`、`v3.2.0/`、`v3.3.0/` …… 全部目录。
3. 升级:只执行「库里版本标记」之后的版本目录。查当前版本: 3. 升级:只执行「库里版本标记」之后的版本目录。查当前版本:
```sql ```sql
SELECT v FROM atrs_sys_config WHERE k = 'db_schema'; SELECT v FROM atrs_sys_config WHERE k = 'db_schema';
......
-- =====================================================================================================
-- v3.3.0 群里 @ 人:接收对象表加 2 个字段(可空,老数据不用补),at_ids 只改注释。
-- at_scenes 为空 = 默认场景(只在要人动手时 @)。
-- ⚠️ 只执行一次(MySQL 的 ADD COLUMN 不能重复执行;字段已存在会报 Duplicate column,可忽略)。
-- =====================================================================================================
ALTER TABLE atrs_im_target MODIFY at_ids VARCHAR(300) NULL COMMENT '群里要 @ 的人(企微 user id,逗号分隔;不是昵称)';
ALTER TABLE atrs_im_target ADD COLUMN at_names JSON NULL COMMENT '@ 的人的姓名 JSON:{user id: 群里的姓名},只用于显示和核对群消息';
ALTER TABLE atrs_im_target ADD COLUMN at_scenes JSON NULL COMMENT '哪些场景要 @ 人 JSON 列表(im.AT_SCENES);空 = 默认场景,[] = 都不 @';
-- 写入表结构版本标记 3.3.0(程序 v3.3.0 启动时要求 ≥ 3.3.0)。必须在本目录其他脚本都执行成功之后再执行。可重复执行。
INSERT INTO atrs_sys_config (k, v, updated_by, updated_at)
VALUES ('db_schema', '{"version": "3.3.0"}', 'sql_script v3.3.0', NOW())
ON DUPLICATE KEY UPDATE v = VALUES(v), updated_by = VALUES(updated_by), updated_at = VALUES(updated_at);
...@@ -190,7 +190,8 @@ const estimate = computed(() => { ...@@ -190,7 +190,8 @@ const estimate = computed(() => {
</template> </template>
<SwitchRow label="每天自动执行" hint="到点预检、到点拉出库明细推送补货推荐。关闭后不预检、不推送,未确认提醒、截单提醒、截单前紧急告警也都不发;仍可在「补货单」点「立即执行补货」手动跑,取数失败重试、每日小结和下面的口径照样生效;SO 单每周同步不受影响。"><el-switch v-model="v.auto_push" /></SwitchRow> <SwitchRow label="每天自动执行" hint="到点预检、到点拉出库明细推送补货推荐。关闭后不预检、不推送,未确认提醒、截单提醒、截单前紧急告警也都不发;仍可在「补货单」点「立即执行补货」手动跑,取数失败重试、每日小结和下面的口径照样生效;SO 单每周同步不受影响。"><el-switch v-model="v.auto_push" /></SwitchRow>
<div class="grid grid-2 mt-3"> <div class="grid grid-2 mt-3">
<el-form-item label="推送时间"> <el-form-item>
<template #label>推送时间<HelpTip text="只有真的走到这个时刻才推送。改成今天已经过去的时间,今天不会推;服务停着错过了也不会补。需要的话到「补货单」点「立即执行补货」。" /></template>
<el-time-select v-model="v.push_time" start="06:00" end="22:00" step="00:15" :clearable="false" :disabled="!v.auto_push" /> <el-time-select v-model="v.push_time" start="06:00" end="22:00" step="00:15" :clearable="false" :disabled="!v.auto_push" />
</el-form-item> </el-form-item>
<el-form-item> <el-form-item>
...@@ -211,7 +212,8 @@ const estimate = computed(() => { ...@@ -211,7 +212,8 @@ const estimate = computed(() => {
</el-form-item> </el-form-item>
</div> </div>
<SwitchRow label="截单后禁止确认(旧规则)" hint="打开后恢复旧规则:过了截单不能刷新 / 确认,截单时把还没完成的定时补货单作废、不顺延。默认关闭(截单只提示风险)。"><el-switch v-model="v.cutoff_hard" /></SwitchRow> <SwitchRow label="截单后禁止确认(旧规则)" hint="打开后恢复旧规则:过了截单不能刷新 / 确认,截单时把还没完成的定时补货单作废、不顺延。默认关闭(截单只提示风险)。"><el-switch v-model="v.cutoff_hard" /></SwitchRow>
<el-form-item label="预检时间"> <el-form-item>
<template #label>预检时间<HelpTip text="只有真的走到这个时刻才预检。改成今天已经过去的时间,今天不会预检,也不会补。" /></template>
<div class="row"> <div class="row">
<el-tag v-for="t in v.preflight_times" :key="t" :closable="v.auto_push" :type="v.auto_push ? 'primary' : 'info'" size="large" @close="v.preflight_times = v.preflight_times.filter((x: string) => x !== t)">{{ t }}</el-tag> <el-tag v-for="t in v.preflight_times" :key="t" :closable="v.auto_push" :type="v.auto_push ? 'primary' : 'info'" size="large" @close="v.preflight_times = v.preflight_times.filter((x: string) => x !== t)">{{ t }}</el-tag>
<el-time-select v-model="newTime" start="06:00" end="22:00" step="00:15" placeholder="添加" class="w-time" :disabled="!v.auto_push" @change="addPreflight" /> <el-time-select v-model="newTime" start="06:00" end="22:00" step="00:15" placeholder="添加" class="w-time" :disabled="!v.auto_push" @change="addPreflight" />
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!