Files
financial_system_frontend/src/components/FeishuDirectoryPanel.vue
T
2026-10-09 16:36:02 +08:00

152 lines
8.9 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<section class="card directory-panel" aria-labelledby="directory-title">
<div class="card-head directory-head">
<div><h2 id="directory-title">飞书通讯录同步</h2><p>同步飞书员工资料与目录状态;不作为 OAuth 登录条件;同步失败会保留当前目录</p></div>
<div class="directory-actions">
<router-link v-if="canManageSchedule" class="btn small" to="/scheduled-tasks">管理自动同步</router-link>
<button class="btn small" type="button" :disabled="loading || submitting" @click="refreshStatus">{{ loading ? '查询中…' : '刷新状态' }}</button>
<button v-if="canSync" class="btn primary" type="button" :disabled="syncDisabled" :aria-busy="submitting" @click="sync">{{ submitting || status?.running ? '同步中…' : '同步飞书通讯录' }}</button>
</div>
</div>
<div class="directory-body">
<p v-if="loading" role="status">正在确认通讯录同步状态…</p>
<div v-if="error" class="inline-alert danger" role="alert"><span>{{ error }}</span><button class="btn small" type="button" :disabled="loading || submitting" @click="refreshStatus">重试查询状态</button></div>
<div aria-live="polite" aria-atomic="true">
<p v-if="submitting || status?.running" role="status">同步正在进行,请勿重复提交。完成后将自动更新状态。</p>
<template v-if="status">
<p v-if="!status.configured">飞书通讯录尚未配置,请联系管理员配置应用凭证与通讯录权限。</p>
<dl class="directory-meta">
<div><dt>当前目录</dt><dd>{{ availabilityLabels[currentAvailability] }}</dd></div>
<div><dt>上次成功更新 <span class="time-zone-label">本地时间</span></dt><dd>{{ formatLocalDateTime(status.lastSuccessfulAt, '暂无') }}</dd></div>
<div><dt>当前版本</dt><dd>{{ status.currentRevision || status.lastSuccessfulRunId || '暂无' }}</dd></div>
<div><dt>配置上下文</dt><dd>{{ contextLabels[currentContext] }}</dd></div>
</dl>
<p v-if="currentContext === 'CHANGED'" class="directory-warning" role="status">应用配置上下文已变化,这是更新提示,不会停用已经可用的当前目录;可同步以更新资料。</p>
<p v-else-if="status.snapshotState === 'STALE'" class="directory-warning" role="status">服务返回旧版 STALE 状态;{{ currentAvailability === 'AVAILABLE' ? '当前目录仍可继续使用,建议同步更新资料。' : '当前服务未确认目录可用,请同步后再添加成员。' }}</p>
</template>
<template v-if="run">
<p>最近运行:{{ triggerLabels[run.trigger] }} · {{ stateLabels[run.state] }} · {{ run.applied ? '已提交' : '未提交,保留当前目录' }}</p>
<p class="muted-copy">运行时间(本地时间):{{ formatLocalDateTime(run.startedAt) }} — {{ formatLocalDateTime(run.finishedAt, '尚未结束') }} · 运行 ID:{{ run.runId }}</p>
<p v-if="run.state === 'FAILED' || run.errorMessage" class="directory-failure" role="alert">{{ run.errorCode || '同步失败' }}:{{ run.errorMessage || '同步未完成,请检查配置后重试。' }}</p>
<dl class="directory-counts"><div v-for="(label, key) in countLabels" :key="key"><dt>{{ label }}</dt><dd>{{ run.counts[key] }}</dd></div></dl>
</template>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
import { directoryAvailability, feishuDirectoryApi, type DirectoryContextState, type DirectoryRun, type DirectoryStatus } from '@/api/feishuDirectory'
import { useUserStore } from '@/store/user'
const emit = defineEmits<{ committed: [] }>()
const userStore = useUserStore()
const canSync = computed(() => userStore.canEdit('system.feishu.directory.sync'))
const canRead = computed(() => userStore.canRead('page.feishu-directory'))
const canManageSchedule = computed(() => userStore.canRead('page.scheduled-tasks'))
const status = ref<DirectoryStatus | null>(null)
const run = ref<DirectoryRun | null>(null)
const loading = ref(false)
const submitting = ref(false)
const uncertain = ref(true)
const error = ref('')
const currentAvailability = computed(() => status.value ? directoryAvailability(status.value) : 'UNAVAILABLE')
const currentContext = computed<DirectoryContextState>(() => {
if (status.value?.contextState === 'MATCH' || status.value?.contextState === 'CHANGED' || status.value?.contextState === 'UNKNOWN') return status.value.contextState
return status.value?.snapshotState === 'CONTEXT_CHANGED' ? 'CHANGED' : 'UNKNOWN'
})
const syncDisabled = computed(() => !canSync.value || loading.value || submitting.value || uncertain.value || !status.value?.configured || status.value.running)
const controller = new AbortController()
let disposed = false
let timer: ReturnType<typeof setTimeout> | undefined
let observedSuccess: string | null | undefined
const availabilityLabels = { AVAILABLE: '可用', NEVER_SYNCED: '尚未同步', UNAVAILABLE: '不可用' }
const contextLabels: Record<DirectoryContextState, string> = { MATCH: '一致', CHANGED: '已变化(仅提示)', UNKNOWN: '未知' }
const stateLabels = { RUNNING: '运行中', SUCCEEDED: '成功', FAILED: '失败' }
const triggerLabels: Record<DirectoryRun['trigger'], string> = { MANUAL: '手动同步', STARTUP: '启动同步', SCHEDULED: '自动同步' }
const countLabels = { departments: '部门', usersSeen: '扫描员工', excluded: '排除', created: '新增用户', updated: '更新用户', outOfScope: '可见范围外' }
// Date getters intentionally use the browser's local timezone instead of
// rendering the server's UTC ISO value. Keep the fallback caller-controlled so
// an absent successful result and an absent finish time can retain their own
// user-facing wording.
const formatLocalDateTime = (value: unknown, fallback = '—') => {
const date = value instanceof Date
? value
: new Date(typeof value === 'string' || typeof value === 'number' ? value : '')
if (!Number.isFinite(date.getTime())) return fallback
const pad = (part: number) => String(part).padStart(2, '0')
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
function committed(id: string) {
if (observedSuccess !== id) {
observedSuccess = id
emit('committed')
}
}
async function refreshStatus() {
if (disposed || !canRead.value || loading.value) return
clearTimeout(timer)
loading.value = true
uncertain.value = true
try {
const next = await feishuDirectoryApi.status(controller.signal)
if (disposed) return
if (observedSuccess !== undefined && next.lastSuccessfulRunId) committed(next.lastSuccessfulRunId)
else observedSuccess = next.lastSuccessfulRunId
status.value = next
run.value = next.lastRun
uncertain.value = false
error.value = ''
if (next.running) timer = setTimeout(() => void refreshStatus(), 5000)
} catch {
if (!disposed) error.value = '无法确认同步状态,已暂停同步操作。请重试查询状态后再操作。'
} finally {
loading.value = false
}
}
async function sync() {
if (syncDisabled.value) return
clearTimeout(timer)
submitting.value = true
uncertain.value = true
error.value = ''
try {
const result = await feishuDirectoryApi.sync(controller.signal)
if (disposed) return
run.value = result
if (result.state === 'SUCCEEDED' && result.complete && result.applied) committed(result.runId)
} catch {
// Includes timeouts, network errors, 409 and failed runs returned as HTTP 503.
// Never enable another POST until GET confirms the server is not running.
if (!disposed) error.value = '同步请求未确认(可能超时或失败),正在查询服务器状态,请勿重复提交。'
} finally {
await refreshStatus()
submitting.value = false
}
}
onMounted(refreshStatus)
onBeforeUnmount(() => { disposed = true; clearTimeout(timer); controller.abort() })
</script>
<style scoped>
.directory-panel { min-width: 0; flex: none; }
.directory-head { flex-wrap: wrap; gap: 12px; }
.directory-head > div:first-child { flex: 1 1 320px; min-width: 0; }
.directory-head p, .directory-body { overflow-wrap: anywhere; }
.directory-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.directory-body { padding: 0 22px 20px; font-size: 12px; color: var(--muted); }
.directory-body p { margin: 10px 0; }
.directory-meta, .directory-counts { display: grid; gap: 12px; margin: 12px 0 0; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
.directory-counts { grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); }
dt { color: var(--muted); } dd { margin: 4px 0 0; color: var(--body); }
.time-zone-label { color: var(--quiet); font-size: 10px; font-weight: 400; white-space: nowrap; }
.directory-failure { color: var(--danger); }
.directory-warning { color: var(--warning); }
</style>