Wecom.vue 19.6 KB
<!-- 消息通道:网关机器人(imhub 网关里的机器人账号)、接收对象(发到哪个群 / 哪个人、做什么用)、消息记录(收发的全部消息 + 助手判定)。
  地址栏 ?tab=logs 直接打开消息记录。 -->
<script setup lang="ts">
import { Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { api } from '@/api'
import HelpTip from '@/components/HelpTip.vue'
import EmptyState from '@/components/EmptyState.vue'
import PageHeader from '@/components/PageHeader.vue'
import Pager from '@/components/Pager.vue'
import Panel from '@/components/Panel.vue'
import StatusPill from '@/components/StatusPill.vue'
import { usePaged } from '@/composables/usePaged'
import { fmtShort, SEVERITY } from '@/format'
import MessageLogs from './MessageLogs.vue'

const route = useRoute()
const ov = ref<any>(null)
const logsRef = ref<InstanceType<typeof MessageLogs> | null>(null)
const bot = ref<any>(null)
const target = ref<any>(null)
const tab = ref(['targets', 'bots', 'logs'].includes(String(route.query.tab)) ? String(route.query.tab) : 'targets')

async function load() {
  try { ov.value = await api.get('/api/wecom/overview') } catch (e: any) { ElMessage.error(e.message) }
}
function loadLogs() { return logsRef.value?.load() }
let timer: any = null
onMounted(() => { load(); timer = setInterval(async () => {       // 收消息状态 30 秒刷新一次(静默)
  try { ov.value = await api.get('/api/wecom/overview') } catch { /* 下次再试 */ }
}, 30000) })
onUnmounted(() => clearInterval(timer))
const bots = computed(() => ov.value?.bots || [])
const syncDown = computed(() => (ov.value?.targets || []).filter((t: any) => t.sync?.state === 'down'))

function editBot(b?: any) { bot.value = b ? { ...b } : { name: '', bot_id: '', channel: 'yjy_ww', enabled: true, note: '' } }
async function saveBot() {
  const b = bot.value
  try {
    if (b.id) await api.put('/api/wecom/bots/' + b.id, b)
    else await api.post('/api/wecom/bots', b)
    ElMessage.success('已保存'); bot.value = null; load()
  } catch (e: any) { ElMessage.error(e.message) }
}
async function delBot(b: any) {
  try { await ElMessageBox.confirm(`删除网关机器人「${b.name}」?`, '删除', { type: 'warning' }) } catch { return }
  try { await api.del('/api/wecom/bots/' + b.id); ElMessage.success('已删除'); load() } catch (e: any) { ElMessage.error(e.message) }
}

const targetOrig = ref('')                       // 打开弹窗时的表单快照,用来判断有没有未保存的改动
const targetDirty = computed(() => !!target.value && JSON.stringify(target.value) !== targetOrig.value)
function editTarget(t?: any) {
  if (!bots.value.length) return ElMessage.warning('请先在「网关机器人」里登记一个机器人')
  // 单人对象的 at_ids / bot_names 在库里是 NULL,表单里统一成空串(否则输入框绑定 null,保存时接口校验不过)
  target.value = t ? { ...t, contact_name: t.contact_name || '', at_ids: t.at_ids || '', bot_names: t.bot_names || '', purposes: [...t.purposes] }
    : { name: '', bot_ref: bots.value[0].id, kind: 'group', contact_id: '', contact_name: '', at_ids: '', bot_names: '', purposes: ['chat', 'alert'], alert_min: 'warn', enabled: true }
  targetOrig.value = JSON.stringify(target.value)
}
/** 告警通知:下拉的值 = 没勾告警用途时是 off,否则是最低级别(purposes 里的 alert 与 alert_min 合成一个选择) */
const alertLevel = computed({
  get: () => target.value?.purposes.includes('alert') ? target.value.alert_min : 'off',
  set: (v: string) => {
    const t = target.value
    const rest = t.purposes.filter((p: string) => p !== 'alert')
    if (v === 'off') t.purposes = rest
    else { t.purposes = [...rest, 'alert']; t.alert_min = v }
  },
})
const chatOn = computed({
  get: () => !!target.value?.purposes.includes('chat'),
  set: (on: boolean) => {
    const t = target.value
    t.purposes = on ? [...t.purposes.filter((p: string) => p !== 'chat'), 'chat'] : t.purposes.filter((p: string) => p !== 'chat')
  },
})
async function saveTarget() {
  const t = target.value
  if (!t.purposes.length) return ElMessage.warning('补货对话和告警通知至少要开一个')
  try {
    if (t.id) await api.put('/api/wecom/targets/' + t.id, t)
    else await api.post('/api/wecom/targets', t)
    ElMessage.success('已保存'); target.value = null; load()
  } catch (e: any) { ElMessage.error(e.message) }
}
async function delTarget(t: any) {
  try { await ElMessageBox.confirm(`删除接收对象「${t.name}」?`, '删除', { type: 'warning' }) } catch { return }
  try { await api.del('/api/wecom/targets/' + t.id); ElMessage.success('已删除'); load() } catch (e: any) { ElMessage.error(e.message) }
}
async function test(t: any) {
  try {
    const r = await api.post(`/api/wecom/targets/${t.id}/test`)
    r.ok ? ElMessage.success('测试消息已发出,请到企业微信里查看') : ElMessage.error('发送失败:' + r.error)
    loadLogs()
  } catch (e: any) { ElMessage.error(e.message) }
}
// 从网关通讯录选群 / 选人:只开放 overview.contact_types 里的四种,选中后回填 contact_id、类型、名称
const picker = ref(false)
const contacts = usePaged(() => '/api/wecom/contacts?bot_ref=' + (target.value?.bot_ref || ''),
  { size: 20, filters: { type: '', keyword: '' } })
const ckwd = ref('')
function openPicker() {
  const t = target.value
  if (!t?.bot_ref) return ElMessage.warning('请先选择使用的网关机器人')
  const types = ov.value?.contact_types || {}
  const cur = contacts.filters.type
  const fit = !cur || types[cur]?.kind === t.kind ? cur : ''
  ckwd.value = contacts.filters.keyword
  picker.value = true
  if (fit !== cur) contacts.filters.type = fit        // 改筛选会触发 usePaged 自动加载
  else contacts.load()
}
function searchContacts() { contacts.filters.keyword = ckwd.value.trim() }
function pick(c: any) {
  const t = target.value
  t.contact_id = c.contact_id
  t.contact_name = c.name || ''
  t.kind = c.kind
  if (!t.name) t.name = c.name
  picker.value = false
}
</script>

<template>
  <div class="page">
    <PageHeader title="消息通道" desc="助手通过 imhub 网关里的网关机器人收发企业微信消息。先登记网关机器人,再配置接收对象:发到哪个群或哪个人、用来做什么。" />
    <div v-if="ov" class="stack">
      <div v-if="syncDown.length" class="notice err">
        imhub 消息同步中断:{{ syncDown.map((t: any) => `「${t.name}」自 ${t.sync.down_since} 起`).join('、') }}收不到消息(发消息正常)。
        已在会话里提醒用户,并发了告警;请联系 imhub 网关维护方检查机器人的消息同步,恢复后会自动通知。
      </div>
      <el-tabs v-model="tab">
        <el-tab-pane label="接收对象" name="targets">
          <Panel flush title="接收对象" desc="「补货对话」对象会收到补货清单、提醒和建单回执,计划员在这里回复「确认」等指令;「告警通知」对象按级别接收异常提醒。">
            <template #extra><el-button type="primary" :icon="Plus" @click="editTarget()">添加接收对象</el-button></template>
            <el-table :data="ov.targets">
              <el-table-column label="名称" min-width="150">
                <template #default="{ row }"><b>{{ row.name }}</b><div class="muted small">{{ row.kind === 'group' ? '群聊' : '单人' }}<template v-if="row.contact_name"> · {{ row.contact_name }}</template> · <span class="mono">{{ row.contact_id }}</span></div></template>
              </el-table-column>
              <el-table-column label="用途" min-width="200">
                <template #default="{ row }">
                  <div class="row">
                    <el-tag v-for="p in row.purposes" :key="p" size="small" :type="p === 'chat' ? 'primary' : 'warning'" effect="light">{{ ov.purposes[p] }}</el-tag>
                    <span v-if="row.purposes.includes('alert')" class="muted small">{{ SEVERITY[row.alert_min]?.text }}及以上</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="群里 @" min-width="120"><template #default="{ row }"><span class="small">{{ row.kind === 'group' ? (row.at_ids || '—') : '—' }}</span><div v-if="row.kind === 'group' && row.purposes.includes('chat')" class="muted small" :class="{ danger: !row.bot_names }">需 @ {{ row.bot_names || '(未填昵称,群消息全部被忽略)' }}</div></template></el-table-column>
              <el-table-column label="收消息" min-width="130">
                <template #default="{ row }">
                  <template v-if="row.sync">
                    <StatusPill v-if="row.sync.state === 'down'" tone="err">imhub 中断</StatusPill>
                    <StatusPill v-else-if="row.sync.state === 'ok'" tone="ok">正常</StatusPill>
                    <StatusPill v-else tone="info">待确认</StatusPill>
                    <div class="muted small">{{ row.sync.state === 'down' ? `自 ${row.sync.down_since} 起收不到` : row.sync.last_ok_at ? `最近确认 ${row.sync.last_ok_at}` : '发出消息后自动确认' }}</div>
                  </template>
                  <span v-else class="muted small">只发告警,不收</span>
                </template>
              </el-table-column>
              <el-table-column label="网关机器人" min-width="120"><template #default="{ row }">{{ row.bot_name }}<span v-if="!row.bot_enabled" class="err small">(已停用)</span></template></el-table-column>
              <el-table-column label="状态" width="90"><template #default="{ row }"><StatusPill :tone="row.enabled ? 'ok' : 'info'">{{ row.enabled ? '启用' : '停用' }}</StatusPill></template></el-table-column>
              <el-table-column label="" width="130" align="right">
                <template #default="{ row }">
                  <el-button link type="primary" @click="editTarget(row)">编辑</el-button>
                  <el-button link type="danger" @click="delTarget(row)">删除</el-button>
                </template>
              </el-table-column>
              <template #empty><EmptyState title="还没有接收对象" desc="至少配置一个「补货对话」对象(通常是配件计划群),补货清单才能推送出去。" /></template>
            </el-table>
          </Panel>
        </el-tab-pane>
        <el-tab-pane label="网关机器人" name="bots">
          <Panel flush title="网关机器人" :desc="`网关:${ov.gateway}(在「系统设置」里修改)`">
            <template #extra><el-button type="primary" :icon="Plus" @click="editBot()">登记网关机器人</el-button></template>
            <el-table :data="bots">
              <el-table-column label="名称" min-width="140"><template #default="{ row }"><b>{{ row.name }}</b></template></el-table-column>
              <el-table-column label="bot_id" min-width="240"><template #default="{ row }"><span class="mono small">{{ row.bot_id }}</span></template></el-table-column>
              <el-table-column prop="channel" label="通道" width="100" />
              <el-table-column label="被使用" width="100"><template #default="{ row }">{{ row.targets }} 个对象</template></el-table-column>
              <el-table-column label="状态" width="90"><template #default="{ row }"><StatusPill :tone="row.enabled ? 'ok' : 'info'">{{ row.enabled ? '启用' : '停用' }}</StatusPill></template></el-table-column>
              <el-table-column prop="note" label="备注" min-width="120" />
              <el-table-column label="" width="130" align="right">
                <template #default="{ row }">
                  <el-button link type="primary" @click="editBot(row)">编辑</el-button>
                  <el-button link type="danger" :disabled="row.targets > 0" @click="delBot(row)">删除</el-button>
                </template>
              </el-table-column>
              <template #empty><EmptyState title="还没有登记网关机器人" desc="bot_id 在 imhub 网关里查看。" /></template>
            </el-table>
          </Panel>
        </el-tab-pane>
        <el-tab-pane label="消息记录" name="logs">
          <MessageLogs ref="logsRef" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-skeleton v-else :rows="8" animated />

    <el-dialog :model-value="!!bot" :title="bot?.id ? '编辑网关机器人' : '登记网关机器人'" width="480px" align-center @close="bot = null">
      <el-form v-if="bot" label-position="top">
        <el-form-item label="名称"><el-input v-model="bot.name" placeholder="如「补货机器人」" /></el-form-item>
        <el-form-item label="bot_id"><el-input v-model="bot.bot_id" class="mono" placeholder="网关里的机器人标识" /></el-form-item>
        <el-form-item><template #label>通道<HelpTip text="默认 yjy_ww,一般不用改" /></template><el-input v-model="bot.channel" /></el-form-item>
        <el-form-item label="启用"><el-switch v-model="bot.enabled" /></el-form-item>
        <el-form-item label="备注"><el-input v-model="bot.note" /></el-form-item>
      </el-form>
      <template #footer><el-button @click="bot = null">取消</el-button><el-button type="primary" @click="saveBot">保存</el-button></template>
    </el-dialog>

    <el-dialog :model-value="!!target" :title="target?.id ? '编辑接收对象' : '添加接收对象'" width="540px" align-center @close="target = null">
      <el-form v-if="target" label-position="top">
        <div class="grid grid-2">
          <el-form-item label="名称"><el-input v-model="target.name" placeholder="如「配件计划群」「张三」" /></el-form-item>
          <el-form-item label="使用网关机器人">
            <el-select v-model="target.bot_ref"><el-option v-for="b in bots" :key="b.id" :label="b.name" :value="b.id" /></el-select>
          </el-form-item>
        </div>
        <el-form-item label="类型">
          <el-radio-group v-model="target.kind"><el-radio-button value="group">群聊</el-radio-button><el-radio-button value="single">单人</el-radio-button></el-radio-group>
        </el-form-item>
        <el-form-item :label="target.kind === 'group' ? '群 ID' : '联系人 ID'">
          <div class="pick-row">
            <el-input v-model="target.contact_id" class="mono" placeholder="可手动填写,或从通讯录选择" @input="target.contact_name = ''" />
            <el-button @click="openPicker">从通讯录选择</el-button>
          </div>
          <div v-if="target.contact_id" class="pick-name" :class="{ muted: !target.contact_name }">
            {{ target.contact_name ? `通讯录名称:${target.contact_name}` : '未关联通讯录名称,可点「从通讯录选择」' }}
          </div>
        </el-form-item>
        <el-form-item v-if="target.kind === 'group'" label="推清单 / 提醒时 @ 的人">
          <el-input v-model="target.at_ids" placeholder="企业微信 user id,多个用逗号分隔" />
        </el-form-item>
        <template v-if="target.kind === 'group' && target.purposes.includes('chat')">
          <el-form-item required><template #label>机器人在群里的昵称<HelpTip text="群里必须 @ 这个昵称才会处理(订、确认提交、不订等操作都一样),没 @ 的消息一律忽略,但会记进消息记录。必须和群里 @ 出来的名字一致,必填" /></template>
            <el-input v-model="target.bot_names" placeholder="如:补货助手;有多个别名用逗号分隔" />
          </el-form-item>
        </template>
        <el-form-item label="补货对话"><div class="row"><el-switch v-model="chatOn" /><span class="muted small">推清单、收回复、回执、提醒</span></div></el-form-item>
        <el-form-item><template #label>告警通知<HelpTip text="选「不接收」就不发告警;否则接收所选级别及以上的告警。「提示」包括每日补货小结;「注意」包括取数端版本过旧等;「异常」「紧急」是需要马上处理的" /></template>
          <el-select v-model="alertLevel" class="w-sev">
            <el-option label="不接收" value="off" />
            <el-option v-for="(s, k) in SEVERITY" :key="k" :label="k === 'critical' ? s.text : `${s.text}及以上`" :value="k" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用"><el-switch v-model="target.enabled" /></el-form-item>
      </el-form>
      <template #footer>
        <div class="dlg-foot">
          <el-tooltip v-if="target?.id" :disabled="!targetDirty" content="有未保存的修改,先保存再测试" placement="top">
            <span><el-button :disabled="targetDirty" @click="test(target)">发送测试消息</el-button></span>
          </el-tooltip>
          <span v-else />
          <div><el-button @click="target = null">取消</el-button><el-button type="primary" @click="saveTarget">保存</el-button></div>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="picker" title="从通讯录选择" width="760px" align-center append-to-body>
      <div class="row pick-bar">
        <el-select v-model="contacts.filters.type" placeholder="全部类型" clearable style="width: 160px">
          <el-option v-for="(c, k) in ov?.contact_types || {}" :key="k" :label="c.text" :value="k" />
        </el-select>
        <el-input v-model="ckwd" placeholder="名称模糊搜索,回车查询" clearable style="width: 240px" @keyup.enter="searchContacts" @clear="searchContacts" />
        <el-button :icon="Refresh" @click="contacts.load()">刷新</el-button>
      </div>
      <el-table v-loading="contacts.loading.value" :data="contacts.rows.value" size="small" height="420" @row-dblclick="pick">
        <el-table-column label="名称" min-width="180">
          <template #default="{ row }"><b>{{ row.name || '(无名称)' }}</b><div class="muted small mono">{{ row.contact_id }}</div></template>
        </el-table-column>
        <el-table-column label="类型" width="100"><template #default="{ row }"><el-tag size="small" :type="row.kind === 'group' ? 'primary' : 'info'" effect="light">{{ row.type_text }}</el-tag></template></el-table-column>
        <el-table-column label="群主 / 人数" width="120"><template #default="{ row }"><span class="small">{{ row.kind === 'group' ? `${row.owner || '—'} · ${row.member_count ?? '—'} 人` : '—' }}</span></template></el-table-column>
        <el-table-column label="最近活跃" width="110"><template #default="{ row }"><span class="small">{{ row.last_active ? fmtShort(row.last_active) : '—' }}</span></template></el-table-column>
        <el-table-column label="" width="130" align="right">
          <template #default="{ row }">
            <span v-if="row.configured" class="muted small">已配置:{{ row.configured }}</span>
            <el-button v-else link type="primary" @click="pick(row)">选择</el-button>
          </template>
        </el-table-column>
        <template #empty><EmptyState title="没有查到" desc="换个类型或名称再试;也可以关掉弹窗手动填写 ID。" /></template>
      </el-table>
      <Pager v-model:page="contacts.page.value" v-model:size="contacts.size.value" :total="contacts.total.value" />
    </el-dialog>
  </div>
</template>

<style scoped>
.content { white-space: pre-wrap; word-break: break-all; font-size: 12.5px; max-height: 110px; overflow: hidden; }
.w-sev { width: 200px; }
.danger { color: var(--c-err); }
.pick-row { display: flex; gap: 8px; width: 100%; }
.pick-row .el-input { flex: 1; }
.pick-name { width: 100%; margin-top: 4px; font-size: 12.5px; line-height: 1.4; }
.dlg-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.pick-bar { margin-bottom: 12px; gap: 8px; flex-wrap: wrap; }
</style>