Files
zkxw/web-admin/src/components/oa-approval/OaCommentPanel.vue
T
zlwuandCursor f9aa16ef31 feat(oa): 评论@人员优先展示同部门用户
OA 评论选人列表改为请求 users/options 时按当前登录用户部门优先排序,Web 与移动 OA 共用后端稳定排序,便于先选到同部门同事。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 14:24:21 +08:00

813 lines
22 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.
<!-- OA 审批详情 · 评论输入(列表已并入审批进度时间线) -->
<template>
<section class="oa-comment-panel">
<div class="oa-comment-panel__composer">
<div class="oa-comment-panel__editor">
<el-input
ref="inputRef"
v-model="draft"
type="textarea"
:rows="3"
maxlength="1024"
show-word-limit
placeholder="填写评论,输入 @ 可提到人员"
@focus="onDraftFocus"
@input="onDraftInput"
@keydown="onDraftKeydown"
/>
<div v-if="atOpen" class="oa-comment-at" v-loading="atLoading">
<button
v-for="(u, idx) in atOptions"
:key="u.id"
type="button"
class="oa-comment-at__item"
:class="{ 'is-active': idx === atActive }"
@mousedown.prevent="pickAtUser(u)"
>
<span class="oa-comment-at__name">{{ u.name }}</span>
</button>
<div v-if="!atLoading && !atOptions.length" class="oa-comment-at__empty">未找到人员</div>
</div>
</div>
<div v-if="mentionUsers.length" class="oa-comment-panel__picked">
<el-tag
v-for="u in mentionUsers"
:key="u.id"
closable
size="small"
effect="plain"
@close="removeMention(u.id)"
>
@{{ u.name }}
</el-tag>
</div>
<div v-if="picked.length" class="oa-comment-panel__files">
<OaCommentFileCards :files="picked" removable @remove="removePicked" />
</div>
<div class="oa-comment-panel__actions">
<el-button class="btn-ghost" @click="openMention">
<el-icon><User /></el-icon>
@人员
</el-button>
<el-button class="btn-ghost" @click="openAttach">
<el-icon><Paperclip /></el-icon>
引用附件
</el-button>
<el-button class="btn-ghost" :loading="uploading" @click="pickUpload">
<el-icon><Upload /></el-icon>
上传附件
</el-button>
<el-button type="primary" class="btn-main" :loading="sending" @click="onSend">
<el-icon><Promotion /></el-icon>
发送
</el-button>
</div>
<input
ref="fileInputRef"
class="oa-comment-file-input"
type="file"
multiple
:accept="OA_UPLOAD_ACCEPT"
@change="onUploadFiles"
/>
</div>
<el-dialog
v-model="attachVisible"
title="引用表单附件"
width="640px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
destroy-on-close
:close-on-click-modal="false"
>
<div v-loading="attachLoading" class="oa-comment-attach">
<div v-if="!attachLoading && !attachGroups.length" class="oa-comment-attach__empty">
暂无可引用附件
</div>
<div v-else class="oa-comment-attach__groups">
<div v-for="g in attachGroups" :key="g.fieldKey" class="oa-comment-attach__group">
<div class="oa-comment-attach__label">{{ g.fieldLabel || g.fieldKey }}</div>
<div class="oa-comment-attach__files">
<button
v-for="f in g.files"
:key="f.url"
type="button"
class="oa-comment-attach__card"
:class="{ 'is-selected': isSelected(f.url) }"
:title="f.fileName || f.url"
@click="toggleUrl(f.url)"
>
<div class="oa-comment-attach__thumb">
<img
v-if="isImageRef(f)"
:src="thumbSrc(f.url)"
:alt="f.fileName || '附件'"
/>
<div
v-else-if="isVideoRef(f)"
class="oa-comment-attach__icon oa-comment-attach__icon--video"
>
<el-icon :size="16"><VideoPlay /></el-icon>
</div>
<div v-else class="oa-comment-attach__icon oa-comment-attach__icon--doc">
<el-icon :size="16"><Document /></el-icon>
</div>
<span v-if="isSelected(f.url)" class="oa-comment-attach__check">
<el-icon :size="12"><Check /></el-icon>
</span>
</div>
<div class="oa-comment-attach__name">{{ f.fileName || f.url }}</div>
</button>
</div>
</div>
</div>
</div>
<template #footer>
<el-button class="btn-ghost" @click="attachVisible = false">
<el-icon><Close /></el-icon>
取消
</el-button>
<el-button
type="primary"
class="btn-main"
:disabled="!attachGroups.length"
@click="confirmAttach"
>
<el-icon><Check /></el-icon>
确定
</el-button>
</template>
</el-dialog>
<el-dialog
v-model="mentionVisible"
title="提到人员"
width="480px"
class="dialog-form-layout"
align-center
append-to-body
modal-class="protocol-dialog-mask"
:close-on-click-modal="false"
>
<el-select
v-model="mentionDraftIds"
multiple
filterable
:loading="userLoading"
placeholder="搜索姓名"
style="width: 100%"
>
<el-option
v-for="u in dialogUserOptions"
:key="u.id"
:label="u.name"
:value="u.id"
/>
</el-select>
<template #footer>
<el-button @click="mentionVisible = false">
<el-icon><Close /></el-icon>
取消
</el-button>
<el-button type="primary" @click="confirmMention">
<el-icon><Check /></el-icon>
确定
</el-button>
</template>
</el-dialog>
</section>
</template>
<script setup lang="ts">
import { Check, Close, Document, Paperclip, Promotion, Upload, User, VideoPlay } from '@element-plus/icons-vue'
import { fetchUserOptions } from '@/api/admin'
import { fetchUploadAttachment } from '@/api/business'
import {
fetchCreateOaComment,
fetchOaFormAttachments,
type OaCommentAttachmentRef
} from '@/api/oaApproval'
import OaCommentFileCards from '@/components/oa-approval/OaCommentFileCards.vue'
import { attachmentFullUrl } from '@/composables/useAttachmentActions'
import { hasOaCommentDraft } from '@/utils/oa-comment-draft'
import { isOaUploadImageFile, isOaUploadVideoFile } from '@/utils/oa-upload-file-type'
defineOptions({ name: 'OaCommentPanel' })
type MentionUser = { id: string; name: string }
const props = defineProps<{
instanceId: string
instanceStatus: string
}>()
const emit = defineEmits<{ refresh: [] }>()
const inputRef = ref<any>(null)
const draft = ref('')
const picked = ref<OaCommentAttachmentRef[]>([])
const sending = ref(false)
const uploading = ref(false)
const fileInputRef = ref<HTMLInputElement | null>(null)
const OA_UPLOAD_ACCEPT = 'image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.zip,.rar'
const mentionUsers = ref<MentionUser[]>([])
const mentionVisible = ref(false)
const mentionDraftIds = ref<string[]>([])
const userLoading = ref(false)
/** 租户内启用用户缓存:@ 与弹窗共用,本地过滤,避免每次请求 */
const allMentionUsers = ref<MentionUser[]>([])
let userCachePromise: Promise<void> | null = null
const dialogUserOptions = computed(() => {
const map = new Map(allMentionUsers.value.map((u) => [u.id, u]))
for (const u of mentionUsers.value) map.set(u.id, u)
return [...map.values()]
})
const atOpen = ref(false)
const atQuery = ref('')
const atStart = ref(-1)
const atActive = ref(0)
const atOptions = ref<MentionUser[]>([])
const atLoading = ref(false)
const attachVisible = ref(false)
const attachLoading = ref(false)
const attachGroups = ref<
Array<{ fieldKey: string; fieldLabel: string; files: OaCommentAttachmentRef[] }>
>([])
const selectedUrls = ref<string[]>([])
function getTextareaEl(): HTMLTextAreaElement | null {
const inst = inputRef.value
if (!inst) return null
if (inst.textarea instanceof HTMLTextAreaElement) return inst.textarea
const el = inst.$el as HTMLElement | undefined
return (el?.querySelector?.('textarea') as HTMLTextAreaElement | null) || null
}
async function ensureUserCache() {
if (allMentionUsers.value.length) return
if (userCachePromise) return userCachePromise
userCachePromise = (async () => {
try {
// 同部门优先:由后端按当前登录用户部门排序
const res = await fetchUserOptions({ prioritizeCallerDept: true })
const list = Array.isArray(res) ? res : []
const next: MentionUser[] = []
const seen = new Set<string>()
for (const u of list) {
const id = String(u?.value || '').trim()
if (!id || seen.has(id)) continue
seen.add(id)
const name = String(u?.label || id).trim() || id
next.push({ id, name })
}
allMentionUsers.value = next
} catch {
allMentionUsers.value = []
} finally {
userCachePromise = null
}
})()
return userCachePromise
}
function filterMentionUsers(keyword: string, excludeIds?: Set<string>): MentionUser[] {
const q = (keyword || '').trim().toLowerCase()
const out: MentionUser[] = []
for (const u of allMentionUsers.value) {
if (excludeIds?.has(u.id)) continue
if (q && !u.name.toLowerCase().includes(q) && !u.id.toLowerCase().includes(q)) {
continue
}
out.push(u)
if (out.length >= 30) break
}
return out
}
function closeAtSuggest() {
atOpen.value = false
atQuery.value = ''
atStart.value = -1
atActive.value = 0
atOptions.value = []
}
async function applyAtSuggest(query: string) {
const needFetch = !allMentionUsers.value.length
if (needFetch) atLoading.value = true
try {
await ensureUserCache()
if (!atOpen.value) return
const pickedIds = new Set(mentionUsers.value.map((u) => u.id))
atOptions.value = filterMentionUsers(query, pickedIds)
if (atActive.value >= atOptions.value.length) {
atActive.value = Math.max(0, atOptions.value.length - 1)
}
} finally {
atLoading.value = false
}
}
function detectAtSuggest() {
const ta = getTextareaEl()
if (!ta) {
closeAtSuggest()
return
}
const pos = ta.selectionStart ?? 0
const before = draft.value.slice(0, pos)
const matched = before.match(/(?:^|[\s\n])(@([^\s@]*))$/)
if (!matched) {
closeAtSuggest()
return
}
const token = matched[1] || ''
const query = matched[2] || ''
atStart.value = before.length - token.length
atQuery.value = query
atOpen.value = true
atActive.value = 0
// 有缓存则同步过滤;无缓存才拉一次
if (allMentionUsers.value.length) {
const pickedIds = new Set(mentionUsers.value.map((u) => u.id))
atOptions.value = filterMentionUsers(query, pickedIds)
} else {
void applyAtSuggest(query)
}
}
function onDraftInput() {
nextTick(() => detectAtSuggest())
}
function onDraftFocus() {
void ensureUserCache()
}
function onDraftKeydown(e: KeyboardEvent) {
if (!atOpen.value) return
if (e.key === 'ArrowDown') {
e.preventDefault()
if (!atOptions.value.length) return
atActive.value = (atActive.value + 1) % atOptions.value.length
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
if (!atOptions.value.length) return
atActive.value = (atActive.value - 1 + atOptions.value.length) % atOptions.value.length
return
}
if (e.key === 'Enter' || e.key === 'Tab') {
const u = atOptions.value[atActive.value]
if (!u) return
e.preventDefault()
pickAtUser(u)
return
}
if (e.key === 'Escape') {
e.preventDefault()
closeAtSuggest()
}
}
function addMentionUser(u: MentionUser) {
if (mentionUsers.value.some((x) => x.id === u.id)) return true
if (mentionUsers.value.length >= 20) {
ElMessage.warning('一次最多@20人')
return false
}
mentionUsers.value.push(u)
return true
}
function pickAtUser(u: MentionUser) {
if (!addMentionUser(u)) return
const start = atStart.value
if (start < 0) {
closeAtSuggest()
return
}
const ta = getTextareaEl()
const end = ta?.selectionStart ?? draft.value.length
const insert = `@${u.name} `
draft.value = `${draft.value.slice(0, start)}${insert}${draft.value.slice(end)}`
closeAtSuggest()
nextTick(() => {
const el = getTextareaEl()
if (!el) return
const pos = start + insert.length
el.focus()
el.setSelectionRange(pos, pos)
})
}
function fileLike(f: OaCommentAttachmentRef) {
return { url: f.url, name: f.fileName }
}
function isImageRef(f: OaCommentAttachmentRef) {
return isOaUploadImageFile(fileLike(f))
}
function isVideoRef(f: OaCommentAttachmentRef) {
return isOaUploadVideoFile(fileLike(f))
}
function thumbSrc(url: string) {
return attachmentFullUrl(url) || url
}
function isSelected(url: string) {
return selectedUrls.value.includes(url)
}
function toggleUrl(url: string) {
const u = String(url || '').trim()
if (!u) return
const idx = selectedUrls.value.indexOf(u)
if (idx >= 0) selectedUrls.value.splice(idx, 1)
else selectedUrls.value.push(u)
}
function removeMention(id: string) {
mentionUsers.value = mentionUsers.value.filter((u) => u.id !== id)
}
async function openMention() {
closeAtSuggest()
mentionDraftIds.value = mentionUsers.value.map((u) => u.id)
mentionVisible.value = true
userLoading.value = !allMentionUsers.value.length
try {
await ensureUserCache()
} finally {
userLoading.value = false
}
}
function confirmMention() {
const map = new Map(allMentionUsers.value.map((u) => [u.id, u.name]))
for (const u of mentionUsers.value) map.set(u.id, u.name)
const next = mentionDraftIds.value
.map((id) => ({ id, name: map.get(id) || id }))
.slice(0, 20)
mentionUsers.value = next
for (const u of next) {
const token = `@${u.name}`
if (!draft.value.includes(token)) {
draft.value = `${draft.value.trimEnd()}${draft.value.trim() ? ' ' : ''}${token} `
}
}
mentionVisible.value = false
}
async function openAttach() {
attachVisible.value = true
attachLoading.value = true
selectedUrls.value = picked.value
.filter((f) => f.source !== 'upload')
.map((f) => f.url)
try {
const res = await fetchOaFormAttachments(props.instanceId)
const items = res?.items || []
attachGroups.value = items
if (!items.length) {
ElMessage.info('暂无可引用附件')
}
} catch (e: any) {
attachGroups.value = []
ElMessage.error(e?.message || '加载附件失败')
} finally {
attachLoading.value = false
}
}
function confirmAttach() {
const map = new Map<string, OaCommentAttachmentRef>()
for (const g of attachGroups.value) {
for (const f of g.files || []) {
if (f?.url) map.set(f.url, f)
}
}
const cited: OaCommentAttachmentRef[] = []
for (const url of selectedUrls.value) {
const found = map.get(url) || picked.value.find((p) => p.url === url && p.source !== 'upload')
if (found) cited.push({ ...found, source: 'form' })
}
const uploads = picked.value.filter((f) => f.source === 'upload')
picked.value = [...cited, ...uploads]
attachVisible.value = false
}
function removePicked(index: number) {
picked.value.splice(index, 1)
}
function pickUpload() {
fileInputRef.value?.click()
}
async function onUploadFiles(ev: Event) {
const input = ev.target as HTMLInputElement
const files = Array.from(input.files || [])
input.value = ''
if (!files.length) return
uploading.value = true
try {
for (const file of files) {
const fd = new FormData()
fd.append('file', file)
fd.append('folder', 'oa-approval')
const res: any = await fetchUploadAttachment(fd)
const url = String(res?.fileUrl || res?.data?.fileUrl || '').trim()
if (!url) {
ElMessage.error(`${file.name || '文件'} 上传失败`)
continue
}
if (picked.value.some((p) => p.url === url)) continue
picked.value.push({
source: 'upload',
fieldKey: '',
fieldLabel: '',
url,
fileName: String(res?.fileName || res?.data?.fileName || file.name || '').trim() || file.name
})
}
} catch (e: any) {
ElMessage.error(e?.message || '上传失败')
} finally {
uploading.value = false
}
}
function draftPending() {
return hasOaCommentDraft({
content: draft.value,
mentionCount: mentionUsers.value.length,
attachmentCount: picked.value.length
})
}
/**
* 审批动作前冲刷未发送草稿:无草稿直接成功;有草稿则等同点击「发送」。
* @returns false 表示发送失败或忙碌,调用方应中止审批动作
*/
async function flushDraft(opts?: { quiet?: boolean }): Promise<boolean> {
if (!draftPending()) return true
if (sending.value || uploading.value) {
ElMessage.warning(uploading.value ? '附件上传中,请稍后再试' : '评论发送中,请稍后再试')
return false
}
const content = draft.value.trim()
sending.value = true
try {
await fetchCreateOaComment(props.instanceId, {
content,
attachmentRefs: picked.value.length ? [...picked.value] : undefined,
mentionUserIds: mentionUsers.value.length
? mentionUsers.value.map((u) => u.id)
: undefined
})
draft.value = ''
picked.value = []
mentionUsers.value = []
closeAtSuggest()
if (!opts?.quiet) ElMessage.success('已发送')
emit('refresh')
return true
} catch (e: any) {
ElMessage.error(e?.message || '发送失败')
return false
} finally {
sending.value = false
}
}
async function onSend() {
if (!draftPending()) {
ElMessage.warning('请填写评论、@人员或添加附件')
return
}
await flushDraft()
}
defineExpose({ flushDraft, draftPending })
onMounted(() => {
void ensureUserCache()
})
</script>
<style scoped lang="scss">
.oa-comment-panel {
max-width: 960px;
margin-top: 12px;
}
.oa-comment-file-input {
position: absolute;
width: 0;
height: 0;
opacity: 0;
pointer-events: none;
}
.oa-comment-panel__files {
margin-top: 8px;
}
.oa-comment-panel__picked {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 8px;
}
.oa-comment-panel__composer {
padding-top: 4px;
}
.oa-comment-panel__editor {
position: relative;
}
.oa-comment-panel__actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
justify-content: flex-end;
margin-top: 10px;
}
.oa-comment-at {
position: absolute;
top: calc(100% - 28px);
left: 0;
z-index: 20;
width: min(320px, 100%);
max-height: 220px;
overflow: auto;
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 8px;
box-shadow: 0 8px 24px rgba(15, 23, 42, 0.12);
}
.oa-comment-at__item {
display: flex;
align-items: center;
width: 100%;
min-height: 36px;
padding: 6px 12px;
text-align: left;
cursor: pointer;
background: transparent;
border: none;
&:hover,
&.is-active {
background: var(--primary-bg, #ecfdf5);
}
}
.oa-comment-at__name {
color: var(--mint-text-strong, #0f172a);
font-size: 13px;
}
.oa-comment-at__empty {
padding: 12px;
color: var(--mint-text-muted, #94a3b8);
font-size: 13px;
text-align: center;
}
.oa-comment-attach {
min-height: 80px;
}
.oa-comment-attach__empty {
padding: 16px 0;
color: var(--mint-text-muted, #94a3b8);
font-size: 13px;
text-align: center;
}
.oa-comment-attach__groups {
display: grid;
gap: 16px;
width: 100%;
}
.oa-comment-attach__label {
margin-bottom: 8px;
color: var(--mint-text-strong, #0f172a);
font-size: 13px;
font-weight: 600;
}
.oa-comment-attach__files {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.oa-comment-attach__card {
display: flex;
flex-direction: column;
width: 88px;
padding: 0;
overflow: hidden;
text-align: left;
cursor: pointer;
background: #fff;
border: 1px solid #e2e8f0;
border-radius: 8px;
transition:
border-color 0.15s,
box-shadow 0.15s;
&:hover {
border-color: #a7f3d0;
box-shadow: 0 2px 8px rgba(16, 185, 129, 0.12);
}
&.is-selected {
border-color: var(--primary, #10b981);
box-shadow: 0 0 0 1px var(--primary, #10b981);
}
}
.oa-comment-attach__thumb {
position: relative;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 64px;
overflow: hidden;
background: #f8fafc;
img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
}
.oa-comment-attach__icon {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 8px;
&--video {
color: #7c3aed;
background: #ede9fe;
}
&--doc {
color: #0284c7;
background: #e0f2fe;
}
}
.oa-comment-attach__check {
position: absolute;
top: 4px;
right: 4px;
display: grid;
place-items: center;
width: 16px;
height: 16px;
color: #fff;
background: var(--primary, #10b981);
border-radius: 50%;
box-shadow: 0 1px 2px rgba(15, 23, 42, 0.18);
}
.oa-comment-attach__name {
display: -webkit-box;
margin: 0;
padding: 4px 6px;
overflow: hidden;
color: var(--mint-text, #334155);
font-size: 11px;
line-height: 1.3;
word-break: break-all;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
</style>