ensureTable(); $companyId = $this->getUserInfo('companyId'); $kefuId = $this->getUserInfo('id'); // 仅返回 enabled 的库(存客宝下发);无分配 → 空列表,触客宝提示联系管理员 $rows = Db::name('kb_touchkebao_config') ->where('companyId', $companyId) ->where('enabled', 1) ->where('kefuId', 0) // 项目级开放 ->select(); $list = []; $defaultKbId = null; foreach ($rows as $r) { $list[] = [ 'id' => (int)$r['kbId'], 'name' => $r['kbName'], 'isDefault' => (bool)$r['isDefault'], ]; if ($r['isDefault']) { $defaultKbId = (int)$r['kbId']; } } // 客服个人当前选择(覆盖默认,须在已开放范围内) $currentKbId = $defaultKbId; $myCurrent = Db::name('kb_touchkebao_config') ->where('companyId', $companyId) ->where('kefuId', $kefuId) ->value('currentKbId'); if ($myCurrent && in_array((int)$myCurrent, array_column($list, 'id'))) { $currentKbId = (int)$myCurrent; } return ResponseHelper::success([ 'defaultKbId' => $defaultKbId, 'currentKbId' => $currentKbId, 'list' => $list, ]); } /** * 客服在已分配范围内切换默认库 * POST /v1/kefu/ai/knowledge-base/select */ public function selectKnowledgeBase() { $this->ensureTable(); $companyId = $this->getUserInfo('companyId'); $kefuId = $this->getUserInfo('id'); $kbId = (int)$this->request->param('kbId', 0); if (!$kbId) { return ResponseHelper::error('kbId 缺失', 400); } // 校验是否在已开放范围内 $allowed = Db::name('kb_touchkebao_config') ->where('companyId', $companyId) ->where('enabled', 1) ->where('kbId', $kbId) ->count(); if (!$allowed) { return ResponseHelper::error('该知识库未对触客宝开放', 403); } $exist = Db::name('kb_touchkebao_config') ->where('companyId', $companyId) ->where('kefuId', $kefuId) ->find(); if ($exist) { Db::name('kb_touchkebao_config')->where('id', $exist['id']) ->update(['currentKbId' => $kbId, 'updateTime' => time()]); } else { Db::name('kb_touchkebao_config')->insert([ 'companyId' => $companyId, 'kefuId' => $kefuId, 'currentKbId' => $kbId, 'enabled' => 0, 'updateTime' => time(), ]); } return ResponseHelper::success(['currentKbId' => $kbId], '已切换'); } }