0, 'msg' => 'Agent 控制器已加载', 'time' => date('Y-m-d H:i:s')]); } /** * 定时任务入口:AI 胶印报工核查 → 入库 agent_难度系数校验结果 */ public function workReportAudit() { $cfg = $this->agentConfig(); // 1. 校验 key $key = (string)$this->request->param('key', ''); if (empty($cfg['cron_key']) || !hash_equals((string)$cfg['cron_key'], $key)) { return json(['code' => 1, 'msg' => '无权限']); } if (empty($cfg['user_id']) || empty($cfg['password'])) { return json(['code' => 1, 'msg' => '请先在 application/extra/agent.php 配置 user_id 和 password']); } $date = $this->request->param('date') ?: date('Y-m-d'); $base = rtrim($cfg['base_url'], '/'); $timeout = (int)$cfg['timeout']; try { // 2. 登录 $loginResp = $this->http('POST', $base . $cfg['login_path'], [ 'user_id' => $cfg['user_id'], 'password' => $cfg['password'], ], null, $timeout); $token = isset($loginResp['access_token']) ? $loginResp['access_token'] : ''; if (!$token) { throw new \RuntimeException('登录失败:' . json_encode($loginResp, JSON_UNESCAPED_UNICODE)); } // 3. 验证登录 $this->http('GET', $base . $cfg['me_path'], null, $token, $timeout); // 4. 提问 $askResp = $this->http('POST', $base . $cfg['ask_path'], [ 'skill_id' => $cfg['skill_id'], 'question' => $date . $cfg['question_suffix'], 'params' => new \stdClass(), 'include_knowledge' => false, ], $token, $timeout); if (empty($askResp['ok']) || empty($askResp['rows']) || !is_array($askResp['rows'])) { throw new \RuntimeException('ask 接口无数据:' . json_encode($askResp, JSON_UNESCAPED_UNICODE)); } // 5. 入库 $saved = $this->saveRows($askResp['rows']); return json([ 'code' => 0, 'msg' => '成功', 'data' => [ 'date' => $date, 'rows' => count($askResp['rows']), 'saved' => $saved, ], ]); } catch (\Exception $e) { return json(['code' => 1, 'msg' => $e->getMessage()]); } } /** * 批量入库 agent_难度系数校验结果 * 数据一致则跳过,不一致才更新,新增才插入 */ private function saveRows($rows) { $data = []; $reportIds = []; foreach ($rows as $row) { if (empty($row['report_id'])) { continue; } $reportIds[] = (int)$row['report_id']; $data[] = [ 'UniqId' => (int)$row['report_id'], '工单编号' => $this->str($row, 'work_order_no', 64), 'sczl_yino' => $this->str($row, 'yjno_no', 64), 'sczl_gxh' => $this->str($row, 'gxh_no', 32), 'sczl_jtbh' => $this->str($row, 'machine_no', 255), 'sczl_rq' => $this->datetime($row, 'report_date'), 'product_code' => $this->str($row, 'product_code', 255), 'product_name' => $this->str($row, 'product_name', 255), 'inventory_spec' => $this->str($row, 'inventory_spec', 255), 'machine_class' => $this->str($row, 'machine_class', 255), 'color_count' => $this->str($row, 'color_count', 255), 'market' => $this->str($row, 'market', 255), 'box_type' => $this->str($row, 'box_type', 255), 'base_wage_coef' => $this->str($row, 'base_wage_coef', 255), 'suggested_wage_coef' => $this->str($row, 'suggested_wage_coef', 255), 'wage_coef' => $this->str($row, 'wage_coef', 255), 'audit_result' => $this->str($row, 'audit_result', 120), 'audit_note' => $this->str($row, 'audit_note', 100), ]; } if (!$data) { return 0; } // 查已有数据,按 UniqId 索引 $exist = Db::name('agent_难度系数校验结果')->where('UniqId', 'in', $reportIds)->column('*', 'UniqId'); $insertData = []; $updateData = []; foreach ($data as $item) { $uid = $item['UniqId']; if (!isset($exist[$uid])) { // 不存在 → 插入 $insertData[] = $item; } else { // 存在 → 对比字段是否变化 $old = $exist[$uid]; $changed = false; foreach ($item as $k => $v) { if ($k === 'UniqId') continue; // 数据库返回的可能是 null,新数据也可能是 null,统一转字符串比较 $oldVal = isset($old[$k]) ? (string)$old[$k] : ''; $newVal = $v !== null ? (string)$v : ''; if ($oldVal !== $newVal) { $changed = true; break; } } if ($changed) { $updateData[] = $item; } } } $saved = 0; // 批量插入 if ($insertData) { $cols = array_keys($insertData[0]); $colSql = '`' . implode('`,`', $cols) . '`'; $bind = []; $values = []; foreach ($insertData as $item) { $ph = []; foreach ($cols as $c) { $ph[] = '?'; $bind[] = $item[$c]; } $values[] = '(' . implode(',', $ph) . ')'; } $sql = 'INSERT INTO `agent_难度系数校验结果` (' . $colSql . ') VALUES ' . implode(',', $values); Db::execute($sql, $bind); $saved += count($insertData); } // 逐条更新(有变化的才更新) foreach ($updateData as $item) { $uid = $item['UniqId']; unset($item['UniqId']); Db::name('agent_难度系数校验结果')->where('UniqId', $uid)->update($item); $saved++; } return $saved; } private function str($row, $key, $length) { if (!isset($row[$key]) || $row[$key] === null) { return null; } return mb_substr((string)$row[$key], 0, $length, 'UTF-8'); } private function datetime($row, $key) { if (empty($row[$key])) { return null; } $ts = strtotime($row[$key]); return $ts ? date('Y-m-d H:i:s', $ts) : null; } private function http($method, $url, $body = null, $token = null, $timeout = 60) { $ch = curl_init(); $headers = ['Accept: application/json']; if ($body !== null) { $headers[] = 'Content-Type: application/json'; } if ($token) { $headers[] = 'Authorization: Bearer ' . $token; } $opts = [ CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLOPT_CONNECTTIMEOUT => 15, CURLOPT_TIMEOUT => $timeout, CURLOPT_HTTPHEADER => $headers, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false, ]; if ($method === 'POST') { $opts[CURLOPT_POST] = true; $opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE); } curl_setopt_array($ch, $opts); $resp = curl_exec($ch); $err = curl_error($ch); $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($resp === false) { throw new \RuntimeException('请求失败:' . $err); } $json = json_decode($resp, true); if (!is_array($json)) { throw new \RuntimeException('返回非 JSON:' . mb_substr($resp, 0, 200)); } if ($code >= 400) { $msg = isset($json['detail']) ? json_encode($json['detail'], JSON_UNESCAPED_UNICODE) : $resp; throw new \RuntimeException('HTTP ' . $code . ':' . mb_substr($msg, 0, 300)); } return $json; } /** * 前端调用:AI 制程检验报表查询 * POST /api/agent/inspectionAsk * * 请求体: * skill_id string 技能 ID,默认 inspection_analysis * question string 问题/工单号 * mode string summary|detail,默认 summary * * 返回 AI 平台 ask 接口的完整 JSON(ok/columns/rows/request_id/...) */ public function inspectionAsk() { $cfg = $this->agentConfig(); $base = rtrim($cfg['base_url'], '/'); $timeout = (int)$cfg['timeout']; $skillId = (string)$this->request->param('skill_id', 'inspection_analysis'); $question = (string)$this->request->param('question', ''); $mode = (string)$this->request->param('mode', 'summary'); if ($question === '') { return json(['code' => 0, 'msg' => '成功', 'data' => ['ok' => false, 'detail' => 'question 不能为空']]); } // 账号优先级:前端传 user_id > 配置默认 admin $userId = (string)$this->request->param('user_id', $cfg['user_id']); // admin 账号强制使用专用密码,其他账号取前端传值或默认 12345678 if ($userId === 'admin') { $password = 'b4f3e215f25d4413ce'; } else { $password = (string)$this->request->param('password', '12345678'); } try { // 1. 登录 $loginResp = $this->http('POST', $base . $cfg['login_path'], [ 'user_id' => $userId, 'password' => $password, ], null, $timeout); $token = isset($loginResp['access_token']) ? $loginResp['access_token'] : ''; if (!$token) { return json(['code' => 0, 'msg' => '成功', 'data' => [ 'ok' => false, 'detail' => 'AI 平台登录失败:' . json_encode($loginResp, JSON_UNESCAPED_UNICODE), ]]); } // 2. 提问 $askResp = $this->http('POST', $base . $cfg['ask_path'], [ 'skill_id' => $skillId, 'question' => $question, 'params' => new \stdClass(), 'include_knowledge' => false, 'mode' => $mode, ], $token, $timeout); return json(['code' => 0, 'msg' => '成功', 'data' => $askResp]); } catch (\Exception $e) { return json(['code' => 0, 'msg' => '成功', 'data' => ['ok' => false, 'detail' => $e->getMessage()]]); } } /** * 前端调用:按产品名称查找同类产品检验报告(宝塔 public/uploads/Inspection 下的 word 文档) * GET /api/agent/getInspectionDoc?cpmc=产品名称 * * 返回 data.found=true 时附带 base64 文件内容,前端直接渲染预览 */ public function getInspectionDoc() { $cpmc = trim((string)$this->request->param('cpmc', '')); if ($cpmc === '') { return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '产品名称为空']]); } $dir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Inspection' . DS; if (!is_dir($dir)) { return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告目录不存在:uploads/Inspection']]); } // 收集可用文档(word / pdf) $candidates = []; foreach ((array)@scandir($dir) as $file) { if ($file === '.' || $file === '..') { continue; } $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION)); if (!in_array($ext, ['docx', 'doc', 'pdf'], true)) { continue; } $candidates[] = [ 'file' => $file, 'base' => pathinfo($file, PATHINFO_FILENAME), 'ext' => $ext, 'norm' => $this->normalizeName(pathinfo($file, PATHINFO_FILENAME)), ]; } if (!$candidates) { return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告目录下暂无文档']]); } $target = $this->normalizeName($cpmc); $match = null; // 1. 完全匹配 foreach ($candidates as $item) { if ($item['norm'] === $target) { $match = $item; break; } } // 2. 包含匹配,取名称最长的(最贴近产品名称) if (!$match) { foreach ($candidates as $item) { if ($item['norm'] !== '' && (strpos($item['norm'], $target) !== false || strpos($target, $item['norm']) !== false)) { if (!$match || mb_strlen($item['norm']) > mb_strlen($match['norm'])) { $match = $item; } } } } if (!$match) { return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '未找到产品「' . $cpmc . '」对应的报告文档']]); } $path = $dir . $match['file']; $size = (int)@filesize($path); if ($size <= 0) { return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档为空']]); } if ($size > 10 * 1024 * 1024) { return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档超过 10MB,建议转换为 PDF 后再预览']]); } $content = @file_get_contents($path); if ($content === false) { return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档读取失败']]); } return json(['code' => 0, 'msg' => '成功', 'data' => [ 'found' => true, 'name' => $match['file'], 'ext' => $match['ext'], 'size' => $size, 'content' => base64_encode($content), ]]); } /** * 名称归一化:去掉空白字符并转小写,用于产品名称与文件名的模糊匹配 */ private function normalizeName($name) { $name = preg_replace('/\s+/u', '', (string)$name); return mb_strtolower($name, 'UTF-8'); } /** * 读 application/extra/agent.php */ private function agentConfig() { $cfgFile = APP_PATH . 'extra' . DS . 'agent' . EXT; return is_file($cfgFile) ? include $cfgFile : []; } }