From 9b1f656790f4bbb28fea23404290b17013999f73 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 16 Sep 2026 21:10:15 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20notify.reply=20=E6=94=AF=E6=8C=81=20ext?= =?UTF-8?q?end=5Fprops.do=20=E5=8A=A8=E4=BD=9C=EF=BC=88openDoor=20/=20regi?= =?UTF-8?q?sterLicensePlate=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 入站通知新增两条相互独立的处理线:文本回复 + 动作指令。 - 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。 --- .../new_wms/notify/ActionDispatcher.php | 175 +++++++++++ .../library/new_wms/notify/ReplyHandler.php | 82 ++++- .../library/new_wms/notify/action/Base.php | 283 ++++++++++++++++++ .../new_wms/notify/action/OpenDoor.php | 177 +++++++++++ .../notify/action/RegisterLicensePlate.php | 253 ++++++++++++++++ 5 files changed, 965 insertions(+), 5 deletions(-) create mode 100644 application/index/library/new_wms/notify/ActionDispatcher.php create mode 100644 application/index/library/new_wms/notify/action/Base.php create mode 100644 application/index/library/new_wms/notify/action/OpenDoor.php create mode 100644 application/index/library/new_wms/notify/action/RegisterLicensePlate.php diff --git a/application/index/library/new_wms/notify/ActionDispatcher.php b/application/index/library/new_wms/notify/ActionDispatcher.php new file mode 100644 index 0000000..d119759 --- /dev/null +++ b/application/index/library/new_wms/notify/ActionDispatcher.php @@ -0,0 +1,175 @@ + // 隐藏入参:字符串 / 数字 / 布尔 / 对象 / 数组 / null + * } + * + * 已注册动作: + * openDoor — 远程开门(value: 闸口号 / 对象) + * registerLicensePlate— 登记车牌临时通行 6 小时(value: 车牌号 / 对象) + * + * 与文本回复相互独立: + * - content 非空 → 照常推送到 IM 群 + * - do 非空 → 执行对应动作(content 为空时也要执行,例如纯开门指令) + * + * 新增动作: + * 1. 在 application/index/library/new_wms/notify/action/ 下新建类,继承 action\Base + * 2. 在下面的 $map 里加一行 do => 类名(大小写不敏感匹配) + */ +class ActionDispatcher +{ + /** + * do => 动作类名 + * @var array + */ + private static $map = [ + 'openDoor' => \app\index\library\new_wms\notify\action\OpenDoor::class, + 'registerLicensePlate' => \app\index\library\new_wms\notify\action\RegisterLicensePlate::class, + ]; + + /** + * 已注册的动作名列表 + * @return array + */ + public static function registered() + { + return array_keys(self::$map); + } + + /** + * 注册(或覆盖)一个动作 + * + * @param string $do 动作名(与 extend_props.do 对应) + * @param string $class 动作类名(需继承 action\Base) + */ + public static function register($do, $class) + { + self::$map[trim((string) $do)] = $class; + } + + /** + * 是否存在可执行的动作 + * + * @param mixed $do + * @return bool + */ + public static function has($do) + { + return self::resolve($do) !== null; + } + + /** + * 执行动作 + * + * 不抛异常:动作失败只记录日志并把失败原因带回响应,不影响文本回复流程。 + * + * @param mixed $do extend_props.do + * @param mixed $value extend_props.value,泛类型 + * @param array $data 通知 data 节点 + * @return array|null null = 没有 do,未执行任何动作 + */ + public static function run($do, $value, array $data = []) + { + $do = is_string($do) ? trim($do) : ''; + if ($do === '') { + return null; + } + + $start = microtime(true); + $class = self::resolve($do); + + if (!$class || !class_exists($class)) { + \think\Log::error("[WmsNotify] 动作未注册: do={$do},已注册: " . implode(', ', self::registered())); + return [ + 'do' => $do, + 'ok' => false, + 'msg' => '动作未注册', + 'cost' => self::cost($start), + ]; + } + + try { + /** @var Base $action */ + $action = new $class(); + $result = $action->execute($value, $data); + $cost = self::cost($start); + + \think\Log::info("[WmsNotify] 动作执行成功: do={$do} cost={$cost}ms value=" . self::encode($value) . " result=" . self::encode($result)); + + return [ + 'do' => $do, + 'ok' => true, + 'msg' => 'ok', + 'result' => $result, + 'cost' => $cost, + ]; + } catch (\Throwable $e) { + $cost = self::cost($start); + + \think\Log::error("[WmsNotify] 动作执行失败: do={$do} cost={$cost}ms value=" . self::encode($value) . " err=" . $e->getMessage()); + + return [ + 'do' => $do, + 'ok' => false, + 'msg' => $e->getMessage(), + 'cost' => $cost, + ]; + } + } + + /** + * 解析 do 对应的动作类名(大小写不敏感) + * + * @param mixed $do + * @return string|null + */ + private static function resolve($do) + { + $do = is_string($do) ? trim($do) : ''; + if ($do === '') { + return null; + } + + if (isset(self::$map[$do])) { + return self::$map[$do]; + } + foreach (self::$map as $name => $class) { + if (strcasecmp($name, $do) === 0) { + return $class; + } + } + + return null; + } + + /** + * 计算耗时(毫秒) + * @param float $start + * @return float + */ + private static function cost($start) + { + return round((microtime(true) - $start) * 1000, 2); + } + + /** + * JSON 编码(便于日志查看,失败时退回 var_export) + * @param mixed $value + * @return string + */ + private static function encode($value) + { + $json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + + return $json === false ? var_export($value, true) : $json; + } +} diff --git a/application/index/library/new_wms/notify/ReplyHandler.php b/application/index/library/new_wms/notify/ReplyHandler.php index a81df45..3321bb2 100644 --- a/application/index/library/new_wms/notify/ReplyHandler.php +++ b/application/index/library/new_wms/notify/ReplyHandler.php @@ -9,6 +9,12 @@ namespace app\index\library\new_wms\notify; * 根据 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 { @@ -32,13 +38,22 @@ class ReplyHandler $userName = $data['user_name'] ?? ''; $extData = $data['ext_data'] ?? null; - \think\Log::error("[WmsNotify] reply 入站: type={$type} ext_id={$extId} group={$groupId} user=" . json_encode($userIds, JSON_UNESCAPED_UNICODE) . " content={$content}"); + // ---- 动作指令: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 重试会重新检测) ---- - if ($groupId && $content) { + // 只有确实要发送文本时才检测:content 为空的纯动作请求不应因通道离线被拒绝 + if ($groupId && $sendable) { $isOnline = ($source === 'qiwe') ? OnlineChecker::qiwe() : OnlineChecker::wx(); if (!$isOnline) { \think\Log::error("[WmsNotify] reply 被拒绝: {$source} 不在线"); @@ -64,12 +79,65 @@ class ReplyHandler } } - // ---- 根据 ext_data.source 判断消息来源,发送回复 ---- - if ($groupId && $content) { + // ---- 执行 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' => null]; + 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; } /** @@ -131,6 +199,10 @@ class ReplyHandler '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)); diff --git a/application/index/library/new_wms/notify/action/Base.php b/application/index/library/new_wms/notify/action/Base.php new file mode 100644 index 0000000..a4ca6da --- /dev/null +++ b/application/index/library/new_wms/notify/action/Base.php @@ -0,0 +1,283 @@ + // 隐藏入参,泛类型:字符串/数字/布尔/对象/数组/null + * } + * + * value 的语义由各子类自行解释(见各子类注释),基类只做归一化,方便子类按键取值。 + * + * 约定: + * - 子类实现 run(),返回数组:会写进接口响应与日志,便于排查 + * - 执行失败直接 throw \Exception,由 ActionDispatcher 统一捕获记录,不影响文本回复 + */ +abstract class Base +{ + /** + * extend_props.value 原始值(泛类型,未做任何转换) + * @var mixed + */ + protected $value; + + /** + * 通知 data 原文(group_id / user_id / user_name / group_name / ext_id ...) + * @var array + */ + protected $data = []; + + /** + * 动作名(与 extend_props.do 对应) + * @return string + */ + abstract public function name(); + + /** + * 执行动作 + * + * @param mixed $value extend_props.value,泛类型 + * @param array $data 通知 data 节点 + * @return array 执行结果(写入接口响应与日志) + * @throws \Exception 执行失败时抛出 + */ + abstract public function run($value, array $data); + + /** + * 统一入口:先固化上下文,再执行 + * + * @param mixed $value + * @param array $data + * @return array + */ + public function execute($value, array $data) + { + $this->value = $value; + $this->data = $data; + + return $this->run($value, $data); + } + + // ==================== 公共能力:Redis / 仓库 / 操作人 / 车牌 ==================== + + /** Redis 连接信息(与项目其它地方的硬编码保持一致) */ + const REDIS_HOST = '127.0.0.1'; + const REDIS_PORT = 6379; + const REDIS_AUTH = 'qwe2019@'; + + /** 查不到群对应仓库时的兜底仓库(与 Chat::openD 的硬编码保持一致,子类可覆盖) */ + const DEFAULT_WAREHOUSE_ID = 5400; + + /** 放行缘由中文名(与 Wms::plateresult 的映射保持一致) */ + const TYPE_TEXT = ['daohuo' => '到货', 'tihuo' => '提货']; + + /** + * 连接 Redis 并选择库 + * + * @param int $db 库号 + * @return \Redis + */ + protected function redis($db) + { + $redis = new \Redis(); + $redis->connect(static::REDIS_HOST, static::REDIS_PORT); + $redis->auth(static::REDIS_AUTH); + $redis->select($db); + + return $redis; + } + + /** + * 解析仓库 ID + * + * 顺序:value.warehouseId →(按通知里的 group_id 反查 qiwe_rooms/rooms)→ 兜底仓库 + * + * @param array $data 通知 data 节点 + * @return array ['id' => int, 'from' => string] + * @throws \Exception 三者都取不到时抛出 + */ + protected function resolveWarehouseId(array $data) + { + // 1. value 里显式指定 + $fromValue = $this->param(['warehouseId', 'warehouse', 'wmsWarehouseId']); + if (is_numeric($fromValue) && intval($fromValue) > 0) { + return ['id' => intval($fromValue), 'from' => 'value']; + } + + // 2. 按群 ID 反查(企微群优先,再查微信群) + $groupId = isset($data['group_id']) ? trim(strval($data['group_id'])) : ''; + if ($groupId !== '') { + try { + $room = (new \app\common\model\qiwe\Rooms())->where(['room_id' => $groupId])->find(); + if (!$room) { + $room = (new \app\common\model\Rooms())->where(['room_id' => $groupId])->find(); + } + if ($room && intval($room['WAREHOUSEID']) > 0) { + return ['id' => intval($room['WAREHOUSEID']), 'from' => "group:{$groupId}"]; + } + } catch (\Exception $e) { + \think\Log::error('[' . $this->name() . "] 反查群仓库失败: " . $e->getMessage()); + } + } + + // 3. 兜底默认仓库 + if (static::DEFAULT_WAREHOUSE_ID > 0) { + return ['id' => static::DEFAULT_WAREHOUSE_ID, 'from' => 'default']; + } + + throw new \Exception('无法确定仓库,请在 extend_props.value 里指定 warehouseId'); + } + + /** + * 解析操作人(写日志用):value.username → 通知里的 user_name → '-' + * + * @param array $data + * @return string + */ + protected function resolveUsername(array $data) + { + $username = $this->param(['username', 'userName', 'operator']); + if ($username !== null && !is_array($username) && !is_object($username) && trim(strval($username)) !== '') { + return trim(strval($username)); + } + + $userName = isset($data['user_name']) ? trim(strval($data['user_name'])) : ''; + + return $userName !== '' ? $userName : '-'; + } + + /** + * 从文本中提取车牌号(正则与 Chat::extractLicensePlates 保持一致,如需调整请两处同步) + * + * @param string $string + * @return array 提取到的车牌列表 + */ + protected static function extractLicensePlates($string) + { + if (!is_string($string) || $string === '') { + return []; + } + + $pattern = '/ + (?:[京津沪渝冀豫云辽黑湘晩鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z]| # 普通省份简称+字母 + 京[A-Z]| # 北京特殊格式 + 沪[A-Z]| # 上海特殊格式 + 浙[A-Z]| # 浙江特殊格式 + 苏[A-Z]| # 江苏特殊格式 + 粤Z) # 港澳车牌 + [A-Z0-9]{4,6} # 4-5位字母数字组合 + |WJ\d{4}[A-Z0-9] # 武警车牌 + |[军海空北沈兰济南广成]\w{5} # 军车车牌 + |\d{6}使 # 使馆车牌另一种格式 + /xu'; + + preg_match_all($pattern, $string, $matches); + + return isset($matches[0]) ? $matches[0] : []; + } + + // ==================== 泛类型 value 处理工具 ==================== + + /** + * 把泛类型 value 归一化成关联数组,便于统一按键取值 + * + * null / '' / [] → [] + * 对象 → (array) 转换 + * 数组 → 原样返回 + * JSON 字符串 → 解码为数组('{...}' / '[...]') + * 其他字符串 / 数字 / 布尔 → ['value' => 原值] + * + * @return array + */ + protected function valueParams() + { + $value = $this->value; + + if ($value === null || $value === '' || $value === []) { + return []; + } + if (is_object($value)) { + return (array) $value; + } + if (is_array($value)) { + return $value; + } + if (is_string($value)) { + $trim = trim($value); + if ($trim !== '' && ($trim[0] === '{' || $trim[0] === '[')) { + $json = json_decode($trim, true); + if (is_array($json)) { + return $json; + } + } + return ['value' => $trim]; + } + + return ['value' => $value]; + } + + /** + * 按候选键名取值(忽略大小写、下划线、中划线差异) + * + * $this->param(['warehouseId', 'WAREHOUSEID']) 等价于取 warehouse_id / warehouseid / warehouse-id ... + * + * @param array $keys 候选键名列表 + * @param mixed $default 取不到时的默认值 + * @return mixed + */ + protected function param(array $keys, $default = null) + { + $params = $this->valueParams(); + if (!$params) { + return $default; + } + + // 归一化参数键:小写 + 去掉 _ - + $normalized = []; + foreach ($params as $k => $v) { + $normalized[self::normalizeKey($k)] = $v; + } + + foreach ($keys as $key) { + $nk = self::normalizeKey($key); + if (array_key_exists($nk, $normalized)) { + return $normalized[$nk]; + } + } + + return $default; + } + + /** + * 判断 value 是否为「对象/数组」形态(而非标量) + * @return bool + */ + protected function isStructuredValue() + { + $value = $this->value; + + if (is_array($value) || is_object($value)) { + return true; + } + if (is_string($value)) { + $trim = trim($value); + return $trim !== '' && ($trim[0] === '{' || $trim[0] === '['); + } + + return false; + } + + /** + * 键名归一化:小写并去掉 _ - 空格 + * @param mixed $key + * @return string + */ + protected static function normalizeKey($key) + { + return str_replace(['_', '-', ' '], '', strtolower((string) $key)); + } +} diff --git a/application/index/library/new_wms/notify/action/OpenDoor.php b/application/index/library/new_wms/notify/action/OpenDoor.php new file mode 100644 index 0000000..eafd6c0 --- /dev/null +++ b/application/index/library/new_wms/notify/action/OpenDoor.php @@ -0,0 +1,177 @@ +resolveWarehouseId($data); + $channel = $this->resolveChannel(); + $carnum = $this->resolveCarnum(); + $username = $this->resolveUsername($data); + + $warehouseId = $warehouse['id']; + $redisKey = "{$warehouseId}_channelNum{$channel}"; + + // ---- 1. 写开门标记,设备轮询时执行抬杆 ---- + $redis = $this->redis(self::REDIS_DB); + $redis->setex($redisKey, self::KEY_TTL, 1); + + // ---- 2. 写开门记录(字段与 Configs::open_door 一致) ---- + $logId = $this->writeDoorLog($warehouseId, $carnum, $username); + + return [ + 'warehouseId' => $warehouseId, + 'warehouseBy' => $warehouse['from'], + 'channelNum' => $channel, + 'redisKey' => $redisKey, + 'redisDb' => self::REDIS_DB, + 'ttl' => self::KEY_TTL, + 'carnum' => $carnum, + 'username' => $username, + 'logId' => $logId, + ]; + } + + /** + * 写开门记录到 ye4s_door_log(失败不影响开门,只记日志) + * + * @param int $warehouseId + * @param string $carnum + * @param string $username + * @return int|null 记录 ID + */ + protected function writeDoorLog($warehouseId, $carnum, $username) + { + try { + $logModel = new \app\common\model\door\Log(); + $logModel->save([ + 'WAREHOUSEID' => $warehouseId, + 'carnum' => $carnum, + 'username' => $username, + 'open_time' => time(), + ]); + + return $logModel->id; + } catch (\Exception $e) { + \think\Log::error('[WmsNotify] openDoor 写 door_log 失败: ' . $e->getMessage()); + + return null; + } + } + + // ==================== 参数解析 ==================== + + /** + * 解析闸口号 + * + * 数字/数字字符串 → 闸口号;对象 → channelNum / channel;其余 → 默认闸口 + * + * @return int + * @throws \Exception 闸口号非法时抛出 + */ + private function resolveChannel() + { + $value = $this->value; + + if ($value === null || $value === '' || is_bool($value)) { + return self::DEFAULT_CHANNEL; + } + + if (is_numeric($value)) { + return $this->checkChannel(intval($value)); + } + + $channel = $this->param(['channelNum', 'channel', 'channelNo']); + if ($channel === null || $channel === '') { + return self::DEFAULT_CHANNEL; + } + if (!is_numeric($channel)) { + throw new \Exception("闸口号非法: " . json_encode($channel, JSON_UNESCAPED_UNICODE)); + } + + return $this->checkChannel(intval($channel)); + } + + /** + * 校验闸口号范围 + * @param int $channel + * @return int + * @throws \Exception + */ + private function checkChannel($channel) + { + if ($channel < self::MIN_CHANNEL || $channel > self::MAX_CHANNEL) { + throw new \Exception("闸口号超出范围(" . self::MIN_CHANNEL . "-" . self::MAX_CHANNEL . "): {$channel}"); + } + + return $channel; + } + + /** + * 解析车牌号(仅用于开门记录) + * + * 对象形态取 carnum / plate / license;非数字字符串直接视为车牌。 + * + * @return string + */ + private function resolveCarnum() + { + $carnum = $this->param(['carnum', 'plate', 'license', 'carNo']); + if ($carnum !== null && !is_array($carnum) && !is_object($carnum)) { + return trim(strval($carnum)); + } + + $value = $this->value; + if (is_string($value) && !is_numeric($value)) { + return trim($value); + } + + return ''; + } +} diff --git a/application/index/library/new_wms/notify/action/RegisterLicensePlate.php b/application/index/library/new_wms/notify/action/RegisterLicensePlate.php new file mode 100644 index 0000000..6cdfd0e --- /dev/null +++ b/application/index/library/new_wms/notify/action/RegisterLicensePlate.php @@ -0,0 +1,253 @@ + 'daohuo', + '拉货' => 'daohuo', + '到访' => 'daohuo', + '提货' => 'tihuo', + ]; + + public function name() + { + return 'registerLicensePlate'; + } + + public function run($value, array $data) + { + $carnum = $this->resolveCarnum(); + if ($carnum === '') { + $json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + throw new \Exception('未识别到车牌号: ' . ($json === false ? var_export($value, true) : $json)); + } + + $warehouse = $this->resolveWarehouseId($data); + $type = $this->resolveType(); + $roomName = $this->resolveRoomName($data); + $username = $this->resolveUsername($data); + + $payload = [ + 'roomName' => $roomName, + 'UserName' => $username, + 'type' => $type, + 'source' => 'new_wms', + 'ext_id' => isset($data['ext_id']) ? strval($data['ext_id']) : '', + 'registered_at' => date('Y-m-d H:i:s'), + ]; + + $storeId = $this->param(['storeId', 'storeid', 'STOREID']); + if (is_numeric($storeId) && intval($storeId) > 0) { + $payload['STOREID'] = intval($storeId); + } + + $redisKey = "{$warehouse['id']}_{$carnum}"; + $redis = $this->redis(self::REDIS_DB); + + // NX:已登记的车牌不覆盖、不重置有效期 + $ok = $redis->set( + $redisKey, + json_encode($payload, JSON_UNESCAPED_UNICODE), + ['NX', 'EX' => self::KEY_TTL] + ); + + if ($ok === false || $ok === null) { + // 已存在:读回原登记信息与剩余有效期,不重置 + $old = json_decode(strval($redis->get($redisKey)), true); + $ttl = $redis->ttl($redisKey); + + return [ + 'registered' => false, + 'msg' => '该车牌已在临时通行中,未重置有效期', + 'carnum' => $carnum, + 'warehouseId'=> $warehouse['id'], + 'warehouseBy'=> $warehouse['from'], + 'redisKey' => $redisKey, + 'redisDb' => self::REDIS_DB, + 'remain' => ($ttl > 0 ? $ttl : null), + 'exist' => is_array($old) ? $old : null, + ]; + } + + return [ + 'registered' => true, + 'msg' => '登记成功', + 'carnum' => $carnum, + 'warehouseId'=> $warehouse['id'], + 'warehouseBy'=> $warehouse['from'], + 'redisKey' => $redisKey, + 'redisDb' => self::REDIS_DB, + 'type' => $type, + 'typeText' => self::TYPE_TEXT[$type] ?? $type, + 'ttl' => self::KEY_TTL, + 'expireAt' => date('Y-m-d H:i:s', time() + self::KEY_TTL), + 'roomName' => $roomName, + 'username' => $username, + ]; + } + + // ==================== 参数解析 ==================== + + /** + * 解析车牌号 + * + * value.carnum/plate → 标量 value → 结构化 value 各标量值拼接,然后统一走车牌正则; + * 自由文本必须能识别出标准车牌,只有显式传的 carnum 字段才允许非标准格式。 + * + * @return string 大写车牌,取不到返回 '' + */ + private function resolveCarnum() + { + $explicit = $this->param(['carnum', 'plate', 'license', 'carNo']); + if (is_array($explicit) || is_object($explicit)) { + $explicit = null; + } + + // 待解析原文:显式字段优先,其次标量 value,最后结构化 value 的标量值拼接 + if ($explicit !== null && trim(strval($explicit)) !== '') { + $raw = trim(strval($explicit)); + } elseif ($this->isStructuredValue()) { + $raw = trim(implode(' ', array_map('strval', $this->valueParams()))); + } elseif (is_scalar($this->value)) { + $raw = trim(strval($this->value)); + } else { + $raw = ''; + } + + if ($raw === '') { + return ''; + } + + // 1. 标准车牌:统一大写再提取(兼容小写写法与文本夹带) + $plates = self::extractLicensePlates(strtoupper($raw)); + if ($plates) { + return $plates[0]; + } + + // 2. 显式字段允许非标准格式(如临时车牌),但必须是「像车牌的短 token」 + if ($explicit !== null && $this->isPlateToken($raw)) { + return strtoupper($raw); + } + + return ''; + } + + /** + * 是否为「像车牌的短 token」:无空白且长度 2-12 + * + * @param string $text + * @return bool + */ + private function isPlateToken($text) + { + if ($text === '' || preg_match('/\s/u', $text)) { + return false; + } + + $len = mb_strlen($text, 'UTF-8'); + + return $len >= 2 && $len <= 12; + } + + /** + * 解析放行缘由:value.type → 文本关键字(到货/提货等)→ 默认 daohuo + * + * @return string daohuo / tihuo + * @throws \Exception 非法值时抛出 + */ + private function resolveType() + { + $type = $this->param(['type', 'reason']); + if ($type === null || trim(strval($type)) === '') { + $type = $this->inferTypeFromText(); + } + if ($type === null || trim(strval($type)) === '') { + return self::DEFAULT_TYPE; + } + + $type = trim(strval($type)); + if (isset(self::TYPE_ALIAS[$type])) { + $type = self::TYPE_ALIAS[$type]; + } + + if (!isset(self::TYPE_TEXT[$type])) { + throw new \Exception("放行缘由非法({$type}),仅支持: " . implode(' / ', array_keys(self::TYPE_TEXT))); + } + + return $type; + } + + /** + * 从标量 value 文本里推断放行缘由(如「提货 粤EH33333」→ tihuo) + * + * 结构化 value 只认显式 type,不做关键字猜词。 + * + * @return string|null + */ + private function inferTypeFromText() + { + if ($this->isStructuredValue() || !is_scalar($this->value)) { + return null; + } + + $text = strval($this->value); + foreach (self::TYPE_ALIAS as $keyword => $type) { + if (strpos($text, $keyword) !== false) { + return $type; + } + } + + return null; + } + + /** + * 解析放行群名(仅记录用):value.roomName → 通知里的 group_name → '' + * + * @param array $data + * @return string + */ + private function resolveRoomName(array $data) + { + $roomName = $this->param(['roomName', 'room', 'groupName']); + if ($roomName !== null && !is_array($roomName) && !is_object($roomName) && trim(strval($roomName)) !== '') { + return trim(strval($roomName)); + } + + return isset($data['group_name']) ? trim(strval($data['group_name'])) : ''; + } +}