liufumingren 9b1f656790 feat: notify.reply 支持 extend_props.do 动作(openDoor / registerLicensePlate)
入站通知新增两条相互独立的处理线:文本回复 + 动作指令。

- content trim 后为空(含纯空白)→ 不对外发送,并跳过 IM 通道在线检测,
  避免纯动作请求被 503 拒绝、WMS 反复重试;ext_id 幂等去重仍生效。
- extend_props.do 映射到 notify/action/ 下的动作类(大小写不敏感),
  extend_props.value 为泛类型入参(字符串/数字/布尔/对象/数组/JSON/null)。
- 新增 openDoor:Redis db2 写 {WAREHOUSEID}_channelNum{N}(TTL 300s)+ 写 door_log。
- 新增 registerLicensePlate:Redis db7 写 {WAREHOUSEID}_{车牌} NX EX 21600(6 小时临时通行),
  与 Chat::daohuo()/tihuo() 同一套机制,入口设备读到即放行并删键。
- 公共能力(Redis 连接、仓库解析、操作人解析、车牌提取)上移到 action/Base,
  两个动作共用;仓库解析顺序:value.warehouseId → group_id 反查群 → 默认 5400。
2026-09-16 21:10:15 +08:00

214 lines
8.0 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace app\index\library\new_wms\notify;
/**
* notify.reply — 消息回复通知
*
* WMS 处理入站消息后,将 AI 回复/绑群结果/面单余额推送到外部系统。
* 根据 data.type 区分:ai / bind / balance / error
*
* 回复消息通过 Redis 队列发送到对应的 IM 群聊。
*
* 两条相互独立的处理线:
* 1. 文本回复:data.content 非空才推送;为空字符串(含纯空白)时不做任何对外发送。
* 2. 动作指令:data.extend_props.do 指定动作(映射见 ActionDispatcher),
* data.extend_props.value 为隐藏入参(泛类型:字符串/数字/对象/数组/null),
* 例如 {"do":"openDoor"} 执行开门。content 为空时动作照常执行。
*/
class ReplyHandler
{
/**
* 处理 reply 通知
*
* @param array $body 请求体 { code, data: { type, content, ext_id, group_id, user_id, ... } }
* @param array $query URL query 参数
* @return array
*/
public function handle(array $body, array $query)
{
$data = $body['data'] ?? [];
$type = $data['type'] ?? '';
$content = $data['content'] ?? '';
$extId = $data['ext_id'] ?? '';
$groupId = $data['group_id'] ?? '';
$userIds = self::parseUserIds($data['user_id'] ?? '');
$groupName = $data['group_name'] ?? '';
$userName = $data['user_name'] ?? '';
$extData = $data['ext_data'] ?? null;
// ---- 动作指令:extend_props.{do, value} ----
$extendProps = $data['extend_props'] ?? null;
$do = is_array($extendProps) ? ($extendProps['do'] ?? '') : '';
$doValue = is_array($extendProps) ? ($extendProps['value'] ?? null) : null;
// ---- 文本内容:trim 后为空视为「无内容」,不对外发送(例如纯开门指令) ----
$sendable = self::isSendableContent($content);
\think\Log::error("[WmsNotify] reply 入站: type={$type} ext_id={$extId} group={$groupId} user=" . json_encode($userIds, JSON_UNESCAPED_UNICODE) . " content=" . self::encodeLog($content) . " do=" . self::encodeLog($do) . " value=" . self::encodeLog($doValue) . " sendable=" . ($sendable ? '1' : '0'));
// ---- 根据 ext_data.source 判断消息来源 ----
$source = is_array($extData) ? ($extData['source'] ?? 'wx') : 'wx';
// ---- 检测对应 IM 通道是否在线(放在去重之前,离线时不写去重键,WMS 重试会重新检测) ----
// 只有确实要发送文本时才检测:content 为空的纯动作请求不应因通道离线被拒绝
if ($groupId && $sendable) {
$isOnline = ($source === 'qiwe') ? OnlineChecker::qiwe() : OnlineChecker::wx();
if (!$isOnline) {
\think\Log::error("[WmsNotify] reply 被拒绝: {$source} 不在线");
return ['code' => 503, 'msg' => "{$source} offline", 'data' => null];
}
}
// ---- 幂等去重 ----
if ($extId) {
try {
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('qwe2019@');
$redis->select(3);
$dedupeKey = "wms_reply:{$extId}";
if ($redis->exists($dedupeKey)) {
\think\Log::info("[WmsNotify] reply 重复推送已忽略: ext_id={$extId}");
return ['code' => 200, 'msg' => 'duplicate', 'data' => null];
}
$redis->setex($dedupeKey, 3600, 1);
} catch (\Exception $e) {
// Redis 不可用时跳过去重,不阻塞
}
}
// ---- 执行 extend_props.do 指定的动作(与文本回复相互独立,content 为空时也执行) ----
$actionResult = ActionDispatcher::run($do, $doValue, $data);
// ---- 根据 ext_data.source 判断消息来源,发送回复(content 为空则跳过) ----
$sent = false;
if ($groupId && $sendable) {
$this->sendToGroup($groupId, $content, $userIds, $source);
$sent = true;
} elseif (!$sendable) {
\think\Log::info("[WmsNotify] reply content 为空,跳过对外发送: ext_id={$extId} group={$groupId}");
}
return [
'code' => 200,
'msg' => 'ok',
'data' => [
'sent' => $sent,
'action' => $actionResult,
],
];
}
/**
* 判断 content 是否需要对外发送
*
* 空字符串(含纯空白)视为无内容不发送;数字 0 / '0'、布尔 true 等仍然发送。
*
* @param mixed $content
* @return bool
*/
private static function isSendableContent($content)
{
if (is_string($content)) {
return trim($content) !== '';
}
if (is_bool($content) || $content === null) {
return false;
}
if (is_numeric($content)) {
return true;
}
return !empty($content);
}
/**
* 日志用的值格式化(字符串原样,其他转 JSON)
*
* @param mixed $value
* @return string
*/
private static function encodeLog($value)
{
if (is_string($value)) {
return $value;
}
$json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
return $json === false ? var_export($value, true) : $json;
}
/**
* 解析 user_id 为数组
*
* 支持以下形式:
* - 数组: ['U001', 'U002']
* - 逗号/空格/分号等分隔字符串: 'U001,U002'、'U001,U002'
* - 单个字符串: 'U001'
* - 纯数字: 12345(JSON 未加引号时)
* 其他类型(null / 对象等)返回空数组。
*
* @param mixed $userId
* @return array 去空去重后的用户 ID 列表(保持顺序)
*/
private static function parseUserIds($userId)
{
if (is_array($userId)) {
$list = $userId;
} elseif (is_string($userId) && trim($userId) !== '') {
$list = preg_split('/[,,、;;|\s]+/u', trim($userId));
} elseif (is_numeric($userId)) {
// 纯数字用户 ID(JSON 未加引号时)
$list = [strval($userId)];
} else {
$list = [];
}
$list = array_map('strval', (array) $list);
$list = array_filter($list, function ($v) {
return $v !== '';
});
return array_values(array_unique($list));
}
/**
* 发送回复消息到 IM 群
*
* 多 @ 兼容两端消费协议:atid 使用逗号拼接多个用户 ID,单条入队。
* - wx 端消费程序原生支持逗号分隔多 atid
* - qiwe 端消费时拆分为多个 subtype:1 项逐个 @
*/
private function sendToGroup($groupId, $content, array $userIds, $source)
{
try {
$redis = new \Redis();
$redis->connect('127.0.0.1', 6379);
$redis->auth('qwe2019@');
$redis->select(2);
// 根据 ext_data.source 选择对应队列
$msgKey = ($source === 'qiwe') ? 'QiweMessage' : 'Message';
$msg = [
'method' => 'sendText',
'wxid' => $groupId,
'msg' => $content,
'atid' => implode(',', $userIds),
'pid' => 0,
];
//企微队列追加入队时间,便于排查与按时间清理积压
if ($msgKey === 'QiweMessage') {
$msg['ts'] = date('Y-m-d H:i:s');
}
$redis->lpush($msgKey, json_encode($msg));
\think\Log::info("[WmsNotify] reply 已发送: source={$source} group={$groupId} key={$msgKey} atUsers=" . json_encode($userIds, JSON_UNESCAPED_UNICODE));
} catch (\Exception $e) {
\think\Log::error("[WmsNotify] reply 发送失败: " . $e->getMessage());
}
}
}