Files
financial_system_frontend/src/components/FeishuDirectoryPanel.vue
T

270 lines
15 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>同步飞书员工资料与目录状态;同步失败会保留当前可用目录。</p></div>
<div class="directory-actions">
<router-link v-if="canManageSchedule" class="btn small" to="/scheduled-tasks">管理自动同步</router-link>
<button v-if="canViewRuns" class="btn small" type="button" @click="openRunsDialog">查看同步记录</button>
<button v-if="canSync" class="btn primary" type="button" :disabled="syncDisabled" :aria-busy="submitting || syncPending" @click="sync">{{ submitting || syncPending || status?.running ? '同步中…' : '同步飞书通讯录' }}</button>
</div>
</div>
<p class="sr-status" aria-live="polite" aria-atomic="true">{{ liveMessage }}</p>
<dialog v-if="canViewRuns" ref="runsDialog" v-dialog-drag class="app-dialog directory-runs-dialog" aria-labelledby="directory-runs-title" aria-modal="true" @cancel="handleRunsCancel" @click="handleRunsBackdrop">
<section class="app-dialog__panel">
<header class="modal-head" data-dialog-drag-handle>
<div><span class="eyebrow">DIRECTORY SYNC HISTORY</span><h2 id="directory-runs-title">同步记录</h2><p>按入队时间从新到旧显示;仅展示安全错误码,不展示上游错误明文。</p></div>
<button class="modal-close" type="button" aria-label="关闭同步记录" @click="closeRunsDialog"></button>
</header>
<div class="modal-body directory-runs-body">
<div class="directory-runs-toolbar"><span class="muted-copy">共 {{ runsTotal }} 条</span><button class="btn small" type="button" :disabled="runsLoading" @click="refreshRuns">{{ runsLoading ? '刷新中…' : '刷新' }}</button></div>
<div v-if="runsLoading" class="load-wrap directory-runs-state" role="status" aria-live="polite"><span class="loader" aria-hidden="true"></span><span>正在加载同步记录…</span></div>
<div v-else-if="runsError" class="empty-state directory-runs-state" role="alert"><strong>同步记录加载失败</strong><span>{{ runsError }}</span><button class="btn small" type="button" @click="refreshRuns">重试</button></div>
<div v-else-if="!runs.length" class="empty-state directory-runs-state"><strong>暂无同步记录</strong><span>通讯录同步运行后,结果会显示在这里。</span></div>
<div v-else class="directory-run-list" role="list" aria-label="飞书通讯录同步记录">
<article v-for="item in runs" :key="item.runId" class="directory-run" role="listitem">
<div class="directory-run__head"><div><span class="state-badge" :class="runTone(item.state)">{{ stateLabels[item.state] }}</span><strong>{{ triggerLabels[item.trigger] }}</strong></div><span>{{ item.applied ? '已生效' : item.complete ? '未生效,保留原目录' : '尚未完成' }}</span></div>
<dl class="directory-run__times"><div><dt>开始时间</dt><dd>{{ formatLocalDateTime(item.startedAt || item.queuedAt, '尚未开始') }}</dd></div><div><dt>结束时间</dt><dd>{{ formatLocalDateTime(item.finishedAt, '尚未结束') }}</dd></div><div><dt>触发方式</dt><dd>{{ triggerLabels[item.trigger] }}</dd></div></dl>
<dl class="directory-run__counts"><div><dt>成功处理</dt><dd>{{ runSummary(item).success }}</dd></div><div><dt>失败运行</dt><dd>{{ runSummary(item).failed }}</dd></div><div><dt>跳过</dt><dd>{{ runSummary(item).skipped }}</dd></div><div><dt>扫描员工</dt><dd>{{ item.counts.usersSeen }}</dd></div></dl>
<p v-if="safeErrorCode(item.errorCode)" class="directory-run__error">安全错误码:<code>{{ safeErrorCode(item.errorCode) }}</code></p>
</article>
</div>
<AppListPagination v-if="!runsLoading && !runsError && runsTotal" :page="runsPage" :page-size="runsPageSize" :total="runsTotal" :disabled="runsLoading" :page-sizes="[10, 20, 50]" aria-label="同步记录分页" @update:page="handleRunsPageChange" @update:page-size="handleRunsPageSizeChange" />
</div>
<footer class="modal-actions"><button class="btn" type="button" @click="closeRunsDialog">关闭</button></footer>
</section>
</dialog>
</section>
</template>
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import { ElMessage } from '@/utils/uiFeedback'
import AppListPagination from '@/components/common/AppListPagination.vue'
import { feishuDirectoryApi, type DirectoryRun, type DirectoryRunRecord, type DirectoryStatus } from '@/api/feishuDirectory'
import { createDirectoryRunRequestGate, createDirectoryStatusPoller, directorySyncOutcome, summarizeDirectoryRun } from '@/components/feishuDirectoryRuns'
import { useAuthorizationStore } from '@/store/authorization'
import { useUserStore } from '@/store/user'
const emit = defineEmits<{ committed: [] }>()
const userStore = useUserStore()
const authorizationStore = useAuthorizationStore()
const canSync = computed(() => userStore.canEdit('system.feishu.directory.sync') && authorizationStore.can('integration.feishu:sync'))
const canRead = computed(() => userStore.canRead('page.feishu-directory') && authorizationStore.can('integration.feishu:read'))
const canViewRuns = computed(() => canRead.value && userStore.canRead('dialog.directory.runs'))
const canManageSchedule = computed(() => userStore.canRead('page.scheduled-tasks') && authorizationStore.can('integration.schedule:read'))
const status = ref<DirectoryStatus | null>(null)
const statusLoading = ref(false)
const submitting = ref(false)
const syncPending = ref(false)
const uncertain = ref(true)
const liveMessage = ref('')
const syncDisabled = computed(() => !canSync.value || statusLoading.value || submitting.value || syncPending.value || uncertain.value || status.value?.running || (!!status.value && !status.value.configured))
const runsDialog = ref<HTMLDialogElement | null>(null)
const runsOpen = ref(false)
const runs = ref<DirectoryRunRecord[]>([])
const runsPage = ref(1)
const runsPageSize = ref(20)
const runsTotal = ref(0)
const runsLoading = ref(false)
const runsError = ref('')
const runsGate = createDirectoryRunRequestGate()
let disposed = false
let statusController: AbortController | null = null
let syncController: AbortController | null = null
let runsController: AbortController | null = null
let observedSuccess: string | null | undefined
const stateLabels: Record<DirectoryRunRecord['state'], string> = { RUNNING: '运行中', SUCCEEDED: '成功', FAILED: '失败' }
const triggerLabels: Record<DirectoryRunRecord['trigger'], string> = { MANUAL: '手动同步', STARTUP: '启动同步', SCHEDULED: '自动同步' }
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())}`
}
const safeErrorCode = (value: unknown) => typeof value === 'string' && /^[A-Z0-9_]{1,80}$/.test(value) ? value : ''
const runSummary = (item: DirectoryRunRecord) => summarizeDirectoryRun(item)
const runTone = (state: DirectoryRunRecord['state']) => state === 'SUCCEEDED' ? 'success' : state === 'FAILED' ? 'danger' : 'running'
const statusPoller = createDirectoryStatusPoller(
() => { void refreshStatus(false) },
() => canRead.value && !disposed,
)
function committed(id: string) {
if (observedSuccess === id) return
observedSuccess = id
emit('committed')
if (runsOpen.value) void loadRuns(true)
}
async function refreshStatus(notifyFailure = false) {
if (disposed || !canRead.value) {
statusPoller.confirmIdle()
return false
}
if (statusLoading.value) return false
statusPoller.clearScheduled()
statusController?.abort()
const controller = new AbortController()
statusController = controller
statusLoading.value = true
uncertain.value = true
try {
const next = await feishuDirectoryApi.status(controller.signal)
if (disposed || controller.signal.aborted || statusController !== controller) return false
if (observedSuccess !== undefined && next.lastSuccessfulRunId) committed(next.lastSuccessfulRunId)
else observedSuccess = next.lastSuccessfulRunId
status.value = next
uncertain.value = false
syncPending.value = next.running
liveMessage.value = next.running ? '通讯录同步正在运行。' : ''
if (next.running) statusPoller.confirmRunning()
else statusPoller.confirmIdle()
return true
} catch {
if (!disposed && !controller.signal.aborted) {
uncertain.value = true
statusPoller.recoverUnknown()
if (notifyFailure) ElMessage.error('无法确认同步状态,请稍后重试。')
}
return false
} finally {
if (statusController === controller) statusLoading.value = false
}
}
async function sync() {
if (syncDisabled.value) return
if (status.value?.running) return void ElMessage.warning('通讯录同步正在运行,请勿重复提交。')
if (status.value && !status.value.configured) return void ElMessage.warning('飞书通讯录尚未配置,暂时无法同步。')
statusPoller.clearScheduled()
syncController?.abort()
const controller = new AbortController()
syncController = controller
submitting.value = true
liveMessage.value = '正在提交飞书通讯录同步。'
try {
const result: DirectoryRun = await feishuDirectoryApi.sync(controller.signal)
if (disposed || controller.signal.aborted) return
const outcome = directorySyncOutcome(result)
if (outcome === 'RUNNING') {
uncertain.value = true
syncPending.value = true
status.value = status.value ? { ...status.value, running: true } : status.value
statusPoller.beginActive()
liveMessage.value = '同步任务已提交,正在等待服务器完成。'
ElMessage.info('同步任务已提交,正在后台同步。')
} else if (outcome === 'APPLIED') {
uncertain.value = false
syncPending.value = false
statusPoller.confirmIdle()
committed(result.runId)
ElMessage.success('飞书通讯录同步成功。')
} else {
uncertain.value = false
syncPending.value = false
statusPoller.confirmIdle()
const code = safeErrorCode(result.errorCode)
const prefix = outcome === 'FAILED' ? '同步失败' : '同步已完成但未生效'
ElMessage.warning(code ? `${prefix}(${code}),已保留原目录。` : `${prefix},已保留原目录。`)
}
} catch {
if (!disposed && !controller.signal.aborted) {
uncertain.value = true
syncPending.value = true
statusPoller.beginActive()
ElMessage.error('同步请求未确认,正在重新确认服务器状态,请勿重复提交。')
}
} finally {
if (!disposed) await refreshStatus(false)
if (syncController === controller) submitting.value = false
}
}
async function loadRuns(resetPage = false) {
if (!runsOpen.value || !canViewRuns.value || disposed) return
if (resetPage) runsPage.value = 1
runsController?.abort()
const controller = new AbortController()
runsController = controller
const requestGeneration = runsGate.begin()
runsLoading.value = true
runsError.value = ''
try {
const page = await feishuDirectoryApi.runs(runsPage.value - 1, runsPageSize.value, controller.signal)
if (disposed || controller.signal.aborted || !runsGate.isCurrent(requestGeneration) || !runsOpen.value) return
runs.value = Array.isArray(page.items) ? page.items : []
runsTotal.value = Number.isFinite(page.total) && page.total > 0 ? Math.floor(page.total) : 0
} catch {
if (disposed || controller.signal.aborted || !runsGate.isCurrent(requestGeneration) || !runsOpen.value) return
runs.value = []
runsError.value = '无法加载同步记录,请稍后重试。'
} finally {
if (runsGate.isCurrent(requestGeneration)) runsLoading.value = false
}
}
function openRunsDialog() {
if (!canViewRuns.value) return
runsOpen.value = true
runsPage.value = 1
runsError.value = ''
if (!runsDialog.value?.open) runsDialog.value?.showModal()
void loadRuns(true)
}
function closeRunsDialog() {
runsOpen.value = false
runsGate.invalidate()
runsController?.abort()
runsLoading.value = false
runsDialog.value?.close()
}
function handleRunsCancel(event: Event) { event.preventDefault(); closeRunsDialog() }
function handleRunsBackdrop(event: MouseEvent) { if (event.target === runsDialog.value) closeRunsDialog() }
function refreshRuns() { void loadRuns(true) }
function handleRunsPageChange(page: number) { runsPage.value = Math.max(1, Math.floor(page)); void loadRuns(false) }
function handleRunsPageSizeChange(size: number) { runsPageSize.value = [10, 20, 50].includes(Number(size)) ? Number(size) : 20; runsPage.value = 1; void loadRuns(false) }
onMounted(() => { void refreshStatus(false) })
onBeforeUnmount(() => {
disposed = true
statusPoller.dispose()
runsGate.invalidate()
statusController?.abort()
syncController?.abort()
runsController?.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-run { overflow-wrap: anywhere; }
.directory-actions { display: flex; flex-wrap: wrap; gap: 8px; }
.directory-runs-dialog { width: min(920px, calc(100vw - 24px)); max-width: calc(100vw - 24px); overflow: hidden; }
.directory-runs-dialog > .app-dialog__panel { width: 100%; min-width: 0; max-width: 100%; }
.directory-runs-body { min-width: 0; min-height: 220px; overflow-x: hidden; overflow-y: auto; }
.directory-runs-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 12px; }
.directory-runs-state { min-height: 190px; }
.directory-run-list { display: grid; min-width: 0; gap: 12px; }
.directory-run { min-width: 0; padding: clamp(12px, 2vw, 18px); border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-raised); }
.directory-run__head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.directory-run__head > div { display: flex; min-width: 0; align-items: center; flex-wrap: wrap; gap: 8px; }
.directory-run__head > span { color: var(--muted); font-size: 11px; text-align: right; }
.directory-run__times, .directory-run__counts { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(140px, 100%), 1fr)); gap: 8px 14px; margin: 12px 0 0; }
.directory-run__counts { grid-template-columns: repeat(auto-fit, minmax(min(90px, 100%), 1fr)); }
.directory-run dt { color: var(--muted); font-size: 10px; }
.directory-run dd { margin: 3px 0 0; color: var(--body); }
.directory-run__error { margin: 12px 0 0; color: var(--danger); }
.directory-run__error code { color: inherit; }
@media (max-width: 450px) {
.directory-actions, .directory-actions .btn { width: 100%; }
.directory-runs-toolbar, .directory-run__head { align-items: stretch; flex-direction: column; }
.directory-run__head > span { text-align: left; }
}
</style>