Agent.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. <?php
  2. namespace app\api\controller;
  3. use think\Controller;
  4. use think\Db;
  5. /**
  6. * AI 报工核查(胶印难度系数)
  7. *
  8. * 不继承 Api 基类,避免被 FastAdmin 登录鉴权拦截。
  9. * 用 URL 参数 key 做简单校验。
  10. *
  11. * 用法(宝塔计划任务每 30 分钟访问一次):
  12. * GET /api/agent/workReportAudit?key=你的cron_key
  13. * GET /api/agent/workReportAudit?key=你的cron_key&date=2026-11-07
  14. */
  15. class Agent extends Controller
  16. {
  17. /**
  18. * 测试入口:验证路由是否通
  19. * GET /api/agent/index
  20. */
  21. public function index()
  22. {
  23. return json(['code' => 0, 'msg' => 'Agent 控制器已加载', 'time' => date('Y-m-d H:i:s')]);
  24. }
  25. /**
  26. * 定时任务入口:AI 胶印报工核查 → 入库 agent_难度系数校验结果
  27. */
  28. public function workReportAudit()
  29. {
  30. $cfg = $this->agentConfig();
  31. // 1. 校验 key
  32. $key = (string)$this->request->param('key', '');
  33. if (empty($cfg['cron_key']) || !hash_equals((string)$cfg['cron_key'], $key)) {
  34. return json(['code' => 1, 'msg' => '无权限']);
  35. }
  36. if (empty($cfg['user_id']) || empty($cfg['password'])) {
  37. return json(['code' => 1, 'msg' => '请先在 application/extra/agent.php 配置 user_id 和 password']);
  38. }
  39. $date = $this->request->param('date') ?: date('Y-m-d');
  40. $base = rtrim($cfg['base_url'], '/');
  41. $timeout = (int)$cfg['timeout'];
  42. try {
  43. // 2. 登录
  44. $loginResp = $this->http('POST', $base . $cfg['login_path'], [
  45. 'user_id' => $cfg['user_id'],
  46. 'password' => $cfg['password'],
  47. ], null, $timeout);
  48. $token = isset($loginResp['access_token']) ? $loginResp['access_token'] : '';
  49. if (!$token) {
  50. throw new \RuntimeException('登录失败:' . json_encode($loginResp, JSON_UNESCAPED_UNICODE));
  51. }
  52. // 3. 验证登录
  53. $this->http('GET', $base . $cfg['me_path'], null, $token, $timeout);
  54. // 4. 提问
  55. $askResp = $this->http('POST', $base . $cfg['ask_path'], [
  56. 'skill_id' => $cfg['skill_id'],
  57. 'question' => $date . $cfg['question_suffix'],
  58. 'params' => new \stdClass(),
  59. 'include_knowledge' => false,
  60. ], $token, $timeout);
  61. if (empty($askResp['ok']) || empty($askResp['rows']) || !is_array($askResp['rows'])) {
  62. throw new \RuntimeException('ask 接口无数据:' . json_encode($askResp, JSON_UNESCAPED_UNICODE));
  63. }
  64. // 5. 入库
  65. $saved = $this->saveRows($askResp['rows']);
  66. return json([
  67. 'code' => 0,
  68. 'msg' => '成功',
  69. 'data' => [
  70. 'date' => $date,
  71. 'rows' => count($askResp['rows']),
  72. 'saved' => $saved,
  73. ],
  74. ]);
  75. } catch (\Exception $e) {
  76. return json(['code' => 1, 'msg' => $e->getMessage()]);
  77. }
  78. }
  79. /**
  80. * 批量入库 agent_难度系数校验结果
  81. * 数据一致则跳过,不一致才更新,新增才插入
  82. */
  83. private function saveRows($rows)
  84. {
  85. $data = [];
  86. $reportIds = [];
  87. foreach ($rows as $row) {
  88. if (empty($row['report_id'])) {
  89. continue;
  90. }
  91. $reportIds[] = (int)$row['report_id'];
  92. $data[] = [
  93. 'UniqId' => (int)$row['report_id'],
  94. '工单编号' => $this->str($row, 'work_order_no', 64),
  95. 'sczl_yino' => $this->str($row, 'yjno_no', 64),
  96. 'sczl_gxh' => $this->str($row, 'gxh_no', 32),
  97. 'sczl_jtbh' => $this->str($row, 'machine_no', 255),
  98. 'sczl_rq' => $this->datetime($row, 'report_date'),
  99. 'product_code' => $this->str($row, 'product_code', 255),
  100. 'product_name' => $this->str($row, 'product_name', 255),
  101. 'inventory_spec' => $this->str($row, 'inventory_spec', 255),
  102. 'machine_class' => $this->str($row, 'machine_class', 255),
  103. 'color_count' => $this->str($row, 'color_count', 255),
  104. 'market' => $this->str($row, 'market', 255),
  105. 'box_type' => $this->str($row, 'box_type', 255),
  106. 'base_wage_coef' => $this->str($row, 'base_wage_coef', 255),
  107. 'suggested_wage_coef' => $this->str($row, 'suggested_wage_coef', 255),
  108. 'wage_coef' => $this->str($row, 'wage_coef', 255),
  109. 'audit_result' => $this->str($row, 'audit_result', 120),
  110. 'audit_note' => $this->str($row, 'audit_note', 100),
  111. ];
  112. }
  113. if (!$data) {
  114. return 0;
  115. }
  116. // 查已有数据,按 UniqId 索引
  117. $exist = Db::name('agent_难度系数校验结果')->where('UniqId', 'in', $reportIds)->column('*', 'UniqId');
  118. $insertData = [];
  119. $updateData = [];
  120. foreach ($data as $item) {
  121. $uid = $item['UniqId'];
  122. if (!isset($exist[$uid])) {
  123. // 不存在 → 插入
  124. $insertData[] = $item;
  125. } else {
  126. // 存在 → 对比字段是否变化
  127. $old = $exist[$uid];
  128. $changed = false;
  129. foreach ($item as $k => $v) {
  130. if ($k === 'UniqId') continue;
  131. // 数据库返回的可能是 null,新数据也可能是 null,统一转字符串比较
  132. $oldVal = isset($old[$k]) ? (string)$old[$k] : '';
  133. $newVal = $v !== null ? (string)$v : '';
  134. if ($oldVal !== $newVal) {
  135. $changed = true;
  136. break;
  137. }
  138. }
  139. if ($changed) {
  140. $updateData[] = $item;
  141. }
  142. }
  143. }
  144. $saved = 0;
  145. // 批量插入
  146. if ($insertData) {
  147. $cols = array_keys($insertData[0]);
  148. $colSql = '`' . implode('`,`', $cols) . '`';
  149. $bind = [];
  150. $values = [];
  151. foreach ($insertData as $item) {
  152. $ph = [];
  153. foreach ($cols as $c) {
  154. $ph[] = '?';
  155. $bind[] = $item[$c];
  156. }
  157. $values[] = '(' . implode(',', $ph) . ')';
  158. }
  159. $sql = 'INSERT INTO `agent_难度系数校验结果` (' . $colSql . ') VALUES ' . implode(',', $values);
  160. Db::execute($sql, $bind);
  161. $saved += count($insertData);
  162. }
  163. // 逐条更新(有变化的才更新)
  164. foreach ($updateData as $item) {
  165. $uid = $item['UniqId'];
  166. unset($item['UniqId']);
  167. Db::name('agent_难度系数校验结果')->where('UniqId', $uid)->update($item);
  168. $saved++;
  169. }
  170. return $saved;
  171. }
  172. private function str($row, $key, $length)
  173. {
  174. if (!isset($row[$key]) || $row[$key] === null) {
  175. return null;
  176. }
  177. return mb_substr((string)$row[$key], 0, $length, 'UTF-8');
  178. }
  179. private function datetime($row, $key)
  180. {
  181. if (empty($row[$key])) {
  182. return null;
  183. }
  184. $ts = strtotime($row[$key]);
  185. return $ts ? date('Y-m-d H:i:s', $ts) : null;
  186. }
  187. private function http($method, $url, $body = null, $token = null, $timeout = 60)
  188. {
  189. $ch = curl_init();
  190. $headers = ['Accept: application/json'];
  191. if ($body !== null) {
  192. $headers[] = 'Content-Type: application/json';
  193. }
  194. if ($token) {
  195. $headers[] = 'Authorization: Bearer ' . $token;
  196. }
  197. $opts = [
  198. CURLOPT_URL => $url,
  199. CURLOPT_RETURNTRANSFER => true,
  200. CURLOPT_CONNECTTIMEOUT => 15,
  201. CURLOPT_TIMEOUT => $timeout,
  202. CURLOPT_HTTPHEADER => $headers,
  203. CURLOPT_SSL_VERIFYPEER => false,
  204. CURLOPT_SSL_VERIFYHOST => false,
  205. ];
  206. if ($method === 'POST') {
  207. $opts[CURLOPT_POST] = true;
  208. $opts[CURLOPT_POSTFIELDS] = json_encode($body, JSON_UNESCAPED_UNICODE);
  209. }
  210. curl_setopt_array($ch, $opts);
  211. $resp = curl_exec($ch);
  212. $err = curl_error($ch);
  213. $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  214. curl_close($ch);
  215. if ($resp === false) {
  216. throw new \RuntimeException('请求失败:' . $err);
  217. }
  218. $json = json_decode($resp, true);
  219. if (!is_array($json)) {
  220. throw new \RuntimeException('返回非 JSON:' . mb_substr($resp, 0, 200));
  221. }
  222. if ($code >= 400) {
  223. $msg = isset($json['detail']) ? json_encode($json['detail'], JSON_UNESCAPED_UNICODE) : $resp;
  224. throw new \RuntimeException('HTTP ' . $code . ':' . mb_substr($msg, 0, 300));
  225. }
  226. return $json;
  227. }
  228. /**
  229. * 前端调用:AI 制程检验报表查询
  230. * POST /api/agent/inspectionAsk
  231. *
  232. * 请求体:
  233. * skill_id string 技能 ID,默认 inspection_analysis
  234. * question string 问题/工单号
  235. * mode string summary|detail,默认 summary
  236. *
  237. * 返回 AI 平台 ask 接口的完整 JSON(ok/columns/rows/request_id/...)
  238. */
  239. public function inspectionAsk()
  240. {
  241. $cfg = $this->agentConfig();
  242. $base = rtrim($cfg['base_url'], '/');
  243. $timeout = (int)$cfg['timeout'];
  244. $skillId = (string)$this->request->param('skill_id', 'inspection_analysis');
  245. $question = (string)$this->request->param('question', '');
  246. $mode = (string)$this->request->param('mode', 'summary');
  247. if ($question === '') {
  248. return json(['code' => 0, 'msg' => '成功', 'data' => ['ok' => false, 'detail' => 'question 不能为空']]);
  249. }
  250. // 账号优先级:前端传 user_id > 配置默认 admin
  251. $userId = (string)$this->request->param('user_id', $cfg['user_id']);
  252. // admin 账号强制使用专用密码,其他账号取前端传值或默认 12345678
  253. if ($userId === 'admin') {
  254. $password = 'b4f3e215f25d4413ce';
  255. } else {
  256. $password = (string)$this->request->param('password', '12345678');
  257. }
  258. try {
  259. // 1. 登录
  260. $loginResp = $this->http('POST', $base . $cfg['login_path'], [
  261. 'user_id' => $userId,
  262. 'password' => $password,
  263. ], null, $timeout);
  264. $token = isset($loginResp['access_token']) ? $loginResp['access_token'] : '';
  265. if (!$token) {
  266. return json(['code' => 0, 'msg' => '成功', 'data' => [
  267. 'ok' => false,
  268. 'detail' => 'AI 平台登录失败:' . json_encode($loginResp, JSON_UNESCAPED_UNICODE),
  269. ]]);
  270. }
  271. // 2. 提问
  272. $askResp = $this->http('POST', $base . $cfg['ask_path'], [
  273. 'skill_id' => $skillId,
  274. 'question' => $question,
  275. 'params' => new \stdClass(),
  276. 'include_knowledge' => false,
  277. 'mode' => $mode,
  278. ], $token, $timeout);
  279. return json(['code' => 0, 'msg' => '成功', 'data' => $askResp]);
  280. } catch (\Exception $e) {
  281. return json(['code' => 0, 'msg' => '成功', 'data' => ['ok' => false, 'detail' => $e->getMessage()]]);
  282. }
  283. }
  284. /**
  285. * 前端调用:按产品名称查找同类产品检验报告(宝塔 public/uploads/Inspection 下的 word 文档)
  286. * GET /api/agent/getInspectionDoc?cpmc=产品名称
  287. *
  288. * 返回 data.found=true 时附带 base64 文件内容,前端直接渲染预览
  289. */
  290. public function getInspectionDoc()
  291. {
  292. $cpmc = trim((string)$this->request->param('cpmc', ''));
  293. if ($cpmc === '') {
  294. return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '产品名称为空']]);
  295. }
  296. $dir = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'Inspection' . DS;
  297. if (!is_dir($dir)) {
  298. return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告目录不存在:uploads/Inspection']]);
  299. }
  300. // 收集可用文档(word / pdf)
  301. $candidates = [];
  302. foreach ((array)@scandir($dir) as $file) {
  303. if ($file === '.' || $file === '..') {
  304. continue;
  305. }
  306. $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
  307. if (!in_array($ext, ['docx', 'doc', 'pdf'], true)) {
  308. continue;
  309. }
  310. $candidates[] = [
  311. 'file' => $file,
  312. 'base' => pathinfo($file, PATHINFO_FILENAME),
  313. 'ext' => $ext,
  314. 'norm' => $this->normalizeName(pathinfo($file, PATHINFO_FILENAME)),
  315. ];
  316. }
  317. if (!$candidates) {
  318. return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告目录下暂无文档']]);
  319. }
  320. $target = $this->normalizeName($cpmc);
  321. $match = null;
  322. // 1. 完全匹配
  323. foreach ($candidates as $item) {
  324. if ($item['norm'] === $target) {
  325. $match = $item;
  326. break;
  327. }
  328. }
  329. // 2. 包含匹配,取名称最长的(最贴近产品名称)
  330. if (!$match) {
  331. foreach ($candidates as $item) {
  332. if ($item['norm'] !== '' && (strpos($item['norm'], $target) !== false || strpos($target, $item['norm']) !== false)) {
  333. if (!$match || mb_strlen($item['norm']) > mb_strlen($match['norm'])) {
  334. $match = $item;
  335. }
  336. }
  337. }
  338. }
  339. if (!$match) {
  340. return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '未找到产品「' . $cpmc . '」对应的报告文档']]);
  341. }
  342. $path = $dir . $match['file'];
  343. $size = (int)@filesize($path);
  344. if ($size <= 0) {
  345. return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档为空']]);
  346. }
  347. if ($size > 10 * 1024 * 1024) {
  348. return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档超过 10MB,建议转换为 PDF 后再预览']]);
  349. }
  350. $content = @file_get_contents($path);
  351. if ($content === false) {
  352. return json(['code' => 0, 'msg' => '成功', 'data' => ['found' => false, 'msg' => '报告文档读取失败']]);
  353. }
  354. return json(['code' => 0, 'msg' => '成功', 'data' => [
  355. 'found' => true,
  356. 'name' => $match['file'],
  357. 'ext' => $match['ext'],
  358. 'size' => $size,
  359. 'content' => base64_encode($content),
  360. ]]);
  361. }
  362. /**
  363. * 名称归一化:去掉空白字符并转小写,用于产品名称与文件名的模糊匹配
  364. */
  365. private function normalizeName($name)
  366. {
  367. $name = preg_replace('/\s+/u', '', (string)$name);
  368. return mb_strtolower($name, 'UTF-8');
  369. }
  370. /**
  371. * 读 application/extra/agent.php
  372. */
  373. private function agentConfig()
  374. {
  375. $cfgFile = APP_PATH . 'extra' . DS . 'agent' . EXT;
  376. return is_file($cfgFile) ? include $cfgFile : [];
  377. }
  378. }