初始化
This commit is contained in:
commit
3a4e81a070
43 files changed
+10871
No files matched your search
@@ -0,0 +1,3 @@
|
|||||||
|
# Optional for static deployments without an /api reverse proxy.
|
||||||
|
# Leave unset when the frontend and backend share an origin.
|
||||||
|
VITE_API_BASE_URL=/api
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
# dependencies
|
||||||
|
node_modules/
|
||||||
|
|
||||||
|
# build output
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
.next/
|
||||||
|
out/
|
||||||
|
|
||||||
|
# local env files
|
||||||
|
.env
|
||||||
|
.env.local
|
||||||
|
.env.*.local
|
||||||
|
|
||||||
|
# logs
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
|
||||||
|
# cache
|
||||||
|
.cache/
|
||||||
|
.vite/
|
||||||
|
.eslintcache
|
||||||
|
|
||||||
|
# test coverage
|
||||||
|
coverage/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.iml
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# temporary files
|
||||||
|
*.tmp
|
||||||
|
*.temp
|
||||||
|
*.swp
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>财务系统 - 统一费用支付平台</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+3567
File diff suppressed because it is too large.
@@ -0,0 +1,35 @@
|
|||||||
|
{
|
||||||
|
"name": "finance-system-frontend",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"test": "node --test src/feishuDirectory.test.mjs src/layout.test.mjs",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@element-plus/icons-vue": "^2.3.0",
|
||||||
|
"@vueuse/core": "^10.7.0",
|
||||||
|
"axios": "^1.6.0",
|
||||||
|
"dayjs": "^1.11.0",
|
||||||
|
"echarts": "^5.4.0",
|
||||||
|
"element-plus": "^2.5.0",
|
||||||
|
"lodash-es": "^4.17.21",
|
||||||
|
"pinia": "^2.1.0",
|
||||||
|
"vue": "^3.4.0",
|
||||||
|
"vue-echarts": "^6.6.0",
|
||||||
|
"vue-router": "^4.2.0"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.0.0",
|
||||||
|
"autoprefixer": "^10.4.0",
|
||||||
|
"postcss": "^8.4.0",
|
||||||
|
"sass": "^1.69.0",
|
||||||
|
"tailwindcss": "^3.4.0",
|
||||||
|
"typescript": "^5.3.0",
|
||||||
|
"vite": "^5.0.0",
|
||||||
|
"vue-tsc": "^3.3.11"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
+121
@@ -0,0 +1,121 @@
|
|||||||
|
<template>
|
||||||
|
<router-view v-slot="{ Component, route }">
|
||||||
|
<!--
|
||||||
|
The root route is Layout, so child menu changes must not replace this
|
||||||
|
component. Keep the key at the top-level route depth and let the nested
|
||||||
|
router-view in Layout update the page content instead.
|
||||||
|
-->
|
||||||
|
<transition name="fade">
|
||||||
|
<component :is="Component" :key="route.matched[0]?.path" />
|
||||||
|
</transition>
|
||||||
|
</router-view>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { onBeforeUnmount, onMounted, watch } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
import {
|
||||||
|
AUTH_DAY_KEY,
|
||||||
|
DEMO_SESSION_TOKEN,
|
||||||
|
TOKEN_KEY,
|
||||||
|
USER_INFO_KEY,
|
||||||
|
getBusinessDay,
|
||||||
|
scheduleNextBusinessDay,
|
||||||
|
} from '@/utils/dailyAuth'
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const workbench = useWorkbenchStore()
|
||||||
|
const router = useRouter()
|
||||||
|
let disposeDailyTimer: (() => void) | null = null
|
||||||
|
let storageSyncTimer: number | null = null
|
||||||
|
|
||||||
|
const clearSessionAndRedirect = () => {
|
||||||
|
// reset increments workbench's request version, so responses from the old
|
||||||
|
// identity cannot repopulate the next user's business snapshot.
|
||||||
|
workbench.reset()
|
||||||
|
userStore.logout()
|
||||||
|
if (router.currentRoute.value.path !== '/login') void router.replace('/login')
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkDailySession = () => {
|
||||||
|
const hadSession = Boolean(
|
||||||
|
localStorage.getItem(TOKEN_KEY) ||
|
||||||
|
localStorage.getItem(USER_INFO_KEY) ||
|
||||||
|
localStorage.getItem(AUTH_DAY_KEY) ||
|
||||||
|
userStore.token,
|
||||||
|
)
|
||||||
|
const valid = userStore.ensureDailyAuth()
|
||||||
|
if (!valid && hadSession) clearSessionAndRedirect()
|
||||||
|
return valid
|
||||||
|
}
|
||||||
|
|
||||||
|
const scheduleDailyCheck = () => {
|
||||||
|
disposeDailyTimer?.()
|
||||||
|
disposeDailyTimer = scheduleNextBusinessDay(() => {
|
||||||
|
checkDailySession()
|
||||||
|
scheduleDailyCheck()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleStorage = (event: StorageEvent) => {
|
||||||
|
if ((event.storageArea && event.storageArea !== localStorage) || (event.key !== null && ![TOKEN_KEY, USER_INFO_KEY, AUTH_DAY_KEY].includes(event.key))) return
|
||||||
|
|
||||||
|
// localStorage is shared by tabs. Coalesce the three writes made during a
|
||||||
|
// login so another tab cannot keep an old Pinia identity with a new token.
|
||||||
|
if (storageSyncTimer !== null) window.clearTimeout(storageSyncTimer)
|
||||||
|
storageSyncTimer = window.setTimeout(() => {
|
||||||
|
storageSyncTimer = null
|
||||||
|
const token = localStorage.getItem(TOKEN_KEY)
|
||||||
|
const valid = userStore.ensureDailyAuth()
|
||||||
|
if (!valid || !token) {
|
||||||
|
clearSessionAndRedirect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
workbench.reset()
|
||||||
|
if (router.currentRoute.value.path !== '/login') void router.replace('/dashboard')
|
||||||
|
}, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialize app
|
||||||
|
const initApp = async () => {
|
||||||
|
if (!checkDailySession()) return
|
||||||
|
|
||||||
|
const token = userStore.token
|
||||||
|
if (token && token !== DEMO_SESSION_TOKEN) {
|
||||||
|
try {
|
||||||
|
await userStore.fetchUserInfo()
|
||||||
|
} catch {
|
||||||
|
workbench.reset()
|
||||||
|
if (router.currentRoute.value.path !== '/login') void router.replace('/login')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
window.addEventListener('storage', handleStorage)
|
||||||
|
scheduleDailyCheck()
|
||||||
|
void initApp()
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(() => userStore.token, scheduleDailyCheck)
|
||||||
|
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
window.removeEventListener('storage', handleStorage)
|
||||||
|
disposeDailyTimer?.()
|
||||||
|
if (storageSyncTimer !== null) window.clearTimeout(storageSyncTimer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
.fade-enter-active,
|
||||||
|
.fade-leave-active {
|
||||||
|
transition: opacity 0.2s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.fade-enter-from,
|
||||||
|
.fade-leave-to {
|
||||||
|
opacity: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
import request from './request'
|
||||||
|
|
||||||
|
export type Status = 'ACTIVE' | 'INACTIVE'
|
||||||
|
|
||||||
|
export interface AdminUser {
|
||||||
|
id: number
|
||||||
|
employeeNo: string
|
||||||
|
realName: string
|
||||||
|
avatarUrl?: string
|
||||||
|
email?: string
|
||||||
|
departmentName?: string
|
||||||
|
position?: string
|
||||||
|
userType?: string
|
||||||
|
status: string
|
||||||
|
feishuStatus?: string
|
||||||
|
feishuOpenId?: string
|
||||||
|
feishuUserId?: string
|
||||||
|
lastLoginAt?: string
|
||||||
|
roleCodes?: string[]
|
||||||
|
groupNames?: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Role {
|
||||||
|
id: number
|
||||||
|
roleCode: string
|
||||||
|
roleName: string
|
||||||
|
description?: string
|
||||||
|
status: Status | string
|
||||||
|
builtIn: boolean
|
||||||
|
memberCount?: number
|
||||||
|
permissionCount?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PermissionItem {
|
||||||
|
code: string
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
parentCode?: string
|
||||||
|
resource?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RolePermissions {
|
||||||
|
permissionCodes: string[]
|
||||||
|
fieldPermissions: Record<string, 'HIDDEN' | 'READ' | 'EDIT'>
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UserGroup {
|
||||||
|
id: number
|
||||||
|
groupCode: string
|
||||||
|
groupName: string
|
||||||
|
description?: string
|
||||||
|
status: Status | string
|
||||||
|
memberCount?: number
|
||||||
|
roleCount?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface GroupCandidate {
|
||||||
|
id: number
|
||||||
|
realName: string
|
||||||
|
employeeNo?: string
|
||||||
|
departmentName?: string
|
||||||
|
feishuOpenId?: string
|
||||||
|
feishuUserId?: string
|
||||||
|
status: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationField {
|
||||||
|
key: string
|
||||||
|
label: string
|
||||||
|
value?: unknown
|
||||||
|
secret: boolean
|
||||||
|
configured: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationProvider {
|
||||||
|
enabled: boolean
|
||||||
|
fields: IntegrationField[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IntegrationConfig {
|
||||||
|
feishu: IntegrationProvider
|
||||||
|
kingdee: IntegrationProvider
|
||||||
|
}
|
||||||
|
|
||||||
|
export const adminApi = {
|
||||||
|
listUsers: (): Promise<AdminUser[]> => request.get('/auth/users'),
|
||||||
|
updateUserRoles: (id: number, roleIds: number[]): Promise<AdminUser> =>
|
||||||
|
request.put(`/auth/users/${id}/roles`, { roleIds }),
|
||||||
|
|
||||||
|
listRoles: (): Promise<Role[]> => request.get('/roles'),
|
||||||
|
createRole: (body: Pick<Role, 'roleCode' | 'roleName' | 'description' | 'status'>): Promise<Role> =>
|
||||||
|
request.post('/roles', body),
|
||||||
|
updateRole: (id: number, body: Partial<Pick<Role, 'roleCode' | 'roleName' | 'description' | 'status'>>): Promise<Role> =>
|
||||||
|
request.put(`/roles/${id}`, body),
|
||||||
|
deleteRole: (id: number): Promise<void> => request.delete(`/roles/${id}`),
|
||||||
|
listPermissions: (): Promise<PermissionItem[]> => request.get('/roles/permissions'),
|
||||||
|
getRolePermissions: (id: number): Promise<RolePermissions> => request.get(`/roles/${id}/permissions`),
|
||||||
|
updateRolePermissions: (id: number, body: RolePermissions): Promise<void> =>
|
||||||
|
request.put(`/roles/${id}/permissions`, body),
|
||||||
|
|
||||||
|
listGroups: (): Promise<UserGroup[]> => request.get('/user-groups'),
|
||||||
|
createGroup: (body: Pick<UserGroup, 'groupCode' | 'groupName' | 'description' | 'status'>): Promise<UserGroup> =>
|
||||||
|
request.post('/user-groups', body),
|
||||||
|
updateGroup: (id: number, body: Partial<Pick<UserGroup, 'groupCode' | 'groupName' | 'description' | 'status'>>): Promise<UserGroup> =>
|
||||||
|
request.put(`/user-groups/${id}`, body),
|
||||||
|
deleteGroup: (id: number): Promise<void> => request.delete(`/user-groups/${id}`),
|
||||||
|
getGroupRoles: (id: number): Promise<{ roleIds: number[] }> => request.get(`/user-groups/${id}/roles`),
|
||||||
|
updateGroupRoles: (id: number, roleIds: number[]): Promise<void> =>
|
||||||
|
request.put(`/user-groups/${id}/roles`, { roleIds }),
|
||||||
|
getGroupMembers: (id: number): Promise<{ userIds: number[] }> => request.get(`/user-groups/${id}/members`),
|
||||||
|
updateGroupMembers: (id: number, userIds: number[]): Promise<void> =>
|
||||||
|
request.put(`/user-groups/${id}/members`, { userIds }),
|
||||||
|
listCandidates: (): Promise<GroupCandidate[]> => request.get('/user-groups/candidates'),
|
||||||
|
|
||||||
|
getIntegrationConfig: (): Promise<IntegrationConfig> => request.get('/integrations/config'),
|
||||||
|
updateIntegrationConfig: (provider: 'FEISHU' | 'KINGDEE', enabled: boolean, values: Record<string, unknown>): Promise<void> =>
|
||||||
|
request.put('/integrations/config', { provider, enabled, values }),
|
||||||
|
testIntegration: (provider: 'FEISHU' | 'KINGDEE'): Promise<{ provider: string; configured: boolean; success: boolean; message: string }> =>
|
||||||
|
request.post('/integrations/config/test', { provider }),
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import request from './request'
|
||||||
|
|
||||||
|
export interface UserProfile {
|
||||||
|
id: number
|
||||||
|
employeeNo: string
|
||||||
|
realName: string
|
||||||
|
avatarUrl: string
|
||||||
|
email: string
|
||||||
|
departmentName: string
|
||||||
|
position: string
|
||||||
|
userType: string
|
||||||
|
status: string
|
||||||
|
feishuStatus: string
|
||||||
|
lastLoginAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LoginResponse {
|
||||||
|
token: string
|
||||||
|
tokenType: string
|
||||||
|
expiresIn: number
|
||||||
|
user: UserProfile
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authApi = {
|
||||||
|
feishuLogin: (code: string, state?: string): Promise<LoginResponse> =>
|
||||||
|
request.post('/auth/feishu-login', { code, state }),
|
||||||
|
|
||||||
|
getAuthUrl: (): Promise<{ authUrl: string }> => request.get('/feishu/auth-url'),
|
||||||
|
|
||||||
|
getUserInfo: (): Promise<UserProfile> =>
|
||||||
|
request.get('/auth/me'),
|
||||||
|
|
||||||
|
refreshToken: (): Promise<LoginResponse> =>
|
||||||
|
request.post('/auth/refresh'),
|
||||||
|
|
||||||
|
logout: (): Promise<void> =>
|
||||||
|
request.post('/auth/logout'),
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import type { CreateApplicationRequest, PaymentRecord, ReimApplicationDetail, ReimApplicationSummary } from './reimbursement'
|
||||||
|
|
||||||
|
export interface FallbackUser {
|
||||||
|
id: number
|
||||||
|
employeeNo: string
|
||||||
|
realName: string
|
||||||
|
avatarUrl: string
|
||||||
|
email: string
|
||||||
|
departmentName: string
|
||||||
|
position: string
|
||||||
|
userType: string
|
||||||
|
status: string
|
||||||
|
feishuStatus: string
|
||||||
|
lastLoginAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FallbackWorkbench {
|
||||||
|
user: FallbackUser
|
||||||
|
reimbursements: ReimApplicationDetail[]
|
||||||
|
payments: PaymentRecord[]
|
||||||
|
notifications: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = (id: string, title: string, owner: string, department: string, amount: number, applicationStatus: string, approvalStatus: string, approvalNode: string, receiptStatus: string, category: string, date: string, returnReason = ''): ReimApplicationDetail => ({
|
||||||
|
id, applicationNo: id, title, applicantName: owner, applicantEmployeeNo: owner === '李志豪' ? 'EMP000086' : 'EMP000102', departmentName: department,
|
||||||
|
expenseTypeId: 1, expenseTypeName: '员工报销', category, totalAmount: amount,
|
||||||
|
description: title === '上海客户现场技术交流差旅' ? '上海客户现场技术交流产生的交通及住宿费用。' : `${title},用于日常业务支持。`,
|
||||||
|
applicationStatus, approvalStatus, currentApprovalNode: approvalNode, receiptStatus, paymentStatus: '未付款', budgetStatus: receiptStatus === '已收单' ? '已转执行' : '已占用',
|
||||||
|
sourceDocNo: `TRIP${date.replace(/-/g, '')}`, sourceStatus: '已同步', payeeName: owner, payeeBankId: 1,
|
||||||
|
bankName: owner === '李志豪' ? '中国工商银行苏州新区支行' : '招商银行苏州工业园区支行', bankAccountMask: owner === '李志豪' ? '6222 **** 0728' : '6214 **** 8001',
|
||||||
|
returnReason, submitTime: `${date} 09:42`, createdAt: `${date} 09:42`, updatedAt: `${date} 10:24`,
|
||||||
|
expenseItems: [{ id: `${id}-1`, seqNo: 1, expenseDate: date, category, description: title, amount }],
|
||||||
|
invoices: amount === 3286.5 ? [] : [{ id: `${id}-invoice`, invoiceNo: `0330026001114${id.slice(-5)}`, invoiceType: '增值税普通发票', issueDate: date, amount, sellerName: '业务服务商', verifyStatus: '已校验' }],
|
||||||
|
attachments: [{ id: `${id}-attachment`, fileName: `${category}证明材料.pdf`, fileType: 'PDF', fileUrl: '' }], approvalRecords: [], payments: [],
|
||||||
|
})
|
||||||
|
|
||||||
|
export const fallbackWorkbench: FallbackWorkbench = {
|
||||||
|
user: { id: 86, employeeNo: 'EMP000086', realName: '李志豪', avatarUrl: '', email: '', departmentName: '销售中心', position: '销售经理', userType: 'EMPLOYEE', status: 'ACTIVE', feishuStatus: '已授权', lastLoginAt: '' },
|
||||||
|
reimbursements: [
|
||||||
|
item('BX20260812001', '上海客户现场技术交流差旅', '李志豪', '销售中心', 3286.5, '已提交', '退回', '申请人补充材料', '未触发', '差旅交通', '2026-08-12', '请补充住宿发票影像,并说明住宿日期。'),
|
||||||
|
item('BX20260809003', '八月客户拜访交通费', '李志豪', '销售中心', 1260, '已提交', '审批中', '应付会计审核', '未触发', '交通费', '2026-08-09'),
|
||||||
|
item('BX20260808006', '研发现场餐费报销', '王忠辉', '数字化中心', 680, '已提交', '审批中', '财务经理审批', '未触发', '业务招待', '2026-08-08'),
|
||||||
|
item('BX20260802011', '苏州园区客户拜访费用', '赵海峰', '供应链中心', 2180, '已提交', '审批通过', '流程已完成', '待收单', '交通费', '2026-08-02'),
|
||||||
|
item('BX20260801009', '七月云资源差旅补贴', '王忠辉', '数字化中心', 3200, '已提交', '审批通过', '流程已完成', '已收单', '差旅补贴', '2026-08-01'),
|
||||||
|
item('BX20260728004', '上海项目住宿费', '赵海峰', '供应链中心', 4100, '已提交', '审批通过', '流程已完成', '已收单', '住宿费', '2026-07-28'),
|
||||||
|
],
|
||||||
|
payments: [{ id: 'PAY-20260803-01', paymentNo: 'PAY-20260803-01', applicationId: 'BX20260728004', paymentAmount: 1800, totalAmount: 4100, paidAmount: 1800, remainingAmount: 2300, paymentMethod: '银行转账', paymentStatus: '有效', operatorName: '周敏', paymentTime: '2026-08-03 15:24', remark: 'FLOW202608030883' }],
|
||||||
|
notifications: 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
export const fallbackLogin = (employeeNo = 'EMP000086'): { token: string; user: FallbackUser } => {
|
||||||
|
const finance = employeeNo.trim().toUpperCase() === 'FINANCE'
|
||||||
|
return {
|
||||||
|
token: 'demo-local-session',
|
||||||
|
user: {
|
||||||
|
...fallbackWorkbench.user,
|
||||||
|
employeeNo: finance ? 'FINANCE-DEMO' : employeeNo,
|
||||||
|
realName: finance ? '财务人员' : employeeNo === 'EMP000086' ? '李志豪' : '员工用户',
|
||||||
|
departmentName: finance ? '财务中心' : fallbackWorkbench.user.departmentName,
|
||||||
|
position: finance ? '财务专员' : fallbackWorkbench.user.position,
|
||||||
|
userType: finance ? 'FINANCE' : 'EMPLOYEE',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const cloneFallback = (): FallbackWorkbench => structuredClone(fallbackWorkbench)
|
||||||
|
|
||||||
|
export const createFallbackDetail = (payload: CreateApplicationRequest, id: string, user: FallbackUser): ReimApplicationDetail => ({
|
||||||
|
id, applicationNo: id, title: payload.title, applicantName: user.realName, applicantEmployeeNo: user.employeeNo, departmentName: user.departmentName,
|
||||||
|
expenseTypeId: payload.expenseTypeId, expenseTypeName: '员工报销', category: payload.category, totalAmount: payload.totalAmount, description: payload.description,
|
||||||
|
applicationStatus: '草稿', approvalStatus: '未触发', currentApprovalNode: '未提交', receiptStatus: '未触发', paymentStatus: '未付款', budgetStatus: '已占用',
|
||||||
|
sourceDocNo: '', sourceStatus: '未关联', payeeName: payload.payeeName, payeeBankId: payload.payeeBankId, bankName: '收款账户', bankAccountMask: '已脱敏', returnReason: '', submitTime: '',
|
||||||
|
createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), expenseItems: payload.items, invoices: [], attachments: [], approvalRecords: [], payments: [],
|
||||||
|
})
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import request from './request'
|
||||||
|
|
||||||
|
export interface DirectoryRun {
|
||||||
|
runId: string
|
||||||
|
trigger: 'MANUAL' | 'STARTUP'
|
||||||
|
state: 'RUNNING' | 'SUCCEEDED' | 'FAILED'
|
||||||
|
startedAt: string
|
||||||
|
finishedAt: string | null
|
||||||
|
complete: boolean
|
||||||
|
applied: boolean
|
||||||
|
counts: Record<'departments' | 'usersSeen' | 'excluded' | 'created' | 'updated' | 'outOfScope', number>
|
||||||
|
errorCode: string | null
|
||||||
|
errorMessage: string | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DirectoryStatus {
|
||||||
|
configured: boolean
|
||||||
|
running: boolean
|
||||||
|
snapshotState: 'UNAVAILABLE' | 'NEVER_SYNCED' | 'FRESH' | 'STALE' | 'CONTEXT_CHANGED'
|
||||||
|
maxStatusAgeSeconds: number
|
||||||
|
lastSuccessfulRunId: string | null
|
||||||
|
lastSuccessfulAt: string | null
|
||||||
|
snapshotExpiresAt: string | null
|
||||||
|
lastRun: DirectoryRun | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DirectoryDepartment {
|
||||||
|
id: string
|
||||||
|
name: string
|
||||||
|
parentId: string
|
||||||
|
// The backend serializes Feishu's potentially-large integer order as text.
|
||||||
|
// Keep it as text at the API boundary so it cannot lose precision in JS.
|
||||||
|
order: string
|
||||||
|
memberCount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DirectoryOrganizationUser {
|
||||||
|
openId: string
|
||||||
|
userId: string
|
||||||
|
name: string
|
||||||
|
email: string
|
||||||
|
mobile: string
|
||||||
|
jobTitle: string
|
||||||
|
employeeType: number | null
|
||||||
|
avatarUrl: string
|
||||||
|
employmentStatus: string
|
||||||
|
departmentIds: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DirectoryOrganization {
|
||||||
|
snapshotState: DirectoryStatus['snapshotState']
|
||||||
|
lastSuccessfulAt: string | null
|
||||||
|
departments: DirectoryDepartment[]
|
||||||
|
users: DirectoryOrganizationUser[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Backend elapsed() caps collection at 300s; allow transport/commit headroom.
|
||||||
|
export const DIRECTORY_SYNC_TIMEOUT = 360_000
|
||||||
|
export const feishuDirectoryApi = {
|
||||||
|
sync: (signal?: AbortSignal): Promise<DirectoryRun> =>
|
||||||
|
request.post('/feishu/directory/sync', undefined, { timeout: DIRECTORY_SYNC_TIMEOUT, signal }),
|
||||||
|
status: (signal?: AbortSignal): Promise<DirectoryStatus> =>
|
||||||
|
request.get('/feishu/directory/status', { signal }),
|
||||||
|
organization: (signal?: AbortSignal): Promise<DirectoryOrganization> =>
|
||||||
|
request.get('/feishu/directory/organization', { signal }),
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import request from './request'
|
||||||
|
|
||||||
|
export interface PageResponse<T> {
|
||||||
|
content: T[]
|
||||||
|
totalElements: number
|
||||||
|
totalPages: number
|
||||||
|
currentPage: number
|
||||||
|
pageSize: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReimApplicationSummary {
|
||||||
|
id: number | string
|
||||||
|
applicationNo: string
|
||||||
|
title: string
|
||||||
|
applicantName: string
|
||||||
|
departmentName: string
|
||||||
|
expenseTypeName: string
|
||||||
|
category: string
|
||||||
|
totalAmount: number
|
||||||
|
applicationStatus: string
|
||||||
|
approvalStatus: string
|
||||||
|
currentApprovalNode: string
|
||||||
|
receiptStatus: string
|
||||||
|
paymentStatus: string
|
||||||
|
budgetStatus: string
|
||||||
|
submitTime: string
|
||||||
|
createdAt: string
|
||||||
|
returnReason?: string
|
||||||
|
paidAmount?: number
|
||||||
|
remainingAmount?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReimApplicationDetail {
|
||||||
|
id: number | string
|
||||||
|
applicationNo: string
|
||||||
|
title: string
|
||||||
|
applicantName: string
|
||||||
|
applicantEmployeeNo: string
|
||||||
|
departmentName: string
|
||||||
|
expenseTypeId: number
|
||||||
|
expenseTypeName: string
|
||||||
|
category: string
|
||||||
|
totalAmount: number
|
||||||
|
description: string
|
||||||
|
applicationStatus: string
|
||||||
|
approvalStatus: string
|
||||||
|
currentApprovalNode: string
|
||||||
|
receiptStatus: string
|
||||||
|
paymentStatus: string
|
||||||
|
budgetStatus: string
|
||||||
|
sourceDocNo: string
|
||||||
|
sourceStatus: string
|
||||||
|
payeeName: string
|
||||||
|
payeeBankId: number
|
||||||
|
bankName: string
|
||||||
|
bankAccountMask: string
|
||||||
|
returnReason: string
|
||||||
|
submitTime: string
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
expenseItems: ExpenseItem[]
|
||||||
|
invoices: Invoice[]
|
||||||
|
attachments: Attachment[]
|
||||||
|
approvalRecords: ApprovalRecord[]
|
||||||
|
payments: PaymentRecord[]
|
||||||
|
paidAmountSnapshot?: number
|
||||||
|
remainingAmountSnapshot?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExpenseItem {
|
||||||
|
id?: number | string
|
||||||
|
seqNo?: number
|
||||||
|
expenseDate: string
|
||||||
|
category: string
|
||||||
|
description?: string
|
||||||
|
amount: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CreateApplicationRequest {
|
||||||
|
title: string
|
||||||
|
expenseTypeId: number
|
||||||
|
category: string
|
||||||
|
totalAmount: number
|
||||||
|
description: string
|
||||||
|
payeeName: string
|
||||||
|
payeeBankId: number
|
||||||
|
items: ExpenseItem[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Invoice {
|
||||||
|
id: number | string
|
||||||
|
invoiceNo: string
|
||||||
|
invoiceType: string
|
||||||
|
issueDate: string
|
||||||
|
amount: number
|
||||||
|
sellerName: string
|
||||||
|
verifyStatus: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Attachment {
|
||||||
|
id: number | string
|
||||||
|
fileName: string
|
||||||
|
fileType: string
|
||||||
|
fileUrl: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApprovalRecord {
|
||||||
|
id: number | string
|
||||||
|
nodeName: string
|
||||||
|
approverName: string
|
||||||
|
action: string
|
||||||
|
comment: string
|
||||||
|
actionTime: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PaymentRecord {
|
||||||
|
id: number | string
|
||||||
|
paymentNo: string
|
||||||
|
applicationId?: number | string
|
||||||
|
paymentAmount: number
|
||||||
|
totalAmount: number
|
||||||
|
paidAmount: number
|
||||||
|
remainingAmount: number
|
||||||
|
paymentMethod: string
|
||||||
|
referenceNo?: string
|
||||||
|
paymentStatus: string
|
||||||
|
operatorName: string
|
||||||
|
paymentTime: string
|
||||||
|
remark: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const reimbursementApi = {
|
||||||
|
getWorkbench: (): Promise<any> =>
|
||||||
|
request.get('/v1/reimbursements/workbench'),
|
||||||
|
|
||||||
|
getMyApplications: (params?: { status?: string; page?: number; size?: number }): Promise<PageResponse<ReimApplicationSummary>> =>
|
||||||
|
request.get('/v1/reimbursements/my', { params }),
|
||||||
|
|
||||||
|
getDetail: (id: number | string): Promise<ReimApplicationDetail> =>
|
||||||
|
request.get(`/v1/reimbursements/${id}`),
|
||||||
|
|
||||||
|
getByApplicationNo: (no: string): Promise<ReimApplicationDetail> =>
|
||||||
|
request.get(`/v1/reimbursements/no/${no}`),
|
||||||
|
|
||||||
|
create: (data: CreateApplicationRequest): Promise<ReimApplicationDetail> =>
|
||||||
|
request.post('/v1/reimbursements', data),
|
||||||
|
|
||||||
|
update: (id: number | string, data: CreateApplicationRequest): Promise<ReimApplicationDetail> =>
|
||||||
|
request.put(`/v1/reimbursements/${id}`, data),
|
||||||
|
|
||||||
|
submit: (id: number | string): Promise<ReimApplicationDetail> =>
|
||||||
|
request.post(`/v1/reimbursements/${id}/submit`),
|
||||||
|
|
||||||
|
receive: (id: number | string): Promise<ReimApplicationDetail> =>
|
||||||
|
request.post(`/v1/reimbursements/${id}/receive`),
|
||||||
|
|
||||||
|
delete: (id: number | string): Promise<void> =>
|
||||||
|
request.delete(`/v1/reimbursements/${id}`),
|
||||||
|
}
|
||||||
|
|
||||||
|
export const accountsPayableApi = {
|
||||||
|
getTasks: (params?: { status?: string; page?: number; size?: number }): Promise<any> =>
|
||||||
|
request.get('/v1/accounts-payable/tasks', { params }),
|
||||||
|
|
||||||
|
getTaskDetail: (id: number | string): Promise<ReimApplicationDetail> =>
|
||||||
|
request.get(`/v1/accounts-payable/tasks/${id}`),
|
||||||
|
|
||||||
|
approve: (applicationId: number | string, comment: string): Promise<void> =>
|
||||||
|
request.post('/v1/accounts-payable/approve', { applicationId, comment }),
|
||||||
|
|
||||||
|
reject: (applicationId: number | string, comment: string, returnReason: string): Promise<void> =>
|
||||||
|
request.post('/v1/accounts-payable/reject', { applicationId, comment, returnReason }),
|
||||||
|
|
||||||
|
getHistory: (): Promise<ApprovalRecord[]> =>
|
||||||
|
request.get('/v1/accounts-payable/history'),
|
||||||
|
}
|
||||||
|
|
||||||
|
export const cashierApi = {
|
||||||
|
getTasks: (params?: { status?: string; page?: number; size?: number }): Promise<any> =>
|
||||||
|
request.get('/v1/cashier/tasks', { params }),
|
||||||
|
|
||||||
|
getTaskDetail: (id: number | string): Promise<any> =>
|
||||||
|
request.get(`/v1/cashier/tasks/${id}`),
|
||||||
|
|
||||||
|
executePayment: (applicationId: number | string, paymentAmount: number, remark?: string, idempotencyKey?: string): Promise<any> =>
|
||||||
|
request.post('/v1/cashier/pay', { applicationId, paymentAmount, remark }, idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : undefined),
|
||||||
|
|
||||||
|
partialPayment: (applicationId: number | string, paymentAmount: number, remark?: string, idempotencyKey?: string): Promise<any> =>
|
||||||
|
request.post('/v1/cashier/partial-pay', { applicationId, paymentAmount, remark }, idempotencyKey ? { headers: { 'Idempotency-Key': idempotencyKey } } : undefined),
|
||||||
|
|
||||||
|
getHistory: (): Promise<PaymentRecord[]> =>
|
||||||
|
request.get('/v1/cashier/history'),
|
||||||
|
}
|
||||||
|
|
||||||
|
export const dashboardApi = {
|
||||||
|
getStats: (): Promise<any> =>
|
||||||
|
request.get('/v1/dashboard/stats'),
|
||||||
|
|
||||||
|
getRecent: (limit?: number): Promise<ReimApplicationSummary[]> =>
|
||||||
|
request.get('/v1/dashboard/recent', { params: { limit } }),
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import type { AxiosRequestConfig } from 'axios'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import router from '@/router'
|
||||||
|
|
||||||
|
type ApiClient = {
|
||||||
|
get<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T>
|
||||||
|
post<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T>
|
||||||
|
put<T = unknown>(url: string, data?: unknown, config?: AxiosRequestConfig): Promise<T>
|
||||||
|
delete<T = unknown>(url: string, config?: AxiosRequestConfig): Promise<T>
|
||||||
|
}
|
||||||
|
|
||||||
|
const axiosClient = axios.create({
|
||||||
|
// Keep the same-origin default for Vite/Nginx proxy deployments while
|
||||||
|
// allowing a static build to call an explicitly configured API origin.
|
||||||
|
baseURL: (import.meta.env.VITE_API_BASE_URL || '/api').replace(/\/$/, ''),
|
||||||
|
timeout: 15000,
|
||||||
|
// Required for the Feishu OAuth state double-submit cookie when the
|
||||||
|
// frontend and API are served from different origins.
|
||||||
|
withCredentials: true,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
})
|
||||||
|
|
||||||
|
const clearSessionAndRedirect = () => {
|
||||||
|
localStorage.removeItem('token')
|
||||||
|
localStorage.removeItem('userInfo')
|
||||||
|
if (router.currentRoute.value.path !== '/login') {
|
||||||
|
void router.push('/login')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestToken = (config: unknown): string | undefined => {
|
||||||
|
const token = (config as { __authToken?: unknown } | undefined)?.__authToken
|
||||||
|
return typeof token === 'string' && token ? token : undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearOnlyIfRequestOwnsSession = (config: unknown) => {
|
||||||
|
const issuedToken = requestToken(config)
|
||||||
|
if (issuedToken && localStorage.getItem('token') === issuedToken) clearSessionAndRedirect()
|
||||||
|
}
|
||||||
|
|
||||||
|
let lastNotification = ''
|
||||||
|
let lastNotificationAt = 0
|
||||||
|
|
||||||
|
const notifyOnce = (message: string, type: 'error' | 'warning' | 'info' = 'error') => {
|
||||||
|
const now = Date.now()
|
||||||
|
if (message === lastNotification && now - lastNotificationAt < 1500) return
|
||||||
|
lastNotification = message
|
||||||
|
lastNotificationAt = now
|
||||||
|
ElMessage[type](message)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Request interceptor - attach JWT token
|
||||||
|
axiosClient.interceptors.request.use(
|
||||||
|
(config) => {
|
||||||
|
const token = localStorage.getItem('token')
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`
|
||||||
|
}
|
||||||
|
const trackedConfig = config as typeof config & { __authToken?: string }
|
||||||
|
trackedConfig.__authToken = token || undefined
|
||||||
|
return config
|
||||||
|
},
|
||||||
|
(error) => Promise.reject(error)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Response interceptor - unwrap ApiResponse wrapper
|
||||||
|
axiosClient.interceptors.response.use(
|
||||||
|
(response) => {
|
||||||
|
const res = response.data
|
||||||
|
// All current backend endpoints return ApiResponse. Keeping the fallback
|
||||||
|
// makes this client safe for a plain health/config response as well.
|
||||||
|
if (!res || typeof res !== 'object' || !('code' in res)) return res
|
||||||
|
|
||||||
|
if (res.code !== 200) {
|
||||||
|
if (res.code === 401) clearOnlyIfRequestOwnsSession(response.config)
|
||||||
|
notifyOnce(res.message || '请求失败')
|
||||||
|
return Promise.reject(new Error(res.message || '请求失败'))
|
||||||
|
}
|
||||||
|
return res.data
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
if (error.response) {
|
||||||
|
const { status, data } = error.response
|
||||||
|
switch (status) {
|
||||||
|
case 401:
|
||||||
|
clearOnlyIfRequestOwnsSession(error.config)
|
||||||
|
notifyOnce('登录已过期,请重新登录')
|
||||||
|
break
|
||||||
|
case 403:
|
||||||
|
notifyOnce('权限不足')
|
||||||
|
break
|
||||||
|
case 404:
|
||||||
|
notifyOnce('请求的资源不存在')
|
||||||
|
break
|
||||||
|
case 409:
|
||||||
|
notifyOnce(data?.message || '业务冲突')
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
notifyOnce(data?.message || '服务器错误')
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
notifyOnce('网络连接失败')
|
||||||
|
}
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
export default axiosClient as unknown as ApiClient
|
||||||
+2532
File diff suppressed because it is too large.
@@ -0,0 +1,140 @@
|
|||||||
|
<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">
|
||||||
|
<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>{{ snapshotLabels[status.snapshotState] }}</dd></div>
|
||||||
|
<div><dt>上次成功同步 <span class="time-zone-label">本地时间</span></dt><dd>{{ formatLocalDateTime(status.lastSuccessfulAt, '暂无') }}</dd></div>
|
||||||
|
<div><dt>快照有效至 <span class="time-zone-label">本地时间</span></dt><dd>{{ formatLocalDateTime(status.snapshotExpiresAt) }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
<p v-if="status.snapshotState === 'STALE' || status.snapshotState === 'CONTEXT_CHANGED'">快照已过期或应用上下文已变化,请重新同步以更新目录资料与业务候选人。</p>
|
||||||
|
</template>
|
||||||
|
<template v-if="run">
|
||||||
|
<p>最近运行:{{ run.trigger === 'STARTUP' ? '启动同步' : '手动同步' }} · {{ 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 { feishuDirectoryApi, type DirectoryRun, type DirectoryStatus } from '@/api/feishuDirectory'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
|
||||||
|
const emit = defineEmits<{ committed: [] }>()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
// Deliberately never use Users.vue's legacy administrator/demo fallback.
|
||||||
|
const canSync = computed(() => userStore.hasPermission('system:feishu:sync'))
|
||||||
|
const canRead = computed(() => canSync.value || userStore.hasPermission('system:feishu:bind'))
|
||||||
|
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 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 snapshotLabels = { UNAVAILABLE: '不可用', NEVER_SYNCED: '尚未同步', FRESH: '有效', STALE: '已过期', CONTEXT_CHANGED: '应用上下文已变化' }
|
||||||
|
const stateLabels = { RUNNING: '运行中', SUCCEEDED: '成功', FAILED: '失败' }
|
||||||
|
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 18px 16px; 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); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div class="page-head"><div><span class="eyebrow">{{ id ? 'EDIT DRAFT' : 'NEW REIMBURSEMENT' }}</span><h1>{{ id && existing?.approvalStatus === '退回' ? '补充退回报销' : id ? '编辑报销草稿' : '发起员工报销' }}</h1><p>{{ id ? '沿用原报销单号,补充材料后重新提交。' : '填写个人垫付费用,提交前检查发票、附件与金额。' }}</p></div><router-link class="btn" to="/applications">取消</router-link></div>
|
||||||
|
<div v-if="loadError" class="inline-alert danger" role="alert"><b>!</b><span>{{ loadError }}</span></div>
|
||||||
|
<div class="step-rail"><div class="step done"><span>1</span><strong>填写报销</strong></div><div class="step active"><span>2</span><strong>材料校验</strong></div><div class="step"><span>3</span><strong>飞书审批</strong></div><div class="step"><span>4</span><strong>财务付款</strong></div></div>
|
||||||
|
<form v-if="!loading" class="form-page" @submit.prevent="save(true)">
|
||||||
|
<section class="section-card"><div class="section-title"><h2>1. 报销信息</h2><span>员工报销 · * 为必填项</span></div><div class="form-grid">
|
||||||
|
<div class="field"><label for="title">报销事项 <em>*</em></label><input id="title" v-model.trim="form.title" required maxlength="100" placeholder="例如:上海客户现场技术交流差旅"></div>
|
||||||
|
<div class="field"><label for="category">费用类型 <em>*</em></label><select id="category" v-model="form.category" required><option v-for="type in expenseTypes" :key="type.id" :value="type.label">{{ type.label }}</option></select></div>
|
||||||
|
<div v-if="showField('application:amount')" class="field"><label for="amount">报销金额(元) <em v-if="editableField('application:amount')">*</em></label><input id="amount" v-model.number="form.totalAmount" type="number" min="0.01" step="0.01" :readonly="readonlyField('application:amount')" :required="editableField('application:amount')" :aria-describedby="readonlyField('application:amount') ? 'amount-permission-help' : undefined"><small v-if="readonlyField('application:amount')" id="amount-permission-help" class="form-help">当前字段只读</small></div>
|
||||||
|
<div class="field"><label>报销人 / 部门</label><input readonly :value="`${userName} · ${department}`"></div>
|
||||||
|
<div v-if="showField('application:payeeName')" class="field"><label for="payee">收款人 <em v-if="editableField('application:payeeName')">*</em></label><input id="payee" v-model.trim="form.payeeName" :readonly="readonlyField('application:payeeName')" maxlength="100" :required="editableField('application:payeeName')"><small v-if="readonlyField('application:payeeName')" class="form-help">当前字段只读</small></div>
|
||||||
|
<div v-if="showField('application:bankAccount')" class="field"><label for="bank">收款账户 ID <em v-if="editableField('application:bankAccount')">*</em></label><input id="bank" v-model.number="form.payeeBankId" type="number" min="1" step="1" :readonly="readonlyField('application:bankAccount')" :required="editableField('application:bankAccount')"><small class="form-help">{{ readonlyField('application:bankAccount') ? '当前字段只读;账户信息不会明文展示。' : '后端当前按账户 ID 关联,详情页只显示脱敏账号。' }}</small></div>
|
||||||
|
<div class="field full"><label for="description">费用说明 <em>*</em></label><textarea id="description" v-model.trim="form.description" required maxlength="500" rows="3"></textarea></div>
|
||||||
|
</div></section>
|
||||||
|
<section class="section-card section-gap"><div class="section-title"><h2>2. 费用明细</h2><button class="btn small" type="button" @click="addItem">+ 添加明细</button></div><div class="expense-items"><div v-for="(item, index) in form.items" :key="item.key" class="expense-item"><div class="field"><label :for="`expense-date-${item.key}`">日期 <em>*</em></label><input :id="`expense-date-${item.key}`" v-model="item.expenseDate" type="date" required></div><div class="field"><label :for="`expense-category-${item.key}`">类别 <em>*</em></label><input :id="`expense-category-${item.key}`" v-model.trim="item.category" required maxlength="50"></div><div class="field"><label :for="`expense-amount-${item.key}`">金额 <em>*</em></label><input :id="`expense-amount-${item.key}`" v-model.number="item.amount" type="number" min="0.01" step="0.01" required></div><div class="field"><label :for="`expense-description-${item.key}`">说明 <em>*</em></label><input :id="`expense-description-${item.key}`" v-model.trim="item.description" required maxlength="200"></div><button v-if="form.items.length > 1" class="remove-item" type="button" :aria-label="`删除第 ${index + 1} 条费用明细`" @click="removeItem(index)">删除</button></div></div><div class="amount-summary" :class="{ 'amount-mismatch': form.totalAmount > 0 && !amountMatches }"><span>明细合计</span><strong>{{ money(itemsTotal) }}</strong><span>申请金额 {{ money(form.totalAmount) }}</span></div></section>
|
||||||
|
<section class="section-card section-gap"><div class="section-title"><h2>3. 发票与附件</h2><span>至少一份材料后可提交</span></div><div class="form-grid"><div class="field"><label for="invoice-no">发票号码</label><input id="invoice-no" v-model.trim="invoiceNumber" maxlength="80"></div><div class="field"><label for="invoice-amount">发票金额</label><input id="invoice-amount" v-model.number="invoiceAmount" type="number" min="0" step="0.01"></div><div class="field"><label for="invoice-file">发票影像</label><input id="invoice-file" type="file" accept="image/*,.pdf" @change="selectFile($event, 'invoice')"><small class="form-help">{{ invoiceFile || '尚未选择文件' }}</small></div><div class="field"><label for="attachment-file">其他附件</label><input id="attachment-file" type="file" multiple @change="selectFile($event, 'attachment')"><small class="form-help">{{ attachmentFiles || '尚未选择文件' }}</small></div></div></section>
|
||||||
|
<div class="form-actions"><button class="btn" type="button" :disabled="saving" @click="save(false)">保存草稿</button><button class="btn primary" type="submit" :disabled="saving" :aria-busy="saving">{{ saving ? '保存中…' : '提交报销' }}</button></div>
|
||||||
|
</form><div v-else class="card load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在读取报销信息…</span></div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, reactive, ref } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import type { CreateApplicationRequest, ExpenseItem } from '@/api/reimbursement'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
|
||||||
|
type FieldLevel = 'HIDDEN' | 'READ' | 'EDIT'
|
||||||
|
interface FormItem extends ExpenseItem { key: number; description: string }
|
||||||
|
const route = useRoute(); const router = useRouter(); const userStore = useUserStore(); const store = useWorkbenchStore(); const id = computed(() => route.params.id ? String(route.params.id) : ''); const existing = computed(() => id.value ? store.getById(id.value) : null); const loading = ref(true); const saving = ref(false); const loadError = ref(''); const invoiceNumber = ref(''); const invoiceAmount = ref(0); const invoiceFile = ref(''); const attachmentFiles = ref(''); let nextKey = 1
|
||||||
|
const userName = computed(() => userStore.userInfo?.realName || store.user?.realName || '用户'); const department = computed(() => userStore.userInfo?.departmentName || store.user?.departmentName || '销售中心'); const expenseTypes = [{ id: 1, label: '差旅交通' }, { id: 2, label: '住宿费' }, { id: 3, label: '业务招待' }, { id: 4, label: '差旅补贴' }, { id: 5, label: '办公费用' }]; const newItem = (value?: Partial<ExpenseItem>): FormItem => ({ key: nextKey++, expenseDate: value?.expenseDate || new Date().toISOString().slice(0, 10), category: value?.category || '', description: value?.description || '', amount: Number(value?.amount || 0), seqNo: value?.seqNo }); const form = reactive({ title: '', category: '差旅交通', totalAmount: 0, description: '', payeeName: '', payeeBankId: undefined as number | undefined, items: [newItem()] })
|
||||||
|
|
||||||
|
// A missing field entry remains editable for compatibility with older roles.
|
||||||
|
// Only a successfully loaded field permission can hide or lock a control.
|
||||||
|
const fieldLevel = (code: string): FieldLevel => { if (!userStore.permissionsLoaded || userStore.permissionsError) return 'EDIT'; return userStore.fieldPermissions[code] || 'EDIT' }; const showField = (code: string) => fieldLevel(code) !== 'HIDDEN'; const readonlyField = (code: string) => fieldLevel(code) === 'READ'; const editableField = (code: string) => fieldLevel(code) === 'EDIT'
|
||||||
|
const itemsTotal = computed(() => form.items.reduce((sum, item) => sum + (Number(item.amount) || 0), 0)); const amountMatches = computed(() => form.items.length > 0 && form.totalAmount > 0 && Math.abs(itemsTotal.value - form.totalAmount) < 0.005); const hasMaterials = computed(() => Boolean(invoiceNumber.value || invoiceAmount.value > 0 || invoiceFile.value || attachmentFiles.value || existing.value?.invoices.length || existing.value?.attachments.length)); const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
|
||||||
|
const hydrate = () => { const item = existing.value; if (!item) return; form.title = item.title; form.category = item.category || '差旅交通'; form.totalAmount = item.totalAmount; form.description = item.description; form.payeeName = item.payeeName || userName.value; form.payeeBankId = item.payeeBankId; form.items = item.expenseItems.length ? item.expenseItems.map(newItem) : [newItem({ amount: item.totalAmount, category: item.category, description: item.title })]; invoiceNumber.value = item.invoices[0]?.invoiceNo || ''; invoiceAmount.value = item.invoices[0]?.amount || 0 }
|
||||||
|
const addItem = () => form.items.push(newItem()); const removeItem = (index: number) => form.items.splice(index, 1); const selectFile = (event: Event, type: 'invoice' | 'attachment') => { const input = event.target as HTMLInputElement; const names = [...(input.files || [])].map(file => file.name).join('、'); if (type === 'invoice') invoiceFile.value = names; else attachmentFiles.value = names }
|
||||||
|
const permissionBlock = (code: string, label: string, value: unknown) => { const level = fieldLevel(code); const missing = value === undefined || value === null || value === '' || Number(value) === 0; return level !== 'EDIT' && missing ? `当前字段“${label}”为${level === 'HIDDEN' ? '隐藏' : '只读'},但业务接口仍要求该字段,请联系管理员开放字段权限后再提交。` : '' }
|
||||||
|
const save = async (submit: boolean) => { loadError.value = ''; const hiddenRequired = [permissionBlock('application:amount', '报销金额', form.totalAmount), permissionBlock('application:payeeName', '收款人', form.payeeName), permissionBlock('application:bankAccount', '收款账户', form.payeeBankId)].find(Boolean); if (hiddenRequired) { loadError.value = hiddenRequired; return } if (!form.title || !form.description || !(form.totalAmount > 0) || !form.payeeName || !(form.payeeBankId && form.items.length && amountMatches.value) || form.items.some(item => !item.expenseDate || !item.category || !item.description || !(item.amount > 0))) { loadError.value = '请完善报销信息,并确保费用明细合计等于报销金额'; return } if (submit && !hasMaterials.value) { loadError.value = '提交前请至少添加一份发票或附件材料'; return } saving.value = true; const payload: CreateApplicationRequest = { title: form.title, expenseTypeId: expenseTypes.find(type => type.label === form.category)?.id || 1, category: form.category, totalAmount: Number(form.totalAmount.toFixed(2)), description: form.description, payeeName: form.payeeName, payeeBankId: form.payeeBankId, items: form.items.map((item, index) => ({ seqNo: index + 1, expenseDate: item.expenseDate, category: item.category, description: item.description, amount: Number(item.amount.toFixed(2)) })) }; try { const saved = await store.save(payload, id.value || undefined); if (store.source === 'fallback') { if (invoiceNumber.value || invoiceAmount.value || invoiceFile.value) saved.invoices = [{ id: `${saved.id}-invoice`, invoiceNo: invoiceNumber.value, invoiceType: '发票影像', issueDate: new Date().toISOString().slice(0, 10), amount: invoiceAmount.value, sellerName: '', verifyStatus: '待校验' }]; if (attachmentFiles.value) saved.attachments = attachmentFiles.value.split('、').map((file, index) => ({ id: `${saved.id}-attachment-${index}`, fileName: file, fileType: 'FILE', fileUrl: '' })) } if (submit) await store.submit(saved.id); ElMessage.success(submit ? '报销已提交' : '草稿已保存'); router.replace(`/applications/${saved.id}`) } catch (error) { loadError.value = error instanceof Error ? error.message : '保存失败,请稍后重试'; ElMessage.error(loadError.value) } finally { saving.value = false } }
|
||||||
|
onMounted(async () => { if (id.value) await store.loadDetail(id.value); else if (!store.reimbursements.length) await store.load(); hydrate(); if (id.value && !existing.value) loadError.value = '未找到该报销单,无法编辑'; loading.value = false })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.form-actions { display: flex; justify-content: flex-end; gap: 9px; padding: 16px 0; }
|
||||||
|
@media (max-width: 560px) { .form-actions { flex-direction: column-reverse; } .form-actions .btn { width: 100%; } }
|
||||||
|
</style>
|
||||||
Vendored
+16
@@ -0,0 +1,16 @@
|
|||||||
|
/// <reference types="vite/client" />
|
||||||
|
|
||||||
|
declare module '*.vue' {
|
||||||
|
import type { DefineComponent } from 'vue'
|
||||||
|
const component: DefineComponent<{}, {}, any>
|
||||||
|
export default component
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImportMetaEnv {
|
||||||
|
readonly VITE_APP_TITLE: string
|
||||||
|
readonly VITE_AUTH_MODE?: 'local' | 'feishu' | string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ImportMeta {
|
||||||
|
readonly env: ImportMetaEnv
|
||||||
|
}
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { parse } from '@vue/compiler-sfc'
|
||||||
|
import ts from 'typescript'
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
|
||||||
|
const source = path => readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||||
|
const panel = parse(source('./components/FeishuDirectoryPanel.vue')).descriptor
|
||||||
|
const result = (overrides = {}) => ({ runId: 'new', state: 'SUCCEEDED', complete: true, applied: true, ...overrides })
|
||||||
|
const snapshot = (overrides = {}) => ({ configured: true, running: false, lastSuccessfulRunId: null, lastRun: null, ...overrides })
|
||||||
|
|
||||||
|
// Execute the actual setup state machine with injected API/lifecycle/timers.
|
||||||
|
// No DOM dependency; template/layout checks below supplement these tests.
|
||||||
|
function setup(api, permissions = ['system:feishu:sync']) {
|
||||||
|
let cleanup, scheduled
|
||||||
|
const events = []
|
||||||
|
const script = ts.transpileModule(panel.scriptSetup.content.replace(/^import .*$/gm, ''), {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
|
||||||
|
}).outputText
|
||||||
|
const state = new Function('computed', 'ref', 'onMounted', 'onBeforeUnmount', 'defineEmits', 'useUserStore', 'feishuDirectoryApi', 'setTimeout', 'clearTimeout', `${script}\nreturn { refreshStatus, sync, syncDisabled, status, error, run, formatLocalDateTime };`)(
|
||||||
|
computed, ref, () => {}, fn => { cleanup = fn }, () => event => events.push(event),
|
||||||
|
() => ({ hasPermission: code => permissions.includes(code) }), api,
|
||||||
|
fn => { scheduled = fn; return 1 }, () => { scheduled = undefined },
|
||||||
|
)
|
||||||
|
return { ...state, events, cleanup: () => cleanup(), poll: () => scheduled?.() }
|
||||||
|
}
|
||||||
|
|
||||||
|
test('directory route and menu are permission-only entry points', () => {
|
||||||
|
const router = source('./router/index.ts')
|
||||||
|
const layout = source('./views/Layout.vue')
|
||||||
|
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
|
||||||
|
assert.match(router, /path: 'feishu-directory'/)
|
||||||
|
assert.match(router, /name: 'FeishuDirectory'/)
|
||||||
|
assert.match(router, /permission: \['system:feishu:sync', 'system:feishu:bind'\]/)
|
||||||
|
assert.doesNotMatch(router.slice(router.indexOf("name: 'FeishuDirectory'"), router.indexOf("name: 'IntegrationConfig'")), /system:user:view|demo-local-session|legacy/i)
|
||||||
|
assert.match(layout, /v-if="canAccess\('feishu-directory'\)"[\s\S]*to="\/feishu-directory"/)
|
||||||
|
assert.match(layout, /'feishu-directory': \['system:feishu:sync', 'system:feishu:bind'\]/)
|
||||||
|
assert.match(page.template.content, /FeishuDirectoryPanel/)
|
||||||
|
assert.doesNotMatch(page.template.content, /FEISHU DIRECTORY|<h1>飞书通讯录<\/h1>|查看飞书通讯录同步状态和最近运行记录|通讯录设置/)
|
||||||
|
assert.doesNotMatch(page.scriptSetup.content, /canViewIntegration|system:integration:view/)
|
||||||
|
assert.doesNotMatch(page.template.content, /secret|credential|token/i)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('directory timestamps use browser local time and safe fallbacks', () => {
|
||||||
|
const state = setup({ status: async () => snapshot() })
|
||||||
|
const previousTz = process.env.TZ
|
||||||
|
process.env.TZ = 'Asia/Shanghai'
|
||||||
|
try {
|
||||||
|
assert.equal(state.formatLocalDateTime('2026-01-02T03:04:05.000Z'), '2026-01-02 11:04:05')
|
||||||
|
} finally {
|
||||||
|
if (previousTz === undefined) delete process.env.TZ
|
||||||
|
else process.env.TZ = previousTz
|
||||||
|
}
|
||||||
|
assert.equal(state.formatLocalDateTime('not-a-date'), '—')
|
||||||
|
assert.equal(state.formatLocalDateTime(null, '暂无'), '暂无')
|
||||||
|
assert.match(panel.template.content, /formatLocalDateTime\(run\.startedAt/)
|
||||||
|
assert.match(panel.template.content, /本地时间/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('API uses unwrapped endpoints, no POST body and bounded-sync timeout headroom', () => {
|
||||||
|
const api = source('./api/feishuDirectory.ts')
|
||||||
|
assert.match(api, /DIRECTORY_SYNC_TIMEOUT = 360_000/)
|
||||||
|
assert.match(api, /request.post\('\/feishu\/directory\/sync', undefined, \{ timeout: DIRECTORY_SYNC_TIMEOUT, signal \}\)/)
|
||||||
|
assert.match(api, /request.get\('\/feishu\/directory\/status'/)
|
||||||
|
assert.match(api, /organization: \(signal\?[\s\S]*request.get\('\/feishu\/directory\/organization'/)
|
||||||
|
for (const field of ['email', 'mobile', 'jobTitle', 'employeeType', 'avatarUrl', 'employmentStatus']) assert.match(api, new RegExp(`\\b${field}\\b`))
|
||||||
|
assert.doesNotMatch(api, /eligibilityReason|eligible\??:/)
|
||||||
|
assert.doesNotMatch(api, /\/api\/feishu/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('organization API types expose Feishu IDs and detail fields', () => {
|
||||||
|
const api = source('./api/feishuDirectory.ts')
|
||||||
|
assert.match(api, /order: string\b/)
|
||||||
|
assert.match(api, /employeeType: number \| null/)
|
||||||
|
for (const field of ['userId', 'openId', 'email', 'mobile', 'jobTitle', 'avatarUrl', 'employmentStatus']) {
|
||||||
|
assert.match(api, new RegExp(`\\b${field}: string\\b`))
|
||||||
|
assert.doesNotMatch(api, new RegExp(`\\b${field}: string \\| null`))
|
||||||
|
}
|
||||||
|
assert.doesNotMatch(api, /employee(?:No|Number)/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('bind-only and missing permissions cannot submit; no legacy fallback', async () => {
|
||||||
|
for (const permissions of [[], ['system:feishu:bind']]) {
|
||||||
|
let posts = 0
|
||||||
|
const state = setup({ status: async () => snapshot(), sync: async () => { posts++ } }, permissions)
|
||||||
|
await state.refreshStatus()
|
||||||
|
await state.sync()
|
||||||
|
assert.equal(state.syncDisabled.value, true)
|
||||||
|
assert.equal(posts, 0)
|
||||||
|
}
|
||||||
|
assert.match(panel.template.content, /v-if="canSync"/)
|
||||||
|
assert.doesNotMatch(panel.scriptSetup.content, /legacyAdmin|useLegacyFallback|userType/)
|
||||||
|
const users = source('./views/Users.vue')
|
||||||
|
assert.doesNotMatch(users, /FeishuDirectoryPanel|refreshDirectoryData/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('organization tree renders departments and employees with safe empty and refresh states', () => {
|
||||||
|
const parsed = parse(source('./views/FeishuDirectory.vue'))
|
||||||
|
const { template, scriptSetup } = parsed.descriptor
|
||||||
|
assert.deepEqual(parsed.errors, [])
|
||||||
|
assert.match(template.content, /@committed="refreshOrganization"/)
|
||||||
|
assert.match(template.content, /class="organization-tree"[^>]*role="tree"/)
|
||||||
|
assert.match(template.content, /v-for="item in visibleDepartments"/)
|
||||||
|
assert.match(template.content, /aria-expanded=/)
|
||||||
|
assert.match(template.content, /class="department-members"/)
|
||||||
|
assert.match(template.content, /v-for="user in paginatedSelectedUsers"/)
|
||||||
|
assert.match(template.content, /class="pagination-footer"/)
|
||||||
|
assert.match(template.content, /<el-pagination[\s\S]*v-model:current-page="selectedPage"/)
|
||||||
|
assert.match(template.content, /v-model:page-size="pageSize"/)
|
||||||
|
assert.match(template.content, /:page-sizes="pageSizes"/)
|
||||||
|
assert.match(template.content, /:total="selectedUsers\.length"/)
|
||||||
|
assert.match(template.content, /layout="total, sizes, prev, pager, next, jumper"/)
|
||||||
|
assert.match(template.content, /@current-change="handlePageChange"/)
|
||||||
|
assert.match(template.content, /@size-change="handlePageSizeChange"/)
|
||||||
|
for (const field of ['userId', 'openId', 'jobTitle', 'email', 'mobile', 'employmentStatus', 'employeeType', 'avatarUrl']) assert.match(template.content, new RegExp(`user\\.${field}`))
|
||||||
|
assert.match(template.content, /user\.avatarUrl[\s\S]*:src="user\.avatarUrl"[\s\S]*:alt=/)
|
||||||
|
assert.match(template.content, /暂无组织架构|通讯录快照不可用/)
|
||||||
|
assert.match(template.content, /组织架构加载失败/)
|
||||||
|
assert.match(scriptSetup.content, /normalizeOrganization/)
|
||||||
|
assert.match(scriptSetup.content, /createsCycle/)
|
||||||
|
assert.match(scriptSetup.content, /descendantDepartmentIds/)
|
||||||
|
assert.match(scriptSetup.content, /departmentIds\.some/)
|
||||||
|
assert.match(scriptSetup.content, /const seen = new Set/)
|
||||||
|
assert.match(scriptSetup.content, /system:feishu:sync.*system:feishu:bind/)
|
||||||
|
assert.match(template.content, /userId[::][^<]*user\.userId/)
|
||||||
|
assert.match(template.content, /openId[::][^<]*user\.openId/)
|
||||||
|
assert.match(scriptSetup.content, /userId: userId \|\| '--'/)
|
||||||
|
assert.match(scriptSetup.content, /openId: openId \|\| '--'/)
|
||||||
|
assert.doesNotMatch(template.content + scriptSetup.content, /employee(?:No|Number)/)
|
||||||
|
assert.doesNotMatch(template.content + scriptSetup.content, /eligible|eligibilityReason|符合资格|不符合资格/)
|
||||||
|
assert.doesNotMatch(scriptSetup.content, /demo-local-session|legacyAdmin|useLegacyFallback|system:user:view/)
|
||||||
|
assert.doesNotMatch(panel.template.content + panel.scriptSetup.content, /符合资格|不符合资格|eligibilityReason/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('organization employee pagination is computed without DOM and layout keeps panels scrollable', () => {
|
||||||
|
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
|
||||||
|
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
|
||||||
|
}).outputText
|
||||||
|
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, selectDepartment, selectedPage, pageSize, pageSizes, totalPages, selectedUsers, paginatedSelectedUsers, handlePageChange, handlePageSizeChange };`)(
|
||||||
|
computed,
|
||||||
|
ref,
|
||||||
|
watch,
|
||||||
|
() => {},
|
||||||
|
() => {},
|
||||||
|
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
|
||||||
|
{ organization: async () => ({}) },
|
||||||
|
)
|
||||||
|
const organization = {
|
||||||
|
snapshotState: 'FRESH',
|
||||||
|
departments: [
|
||||||
|
{ id: 'root', name: '总部', parentId: '', order: 0, memberCount: 25 },
|
||||||
|
{ id: 'other', name: '其他', parentId: '', order: 1, memberCount: 0 },
|
||||||
|
],
|
||||||
|
users: Array.from({ length: 25 }, (_, index) => ({
|
||||||
|
userId: `user-${index + 1}`,
|
||||||
|
openId: `open-${index + 1}`,
|
||||||
|
name: `员工${index + 1}`,
|
||||||
|
departmentIds: ['root'],
|
||||||
|
})),
|
||||||
|
}
|
||||||
|
state.applyOrganization(organization)
|
||||||
|
assert.equal(state.pageSize.value, 10)
|
||||||
|
assert.deepEqual(state.pageSizes, [10, 20, 50, 100])
|
||||||
|
assert.equal(state.selectedUsers.value.length, 25)
|
||||||
|
assert.equal(state.totalPages.value, 3)
|
||||||
|
assert.deepEqual(state.paginatedSelectedUsers.value.map(user => user.userId), ['user-1', 'user-2', 'user-3', 'user-4', 'user-5', 'user-6', 'user-7', 'user-8', 'user-9', 'user-10'])
|
||||||
|
|
||||||
|
state.handlePageChange(2)
|
||||||
|
assert.equal(state.selectedPage.value, 2)
|
||||||
|
assert.equal(state.paginatedSelectedUsers.value[0].userId, 'user-11')
|
||||||
|
state.handlePageChange(3)
|
||||||
|
assert.equal(state.selectedPage.value, 3)
|
||||||
|
assert.equal(state.paginatedSelectedUsers.value.length, 5)
|
||||||
|
state.handlePageChange(99)
|
||||||
|
assert.equal(state.selectedPage.value, 3)
|
||||||
|
state.handlePageChange(0)
|
||||||
|
assert.equal(state.selectedPage.value, 1)
|
||||||
|
|
||||||
|
state.handlePageChange(3)
|
||||||
|
state.handlePageSizeChange(20)
|
||||||
|
assert.equal(state.pageSize.value, 20)
|
||||||
|
assert.equal(state.selectedPage.value, 1)
|
||||||
|
assert.equal(state.totalPages.value, 2)
|
||||||
|
assert.equal(state.paginatedSelectedUsers.value.length, 20)
|
||||||
|
state.handlePageChange(99)
|
||||||
|
assert.equal(state.selectedPage.value, 2)
|
||||||
|
state.handlePageSizeChange(100)
|
||||||
|
assert.equal(state.pageSize.value, 100)
|
||||||
|
assert.equal(state.selectedPage.value, 1)
|
||||||
|
assert.equal(state.totalPages.value, 1)
|
||||||
|
|
||||||
|
state.applyOrganization(organization)
|
||||||
|
assert.equal(state.selectedPage.value, 1)
|
||||||
|
state.handlePageChange(2)
|
||||||
|
state.selectDepartment('other')
|
||||||
|
assert.equal(state.selectedPage.value, 1)
|
||||||
|
assert.equal(state.totalPages.value, 1)
|
||||||
|
|
||||||
|
const styles = page.styles.map(style => style.content).join('\n')
|
||||||
|
assert.match(styles, /\.directory-page \{[^}]*min-height: 100%/)
|
||||||
|
assert.match(styles, /\.organization-card \{[^}]*flex: 1 1 auto/)
|
||||||
|
assert.match(styles, /\.organization-layout \{[^}]*flex: 1 1 0/)
|
||||||
|
assert.match(styles, /\.organization-layout \{[^}]*height: auto[^}]*min-height: 0/)
|
||||||
|
assert.doesNotMatch(styles, /\.organization-layout \{[^}]*height: clamp\(/)
|
||||||
|
assert.match(styles, /min-height: 0/)
|
||||||
|
assert.match(styles, /\.member-list[^}]*overflow-y: auto/)
|
||||||
|
assert.match(styles, /\.pagination-footer[^}]*flex: none/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('department counts aggregate unique employees across descendants', () => {
|
||||||
|
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
|
||||||
|
assert.match(page.template.content, /departmentMemberCounts\.get\(item\.node\.id\)/)
|
||||||
|
assert.match(page.scriptSetup.content, /const departmentMemberCounts = computed/)
|
||||||
|
assert.match(page.scriptSetup.content, /descendantDepartmentIds\.value\.get\(department\.id\)/)
|
||||||
|
assert.match(page.scriptSetup.content, /counts\.set\(department\.id, usersInDepartments\(ids\)\.length\)/)
|
||||||
|
|
||||||
|
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
|
||||||
|
}).outputText
|
||||||
|
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, departmentMemberCounts, selectedUsers };`)(
|
||||||
|
computed,
|
||||||
|
ref,
|
||||||
|
watch,
|
||||||
|
() => {},
|
||||||
|
() => {},
|
||||||
|
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
|
||||||
|
{ organization: async () => ({}) },
|
||||||
|
)
|
||||||
|
state.applyOrganization({
|
||||||
|
snapshotState: 'FRESH',
|
||||||
|
lastSuccessfulAt: null,
|
||||||
|
departments: [
|
||||||
|
{ id: 'root', name: '总部', parentId: '', order: 0, memberCount: 1 },
|
||||||
|
{ id: 'child', name: '子部门', parentId: 'root', order: 0, memberCount: 2 },
|
||||||
|
],
|
||||||
|
users: [
|
||||||
|
{ openId: 'open-root', userId: 'employee-root', name: '甲', email: '', mobile: '', jobTitle: '', employeeType: 1, avatarUrl: '', employmentStatus: '', departmentIds: ['root'] },
|
||||||
|
{ openId: 'open-child', userId: 'employee-child', name: '乙', email: '', mobile: '', jobTitle: '', employeeType: null, avatarUrl: '', employmentStatus: '', departmentIds: ['child'] },
|
||||||
|
{ openId: 'open-child-duplicate', userId: 'employee-child', name: '乙', email: '', mobile: '', jobTitle: '', employeeType: null, avatarUrl: '', employmentStatus: '', departmentIds: ['child'] },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
assert.equal(state.departmentMemberCounts.value.get('root'), 2)
|
||||||
|
assert.equal(state.departmentMemberCounts.value.get('child'), 1)
|
||||||
|
assert.equal(state.selectedUsers.value.length, 2)
|
||||||
|
assert.equal(state.selectedUsers.value.find(user => user.userId === 'employee-root').employeeType, 1)
|
||||||
|
assert.equal(state.selectedUsers.value.find(user => user.userId === 'employee-child').employeeType, null)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('organization normalization provides safe Feishu ID fallbacks and an ID-free deduplication key', () => {
|
||||||
|
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
|
||||||
|
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
|
||||||
|
}).outputText
|
||||||
|
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, selectedUsers };`)(
|
||||||
|
computed,
|
||||||
|
ref,
|
||||||
|
watch,
|
||||||
|
() => {},
|
||||||
|
() => {},
|
||||||
|
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
|
||||||
|
{ organization: async () => ({}) },
|
||||||
|
)
|
||||||
|
state.applyOrganization({
|
||||||
|
snapshotState: 'FRESH',
|
||||||
|
lastSuccessfulAt: null,
|
||||||
|
departments: [{ id: 'root', name: '总部', parentId: '', order: 0, memberCount: 2 }],
|
||||||
|
users: [
|
||||||
|
{ name: '无 ID 员工', email: '', mobile: '', departmentIds: ['root'] },
|
||||||
|
{ name: '无 ID 员工', email: '', mobile: '', departmentIds: ['root'] },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
assert.equal(state.selectedUsers.value.length, 1)
|
||||||
|
assert.equal(state.selectedUsers.value[0].userId, '--')
|
||||||
|
assert.equal(state.selectedUsers.value[0].openId, '--')
|
||||||
|
assert.equal(state.selectedUsers.value[0].jobTitle, '--')
|
||||||
|
assert.equal(state.selectedUsers.value[0].email, '--')
|
||||||
|
assert.equal(state.selectedUsers.value[0].mobile, '--')
|
||||||
|
assert.equal(state.selectedUsers.value[0].employmentStatus, '--')
|
||||||
|
assert.equal(state.selectedUsers.value[0].employeeType, null)
|
||||||
|
assert.match(page.template.content, /user\.employeeType \?\? '--'/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('department order stays precise for decimal strings and accepts legacy numbers', () => {
|
||||||
|
const page = parse(source('./views/FeishuDirectory.vue')).descriptor
|
||||||
|
const script = ts.transpileModule(page.scriptSetup.content.replace(/^import .*$/gm, ''), {
|
||||||
|
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },
|
||||||
|
}).outputText
|
||||||
|
const state = new Function('computed', 'ref', 'watch', 'onMounted', 'onBeforeUnmount', 'useUserStore', 'feishuDirectoryApi', `${script}\nreturn { applyOrganization, departmentNodes };`)(
|
||||||
|
computed,
|
||||||
|
ref,
|
||||||
|
watch,
|
||||||
|
() => {},
|
||||||
|
() => {},
|
||||||
|
() => ({ permissionsLoaded: false, permissionsError: '', hasPermission: () => false }),
|
||||||
|
{ organization: async () => ({}) },
|
||||||
|
)
|
||||||
|
state.applyOrganization({
|
||||||
|
snapshotState: 'FRESH',
|
||||||
|
lastSuccessfulAt: null,
|
||||||
|
departments: [
|
||||||
|
{ id: 'larger', name: '较大', parentId: '', order: '9007199254740993', memberCount: 0 },
|
||||||
|
{ id: 'smaller', name: '较小', parentId: '', order: '9007199254740992', memberCount: 0 },
|
||||||
|
{ id: 'legacy', name: '旧版', parentId: '', order: 3, memberCount: 0 },
|
||||||
|
],
|
||||||
|
users: [],
|
||||||
|
})
|
||||||
|
assert.deepEqual(state.departmentNodes.value.map(node => [node.id, node.order]), [
|
||||||
|
['legacy', '3'],
|
||||||
|
['smaller', '9007199254740992'],
|
||||||
|
['larger', '9007199254740993'],
|
||||||
|
])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('duplicate submits blocked and committed success emitted only once', async () => {
|
||||||
|
let resolve, posts = 0, current = snapshot()
|
||||||
|
const state = setup({ status: async () => current, sync: () => { posts++; return new Promise(done => { resolve = done }) } })
|
||||||
|
await state.refreshStatus()
|
||||||
|
const pending = state.sync()
|
||||||
|
await state.sync()
|
||||||
|
assert.equal(posts, 1)
|
||||||
|
assert.equal(state.syncDisabled.value, true)
|
||||||
|
current = snapshot({ lastSuccessfulRunId: 'new', lastRun: result() })
|
||||||
|
resolve(result())
|
||||||
|
await pending
|
||||||
|
assert.deepEqual(state.events, ['committed'])
|
||||||
|
assert.equal(state.syncDisabled.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('timeout queries status, stays locked on status failure, then polls running to success', async () => {
|
||||||
|
let fail = false, current = snapshot(), reads = 0
|
||||||
|
const state = setup({ status: async () => { reads++; if (fail) throw Error('offline'); return current }, sync: async () => { fail = true; throw Error('timeout') } })
|
||||||
|
await state.refreshStatus()
|
||||||
|
await state.sync()
|
||||||
|
assert.equal(reads, 2)
|
||||||
|
assert.equal(state.syncDisabled.value, true)
|
||||||
|
assert.match(state.error.value, /重试查询状态/)
|
||||||
|
fail = false
|
||||||
|
current = snapshot({ running: true, lastRun: result({ state: 'RUNNING', applied: false }) })
|
||||||
|
await state.refreshStatus()
|
||||||
|
assert.equal(state.syncDisabled.value, true)
|
||||||
|
current = snapshot({ lastSuccessfulRunId: 'new', lastRun: result() })
|
||||||
|
await state.poll()
|
||||||
|
assert.deepEqual(state.events, ['committed'])
|
||||||
|
assert.equal(state.syncDisabled.value, false)
|
||||||
|
state.cleanup()
|
||||||
|
assert.equal(state.poll(), undefined)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('failed run preserves last success and exposes server failure without success event', async () => {
|
||||||
|
let current = snapshot({ lastSuccessfulRunId: 'old', lastSuccessfulAt: 'yesterday' })
|
||||||
|
const failed = result({ state: 'FAILED', applied: false, complete: false, errorCode: 'LIMIT', errorMessage: '超出限制' })
|
||||||
|
const state = setup({ status: async () => current, sync: async () => { current = { ...current, lastRun: failed }; throw Error('503') } })
|
||||||
|
await state.refreshStatus()
|
||||||
|
await state.sync()
|
||||||
|
assert.deepEqual(state.events, [])
|
||||||
|
assert.equal(state.status.value.lastSuccessfulAt, 'yesterday')
|
||||||
|
assert.equal(state.run.value.errorCode, 'LIMIT')
|
||||||
|
assert.equal(state.syncDisabled.value, false)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('unconfigured service is disabled; panel has accessible status, retry and wrapping layout', async () => {
|
||||||
|
const state = setup({ status: async () => snapshot({ configured: false }) })
|
||||||
|
await state.refreshStatus()
|
||||||
|
assert.equal(state.syncDisabled.value, true)
|
||||||
|
assert.match(panel.template.content, /aria-live="polite"/)
|
||||||
|
assert.match(panel.template.content, /role="alert"/)
|
||||||
|
assert.match(panel.template.content, /同步飞书员工资料与目录状态;不作为 OAuth 登录条件;同步失败不覆盖上次结果/)
|
||||||
|
assert.match(panel.styles[0].content, /flex-wrap: wrap/)
|
||||||
|
assert.match(panel.styles[0].content, /overflow-wrap: anywhere/)
|
||||||
|
assert.match(source('./views/Login.vue'), /通讯录同步用于员工资料与业务管理,不作为登录条件/)
|
||||||
|
})
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
// Structural layout regressions. Run with: node --test src/layout.test.mjs
|
||||||
|
// These checks do not replace viewport/browser measurements.
|
||||||
|
import test from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { readFileSync } from 'node:fs'
|
||||||
|
import { parse as parseVue } from '@vue/compiler-sfc'
|
||||||
|
import postcss from 'postcss'
|
||||||
|
|
||||||
|
const source = path => readFileSync(new URL(path, import.meta.url), 'utf8')
|
||||||
|
const css = postcss.parse(source('./assets/main.css'))
|
||||||
|
test('finance summary cards fill three columns without a vacant fourth track', () => {
|
||||||
|
assert.equal(declarations('.finance-kpis')['grid-template-columns'], 'repeat(3, minmax(0, 1fr))')
|
||||||
|
css.walkRules(rule => {
|
||||||
|
if (!rule.selector.split(',').map(selector => selector.trim()).includes('.finance-kpis')) return
|
||||||
|
if (rule.parent.type !== 'atrule') return
|
||||||
|
const tracks = rule.nodes.find(node => node.prop === 'grid-template-columns')?.value
|
||||||
|
assert.notEqual(tracks, 'repeat(2, minmax(0, 1fr))')
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
function declarations(selector, stylesheet = css, responsive = false) {
|
||||||
|
const values = {}
|
||||||
|
stylesheet.walkRules(selector, rule => {
|
||||||
|
if (!responsive && rule.parent.type === 'atrule') return
|
||||||
|
rule.walkDecls(declaration => { values[declaration.prop] = declaration.value })
|
||||||
|
})
|
||||||
|
return values
|
||||||
|
}
|
||||||
|
|
||||||
|
test('list pages opt in without fixed table or row heights', () => {
|
||||||
|
for (const name of ['Applications', 'FinanceReceipt', 'Payments', 'Sources', 'Logs', 'ExpenseTypes', 'Payees', 'Users']) {
|
||||||
|
const { descriptor, errors } = parseVue(source(`./views/${name}.vue`))
|
||||||
|
assert.deepEqual(errors, [])
|
||||||
|
assert.match(descriptor.template.content, /class="[^"]*page-content/)
|
||||||
|
}
|
||||||
|
assert.equal(declarations('.main-area').display, 'flex')
|
||||||
|
assert.equal(declarations('.main-area')['min-height'], '100vh')
|
||||||
|
assert.equal(declarations('.page-stage').flex, '1 0 auto')
|
||||||
|
assert.equal(declarations('.data-table').height, undefined)
|
||||||
|
assert.equal(declarations('.table-wrap')['overflow-x'], 'auto')
|
||||||
|
assert.match(source('./views/Applications.vue'), /role="tabpanel"\s+class="fill-list-card"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('metadata tables have keyboard-accessible local scroll regions and loading states', () => {
|
||||||
|
for (const name of ['Sources', 'ExpenseTypes', 'Payees']) {
|
||||||
|
const template = parseVue(source(`./views/${name}.vue`)).descriptor.template.content
|
||||||
|
assert.match(template, /class="table-wrap"[^<]*tabindex="0"[^<]*role="region"[^<]*><table/)
|
||||||
|
assert.match(template, /v-else class="load-wrap" role="status"/)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
test('group list starts full width and only splits when a group is selected', () => {
|
||||||
|
const text = source('./views/Users.vue')
|
||||||
|
const styles = postcss.parse(parseVue(text).descriptor.styles[0].content)
|
||||||
|
assert.match(text, /:class="\{ 'has-group-detail': selectedGroup \}"/)
|
||||||
|
assert.equal(declarations('.group-layout', styles)['grid-template-columns'], 'minmax(0, 1fr)')
|
||||||
|
assert.equal(declarations('.has-group-detail .group-layout', styles)['grid-template-columns'], 'minmax(0, .9fr) minmax(0, 1.1fr)')
|
||||||
|
assert.equal(declarations('.candidate-copy', styles)['min-width'], '0')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('system management navigation is visible for admin, integration, or Feishu access', () => {
|
||||||
|
const template = parseVue(source('./views/Layout.vue')).descriptor.template.content
|
||||||
|
assert.match(template, /class="nav-group admin-nav" v-if="canAccess\('admin'\) \|\| canAccess\('integration'\) \|\| canAccess\('feishu-directory'\)"/)
|
||||||
|
assert.match(template, /<router-link v-if="canAccess\('admin'\)" to="\/users"/)
|
||||||
|
assert.match(template, /<router-link v-if="canAccess\('integration'\)" to="\/integration-config"/)
|
||||||
|
assert.match(template, /<router-link v-if="canAccess\('feishu-directory'\)" to="\/feishu-directory"/)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('provider cards stretch with footer actions following a growing body', () => {
|
||||||
|
const styles = postcss.parse(parseVue(source('./views/IntegrationConfig.vue')).descriptor.styles[0].content)
|
||||||
|
assert.equal(declarations('.integration-grid', styles)['align-items'], 'stretch')
|
||||||
|
assert.match(declarations('.integration-grid', styles)['grid-template-columns'], /auto-fit/)
|
||||||
|
assert.equal(declarations('.integration-card', styles)['flex-direction'], 'column')
|
||||||
|
assert.equal(declarations('.integration-body', styles).flex, '1')
|
||||||
|
assert.equal(declarations('.integration-actions', styles)['margin-top'], 'auto')
|
||||||
|
})
|
||||||
|
|
||||||
|
test('expense rows have four field tracks and an action track only with a delete button', () => {
|
||||||
|
const tracks = declarations('.expense-item')['grid-template-columns']
|
||||||
|
assert.equal((tracks.match(/minmax\(/g) || []).length, 4)
|
||||||
|
assert.match(tracks, /^minmax\(160px,/)
|
||||||
|
assert.equal(declarations('.expense-item:has(> .remove-item)')['grid-template-columns'], `${tracks} 34px`)
|
||||||
|
const responsive = []
|
||||||
|
css.walkRules(rule => {
|
||||||
|
if (rule.parent.type === 'atrule' && rule.selector.includes('.expense-item:has')) {
|
||||||
|
responsive.push([rule.parent.params, rule.nodes.find(node => node.prop === 'grid-template-columns')?.value])
|
||||||
|
}
|
||||||
|
})
|
||||||
|
assert.deepEqual(responsive, [
|
||||||
|
['(max-width: 1180px)', 'repeat(2, minmax(0, 1fr))'],
|
||||||
|
['(max-width: 680px)', 'minmax(0, 1fr)'],
|
||||||
|
])
|
||||||
|
assert.equal(declarations('.side-panel').height, 'max-content')
|
||||||
|
assert.equal(declarations('.detail-layout')['grid-template-columns'], 'minmax(0, 1fr) 295px')
|
||||||
|
})
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import { createPinia } from 'pinia'
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||||
|
import App from './App.vue'
|
||||||
|
import router from './router'
|
||||||
|
import './assets/main.css'
|
||||||
|
|
||||||
|
const app = createApp(App)
|
||||||
|
|
||||||
|
// Register Element Plus icons
|
||||||
|
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||||
|
app.component(key, component)
|
||||||
|
}
|
||||||
|
|
||||||
|
app.use(createPinia())
|
||||||
|
app.use(router)
|
||||||
|
app.use(ElementPlus, { locale: zhCn })
|
||||||
|
app.mount('#app')
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import type { RouteRecordRaw } from 'vue-router'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
import { AUTH_DAY_KEY, DEMO_SESSION_TOKEN, TOKEN_KEY, getBusinessDay } from '@/utils/dailyAuth'
|
||||||
|
|
||||||
|
const routes: RouteRecordRaw[] = [
|
||||||
|
{
|
||||||
|
path: '/login',
|
||||||
|
name: 'Login',
|
||||||
|
component: () => import('@/views/Login.vue'),
|
||||||
|
meta: { requiresAuth: false },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
component: () => import('@/views/Layout.vue'),
|
||||||
|
meta: { requiresAuth: true },
|
||||||
|
children: [
|
||||||
|
{ path: '', redirect: '/dashboard' },
|
||||||
|
{
|
||||||
|
path: 'dashboard',
|
||||||
|
name: 'Dashboard',
|
||||||
|
component: () => import('@/views/Dashboard.vue'),
|
||||||
|
meta: { title: '工作台', permission: ['applications', 'reimbursement:view-own'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'applications',
|
||||||
|
name: 'Applications',
|
||||||
|
component: () => import('@/views/Applications.vue'),
|
||||||
|
meta: { title: '我的报销', permission: ['applications', 'reimbursement:view-own'], roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'applications/new',
|
||||||
|
name: 'ApplicationNew',
|
||||||
|
component: () => import('@/components/ReimbursementForm.vue'),
|
||||||
|
meta: { title: '发起报销', permission: 'reimbursement:create', roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'applications/:id',
|
||||||
|
name: 'ApplicationDetail',
|
||||||
|
component: () => import('@/views/ApplicationDetail.vue'),
|
||||||
|
meta: { title: '报销单详情', hidden: true, permission: ['applications', 'reimbursement:view-own'], roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'applications/:id/edit',
|
||||||
|
name: 'ApplicationEdit',
|
||||||
|
component: () => import('@/components/ReimbursementForm.vue'),
|
||||||
|
meta: { title: '编辑报销', hidden: true, permission: 'reimbursement:create', roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'finance-receipt',
|
||||||
|
name: 'FinanceReceipt',
|
||||||
|
component: () => import('@/views/FinanceReceipt.vue'),
|
||||||
|
meta: { title: '财务待收单', permission: 'receipt:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'sources',
|
||||||
|
name: 'Sources',
|
||||||
|
component: () => import('@/views/Sources.vue'),
|
||||||
|
meta: { title: '业务单据', permission: 'reimbursement:view-all', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'payments',
|
||||||
|
name: 'Payments',
|
||||||
|
component: () => import('@/views/Payments.vue'),
|
||||||
|
meta: { title: '待付款', permission: 'payment:register', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'logs',
|
||||||
|
name: 'Logs',
|
||||||
|
component: () => import('@/views/Logs.vue'),
|
||||||
|
meta: { title: '操作日志', permission: 'approval:view', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'expense-types',
|
||||||
|
name: 'ExpenseTypes',
|
||||||
|
component: () => import('@/views/ExpenseTypes.vue'),
|
||||||
|
meta: { title: '费用类型', permission: 'master-data:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'payees',
|
||||||
|
name: 'Payees',
|
||||||
|
component: () => import('@/views/Payees.vue'),
|
||||||
|
meta: { title: '付款对象', permission: 'master-data:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'users',
|
||||||
|
name: 'Users',
|
||||||
|
component: () => import('@/views/Users.vue'),
|
||||||
|
meta: { title: '用户管理', permission: 'system:user:view', roles: ['ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'feishu-directory',
|
||||||
|
name: 'FeishuDirectory',
|
||||||
|
component: () => import('@/views/FeishuDirectory.vue'),
|
||||||
|
meta: { title: '飞书通讯录', permission: ['system:feishu:sync', 'system:feishu:bind'] },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'integration-config',
|
||||||
|
name: 'IntegrationConfig',
|
||||||
|
component: () => import('@/views/IntegrationConfig.vue'),
|
||||||
|
meta: { title: '配置管理', permission: 'system:integration:view', roles: ['ADMIN', 'SUPER_ADMIN'] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const router = createRouter({ history: createWebHistory(), routes })
|
||||||
|
|
||||||
|
router.beforeEach(async (to, _from, next) => {
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const workbench = useWorkbenchStore()
|
||||||
|
const requiresAuth = to.matched.some(r => r.meta.requiresAuth)
|
||||||
|
const hadSession = Boolean(localStorage.getItem(TOKEN_KEY) || localStorage.getItem(AUTH_DAY_KEY) || userStore.token)
|
||||||
|
const isOAuthCallback = to.path === '/login' && Boolean(to.query.token || to.query.code || to.query.error)
|
||||||
|
const dailyValid = userStore.ensureDailyAuth()
|
||||||
|
|
||||||
|
if (!dailyValid && hadSession) workbench.reset()
|
||||||
|
|
||||||
|
const token = userStore.token
|
||||||
|
|
||||||
|
if (requiresAuth && !token) return next('/login')
|
||||||
|
|
||||||
|
// Validate a real token before allowing either a protected page or a login
|
||||||
|
// redirect. This also turns an expired token/API failure into a full logout.
|
||||||
|
if (token && token !== DEMO_SESSION_TOKEN && !isOAuthCallback) {
|
||||||
|
try {
|
||||||
|
await userStore.fetchUserInfo()
|
||||||
|
} catch {
|
||||||
|
userStore.logout()
|
||||||
|
workbench.reset()
|
||||||
|
return next('/login')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (to.path === '/login' && token && !isOAuthCallback) return next('/dashboard')
|
||||||
|
|
||||||
|
const requiredRoles = to.matched.flatMap(r => (r.meta.roles as string[] | undefined) || [])
|
||||||
|
const requiredPermissions = to.matched.flatMap(record => {
|
||||||
|
const permission = record.meta.permission as string | string[] | undefined
|
||||||
|
return permission ? (Array.isArray(permission) ? permission : [permission]) : []
|
||||||
|
})
|
||||||
|
const userType = userStore.userInfo?.userType || ''
|
||||||
|
const useLegacyFallback = token === DEMO_SESSION_TOKEN
|
||||||
|
// The directory is permission-only, including for the local demo session;
|
||||||
|
// never allow its route through the unrelated legacy role fallback.
|
||||||
|
const isFeishuDirectoryRoute = to.matched.some(record => record.name === 'FeishuDirectory')
|
||||||
|
|
||||||
|
// A real session is permission-first. Legacy userType checks are retained
|
||||||
|
// only for the local demo session or when the permission service itself is
|
||||||
|
// unavailable, so a custom role cannot be rejected by stale role metadata.
|
||||||
|
if (requiredPermissions.length > 0 && (!useLegacyFallback || isFeishuDirectoryRoute)) {
|
||||||
|
try {
|
||||||
|
await userStore.loadPermissions()
|
||||||
|
} catch {
|
||||||
|
if (!requiredRoles.includes(userType)) {
|
||||||
|
return next({ path: '/dashboard', query: { denied: String(to.meta.title || '该页面') } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (userStore.permissionsLoaded && !userStore.permissionsError) {
|
||||||
|
if (!requiredPermissions.some(permission => userStore.hasPermission(permission))) {
|
||||||
|
return next({ path: '/dashboard', query: { denied: String(to.meta.title || '该页面') } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (requiredRoles.length > 0 && (!requiredPermissions.length || useLegacyFallback)) {
|
||||||
|
if (!requiredRoles.includes(userType)) {
|
||||||
|
return next({ path: '/dashboard', query: { denied: String(to.meta.title || '该页面') } })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
next()
|
||||||
|
})
|
||||||
|
|
||||||
|
export default router
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export const useAppStore = defineStore('app', () => {
|
||||||
|
const sidebarCollapsed = ref(false)
|
||||||
|
const loading = ref(false)
|
||||||
|
const notifications = ref(3)
|
||||||
|
|
||||||
|
const toggleSidebar = () => { sidebarCollapsed.value = !sidebarCollapsed.value }
|
||||||
|
|
||||||
|
return { sidebarCollapsed, loading, notifications, toggleSidebar }
|
||||||
|
})
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
import { authApi, type UserProfile } from '@/api/auth'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import {
|
||||||
|
AUTH_DAY_KEY,
|
||||||
|
DEMO_SESSION_TOKEN,
|
||||||
|
TOKEN_KEY,
|
||||||
|
USER_INFO_KEY,
|
||||||
|
clearStoredSession,
|
||||||
|
getBusinessDay,
|
||||||
|
saveAuthDay,
|
||||||
|
} from '@/utils/dailyAuth'
|
||||||
|
|
||||||
|
const readStoredUser = (): UserProfile | null => {
|
||||||
|
try {
|
||||||
|
const value = localStorage.getItem(USER_INFO_KEY)
|
||||||
|
return value ? JSON.parse(value) as UserProfile : null
|
||||||
|
} catch {
|
||||||
|
localStorage.removeItem(USER_INFO_KEY)
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const FEISHU_OAUTH_ATTEMPT_KEY = 'feishuOAuthAttempt'
|
||||||
|
|
||||||
|
const randomAttemptId = () => {
|
||||||
|
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
|
||||||
|
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
const token = ref(localStorage.getItem(TOKEN_KEY) || '')
|
||||||
|
const userInfo = ref<UserProfile | null>(readStoredUser())
|
||||||
|
const permissionCodes = ref<string[]>([])
|
||||||
|
const fieldPermissions = ref<Record<string, 'HIDDEN' | 'READ' | 'EDIT'>>({})
|
||||||
|
const permissionsLoaded = ref(false)
|
||||||
|
const permissionsError = ref('')
|
||||||
|
let permissionRequest: Promise<void> | null = null
|
||||||
|
let sessionVersion = 0
|
||||||
|
|
||||||
|
const isLoggedIn = computed(() => !!token.value)
|
||||||
|
const isFinance = computed(() => ['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(userInfo.value?.userType || ''))
|
||||||
|
|
||||||
|
const isValidUser = (user: unknown): user is UserProfile => {
|
||||||
|
if (!user || typeof user !== 'object') return false
|
||||||
|
const candidate = user as Partial<UserProfile>
|
||||||
|
return Boolean(candidate.id && candidate.realName && candidate.userType)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep the marker behind the verified identity. This is the only operation
|
||||||
|
// that turns a token/user pair into an authenticated session for today.
|
||||||
|
const completeLogin = (jwt: string, user: UserProfile) => {
|
||||||
|
if (!jwt || !isValidUser(user)) throw new Error('登录响应缺少有效身份信息')
|
||||||
|
sessionVersion += 1
|
||||||
|
token.value = jwt
|
||||||
|
userInfo.value = user
|
||||||
|
localStorage.setItem(TOKEN_KEY, jwt)
|
||||||
|
localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))
|
||||||
|
saveAuthDay()
|
||||||
|
}
|
||||||
|
|
||||||
|
const beginFeishuLogin = () => {
|
||||||
|
const attempt = randomAttemptId()
|
||||||
|
sessionStorage.setItem(FEISHU_OAUTH_ATTEMPT_KEY, attempt)
|
||||||
|
localStorage.setItem(FEISHU_OAUTH_ATTEMPT_KEY, attempt)
|
||||||
|
return attempt
|
||||||
|
}
|
||||||
|
|
||||||
|
const isCurrentFeishuLogin = (attempt: string | null | undefined) => {
|
||||||
|
return Boolean(attempt)
|
||||||
|
&& sessionStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt
|
||||||
|
&& localStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearFeishuLogin = (attempt: string | null | undefined) => {
|
||||||
|
if (sessionStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt) {
|
||||||
|
sessionStorage.removeItem(FEISHU_OAUTH_ATTEMPT_KEY)
|
||||||
|
}
|
||||||
|
if (localStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt) {
|
||||||
|
localStorage.removeItem(FEISHU_OAUTH_ATTEMPT_KEY)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const feishuLogin = async (code: string, state?: string, attempt?: string) => {
|
||||||
|
if (!isCurrentFeishuLogin(attempt)) throw new Error('登录状态已更新,请重新登录')
|
||||||
|
const requestVersion = sessionVersion
|
||||||
|
const res = await authApi.feishuLogin(code, state)
|
||||||
|
if (requestVersion !== sessionVersion || !isCurrentFeishuLogin(attempt)) {
|
||||||
|
throw new Error('登录状态已更新,请重新登录')
|
||||||
|
}
|
||||||
|
completeLogin(res.token, res.user)
|
||||||
|
clearFeishuLogin(attempt)
|
||||||
|
}
|
||||||
|
|
||||||
|
const setToken = async (jwt: string) => {
|
||||||
|
if (!jwt) throw new Error('登录响应缺少有效令牌')
|
||||||
|
sessionVersion += 1
|
||||||
|
token.value = jwt
|
||||||
|
userInfo.value = null
|
||||||
|
localStorage.setItem(TOKEN_KEY, jwt)
|
||||||
|
localStorage.removeItem(USER_INFO_KEY)
|
||||||
|
await fetchUserInfo()
|
||||||
|
// fetchUserInfo validates the callback token and user before this marker
|
||||||
|
// is saved. A failed request clears the whole local session.
|
||||||
|
saveAuthDay()
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshToken = async () => {
|
||||||
|
const requestVersion = sessionVersion
|
||||||
|
const requestToken = token.value
|
||||||
|
if (!requestToken) throw new Error('未登录')
|
||||||
|
const response = await authApi.refreshToken()
|
||||||
|
if (requestVersion !== sessionVersion || token.value !== requestToken || localStorage.getItem(TOKEN_KEY) !== requestToken) {
|
||||||
|
throw new Error('登录状态已更新,请重新登录')
|
||||||
|
}
|
||||||
|
completeLogin(response.token, response.user)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchUserInfo = async () => {
|
||||||
|
const requestVersion = sessionVersion
|
||||||
|
const requestToken = token.value || localStorage.getItem(TOKEN_KEY) || ''
|
||||||
|
if (!requestToken) {
|
||||||
|
logout()
|
||||||
|
throw new Error('未登录')
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const user = await authApi.getUserInfo()
|
||||||
|
if (requestVersion !== sessionVersion || token.value !== requestToken || localStorage.getItem(TOKEN_KEY) !== requestToken) {
|
||||||
|
throw new Error('登录状态已更新,请重新加载页面')
|
||||||
|
}
|
||||||
|
if (!isValidUser(user)) throw new Error('用户信息无效')
|
||||||
|
userInfo.value = user
|
||||||
|
localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))
|
||||||
|
return user
|
||||||
|
} catch (error) {
|
||||||
|
// Do not let a late response from an old session clear a newer login.
|
||||||
|
if (requestVersion === sessionVersion && token.value === requestToken && localStorage.getItem(TOKEN_KEY) === requestToken) logout()
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate local session age and synchronize Pinia with storage. A missing
|
||||||
|
* marker is invalid for real JWT sessions; the demo fallback is allowed one
|
||||||
|
* migration when it already has a complete locally-verified user object.
|
||||||
|
*/
|
||||||
|
const ensureDailyAuth = (): boolean => {
|
||||||
|
const storedToken = localStorage.getItem(TOKEN_KEY) || ''
|
||||||
|
const storedDay = localStorage.getItem(AUTH_DAY_KEY)
|
||||||
|
const storedUser = readStoredUser()
|
||||||
|
|
||||||
|
if (!storedToken) {
|
||||||
|
const hadState = Boolean(token.value || userInfo.value || storedUser || storedDay)
|
||||||
|
token.value = ''
|
||||||
|
userInfo.value = null
|
||||||
|
if (hadState) {
|
||||||
|
sessionVersion += 1
|
||||||
|
clearStoredSession()
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// workbench.loginFallback is an existing development entry point and
|
||||||
|
// writes its complete token/user pair synchronously. Give that pair a
|
||||||
|
// marker on first use, while still rejecting any explicitly stale marker.
|
||||||
|
if (!storedDay && storedToken === DEMO_SESSION_TOKEN && isValidUser(storedUser)) {
|
||||||
|
token.value = storedToken
|
||||||
|
userInfo.value = storedUser
|
||||||
|
saveAuthDay()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if (storedDay !== getBusinessDay()) {
|
||||||
|
sessionVersion += 1
|
||||||
|
clearStoredSession()
|
||||||
|
token.value = ''
|
||||||
|
userInfo.value = null
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
token.value = storedToken
|
||||||
|
userInfo.value = storedUser
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
sessionVersion += 1
|
||||||
|
token.value = ''
|
||||||
|
userInfo.value = null
|
||||||
|
permissionCodes.value = []
|
||||||
|
fieldPermissions.value = {}
|
||||||
|
permissionsLoaded.value = false
|
||||||
|
permissionsError.value = ''
|
||||||
|
clearStoredSession()
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadPermissions = async (force = false) => {
|
||||||
|
if (!force && permissionsLoaded.value && !permissionsError.value) return
|
||||||
|
if (permissionRequest && !force) return permissionRequest
|
||||||
|
permissionRequest = (async () => {
|
||||||
|
permissionsError.value = ''
|
||||||
|
try {
|
||||||
|
const result = await request.get<{
|
||||||
|
roleCodes?: string[]
|
||||||
|
permissionCodes?: string[]
|
||||||
|
fieldPermissions?: Record<string, 'HIDDEN' | 'READ' | 'EDIT'>
|
||||||
|
}>('/roles/current-permissions')
|
||||||
|
permissionCodes.value = Array.isArray(result?.permissionCodes) ? result.permissionCodes : []
|
||||||
|
fieldPermissions.value = result?.fieldPermissions || {}
|
||||||
|
permissionsLoaded.value = true
|
||||||
|
} catch (error) {
|
||||||
|
permissionCodes.value = []
|
||||||
|
fieldPermissions.value = {}
|
||||||
|
permissionsLoaded.value = false
|
||||||
|
permissionsError.value = error instanceof Error ? error.message : '权限加载失败'
|
||||||
|
throw error
|
||||||
|
} finally {
|
||||||
|
permissionRequest = null
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
return permissionRequest
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasPermission = (code: string) => permissionsLoaded.value && !permissionsError.value && permissionCodes.value.includes(code)
|
||||||
|
|
||||||
|
return {
|
||||||
|
token,
|
||||||
|
userInfo,
|
||||||
|
isLoggedIn,
|
||||||
|
isFinance,
|
||||||
|
feishuLogin,
|
||||||
|
beginFeishuLogin,
|
||||||
|
isCurrentFeishuLogin,
|
||||||
|
clearFeishuLogin,
|
||||||
|
completeLogin,
|
||||||
|
setToken,
|
||||||
|
refreshToken,
|
||||||
|
fetchUserInfo,
|
||||||
|
ensureDailyAuth,
|
||||||
|
permissionCodes,
|
||||||
|
fieldPermissions,
|
||||||
|
permissionsLoaded,
|
||||||
|
permissionsError,
|
||||||
|
loadPermissions,
|
||||||
|
hasPermission,
|
||||||
|
logout,
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { accountsPayableApi, cashierApi, reimbursementApi, type CreateApplicationRequest, type PaymentRecord, type ReimApplicationDetail, type ReimApplicationSummary } from '@/api/reimbursement'
|
||||||
|
import { cloneFallback, createFallbackDetail, fallbackLogin, type FallbackUser } from '@/api/fallback'
|
||||||
|
|
||||||
|
export type DataSource = 'connecting' | 'api' | 'fallback' | 'error'
|
||||||
|
export type StatusTone = 'info' | 'pending' | 'success' | 'danger' | 'draft' | 'neutral'
|
||||||
|
const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '已提交', PENDING: '审批中', APPROVING: '审批中', APPROVED: '审批通过', REJECTED: '退回', RETURNED: '退回', CANCELLED: '已取消', RECEIPT_PENDING: '待收单', RECEIVED: '已收单', UNRECEIVED: '未触发', UNPAID: '未付款', PARTIAL: '部分付款', PAID: '已付款', OCCUPIED: '已占用', EXECUTED: '已转执行', ACTIVE: '有效', INACTIVE: '停用' }
|
||||||
|
const toneMap: Record<string, StatusTone> = { 草稿: 'draft', 已提交: 'info', 审批中: 'pending', 审批通过: 'success', 退回: 'danger', 未触发: 'neutral', 待收单: 'pending', 已收单: 'success', 未付款: 'neutral', 部分付款: 'info', 已付款: 'success', 已占用: 'info', 已转执行: 'success', 有效: 'success' }
|
||||||
|
const text = (value: unknown, fallback = '') => String(value ?? fallback)
|
||||||
|
const number = (value: unknown) => Number(value || 0)
|
||||||
|
const status = (value: unknown, fallback: string) => labels[text(value)] || text(value, fallback)
|
||||||
|
const budgetStatus = (value: unknown) => ({ PENDING: '待处理', OCCUPIED: '已占用', EXECUTED: '已转执行' }[text(value)] || status(value, '已占用'))
|
||||||
|
|
||||||
|
export const useWorkbenchStore = defineStore('workbench', () => {
|
||||||
|
const user = ref<FallbackUser | null>(null)
|
||||||
|
const reimbursements = ref<ReimApplicationDetail[]>([])
|
||||||
|
const payments = ref<PaymentRecord[]>([])
|
||||||
|
const source = ref<DataSource>('connecting')
|
||||||
|
const loading = ref(false)
|
||||||
|
const error = ref('')
|
||||||
|
const financeQueueError = ref('')
|
||||||
|
const notifications = ref(0)
|
||||||
|
const fallbackPaymentKeys = new Map<string, PaymentRecord>()
|
||||||
|
let loadPromise: Promise<void> | null = null
|
||||||
|
let sessionVersion = 0
|
||||||
|
const queueVersions: Record<'receipt' | 'payment', number> = { receipt: 0, payment: 0 }
|
||||||
|
|
||||||
|
const normalizePayment = (raw: any): PaymentRecord => ({ id: raw.id ?? raw.paymentNo ?? `payment-${Date.now()}`, paymentNo: text(raw.paymentNo, raw.reference || raw.id), applicationId: raw.applicationId ?? raw.reimbursementId, paymentAmount: number(raw.paymentAmount ?? raw.amount), totalAmount: number(raw.totalAmount), paidAmount: number(raw.paidAmount ?? raw.amount), remainingAmount: number(raw.remainingAmount), paymentMethod: text(raw.paymentMethod, raw.method || '银行转账'), referenceNo: text(raw.referenceNo, raw.reference), paymentStatus: status(raw.paymentStatus, '有效'), operatorName: text(raw.operatorName, raw.operator || '—'), paymentTime: text(raw.paymentTime, raw.time), remark: text(raw.remark, raw.referenceNo || raw.reference) })
|
||||||
|
const maskAccount = (value: unknown) => {
|
||||||
|
const account = text(value)
|
||||||
|
if (!account || account.includes('*')) return account
|
||||||
|
const digits = account.replace(/\s+/g, '')
|
||||||
|
return digits.length > 4 ? `**** ${digits.slice(-4)}` : '已脱敏'
|
||||||
|
}
|
||||||
|
const normalize = (raw: any): ReimApplicationDetail => {
|
||||||
|
const paymentsForItem = payments.value.filter(payment => String(payment.applicationId) === String(raw.id))
|
||||||
|
const amount = number(raw.totalAmount ?? raw.amount)
|
||||||
|
// “退回” belongs to approvalStatus. Keep the application fact as submitted.
|
||||||
|
const application = text(raw.applicationStatus) === '草稿' || text(raw.applicationStatus) === 'DRAFT' || text(raw.status) === 'DRAFT'
|
||||||
|
? '草稿'
|
||||||
|
: '已提交'
|
||||||
|
const approvalRaw = text(raw.approvalStatus ?? raw.applicationStatus)
|
||||||
|
const approval = application === '草稿' && !['退回', 'REJECTED', 'RETURNED', 'CANCELLED', '已取消'].includes(approvalRaw)
|
||||||
|
? '未触发'
|
||||||
|
: status(approvalRaw, '未触发')
|
||||||
|
const receiptRaw = text(raw.receiptStatus)
|
||||||
|
const receipt = approval === '审批通过' && (!receiptRaw || ['UNRECEIVED', '未触发'].includes(receiptRaw))
|
||||||
|
? '待收单'
|
||||||
|
: status(raw.receiptStatus, '未触发')
|
||||||
|
return {
|
||||||
|
...raw, id: raw.id, applicationNo: text(raw.applicationNo, raw.id), title: text(raw.title, '未命名报销'), applicantName: text(raw.applicantName, raw.owner || raw.payeeName), applicantEmployeeNo: text(raw.applicantEmployeeNo), departmentName: text(raw.departmentName, raw.department), expenseTypeId: number(raw.expenseTypeId || 1), expenseTypeName: text(raw.expenseTypeName, raw.expenseType || '员工报销'), category: text(raw.category), totalAmount: amount, applicationStatus: application, approvalStatus: approval, currentApprovalNode: text(raw.currentApprovalNode, raw.approvalNode || '—'), receiptStatus: receipt, paymentStatus: status(raw.paymentStatus, '未付款'), budgetStatus: budgetStatus(raw.budgetStatus), sourceDocNo: text(raw.sourceDocNo), sourceStatus: text(raw.sourceStatus, '未关联'), payeeName: text(raw.payeeName, raw.payee), payeeBankId: number(raw.payeeBankId), bankName: text(raw.bankName), bankAccountMask: maskAccount(raw.bankAccountMask), returnReason: text(raw.returnReason), submitTime: text(raw.submitTime, raw.date), createdAt: text(raw.createdAt, raw.date), updatedAt: text(raw.updatedAt, raw.lastUpdated), paidAmountSnapshot: raw.paidAmount == null ? undefined : number(raw.paidAmount), remainingAmountSnapshot: raw.remainingAmount == null ? undefined : number(raw.remainingAmount), expenseItems: Array.isArray(raw.expenseItems) ? raw.expenseItems : [], invoices: Array.isArray(raw.invoices) ? raw.invoices : [], attachments: Array.isArray(raw.attachments) ? raw.attachments : [], approvalRecords: Array.isArray(raw.approvalRecords) ? raw.approvalRecords : [], payments: paymentsForItem,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const refreshPaymentStatuses = () => reimbursements.value.forEach(item => { const linked = payments.value.filter(payment => String(payment.applicationId) === String(item.id)); if (linked.length || source.value === 'fallback' || item.paidAmountSnapshot !== undefined) { const paid = paidAmount(item); item.paymentStatus = paid <= 0 ? '未付款' : paid >= item.totalAmount ? '已付款' : '部分付款'; item.payments = linked } })
|
||||||
|
const paidAmount = (item: ReimApplicationDetail) => { const linked = payments.value.filter(payment => String(payment.applicationId) === String(item.id) && payment.paymentStatus !== '无效'); if (linked.length) return linked.reduce((sum, payment) => sum + number(payment.paymentAmount || payment.paidAmount), 0); return item.paidAmountSnapshot ?? 0 }
|
||||||
|
const balance = (item: ReimApplicationDetail) => Math.max(0, number(item.totalAmount) - paidAmount(item))
|
||||||
|
const summaries = computed<ReimApplicationSummary[]>(() => reimbursements.value.map(item => ({ ...item } as ReimApplicationSummary)))
|
||||||
|
|
||||||
|
const setSnapshot = (payload: any, nextSource: DataSource) => { payments.value = (payload?.payments || []).map(normalizePayment); const rows: ReimApplicationDetail[] = (payload?.reimbursements || payload?.content || []).map(normalize); user.value = nextSource === 'fallback' ? (user.value || payload?.user) : (payload?.user || user.value); reimbursements.value = nextSource === 'fallback' && user.value?.userType === 'EMPLOYEE' ? rows.filter((item: ReimApplicationDetail) => item.applicantName === user.value?.realName) : rows; notifications.value = number(payload?.notifications); source.value = nextSource; refreshPaymentStatuses() }
|
||||||
|
const load = async () => {
|
||||||
|
if (loadPromise) return loadPromise
|
||||||
|
const requestVersion = sessionVersion
|
||||||
|
const currentPromise: Promise<void> = (async () => {
|
||||||
|
loading.value = true
|
||||||
|
error.value = ''
|
||||||
|
try {
|
||||||
|
const payload = await reimbursementApi.getWorkbench()
|
||||||
|
if (!payload || (!Array.isArray(payload.reimbursements) && !Array.isArray(payload.content))) throw new Error('工作台数据格式不兼容')
|
||||||
|
if (requestVersion !== sessionVersion) return
|
||||||
|
setSnapshot(payload, 'api')
|
||||||
|
} catch {
|
||||||
|
if (requestVersion !== sessionVersion) return
|
||||||
|
const canFallback = import.meta.env.DEV && typeof window !== 'undefined' && ['localhost', '127.0.0.1'].includes(window.location.hostname)
|
||||||
|
if (canFallback) {
|
||||||
|
setSnapshot(cloneFallback(), 'fallback')
|
||||||
|
error.value = '数据服务暂不可用,当前显示本地可用数据;新增和付款操作仅保留在当前会话。'
|
||||||
|
} else {
|
||||||
|
reimbursements.value = []
|
||||||
|
payments.value = []
|
||||||
|
source.value = 'error'
|
||||||
|
error.value = '无法连接财务服务,请联系管理员;为避免展示过期数据,业务记录已隐藏。'
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (requestVersion === sessionVersion) loading.value = false
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
loadPromise = currentPromise
|
||||||
|
try {
|
||||||
|
await currentPromise
|
||||||
|
} finally {
|
||||||
|
if (loadPromise === currentPromise) loadPromise = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const loadList = async () => { if (reimbursements.value.length) return; await load() }
|
||||||
|
const loadDetail = async (id: string | number) => {
|
||||||
|
const requestVersion = sessionVersion
|
||||||
|
await loadList()
|
||||||
|
if (requestVersion !== sessionVersion) return null
|
||||||
|
if (source.value !== 'api') return getById(id)
|
||||||
|
try {
|
||||||
|
const detail = await reimbursementApi.getDetail(id)
|
||||||
|
if (requestVersion !== sessionVersion) return null
|
||||||
|
const normalized = normalize(detail)
|
||||||
|
reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item)
|
||||||
|
const detailPayments = (detail.payments || []).map((payment: any) => normalizePayment({ ...payment, applicationId: id }))
|
||||||
|
payments.value = payments.value.filter(payment => String(payment.applicationId) !== String(id)).concat(detailPayments)
|
||||||
|
refreshPaymentStatuses()
|
||||||
|
return normalized
|
||||||
|
} catch {
|
||||||
|
return getById(id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const loadFinanceQueue = async (kind: 'receipt' | 'payment') => {
|
||||||
|
const requestVersion = sessionVersion
|
||||||
|
const queueVersion = ++queueVersions[kind]
|
||||||
|
await loadList()
|
||||||
|
if (requestVersion !== sessionVersion || source.value !== 'api') return
|
||||||
|
try {
|
||||||
|
const allRows: any[] = []
|
||||||
|
let page = 0
|
||||||
|
let total = Number.POSITIVE_INFINITY
|
||||||
|
do {
|
||||||
|
const payload = kind === 'receipt'
|
||||||
|
? await accountsPayableApi.getTasks({ status: 'APPROVED', page, size: 100 })
|
||||||
|
: await cashierApi.getTasks({ status: 'PENDING', page, size: 100 })
|
||||||
|
if (requestVersion !== sessionVersion || queueVersion !== queueVersions[kind]) return
|
||||||
|
const rows = payload?.content || payload?.tasks || payload?.records || (Array.isArray(payload) ? payload : [])
|
||||||
|
allRows.push(...rows)
|
||||||
|
total = Number(payload?.totalElements ?? payload?.total ?? allRows.length)
|
||||||
|
page += 1
|
||||||
|
if (!rows.length || rows.length < 100 || page >= 1000) break
|
||||||
|
} while (allRows.length < total)
|
||||||
|
if (requestVersion !== sessionVersion || queueVersion !== queueVersions[kind]) return
|
||||||
|
const normalized: ReimApplicationDetail[] = allRows.map((row: any) => normalize(row))
|
||||||
|
const byId = new Map(reimbursements.value.map(item => [String(item.id), item]))
|
||||||
|
normalized.forEach((item: ReimApplicationDetail) => byId.set(String(item.id), item))
|
||||||
|
reimbursements.value = [...byId.values()]
|
||||||
|
refreshPaymentStatuses()
|
||||||
|
financeQueueError.value = ''
|
||||||
|
} catch {
|
||||||
|
if (requestVersion === sessionVersion && queueVersion === queueVersions[kind]) financeQueueError.value = kind === 'receipt' ? '无法读取财务收单队列,请重试。' : '无法读取待付款队列,请重试。'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const getById = (id: string | number) => reimbursements.value.find(item => String(item.id) === String(id)) || null
|
||||||
|
const saveMutation = async <T>(operation: () => Promise<T>, fallbackOperation: () => T) => { if (source.value === 'fallback') return fallbackOperation(); return operation() }
|
||||||
|
const save = async (payload: CreateApplicationRequest, id?: string | number) => {
|
||||||
|
const requestVersion = sessionVersion
|
||||||
|
const local = () => { const existing = id ? getById(id) : null; if (existing && (existing.applicantName !== user.value?.realName || !['草稿', '退回', '已取消'].includes(existing.approvalStatus === '退回' ? '退回' : existing.approvalStatus === '已取消' ? '已取消' : existing.applicationStatus))) throw new Error('只能修改本人草稿、退回或已取消的报销'); const result = existing ? normalize({ ...existing, ...payload, expenseItems: payload.items }) : createFallbackDetail(payload, `BX${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${String(Date.now()).slice(-4)}`, user.value || fallbackLogin().user); if (existing) reimbursements.value = reimbursements.value.map(item => item.id === existing.id ? result : item); else reimbursements.value.unshift(result); return result }
|
||||||
|
const result = await saveMutation(() => id ? reimbursementApi.update(id, payload) : reimbursementApi.create(payload), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback') { const normalized = normalize(result); if (id) reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item); else reimbursements.value.unshift(normalized); return normalized } return result
|
||||||
|
}
|
||||||
|
const submit = async (id: string | number) => { const requestVersion = sessionVersion; const local = () => { const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.applicantName !== user.value?.realName) throw new Error('只能提交本人报销'); if (item.applicationStatus !== '草稿' && item.approvalStatus !== '退回' && item.approvalStatus !== '已取消') throw new Error('只能提交草稿、退回或已取消报销'); item.applicationStatus = '已提交'; item.approvalStatus = '审批中'; item.currentApprovalNode = '部门负责人审批'; return item }; const result = await saveMutation(() => reimbursementApi.submit(id), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback' && result) { const normalized = normalize(result); reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item); return normalized } return result }
|
||||||
|
const receive = async (id: string | number) => { const requestVersion = sessionVersion; const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.approvalStatus !== '审批通过') throw new Error('仅审批通过的报销可以收单'); if (source.value === 'fallback') { if (!['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(user.value?.userType || '')) throw new Error('仅财务人员可以确认收单'); item.receiptStatus = '已收单'; item.updatedAt = new Date().toISOString(); return item } const result = await reimbursementApi.receive(id); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); const normalized = normalize(result); reimbursements.value = reimbursements.value.map(row => String(row.id) === String(id) ? normalized : row); return normalized }
|
||||||
|
const pay = async (id: string | number, amount: number, remark: string, idempotencyKey: string) => { const requestVersion = sessionVersion; const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.receiptStatus !== '已收单') throw new Error('申请尚未完成财务收单,无法付款'); if (!(amount > 0) || amount > balance(item) + 0.005) throw new Error(`付款金额须大于 0 且不超过未付余额 ¥ ${balance(item).toFixed(2)}`); const local = () => { const previous = fallbackPaymentKeys.get(idempotencyKey); if (previous) return previous; const record: PaymentRecord = { id: `PAY-${Date.now()}`, paymentNo: `PAY-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${String(Date.now()).slice(-4)}`, applicationId: id, paymentAmount: amount, totalAmount: item.totalAmount, paidAmount: amount, remainingAmount: balance(item) - amount, paymentMethod: '银行转账', paymentStatus: '有效', operatorName: user.value?.realName || '财务人员', paymentTime: new Date().toISOString().slice(0, 16).replace('T', ' '), remark: remark || idempotencyKey }; fallbackPaymentKeys.set(idempotencyKey, record); payments.value.unshift(record); refreshPaymentStatuses(); return record }; const result = await saveMutation(() => (amount < balance(item) ? cashierApi.partialPayment(id, amount, remark, idempotencyKey) : cashierApi.executePayment(id, amount, remark, idempotencyKey)), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback') { const record = normalizePayment({ ...(result || {}), applicationId: id, paymentStatus: result?.paymentStatus || result?.status || '有效', totalAmount: item.totalAmount }); payments.value.unshift(record); refreshPaymentStatuses() } return result }
|
||||||
|
const reset = () => { sessionVersion += 1; queueVersions.receipt += 1; queueVersions.payment += 1; loadPromise = null; user.value = null; reimbursements.value = []; payments.value = []; source.value = 'connecting'; loading.value = false; error.value = ''; financeQueueError.value = ''; notifications.value = 0; fallbackPaymentKeys.clear() }
|
||||||
|
const loginFallback = (employeeNo?: string) => { reset(); const result = fallbackLogin(employeeNo); user.value = result.user; localStorage.setItem('token', result.token); localStorage.setItem('userInfo', JSON.stringify(result.user)); return result }
|
||||||
|
return { user, reimbursements, payments, source, loading, error, financeQueueError, notifications, summaries, balance, paidAmount, load, loadList, loadDetail, loadFinanceQueue, getById, save, submit, receive, pay, loginFallback, reset, refreshPaymentStatuses }
|
||||||
|
})
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
export const AUTH_DAY_KEY = 'finance.auth-day'
|
||||||
|
export const TOKEN_KEY = 'token'
|
||||||
|
export const USER_INFO_KEY = 'userInfo'
|
||||||
|
export const DEMO_SESSION_TOKEN = 'demo-local-session'
|
||||||
|
|
||||||
|
const SHANGHAI_TIME_ZONE = 'Asia/Shanghai'
|
||||||
|
const SHANGHAI_OFFSET_MS = 8 * 60 * 60 * 1000
|
||||||
|
|
||||||
|
const shanghaiDateParts = (date: Date) => {
|
||||||
|
const parts = new Intl.DateTimeFormat('en-US', {
|
||||||
|
timeZone: SHANGHAI_TIME_ZONE,
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
}).formatToParts(date)
|
||||||
|
|
||||||
|
const values = Object.fromEntries(parts.map(part => [part.type, part.value]))
|
||||||
|
return {
|
||||||
|
year: Number(values.year),
|
||||||
|
month: Number(values.month),
|
||||||
|
day: Number(values.day),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The business day used by authentication, independent of the browser locale. */
|
||||||
|
export const getBusinessDay = (date = new Date()): string => {
|
||||||
|
const { year, month, day } = shanghaiDateParts(date)
|
||||||
|
return `${year.toString().padStart(4, '0')}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
export const saveAuthDay = (day = getBusinessDay()) => {
|
||||||
|
localStorage.setItem(AUTH_DAY_KEY, day)
|
||||||
|
}
|
||||||
|
|
||||||
|
export const clearStoredSession = () => {
|
||||||
|
localStorage.removeItem(TOKEN_KEY)
|
||||||
|
localStorage.removeItem(USER_INFO_KEY)
|
||||||
|
localStorage.removeItem(AUTH_DAY_KEY)
|
||||||
|
}
|
||||||
|
|
||||||
|
const millisecondsUntilNextBusinessDay = () => {
|
||||||
|
const { year, month, day } = shanghaiDateParts(new Date())
|
||||||
|
// Asia/Shanghai uses UTC+08:00. The next local midnight is therefore this
|
||||||
|
// UTC timestamp minus eight hours.
|
||||||
|
const nextMidnight = Date.UTC(year, month - 1, day + 1) - SHANGHAI_OFFSET_MS
|
||||||
|
return Math.max(1000, nextMidnight - Date.now() + 25)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Schedule exactly one callback. Call the returned disposer before rescheduling. */
|
||||||
|
export const scheduleNextBusinessDay = (callback: () => void): (() => void) => {
|
||||||
|
if (typeof window === 'undefined') return () => undefined
|
||||||
|
const timer = window.setTimeout(callback, millisecondsUntilNextBusinessDay())
|
||||||
|
return () => window.clearTimeout(timer)
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<div class="page-head"><div><span class="eyebrow">REIMBURSEMENT DETAIL</span><h1>报销单详情</h1><p>{{ item ? `${item.applicationNo} · ${item.title}` : `单号:${route.params.id}` }}</p></div><div class="head-actions"><button class="btn" @click="router.back()">← 返回</button><button v-if="item" class="btn" @click="print">打印详情</button><router-link v-if="canEdit" class="btn primary" :to="editRoute">{{ item?.approvalStatus === '退回' ? '补充材料' : '编辑草稿' }}</router-link></div></div>
|
||||||
|
<div v-if="store.loading" class="load-wrap"><span class="loader"></span><p>正在读取报销详情…</p></div>
|
||||||
|
<div v-else-if="!item" class="card empty-state"><strong>未找到该报销单</strong><span>单号「{{ route.params.id }}」不存在或已被删除,请返回我的报销重试。</span><router-link class="btn" to="/applications">返回我的报销</router-link></div>
|
||||||
|
<template v-else>
|
||||||
|
<div v-if="item.approvalStatus === '退回'" class="inline-alert danger" role="alert"><b>!</b><span><strong>审批退回,需补充材料</strong><br>{{ item.returnReason || '请查看审批意见' }}</span><router-link class="btn small" :to="`/applications/${item.id}/edit`">去补充</router-link></div>
|
||||||
|
<div class="detail-layout"><div>
|
||||||
|
<div class="status-strip" aria-label="报销流程独立状态"><div><small>申请状态</small><span class="tag" :class="tone(item.applicationStatus)">{{ item.applicationStatus }}</span></div><div><small>审批状态</small><span class="tag" :class="tone(item.approvalStatus)">{{ item.approvalStatus }}</span></div><div><small>收单状态</small><span class="tag" :class="tone(item.receiptStatus)">{{ item.receiptStatus }}</span></div><div><small>付款状态</small><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></div></div>
|
||||||
|
<div class="workflow" aria-label="报销流程"><div v-for="(step,index) in workflow" :key="step.name" class="workflow-step" :class="step.tone"><span>{{ index + 1 }}</span><div><strong>{{ step.name }}</strong><small>{{ step.value }}</small></div></div></div>
|
||||||
|
<section class="section-card"><div class="section-title"><h2>报销信息</h2><span>{{ item.category }}</span></div><div class="form-grid"><div class="field"><label>报销人 / 部门</label><input readonly :value="`${item.applicantName} / ${item.departmentName}`"></div><div class="field"><label>费用类型</label><input readonly :value="`${item.expenseTypeName} · ${item.category}`"></div><div class="field"><label>申请金额</label><input readonly :value="money(item.totalAmount)"></div><div class="field"><label>申请日期</label><input readonly :value="item.createdAt?.slice(0,10) || '-' "></div><div class="field"><label>收款人 / 账户</label><input readonly :value="`${item.payeeName} · ${item.bankAccountMask || '已脱敏'}`"></div><div class="field full"><label>报销说明</label><textarea readonly :value="item.description"></textarea></div></div></section>
|
||||||
|
<section class="source-card"><div class="source-card-head"><div><span class="eyebrow">KINGDEE SOURCE · READ ONLY</span><h3>{{ item.sourceDocNo || '未关联源单' }} <small>{{ item.sourceStatus }}</small></h3></div><span class="tag success">只读</span></div><div class="source-grid"><div><span>来源系统</span><strong>{{ item.sourceDocNo ? '金蝶 ERP' : '暂无' }}</strong></div><div><span>源单编号</span><strong>{{ item.sourceDocNo || '—' }}</strong></div><div><span>来源状态</span><strong>{{ item.sourceStatus }}</strong></div><div><span>收款人</span><strong>{{ item.payeeName }}</strong></div><div><span>开户银行</span><strong>{{ item.bankName || '—' }}</strong></div><div><span>账号</span><strong>{{ item.bankAccountMask || '已脱敏' }}</strong></div></div><p><b>只读说明</b> 来源单据由外部系统同步,需修改业务事实请回到金蝶维护后重新同步。</p></section>
|
||||||
|
<section class="section-card"><div class="section-title"><h2>费用明细</h2><span>{{ item.expenseItems.length }} 条</span></div><div v-if="item.expenseItems.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>日期</th><th>类别</th><th>说明</th><th class="amount">金额</th></tr></thead><tbody><tr v-for="expense in item.expenseItems" :key="expense.id || expense.seqNo"><td data-label="日期">{{ expense.expenseDate }}</td><td data-label="类别">{{ expense.category }}</td><td data-label="说明">{{ expense.description }}</td><td data-label="金额" class="amount">{{ money(expense.amount) }}</td></tr></tbody></table></div></section>
|
||||||
|
<section class="section-card"><div class="section-title"><h2>发票</h2><span>{{ item.invoices.length }} 张</span></div><div v-if="item.invoices.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>发票号码</th><th class="amount">发票金额</th><th>校验状态</th></tr></thead><tbody><tr v-for="invoice in item.invoices" :key="invoice.id"><td data-label="发票号码">{{ invoice.invoiceNo }}</td><td data-label="发票金额" class="amount">{{ money(invoice.amount) }}</td><td data-label="校验状态">{{ invoice.verifyStatus }}</td></tr></tbody></table></div><div v-else class="empty-state"><strong>暂无发票</strong><span>请按费用事项补充发票或证明材料</span></div></section>
|
||||||
|
<section class="section-card"><div class="section-title"><h2>附件材料</h2><span>{{ item.attachments.length }} 份</span></div><div v-if="item.attachments.length" class="attachment-grid"><div v-for="file in item.attachments" :key="file.id" class="attachment-item"><span class="file-icon">PDF</span><div><strong>{{ file.fileName }}</strong><small>{{ file.fileType }} · 只读材料</small></div></div></div><div v-else class="empty-state">尚未上传附件</div></section>
|
||||||
|
<section class="section-card"><div class="section-title"><h2>审批、收单与付款时间线</h2><span>状态留痕</span></div><div class="timeline"><div v-for="entry in timeline" :key="entry.name" class="timeline-item" :class="entry.done ? 'done' : 'pending'"><span class="timeline-dot"></span><div><strong>{{ entry.name }}</strong><p>{{ entry.copy }}</p><time>{{ entry.time }}</time></div></div></div></section>
|
||||||
|
</div><aside class="card side-panel"><div class="summary-block"><h3>金额汇总</h3><div class="amount-highlight">{{ money(item.totalAmount) }}</div><div class="summary-row"><span>已付款</span><strong>{{ money(store.paidAmount(item)) }}</strong></div><div class="summary-row"><span>未付款</span><strong>{{ money(store.balance(item)) }}</strong></div><div class="summary-total"><span>付款进度</span><strong>{{ item.totalAmount ? `${Math.round(store.paidAmount(item) / item.totalAmount * 100)}%` : '0%' }}</strong></div></div><div class="summary-block"><h3>付款记录</h3><div v-if="item.payments.length"><div v-for="payment in item.payments" :key="payment.id" class="payment-record"><strong>{{ payment.paymentNo }}</strong><span>{{ money(payment.paymentAmount) }} · {{ payment.paymentTime }}</span><small>{{ payment.paymentMethod }} · {{ payment.operatorName }}</small></div></div><div v-else class="muted-copy">暂无实际付款记录</div></div></aside></div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted } from 'vue'; import { useRoute, useRouter } from 'vue-router'; import { useUserStore } from '@/store/user'; import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
const route=useRoute(); const router=useRouter(); const store=useWorkbenchStore(); const userStore=useUserStore(); const item=computed(()=>store.getById(String(route.params.id))); const canEdit=computed(()=>!!item.value && item.value.applicantName===userStore.userInfo?.realName && (item.value.applicationStatus==='草稿'||item.value.approvalStatus==='退回')); const editRoute=computed(()=>item.value?`/applications/${item.value.id}/edit`:'/applications'); const money=(v:number)=>`¥ ${Number(v||0).toLocaleString('zh-CN',{minimumFractionDigits:2})}`; const tone=(v:string)=>({草稿:'draft',已提交:'info',审批中:'pending',审批通过:'success',退回:'danger',待收单:'pending',已收单:'success',未付款:'neutral',部分付款:'info',已付款:'success',未触发:'neutral'} as Record<string,string>)[v]||'neutral'; const print=()=>window.print()
|
||||||
|
const workflow=computed(()=>item.value?[{name:'申请',value:item.value.applicationStatus,tone:tone(item.value.applicationStatus)},{name:'审批',value:item.value.approvalStatus,tone:tone(item.value.approvalStatus)},{name:'收单',value:item.value.receiptStatus,tone:tone(item.value.receiptStatus)},{name:'付款',value:item.value.paymentStatus,tone:tone(item.value.paymentStatus)}]:[])
|
||||||
|
const timeline=computed(()=>{const current=item.value;if(!current)return[];return[{name:'申请提交',copy:current.applicationStatus==='草稿'?'尚未提交申请':`${current.applicantName} 已提交报销申请`,done:current.applicationStatus!=='草稿',time:current.submitTime||current.createdAt||'待触发'},{name:'飞书审批',copy:current.approvalStatus==='退回'?`退回:${current.returnReason||'需补充材料'}`:current.approvalStatus==='审批通过'?'审批通过,结果已同步':`当前节点:${current.currentApprovalNode}`,done:current.approvalStatus!=='未触发',time:current.updatedAt||'待触发'},{name:'财务收单',copy:current.receiptStatus==='已收单'?'财务已完成收单':current.receiptStatus==='待收单'?'等待财务办理收单':'审批通过后激活',done:current.receiptStatus==='已收单',time:current.updatedAt||'待触发'},{name:'付款登记',copy:current.paymentStatus==='未付款'?'等待外部支付并登记凭据':`累计已付 ${money(store.paidAmount(current))}`,done:current.paymentStatus==='已付款',time:current.updatedAt||'待办理'}]})
|
||||||
|
onMounted(()=>{void store.loadDetail(String(route.params.id))})
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page-content">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">MY EXPENSES</span>
|
||||||
|
<h1>我的报销</h1>
|
||||||
|
<p>集中查看报销申请及审批、收单、付款进度。</p>
|
||||||
|
</div>
|
||||||
|
<div class="head-actions">
|
||||||
|
<button class="btn" type="button" :disabled="loadingState" @click="reload">刷新</button>
|
||||||
|
<router-link class="btn primary" to="/applications/new">+ 发起报销</router-link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="loadingState" class="load-wrap" role="status" aria-live="polite">
|
||||||
|
<span class="loader" aria-hidden="true"></span>
|
||||||
|
<p>正在加载报销记录…</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="hasBlockingError" class="card empty-state" role="alert">
|
||||||
|
<strong>报销记录暂时无法加载</strong>
|
||||||
|
<span>请检查网络连接后重试,系统不会以空列表代替异常数据。</span>
|
||||||
|
<button class="btn" type="button" @click="reload">重新加载</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="page-content">
|
||||||
|
<div v-if="hasDataNotice" class="inline-alert" role="status" aria-live="polite">
|
||||||
|
<b aria-hidden="true">i</b>
|
||||||
|
<span>数据服务暂时不可用,当前记录可能不完整。</span>
|
||||||
|
<button class="btn small" type="button" @click="reload">重试</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card fill-list-card">
|
||||||
|
<div class="tabs" role="tablist" aria-label="报销列表筛选">
|
||||||
|
<button
|
||||||
|
v-for="tab in tabs"
|
||||||
|
:id="`application-tab-${tab.key}`"
|
||||||
|
:key="tab.key"
|
||||||
|
class="tab"
|
||||||
|
:class="{ active: currentTab === tab.key }"
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
:aria-selected="currentTab === tab.key"
|
||||||
|
:aria-controls="applicationsPanelId"
|
||||||
|
@click="currentTab = tab.key"
|
||||||
|
>
|
||||||
|
{{ tab.label }} <small>({{ tabCounts[tab.key] }})</small>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div
|
||||||
|
:id="applicationsPanelId"
|
||||||
|
role="tabpanel"
|
||||||
|
class="fill-list-card"
|
||||||
|
:aria-labelledby="`application-tab-${currentTab}`"
|
||||||
|
>
|
||||||
|
<div class="filter-bar">
|
||||||
|
<label class="filter-search">
|
||||||
|
<span aria-hidden="true">⌕</span>
|
||||||
|
<input v-model="query" type="search" placeholder="搜索单号、事项或申请人" aria-label="搜索报销">
|
||||||
|
</label>
|
||||||
|
<select v-model="applicationFilter" aria-label="按申请状态筛选">
|
||||||
|
<option value="">全部申请状态</option>
|
||||||
|
<option value="草稿">草稿</option>
|
||||||
|
<option value="已提交">已提交</option>
|
||||||
|
</select>
|
||||||
|
<select v-model="approvalFilter" aria-label="按审批状态筛选">
|
||||||
|
<option value="">全部审批状态</option>
|
||||||
|
<option value="审批中">审批中</option>
|
||||||
|
<option value="审批通过">审批通过</option>
|
||||||
|
<option value="退回">退回</option>
|
||||||
|
</select>
|
||||||
|
<span class="filter-spacer"></span>
|
||||||
|
<span class="tag info" aria-live="polite">{{ filtered.length }} 笔结果</span>
|
||||||
|
<button v-if="hasFilters" class="table-action" type="button" @click="clearFilters">清除筛选</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="store.reimbursements.length && filtered.length" class="table-wrap">
|
||||||
|
<table class="data-table responsive-table" aria-label="报销申请列表">
|
||||||
|
<caption class="sr-only">报销申请列表,包含申请、审批、收单和付款状态</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">报销单号</th>
|
||||||
|
<th scope="col">报销事项</th>
|
||||||
|
<th scope="col" class="amount">报销金额</th>
|
||||||
|
<th scope="col">申请状态</th>
|
||||||
|
<th scope="col">审批状态</th>
|
||||||
|
<th scope="col">收单状态</th>
|
||||||
|
<th scope="col">付款状态</th>
|
||||||
|
<th scope="col">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in filtered" :key="item.id">
|
||||||
|
<td data-label="报销单号">
|
||||||
|
<router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link>
|
||||||
|
<small>{{ item.createdAt?.slice(0, 10) || '-' }}</small>
|
||||||
|
</td>
|
||||||
|
<td data-label="报销事项">
|
||||||
|
<strong>{{ item.title }}</strong>
|
||||||
|
<small>{{ item.category || item.expenseTypeName }} · {{ item.applicantName }}</small>
|
||||||
|
</td>
|
||||||
|
<td data-label="报销金额" class="amount">{{ money(item.totalAmount) }}</td>
|
||||||
|
<td data-label="申请状态"><span class="tag" :class="tone(item.applicationStatus)">{{ item.applicationStatus }}</span></td>
|
||||||
|
<td data-label="审批状态"><span class="tag" :class="tone(item.approvalStatus)">{{ item.approvalStatus }}</span></td>
|
||||||
|
<td data-label="收单状态"><span class="tag" :class="tone(item.receiptStatus)">{{ item.receiptStatus }}</span></td>
|
||||||
|
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
|
||||||
|
<td data-label="操作">
|
||||||
|
<router-link class="table-action" :to="`/applications/${item.id}`">查看详情</router-link>
|
||||||
|
<router-link v-if="editable(item)" class="table-action" :to="`/applications/${item.id}/edit`">
|
||||||
|
{{ item.approvalStatus === '退回' ? '补充材料' : '编辑草稿' }}
|
||||||
|
</router-link>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="!store.reimbursements.length" class="empty-state">
|
||||||
|
<strong>暂无报销记录</strong>
|
||||||
|
<span>发起一笔报销后,申请进度会显示在这里。</span>
|
||||||
|
<router-link class="btn primary" to="/applications/new">发起报销</router-link>
|
||||||
|
</div>
|
||||||
|
<div v-else class="empty-state">
|
||||||
|
<strong>没有符合条件的报销</strong>
|
||||||
|
<span>请调整搜索关键词或筛选条件。</span>
|
||||||
|
<button class="btn" type="button" @click="clearFilters">清除筛选</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
|
||||||
|
type ApplicationTabKey = 'all' | 'mine' | 'approval' | 'returned' | 'paid'
|
||||||
|
type ApplicationTab = { key: ApplicationTabKey; label: string }
|
||||||
|
|
||||||
|
const store = useWorkbenchStore()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const route = useRoute()
|
||||||
|
const query = ref(String(route.query.q || ''))
|
||||||
|
const currentTab = ref<ApplicationTabKey>('all')
|
||||||
|
const applicationFilter = ref('')
|
||||||
|
const approvalFilter = ref('')
|
||||||
|
const hasLoaded = ref(Boolean(store.reimbursements.length))
|
||||||
|
const applicationsPanelId = 'applications-list-panel'
|
||||||
|
|
||||||
|
const tabs: ApplicationTab[] = [
|
||||||
|
{ key: 'all', label: '全部' },
|
||||||
|
{ key: 'mine', label: '我发起的' },
|
||||||
|
{ key: 'approval', label: '审批中' },
|
||||||
|
{ key: 'returned', label: '退回补充' },
|
||||||
|
{ key: 'paid', label: '已付款' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const isMine = (item: ReimApplicationDetail) => item.applicantName === (userStore.userInfo?.realName || store.user?.realName)
|
||||||
|
|
||||||
|
const matchesTab = (item: ReimApplicationDetail, tab: ApplicationTabKey) => (
|
||||||
|
tab === 'all' ||
|
||||||
|
(tab === 'mine' && isMine(item)) ||
|
||||||
|
(tab === 'approval' && item.approvalStatus === '审批中') ||
|
||||||
|
(tab === 'returned' && item.approvalStatus === '退回') ||
|
||||||
|
(tab === 'paid' && item.paymentStatus === '已付款')
|
||||||
|
)
|
||||||
|
|
||||||
|
const tabCounts = computed<Record<ApplicationTabKey, number>>(() => ({
|
||||||
|
all: store.reimbursements.length,
|
||||||
|
mine: store.reimbursements.filter(item => matchesTab(item, 'mine')).length,
|
||||||
|
approval: store.reimbursements.filter(item => matchesTab(item, 'approval')).length,
|
||||||
|
returned: store.reimbursements.filter(item => matchesTab(item, 'returned')).length,
|
||||||
|
paid: store.reimbursements.filter(item => matchesTab(item, 'paid')).length,
|
||||||
|
}))
|
||||||
|
|
||||||
|
const filtered = computed(() => {
|
||||||
|
const normalizedQuery = query.value.trim().toLowerCase()
|
||||||
|
return store.reimbursements.filter(item => (
|
||||||
|
(!normalizedQuery || `${item.applicationNo} ${item.title} ${item.applicantName} ${item.payeeName}`.toLowerCase().includes(normalizedQuery)) &&
|
||||||
|
(!applicationFilter.value || item.applicationStatus === applicationFilter.value) &&
|
||||||
|
(!approvalFilter.value || item.approvalStatus === approvalFilter.value) &&
|
||||||
|
matchesTab(item, currentTab.value)
|
||||||
|
))
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadingState = computed(() => store.loading || !hasLoaded.value)
|
||||||
|
const hasBlockingError = computed(() => hasLoaded.value && store.source === 'error')
|
||||||
|
const hasDataNotice = computed(() => hasLoaded.value && Boolean(store.error) && !hasBlockingError.value)
|
||||||
|
const hasFilters = computed(() => Boolean(query.value.trim() || applicationFilter.value || approvalFilter.value || currentTab.value !== 'all'))
|
||||||
|
|
||||||
|
const reload = async () => {
|
||||||
|
hasLoaded.value = false
|
||||||
|
await store.load()
|
||||||
|
hasLoaded.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const clearFilters = () => {
|
||||||
|
query.value = ''
|
||||||
|
applicationFilter.value = ''
|
||||||
|
approvalFilter.value = ''
|
||||||
|
currentTab.value = 'all'
|
||||||
|
}
|
||||||
|
|
||||||
|
const editable = (item: ReimApplicationDetail) => isMine(item) && (item.applicationStatus === '草稿' || item.approvalStatus === '退回')
|
||||||
|
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
|
||||||
|
const tone = (value: string) => ({
|
||||||
|
草稿: 'draft', 已提交: 'info', 审批中: 'pending', 审批通过: 'success', 退回: 'danger',
|
||||||
|
待收单: 'pending', 已收单: 'success', 未付款: 'neutral', 部分付款: 'info', 已付款: 'success', 未触发: 'neutral',
|
||||||
|
} as Record<string, string>)[value] || 'neutral'
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
if (!store.reimbursements.length) await store.load()
|
||||||
|
hasLoaded.value = true
|
||||||
|
})
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
<template>
|
||||||
|
<div class="dashboard-page">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">{{ isFinance ? '财务工作台' : '员工报销' }}</span>
|
||||||
|
<h1>{{ isFinance ? '财务处理工作台' : '我的报销工作台' }}</h1>
|
||||||
|
<p v-if="isFinance">你好,{{ userName }}。集中处理收单、付款和业务单据。</p>
|
||||||
|
<p v-else>你好,{{ userName }}。查看报销进度,及时处理退回事项。</p>
|
||||||
|
</div>
|
||||||
|
<div class="head-actions">
|
||||||
|
<template v-if="isFinance">
|
||||||
|
<router-link class="btn" to="/finance-receipt">查看待收单</router-link>
|
||||||
|
<router-link class="btn" to="/payments">查看待付款</router-link>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<router-link class="btn primary" to="/applications/new"><Plus /> 发起报销</router-link>
|
||||||
|
<router-link class="btn" to="/applications">查看我的报销</router-link>
|
||||||
|
</template>
|
||||||
|
<button class="btn" type="button" :disabled="store.loading || financeQueueLoading" @click="refresh">
|
||||||
|
<Refresh /> 刷新数据
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="store.loading || financeQueueLoading || (store.source === 'connecting' && !store.reimbursements.length)" class="load-wrap" role="status" aria-live="polite">
|
||||||
|
<span class="loader"></span>
|
||||||
|
<p>正在读取工作台数据…</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="store.source === 'error' || financeQueueError" class="card dashboard-error" role="alert">
|
||||||
|
<WarningFilled aria-hidden="true" />
|
||||||
|
<strong>工作台暂时无法加载</strong>
|
||||||
|
<p>{{ financeQueueError || '业务数据同步失败,请重试。当前未展示业务记录。' }}</p>
|
||||||
|
<button class="btn primary" type="button" @click="refresh"><Refresh /> 重新同步</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<section class="welcome-panel">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">数据概览</span>
|
||||||
|
<h2>{{ isFinance ? '今日处理重点' : '报销进度,随时掌握' }}</h2>
|
||||||
|
<p v-if="isFinance">待收单和待付款队列按独立业务状态呈现,金额以当前同步结果为准。</p>
|
||||||
|
<p v-else>审批、收单和付款状态分别展示,退回事项可以直接继续处理。</p>
|
||||||
|
</div>
|
||||||
|
<div class="sync-status" :class="{ warning: store.source === 'fallback' || !!store.error }">
|
||||||
|
<span class="sync-dot"></span>
|
||||||
|
<div>
|
||||||
|
<strong>数据同步</strong>
|
||||||
|
<small>{{ syncDescription }}</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div v-if="!isFinance" class="metrics">
|
||||||
|
<div class="metric warn">
|
||||||
|
<small>退回待办</small>
|
||||||
|
<strong>{{ returned.length }}</strong>
|
||||||
|
<span>{{ returned.length ? '项待补充材料' : '暂无待处理事项' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<small>审批中</small>
|
||||||
|
<strong>{{ approving.length }}</strong>
|
||||||
|
<span>申请正在审批流程中</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<small>待付款</small>
|
||||||
|
<strong>{{ pendingPayment.length }}</strong>
|
||||||
|
<span>{{ money(pendingPaymentAmount) }} 待支付</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric success">
|
||||||
|
<small>本月报销金额</small>
|
||||||
|
<strong>{{ money(monthTotal) }}</strong>
|
||||||
|
<span>{{ monthCount }} 笔本月申请</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="metrics finance-dashboard-metrics">
|
||||||
|
<div class="metric warn">
|
||||||
|
<small>待收单</small>
|
||||||
|
<strong>{{ receipt.length }}</strong>
|
||||||
|
<span>审批通过,等待财务确认</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<small>待付款</small>
|
||||||
|
<strong>{{ payable.length }}</strong>
|
||||||
|
<span>已收单且存在未付余额</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric success">
|
||||||
|
<small>待付款金额</small>
|
||||||
|
<strong>{{ money(payableAmount) }}</strong>
|
||||||
|
<span>当前未付余额合计</span>
|
||||||
|
</div>
|
||||||
|
<div class="metric">
|
||||||
|
<small>已收单</small>
|
||||||
|
<strong>{{ received.length }}</strong>
|
||||||
|
<span>{{ money(receivedAmount) }} 已进入付款环节</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="!isFinance" class="grid two">
|
||||||
|
<section class="card fill-list-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>退回待办</h2><p>需要你补充材料的报销事项</p></div>
|
||||||
|
<span class="tag danger">{{ returned.length }} 项</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body task-list fill-card-body">
|
||||||
|
<div v-for="item in returned" :key="item.id" class="task-item">
|
||||||
|
<span class="task-icon danger-icon" aria-hidden="true"><WarningFilled /></span>
|
||||||
|
<div><strong>{{ item.title }}</strong><small>{{ item.returnReason || '请补充材料' }} · {{ money(item.totalAmount) }}</small></div>
|
||||||
|
<router-link class="table-action" :to="`/applications/${item.id}/edit`">去补充</router-link>
|
||||||
|
</div>
|
||||||
|
<div v-if="!returned.length" class="empty-state"><CircleCheckFilled aria-hidden="true" /><strong>暂无需要补充的报销</strong><span>新的审批消息会同步到这里</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card fill-list-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>报销状态</h2><p>审批和付款中的申请</p></div>
|
||||||
|
<span class="tag info">我的申请</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body task-list fill-card-body">
|
||||||
|
<div class="finance-line">
|
||||||
|
<span class="flow-badge" aria-hidden="true"><Refresh /></span>
|
||||||
|
<div><strong>审批中</strong><small>{{ approving.length }} 笔申请正在审批</small></div>
|
||||||
|
<router-link class="table-action" to="/applications">查看</router-link>
|
||||||
|
</div>
|
||||||
|
<div class="finance-line">
|
||||||
|
<span class="flow-badge payment-badge" aria-hidden="true"><Wallet /></span>
|
||||||
|
<div><strong>待付款</strong><small>{{ pendingPayment.length }} 笔,{{ money(pendingPaymentAmount) }} 待支付</small></div>
|
||||||
|
<router-link class="table-action" to="/applications">查看</router-link>
|
||||||
|
</div>
|
||||||
|
<div v-if="!approving.length && !pendingPayment.length" class="empty-state compact-empty"><strong>暂无进行中的事项</strong><span>申请状态更新后会显示在这里</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else class="grid two">
|
||||||
|
<section class="card fill-list-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>待收单队列</h2><p>审批通过,等待财务确认收单</p></div>
|
||||||
|
<span class="tag pending">{{ receipt.length }} 笔</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body task-list fill-card-body">
|
||||||
|
<div v-for="item in receipt.slice(0, 5)" :key="item.id" class="finance-line">
|
||||||
|
<span class="flow-badge receipt-badge" aria-hidden="true"><Tickets /></span>
|
||||||
|
<div><strong>{{ item.applicationNo }}</strong><small>{{ item.applicantName }} · {{ item.title }} · {{ money(item.totalAmount) }}</small></div>
|
||||||
|
<router-link class="table-action" to="/finance-receipt">处理</router-link>
|
||||||
|
</div>
|
||||||
|
<div v-if="!receipt.length" class="empty-state"><CircleCheckFilled aria-hidden="true" /><strong>待收单队列为空</strong><span>新的审批结果同步后会显示在这里</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card fill-list-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>待付款队列</h2><p>已收单且存在未付余额</p></div>
|
||||||
|
<span class="tag info">{{ payable.length }} 笔</span>
|
||||||
|
</div>
|
||||||
|
<div class="card-body task-list fill-card-body">
|
||||||
|
<div v-for="item in payable.slice(0, 5)" :key="item.id" class="finance-line">
|
||||||
|
<span class="flow-badge payment-badge" aria-hidden="true"><Wallet /></span>
|
||||||
|
<div><strong>{{ item.applicationNo }}</strong><small>{{ item.applicantName }} · 未付 {{ money(store.balance(item)) }}</small></div>
|
||||||
|
<router-link class="table-action" to="/payments">处理</router-link>
|
||||||
|
</div>
|
||||||
|
<div v-if="!payable.length" class="empty-state"><CircleCheckFilled aria-hidden="true" /><strong>待付款队列为空</strong><span>完成收单的申请会进入这里</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section v-if="isFinance" class="card section-gap">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>已收单记录</h2><p>已完成财务收单的报销申请</p></div>
|
||||||
|
<router-link class="card-link" to="/payments">查看付款队列 <ArrowRight /></router-link>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table v-if="received.length" class="data-table responsive-table">
|
||||||
|
<thead><tr><th>报销单号</th><th>报销人 / 事项</th><th class="amount">申请金额</th><th>收单状态</th><th>付款状态</th><th>未付余额</th><th>操作</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in received.slice(0, 6)" :key="item.id">
|
||||||
|
<td data-label="报销单号"><router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link><small>{{ date(item.updatedAt || item.createdAt) }}</small></td>
|
||||||
|
<td data-label="报销人 / 事项"><strong>{{ item.applicantName }}</strong><small>{{ item.title }}</small></td>
|
||||||
|
<td data-label="申请金额" class="amount">{{ money(item.totalAmount) }}</td>
|
||||||
|
<td data-label="收单状态"><span class="tag success">{{ item.receiptStatus }}</span></td>
|
||||||
|
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
|
||||||
|
<td data-label="未付余额" class="amount">{{ money(store.balance(item)) }}</td>
|
||||||
|
<td data-label="操作"><router-link class="table-action" to="/payments">查看付款</router-link></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div v-if="!received.length" class="empty-state"><strong>暂无已收单记录</strong><span>完成收单的申请会显示在这里</span></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section v-else class="card section-gap">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>最近报销</h2><p>查看我的申请、审批、收单和付款状态</p></div>
|
||||||
|
<router-link class="card-link" to="/applications">查看全部 <ArrowRight /></router-link>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table v-if="mine.length" class="data-table responsive-table">
|
||||||
|
<thead><tr><th>报销单号</th><th>报销事项</th><th class="amount">报销金额</th><th>申请状态</th><th>审批状态</th><th>收单</th><th>付款</th><th>操作</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in mine.slice(0, 6)" :key="item.id">
|
||||||
|
<td data-label="报销单号"><router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link><small>{{ date(item.updatedAt || item.createdAt) }}</small></td>
|
||||||
|
<td data-label="报销事项"><strong>{{ item.title }}</strong><small>{{ item.category }}</small></td>
|
||||||
|
<td data-label="报销金额" class="amount">{{ money(item.totalAmount) }}</td>
|
||||||
|
<td data-label="申请状态"><span class="tag" :class="tone(item.applicationStatus)">{{ item.applicationStatus }}</span></td>
|
||||||
|
<td data-label="审批状态"><span class="tag" :class="tone(item.approvalStatus)">{{ item.approvalStatus }}</span></td>
|
||||||
|
<td data-label="收单状态"><span class="tag" :class="tone(item.receiptStatus)">{{ item.receiptStatus }}</span></td>
|
||||||
|
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
|
||||||
|
<td data-label="操作"><router-link class="table-action" :to="`/applications/${item.id}`">查看详情</router-link></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div v-if="!mine.length" class="empty-state"><strong>暂无报销记录</strong><span>发起报销后,申请进度会显示在这里</span><router-link class="btn small" to="/applications/new">发起报销</router-link></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref, watch } from 'vue'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const store = useWorkbenchStore()
|
||||||
|
const financeQueueLoading = ref(false)
|
||||||
|
const financeQueueError = ref('')
|
||||||
|
|
||||||
|
const userName = computed(() => userStore.userInfo?.realName || store.user?.realName || '用户')
|
||||||
|
const userType = computed(() => userStore.userInfo?.userType || store.user?.userType || '')
|
||||||
|
const isFinance = computed(() => ['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(userType.value))
|
||||||
|
const mine = computed(() => isFinance.value
|
||||||
|
? store.reimbursements
|
||||||
|
: store.reimbursements.filter(item => item.applicantName === userName.value))
|
||||||
|
const returned = computed(() => mine.value.filter(item => item.approvalStatus === '退回'))
|
||||||
|
const approving = computed(() => mine.value.filter(item => item.approvalStatus === '审批中'))
|
||||||
|
const receipt = computed(() => store.reimbursements.filter(item => item.approvalStatus === '审批通过' && item.receiptStatus === '待收单'))
|
||||||
|
const received = computed(() => store.reimbursements.filter(item => item.receiptStatus === '已收单'))
|
||||||
|
const payable = computed(() => received.value.filter(item => store.balance(item) > 0))
|
||||||
|
const pendingPayment = computed(() => mine.value.filter(item => item.receiptStatus === '已收单' && store.balance(item) > 0))
|
||||||
|
const pendingPaymentAmount = computed(() => pendingPayment.value.reduce((sum, item) => sum + store.balance(item), 0))
|
||||||
|
const payableAmount = computed(() => payable.value.reduce((sum, item) => sum + store.balance(item), 0))
|
||||||
|
const receivedAmount = computed(() => received.value.reduce((sum, item) => sum + item.totalAmount, 0))
|
||||||
|
const currentMonth = computed(() => {
|
||||||
|
const now = new Date()
|
||||||
|
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
|
||||||
|
})
|
||||||
|
const monthRows = computed(() => mine.value.filter(item => String(item.createdAt || item.submitTime).slice(0, 7) === currentMonth.value))
|
||||||
|
const monthTotal = computed(() => monthRows.value.reduce((sum, item) => sum + item.totalAmount, 0))
|
||||||
|
const monthCount = computed(() => monthRows.value.length)
|
||||||
|
const syncDescription = computed(() => {
|
||||||
|
if (store.source === 'fallback') return '服务暂不可用,当前展示缓存数据'
|
||||||
|
if (store.error) return '同步需要关注,请稍后重试'
|
||||||
|
if (store.source === 'api') return '业务数据已更新'
|
||||||
|
return '正在同步业务数据'
|
||||||
|
})
|
||||||
|
|
||||||
|
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
|
||||||
|
const date = (value: string) => value?.slice(0, 16) || '-'
|
||||||
|
const tone = (value: string) => ({
|
||||||
|
草稿: 'draft', 已提交: 'info', 审批中: 'pending', 审批通过: 'success', 退回: 'danger',
|
||||||
|
待收单: 'pending', 已收单: 'success', 未付款: 'neutral', 部分付款: 'info', 已付款: 'success',
|
||||||
|
未触发: 'neutral', 已取消: 'neutral',
|
||||||
|
} as Record<string, string>)[value] || 'neutral'
|
||||||
|
const loadDashboardData = async () => {
|
||||||
|
financeQueueError.value = ''
|
||||||
|
if (!isFinance.value) {
|
||||||
|
if (!store.reimbursements.length || store.source === 'error') await store.load()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
financeQueueLoading.value = true
|
||||||
|
store.financeQueueError = ''
|
||||||
|
try {
|
||||||
|
const queueErrors: string[] = []
|
||||||
|
await store.loadFinanceQueue('receipt')
|
||||||
|
if (store.financeQueueError) queueErrors.push(store.financeQueueError)
|
||||||
|
await store.loadFinanceQueue('payment')
|
||||||
|
if (store.financeQueueError && !queueErrors.includes(store.financeQueueError)) queueErrors.push(store.financeQueueError)
|
||||||
|
financeQueueError.value = queueErrors.join(';')
|
||||||
|
} finally {
|
||||||
|
financeQueueLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const refresh = () => { void loadDashboardData() }
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await loadDashboardData()
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(isFinance, () => { void loadDashboardData() })
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page-content">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">EXPENSE TYPES</span>
|
||||||
|
<h1>费用类型</h1>
|
||||||
|
<p>管理费用类型分类。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card fill-list-card">
|
||||||
|
<div class="table-wrap" v-if="items.length > 0" tabindex="0" role="region" aria-label="费用类型列表"><table class="data-table">
|
||||||
|
<thead><tr><th>编码</th><th>名称</th><th>分类</th><th>状态</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in items" :key="item.id">
|
||||||
|
<td><small>{{ item.code }}</small></td>
|
||||||
|
<td><strong>{{ item.name }}</strong></td>
|
||||||
|
<td><span class="tag">{{ item.category }}</span></td>
|
||||||
|
<td><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
<div class="empty-state" v-else-if="loaded"><strong>暂无费用类型</strong></div>
|
||||||
|
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载费用类型…</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import request from '@/api/request'
|
||||||
|
const items = ref<any[]>([])
|
||||||
|
const loaded = ref(false)
|
||||||
|
onMounted(async () => { try { items.value = await request.get('/metadata/expense-types') || [] } catch {} finally { loaded.value = true } })
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
<template>
|
||||||
|
<div class="directory-page page-content">
|
||||||
|
<FeishuDirectoryPanel @committed="refreshOrganization" />
|
||||||
|
|
||||||
|
<section class="card organization-card" aria-labelledby="organization-title">
|
||||||
|
<div class="card-head organization-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">ORGANIZATION</span>
|
||||||
|
<h2 id="organization-title">组织架构</h2>
|
||||||
|
<p>选择部门查看该部门及下级部门的飞书员工资料。</p>
|
||||||
|
</div>
|
||||||
|
<div class="organization-actions">
|
||||||
|
<span v-if="organization" class="muted-copy">快照状态:{{ snapshotLabels[organization.snapshotState] }}</span>
|
||||||
|
<button class="btn small" type="button" :disabled="organizationLoading || !canRead" @click="refreshOrganization">{{ organizationLoading ? '加载中…' : '刷新组织架构' }}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="!canRead" class="empty-state organization-state" role="alert">
|
||||||
|
<strong>无权查看通讯录</strong>
|
||||||
|
<span>当前账号没有飞书通讯录查看权限。</span>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="organizationLoading" class="load-wrap organization-state" role="status" aria-live="polite">
|
||||||
|
<span class="loader" aria-hidden="true"></span>
|
||||||
|
<span>正在加载飞书组织架构…</span>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="organizationError" class="empty-state organization-state" role="alert">
|
||||||
|
<strong>组织架构加载失败</strong>
|
||||||
|
<span>{{ organizationError }}</span>
|
||||||
|
<button class="btn small" type="button" @click="refreshOrganization">重试</button>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="!hasSnapshot" class="empty-state organization-state">
|
||||||
|
<strong>{{ organization?.snapshotState === 'UNAVAILABLE' ? '通讯录快照不可用' : '暂无组织架构' }}</strong>
|
||||||
|
<span>{{ organization?.snapshotState === 'NEVER_SYNCED' ? '首次同步成功后,组织架构会显示在这里。' : '同步成功后,组织架构会显示在这里。' }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="organization-layout">
|
||||||
|
<div class="organization-tree-wrap">
|
||||||
|
<div class="organization-summary">
|
||||||
|
<span>最近成功同步(本地时间):{{ formatLocalDateTime(organization?.lastSuccessfulAt, '暂无') }}</span>
|
||||||
|
<span>{{ departments.length }} 个部门 · {{ users.length }} 名员工</span>
|
||||||
|
</div>
|
||||||
|
<p v-if="organization?.snapshotState === 'STALE' || organization?.snapshotState === 'CONTEXT_CHANGED'" class="inline-note" role="status">当前展示的是过期或上下文已变化的快照,请同步后再作为最新目录使用。</p>
|
||||||
|
<ul class="organization-tree" role="tree" aria-label="飞书组织架构">
|
||||||
|
<li v-for="item in visibleDepartments" :key="item.node.id" role="treeitem" :aria-level="item.depth + 1" :aria-expanded="item.node.children.length ? isExpanded(item.node.id) : undefined" :aria-selected="selectedDepartmentId === item.node.id">
|
||||||
|
<div class="department-row" :style="{ '--department-depth': item.depth }">
|
||||||
|
<button v-if="item.node.children.length" class="tree-toggle" type="button" :aria-label="`${isExpanded(item.node.id) ? '收起' : '展开'}${item.node.name}`" @click.stop="toggleDepartmentAndSelect(item.node.id)"><span aria-hidden="true">{{ isExpanded(item.node.id) ? '−' : '+' }}</span></button>
|
||||||
|
<span v-else class="tree-toggle-spacer" aria-hidden="true"></span>
|
||||||
|
<button class="department-button" :class="{ selected: selectedDepartmentId === item.node.id }" type="button" :aria-current="selectedDepartmentId === item.node.id ? 'true' : undefined" @click="selectDepartment(item.node.id)">
|
||||||
|
<span class="department-name">{{ item.node.name }}</span>
|
||||||
|
<span class="department-count">{{ departmentMemberCounts.get(item.node.id) ?? 0 }} 人</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="department-members" aria-labelledby="members-title">
|
||||||
|
<div class="section-title">
|
||||||
|
<h3 id="members-title">{{ selectedDepartment?.name || '部门员工' }}<small v-if="selectedDepartment?.children.length" class="children-label">(含下级部门)</small></h3>
|
||||||
|
<span>{{ selectedUsers.length }} 人</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="!selectedUsers.length" class="empty-state compact-empty">
|
||||||
|
<strong>该部门暂无员工</strong>
|
||||||
|
<span>请选择其他部门查看员工。</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="member-list" role="list" aria-label="部门员工列表">
|
||||||
|
<div v-for="user in paginatedSelectedUsers" :key="user.internalKey" class="member-row" role="listitem">
|
||||||
|
<div v-if="user.avatarUrl" class="member-avatar-wrap"><img class="member-avatar" :src="user.avatarUrl" :alt="`${user.name}的头像`" loading="lazy"></div>
|
||||||
|
<div v-else class="member-avatar member-avatar-placeholder" aria-hidden="true">{{ user.name.charAt(0) || '人' }}</div>
|
||||||
|
<div class="member-copy">
|
||||||
|
<strong>{{ user.name }}</strong>
|
||||||
|
<span>userId:{{ user.userId }}</span>
|
||||||
|
<span>openId:{{ user.openId }}</span>
|
||||||
|
<dl class="member-details">
|
||||||
|
<div><dt>职位</dt><dd>{{ user.jobTitle }}</dd></div>
|
||||||
|
<div><dt>邮箱</dt><dd>{{ user.email }}</dd></div>
|
||||||
|
<div><dt>手机</dt><dd>{{ user.mobile }}</dd></div>
|
||||||
|
<div><dt>任职状态</dt><dd>{{ user.employmentStatus }}</dd></div>
|
||||||
|
<div><dt>员工类型</dt><dd>{{ user.employeeType ?? '--' }}</dd></div>
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<footer v-if="selectedUsers.length" class="pagination-footer" aria-label="员工列表分页">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="selectedPage"
|
||||||
|
v-model:page-size="pageSize"
|
||||||
|
:page-sizes="pageSizes"
|
||||||
|
:total="selectedUsers.length"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
small
|
||||||
|
@current-change="handlePageChange"
|
||||||
|
@size-change="handlePageSizeChange"
|
||||||
|
/>
|
||||||
|
</footer>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||||
|
import FeishuDirectoryPanel from '@/components/FeishuDirectoryPanel.vue'
|
||||||
|
import { feishuDirectoryApi, type DirectoryDepartment, type DirectoryOrganization, type DirectoryOrganizationUser } from '@/api/feishuDirectory'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
|
||||||
|
type DepartmentNode = DirectoryDepartment & { children: DepartmentNode[] }
|
||||||
|
type VisibleDepartment = { node: DepartmentNode; depth: number }
|
||||||
|
type SafeOrganizationUser = Pick<DirectoryOrganizationUser, 'userId' | 'openId' | 'name' | 'email' | 'mobile' | 'jobTitle' | 'employeeType' | 'avatarUrl' | 'employmentStatus' | 'departmentIds'> & { internalKey: string }
|
||||||
|
type SafeOrganization = Omit<DirectoryOrganization, 'users'> & { users: SafeOrganizationUser[] }
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const canRead = computed(() => (
|
||||||
|
userStore.permissionsLoaded
|
||||||
|
&& !userStore.permissionsError
|
||||||
|
&& (userStore.hasPermission('system:feishu:sync') || userStore.hasPermission('system:feishu:bind'))
|
||||||
|
))
|
||||||
|
const organization = ref<SafeOrganization | null>(null)
|
||||||
|
const organizationLoading = ref(false)
|
||||||
|
const organizationError = ref('')
|
||||||
|
const selectedDepartmentId = ref<string | null>(null)
|
||||||
|
const selectedPage = ref(1)
|
||||||
|
const pageSizes = [10, 20, 50, 100]
|
||||||
|
const pageSize = ref(10)
|
||||||
|
const expandedDepartmentIds = ref<Set<string>>(new Set())
|
||||||
|
const snapshotLabels = { UNAVAILABLE: '不可用', NEVER_SYNCED: '尚未同步', FRESH: '有效', STALE: '已过期', CONTEXT_CHANGED: '应用上下文已变化' }
|
||||||
|
const disposed = ref(false)
|
||||||
|
let organizationController: AbortController | null = null
|
||||||
|
let organizationRequest = 0
|
||||||
|
|
||||||
|
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 text = (value: unknown, fallback = '') => {
|
||||||
|
const result = String(value ?? '').trim()
|
||||||
|
return result && result !== 'undefined' && result !== 'null' ? result : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
const safeAvatarUrl = (value: unknown) => {
|
||||||
|
const result = text(value)
|
||||||
|
return /^(https?:\/\/|\/)/i.test(result) ? result : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const safeNumber = (value: unknown, fallback = 0) => {
|
||||||
|
const number = Number(value)
|
||||||
|
return Number.isFinite(number) ? number : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
// Department order is an integer, but it is serialized as a decimal string by
|
||||||
|
// the backend. Never pass it through Number: distinct values above 2^53 must
|
||||||
|
// remain distinct. Numeric values are accepted here for older payloads.
|
||||||
|
const normalizeDepartmentOrder = (value: unknown, fallback: number | string) => {
|
||||||
|
const candidate = typeof value === 'number'
|
||||||
|
? Number.isFinite(value) && Number.isInteger(value) ? BigInt(value).toString() : ''
|
||||||
|
: typeof value === 'bigint'
|
||||||
|
? String(value)
|
||||||
|
: typeof value === 'string' ? value.trim() : ''
|
||||||
|
if (!/^[+-]?\d+$/.test(candidate)) return String(fallback)
|
||||||
|
const negative = candidate.startsWith('-')
|
||||||
|
const digits = candidate.replace(/^[+-]/, '').replace(/^0+(?=\d)/, '')
|
||||||
|
return digits === '0' ? '0' : `${negative ? '-' : ''}${digits}`
|
||||||
|
}
|
||||||
|
|
||||||
|
const compareDepartmentOrder = (left: string, right: string) => {
|
||||||
|
// normalizeDepartmentOrder guarantees these are decimal integers, so
|
||||||
|
// BigInt compares arbitrarily large values without rounding.
|
||||||
|
const leftValue = BigInt(left)
|
||||||
|
const rightValue = BigInt(right)
|
||||||
|
return leftValue < rightValue ? -1 : leftValue > rightValue ? 1 : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
const safeEmployeeType = (value: unknown): number | null => (
|
||||||
|
typeof value === 'number' && Number.isInteger(value) ? value : null
|
||||||
|
)
|
||||||
|
|
||||||
|
const normalizeOrganization = (value: unknown): SafeOrganization => {
|
||||||
|
const source = value && typeof value === 'object' ? value as Partial<DirectoryOrganization> : {}
|
||||||
|
const departmentIds = new Set<string>()
|
||||||
|
const departments: DirectoryDepartment[] = []
|
||||||
|
if (Array.isArray(source.departments)) {
|
||||||
|
source.departments.forEach((department, index) => {
|
||||||
|
if (!department || typeof department !== 'object') return
|
||||||
|
const id = text(department.id)
|
||||||
|
if (!id || departmentIds.has(id)) return
|
||||||
|
departmentIds.add(id)
|
||||||
|
departments.push({
|
||||||
|
id,
|
||||||
|
name: text(department.name, '未命名部门'),
|
||||||
|
parentId: text(department.parentId),
|
||||||
|
order: normalizeDepartmentOrder(department.order, index),
|
||||||
|
memberCount: Math.max(0, safeNumber(department.memberCount)),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const users: SafeOrganizationUser[] = []
|
||||||
|
if (Array.isArray(source.users)) {
|
||||||
|
source.users.forEach(user => {
|
||||||
|
if (!user || typeof user !== 'object') return
|
||||||
|
const candidate = user as Partial<DirectoryOrganizationUser>
|
||||||
|
const departmentIdsForUser = Array.isArray(candidate.departmentIds)
|
||||||
|
? candidate.departmentIds.map(id => text(id)).filter(Boolean)
|
||||||
|
: []
|
||||||
|
const userId = text(candidate.userId)
|
||||||
|
const openId = text(candidate.openId)
|
||||||
|
const name = text(candidate.name, '未命名员工')
|
||||||
|
const email = text(candidate.email, '--')
|
||||||
|
const mobile = text(candidate.mobile, '--')
|
||||||
|
users.push({
|
||||||
|
internalKey: userId || openId || `${name}-${email}-${mobile}`,
|
||||||
|
userId: userId || '--',
|
||||||
|
openId: openId || '--',
|
||||||
|
name,
|
||||||
|
email,
|
||||||
|
mobile,
|
||||||
|
jobTitle: text(candidate.jobTitle, '--'),
|
||||||
|
employeeType: safeEmployeeType(candidate.employeeType),
|
||||||
|
avatarUrl: safeAvatarUrl(candidate.avatarUrl),
|
||||||
|
employmentStatus: text(candidate.employmentStatus, '--'),
|
||||||
|
departmentIds: departmentIdsForUser,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const snapshotState = ['UNAVAILABLE', 'NEVER_SYNCED', 'FRESH', 'STALE', 'CONTEXT_CHANGED'].includes(String(source.snapshotState))
|
||||||
|
? source.snapshotState as DirectoryOrganization['snapshotState']
|
||||||
|
: 'UNAVAILABLE'
|
||||||
|
return { snapshotState, lastSuccessfulAt: source.lastSuccessfulAt || null, departments, users }
|
||||||
|
}
|
||||||
|
|
||||||
|
const departments = computed(() => organization.value?.departments || [])
|
||||||
|
const users = computed(() => organization.value?.users || [])
|
||||||
|
const departmentNodes = computed(() => {
|
||||||
|
const nodes = new Map<string, DepartmentNode>()
|
||||||
|
departments.value.forEach(department => nodes.set(department.id, { ...department, children: [] }))
|
||||||
|
const roots: DepartmentNode[] = []
|
||||||
|
const parentIds = new Map(departments.value.map(department => [department.id, department.parentId]))
|
||||||
|
const createsCycle = (childId: string, parentId: string) => {
|
||||||
|
const seen = new Set<string>()
|
||||||
|
let current: string | undefined = parentId
|
||||||
|
while (current && !seen.has(current)) {
|
||||||
|
if (current === childId) return true
|
||||||
|
seen.add(current)
|
||||||
|
current = parentIds.get(current)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
nodes.forEach(node => {
|
||||||
|
const parent = node.parentId && nodes.get(node.parentId)
|
||||||
|
if (parent && parent.id !== node.id && !createsCycle(node.id, parent.id)) parent.children.push(node)
|
||||||
|
else roots.push(node)
|
||||||
|
})
|
||||||
|
const sortNodes = (items: DepartmentNode[]) => {
|
||||||
|
items.sort((left, right) => compareDepartmentOrder(left.order, right.order) || left.name.localeCompare(right.name, 'zh-CN') || left.id.localeCompare(right.id))
|
||||||
|
items.forEach(item => sortNodes(item.children))
|
||||||
|
}
|
||||||
|
sortNodes(roots)
|
||||||
|
return roots
|
||||||
|
})
|
||||||
|
const departmentIndex = computed(() => {
|
||||||
|
const index = new Map<string, DepartmentNode>()
|
||||||
|
const visit = (nodes: DepartmentNode[]) => nodes.forEach(node => { index.set(node.id, node); visit(node.children) })
|
||||||
|
visit(departmentNodes.value)
|
||||||
|
return index
|
||||||
|
})
|
||||||
|
const descendantDepartmentIds = computed(() => {
|
||||||
|
const result = new Map<string, Set<string>>()
|
||||||
|
const collect = (node: DepartmentNode): Set<string> => {
|
||||||
|
const ids = new Set([node.id])
|
||||||
|
node.children.forEach(child => collect(child).forEach(id => ids.add(id)))
|
||||||
|
result.set(node.id, ids)
|
||||||
|
return ids
|
||||||
|
}
|
||||||
|
departmentNodes.value.forEach(root => collect(root))
|
||||||
|
return result
|
||||||
|
})
|
||||||
|
const visibleDepartments = computed<VisibleDepartment[]>(() => {
|
||||||
|
const result: VisibleDepartment[] = []
|
||||||
|
const visit = (nodes: DepartmentNode[], depth: number) => nodes.forEach(node => {
|
||||||
|
result.push({ node, depth })
|
||||||
|
if (node.children.length && expandedDepartmentIds.value.has(node.id)) visit(node.children, depth + 1)
|
||||||
|
})
|
||||||
|
visit(departmentNodes.value, 0)
|
||||||
|
return result
|
||||||
|
})
|
||||||
|
const selectedDepartment = computed(() => selectedDepartmentId.value ? departmentIndex.value.get(selectedDepartmentId.value) || null : null)
|
||||||
|
const selectedDepartmentIds = computed(() => selectedDepartmentId.value ? descendantDepartmentIds.value.get(selectedDepartmentId.value) || new Set<string>() : new Set<string>())
|
||||||
|
const usersInDepartments = (departmentIds: ReadonlySet<string>) => {
|
||||||
|
const seen = new Set<string>()
|
||||||
|
return users.value
|
||||||
|
.filter(user => user.departmentIds.some(departmentId => departmentIds.has(departmentId)))
|
||||||
|
.filter(user => {
|
||||||
|
if (seen.has(user.internalKey)) return false
|
||||||
|
seen.add(user.internalKey)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
const departmentMemberCounts = computed(() => {
|
||||||
|
const counts = new Map<string, number>()
|
||||||
|
departments.value.forEach(department => {
|
||||||
|
const ids = descendantDepartmentIds.value.get(department.id) || new Set([department.id])
|
||||||
|
counts.set(department.id, usersInDepartments(ids).length)
|
||||||
|
})
|
||||||
|
return counts
|
||||||
|
})
|
||||||
|
const selectedUsers = computed<SafeOrganizationUser[]>(() => {
|
||||||
|
if (!selectedDepartmentId.value) return []
|
||||||
|
return usersInDepartments(selectedDepartmentIds.value)
|
||||||
|
})
|
||||||
|
const totalPages = computed(() => Math.max(1, Math.ceil(selectedUsers.value.length / pageSize.value)))
|
||||||
|
const paginatedSelectedUsers = computed(() => {
|
||||||
|
const page = Math.min(selectedPage.value, totalPages.value)
|
||||||
|
const start = (page - 1) * pageSize.value
|
||||||
|
return selectedUsers.value.slice(start, start + pageSize.value)
|
||||||
|
})
|
||||||
|
const hasSnapshot = computed(() => Boolean(organization.value && !['UNAVAILABLE', 'NEVER_SYNCED'].includes(organization.value.snapshotState) && departments.value.length))
|
||||||
|
|
||||||
|
const isExpanded = (id: string) => expandedDepartmentIds.value.has(id)
|
||||||
|
const clampPage = (page: number) => Math.min(Math.max(1, Number.isFinite(page) ? Math.trunc(page) : 1), totalPages.value)
|
||||||
|
const handlePageChange = (page: number) => {
|
||||||
|
selectedPage.value = clampPage(page)
|
||||||
|
}
|
||||||
|
const handlePageSizeChange = (size: number) => {
|
||||||
|
const nextSize = Number(size)
|
||||||
|
pageSize.value = pageSizes.includes(nextSize) ? nextSize : pageSizes[0]
|
||||||
|
selectedPage.value = 1
|
||||||
|
}
|
||||||
|
watch(pageSize, () => {
|
||||||
|
selectedPage.value = 1
|
||||||
|
}, { flush: 'sync' })
|
||||||
|
watch([selectedPage, () => selectedUsers.value.length], () => {
|
||||||
|
const page = clampPage(selectedPage.value)
|
||||||
|
if (selectedPage.value !== page) selectedPage.value = page
|
||||||
|
}, { flush: 'sync' })
|
||||||
|
const toggleDepartment = (id: string) => {
|
||||||
|
const next = new Set(expandedDepartmentIds.value)
|
||||||
|
if (next.has(id)) next.delete(id)
|
||||||
|
else next.add(id)
|
||||||
|
expandedDepartmentIds.value = next
|
||||||
|
}
|
||||||
|
const toggleDepartmentAndSelect = (id: string) => {
|
||||||
|
selectedDepartmentId.value = id
|
||||||
|
selectedPage.value = 1
|
||||||
|
toggleDepartment(id)
|
||||||
|
}
|
||||||
|
const selectDepartment = (id: string) => {
|
||||||
|
selectedDepartmentId.value = id
|
||||||
|
selectedPage.value = 1
|
||||||
|
const node = departmentIndex.value.get(id)
|
||||||
|
if (node?.children.length) {
|
||||||
|
const next = new Set(expandedDepartmentIds.value)
|
||||||
|
const expand = (current: DepartmentNode) => {
|
||||||
|
next.add(current.id)
|
||||||
|
current.children.forEach(child => expand(child))
|
||||||
|
}
|
||||||
|
expand(node)
|
||||||
|
expandedDepartmentIds.value = next
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const applyOrganization = (value: unknown) => {
|
||||||
|
const next = normalizeOrganization(value)
|
||||||
|
organization.value = next
|
||||||
|
selectedPage.value = 1
|
||||||
|
const roots = departmentNodes.value
|
||||||
|
const knownIds = new Set(departments.value.map(department => department.id))
|
||||||
|
const expanded = new Set([...expandedDepartmentIds.value].filter(id => knownIds.has(id)))
|
||||||
|
if (!expanded.size) roots.forEach(root => expanded.add(root.id))
|
||||||
|
expandedDepartmentIds.value = expanded
|
||||||
|
if (!selectedDepartmentId.value || !knownIds.has(selectedDepartmentId.value)) selectedDepartmentId.value = roots[0]?.id || null
|
||||||
|
}
|
||||||
|
|
||||||
|
const refreshOrganization = async () => {
|
||||||
|
if (!canRead.value || disposed.value) return
|
||||||
|
selectedPage.value = 1
|
||||||
|
const requestId = ++organizationRequest
|
||||||
|
organizationController?.abort()
|
||||||
|
const controller = new AbortController()
|
||||||
|
organizationController = controller
|
||||||
|
organizationLoading.value = true
|
||||||
|
organizationError.value = ''
|
||||||
|
try {
|
||||||
|
const next = await feishuDirectoryApi.organization(controller.signal)
|
||||||
|
if (disposed.value || requestId !== organizationRequest) return
|
||||||
|
applyOrganization(next)
|
||||||
|
} catch (error) {
|
||||||
|
if (disposed.value || requestId !== organizationRequest || controller.signal.aborted) return
|
||||||
|
organizationError.value = error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
|
||||||
|
} finally {
|
||||||
|
if (requestId === organizationRequest) organizationLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => { void refreshOrganization() })
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
disposed.value = true
|
||||||
|
organizationRequest += 1
|
||||||
|
organizationController?.abort()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.directory-page { min-height: 100%; min-width: 0; }
|
||||||
|
.directory-page > .directory-panel { margin-top: 0; }
|
||||||
|
.organization-card { display: flex; flex: 1 1 auto; min-width: 0; min-height: 0; margin-top: 16px; flex-direction: column; }
|
||||||
|
.organization-head { flex-wrap: wrap; gap: 12px; }
|
||||||
|
.organization-head > div:first-child { min-width: 0; flex: 1 1 320px; }
|
||||||
|
.organization-head p, .organization-summary, .member-copy { overflow-wrap: anywhere; }
|
||||||
|
.organization-actions { display: flex; align-items: center; flex-wrap: wrap; justify-content: flex-end; gap: 8px; }
|
||||||
|
.organization-state { min-height: 160px; padding: 28px 18px; flex: 1 1 auto; }
|
||||||
|
.organization-state .btn { margin-top: 12px; }
|
||||||
|
.organization-layout { display: grid; flex: 1 1 0; height: auto; min-height: 0; min-width: 0; align-items: stretch; grid-template-columns: minmax(220px, .8fr) minmax(300px, 1.2fr); gap: 16px; padding: 0 18px 18px; }
|
||||||
|
.organization-tree-wrap, .department-members { display: flex; min-width: 0; min-height: 0; height: 100%; flex-direction: column; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-raised); overflow: hidden; }
|
||||||
|
.organization-summary { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 5px 14px; padding: 12px 14px; border-bottom: 1px solid var(--line); color: var(--muted); font-size: 11px; }
|
||||||
|
.inline-note { margin: 10px 14px; color: var(--warning); font-size: 11px; }
|
||||||
|
.organization-tree { min-height: 0; flex: 1 1 auto; padding: 8px 0; overflow-y: auto; list-style: none; }
|
||||||
|
.department-row { display: flex; min-width: 0; align-items: center; gap: 3px; padding: 2px 8px 2px calc(8px + var(--department-depth) * 19px); }
|
||||||
|
.tree-toggle, .tree-toggle-spacer { display: grid; width: 24px; height: 30px; flex: none; place-items: center; }
|
||||||
|
.tree-toggle { border: 0; border-radius: 4px; background: transparent; color: var(--muted); }
|
||||||
|
.tree-toggle:hover { background: var(--blue-soft); color: var(--blue); }
|
||||||
|
.department-button { display: flex; min-width: 0; flex: 1; align-items: center; justify-content: space-between; gap: 8px; min-height: 30px; padding: 4px 8px; border: 1px solid transparent; border-radius: 5px; background: transparent; color: var(--body); text-align: left; }
|
||||||
|
.department-button:hover, .department-button.selected { background: var(--blue-soft); color: var(--blue-dark); }
|
||||||
|
.department-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.department-count { flex: none; color: var(--quiet); font-size: 10px; }
|
||||||
|
.department-members { background: #fff; }
|
||||||
|
.department-members .section-title { flex: none; padding: 13px 14px; border-bottom: 1px solid var(--line); }
|
||||||
|
.department-members .section-title h3 { min-width: 0; overflow-wrap: anywhere; }
|
||||||
|
.children-label { color: var(--muted); font-size: 11px; font-weight: 400; white-space: nowrap; }
|
||||||
|
.department-members .empty-state { min-height: 0; }
|
||||||
|
.department-members > .compact-empty { flex: 1 1 auto; }
|
||||||
|
.member-list { min-height: 0; flex: 1 1 auto; padding: 0 14px; overflow-y: auto; }
|
||||||
|
.member-row { display: grid; grid-template-columns: 42px minmax(0, 1fr); align-items: start; gap: 11px; padding: 12px 0; border-bottom: 1px solid var(--line); }
|
||||||
|
.member-row:last-child { border-bottom: 0; }
|
||||||
|
.member-avatar-wrap, .member-avatar { display: grid; width: 42px; height: 42px; flex: none; place-items: center; border-radius: 50%; }
|
||||||
|
.member-avatar-wrap { overflow: hidden; background: var(--blue-soft); }
|
||||||
|
.member-avatar { object-fit: cover; background: var(--blue-soft); color: var(--blue); font-size: 15px; font-weight: 700; }
|
||||||
|
.member-avatar-placeholder { border: 1px solid var(--line); }
|
||||||
|
.member-copy { min-width: 0; }
|
||||||
|
.member-copy strong, .member-copy span { display: block; }
|
||||||
|
.member-copy strong { color: var(--body); font-size: 12px; }
|
||||||
|
.member-copy span { margin-top: 2px; color: var(--muted); font-size: 11px; }
|
||||||
|
.member-details { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 7px 12px; margin-top: 9px; }
|
||||||
|
.member-details dt { color: var(--quiet); font-size: 10px; }
|
||||||
|
.member-details dd { margin: 1px 0 0; overflow-wrap: anywhere; color: var(--body); font-size: 11px; }
|
||||||
|
.pagination-footer { display: flex; min-width: 0; flex: none; align-items: center; justify-content: flex-end; gap: 8px; padding: 9px 14px; border-top: 1px solid var(--line); color: var(--muted); font-size: 11px; overflow: hidden; }
|
||||||
|
.pagination-footer :deep(.el-pagination) { width: 100%; max-width: 100%; min-width: 0; height: auto; flex-wrap: wrap; justify-content: flex-end; row-gap: 6px; white-space: normal; }
|
||||||
|
.pagination-footer :deep(.el-pagination .el-pager) { max-width: 100%; flex-wrap: wrap; }
|
||||||
|
.pagination-footer :deep(.el-pagination__jump) { margin-left: 0; }
|
||||||
|
@media (max-width: 760px) {
|
||||||
|
.organization-layout { grid-template-columns: minmax(0, 1fr); grid-template-rows: repeat(2, minmax(260px, 1fr)); flex: 1 1 auto; }
|
||||||
|
.organization-tree-wrap, .department-members { height: auto; min-height: 260px; }
|
||||||
|
.organization-actions { justify-content: flex-start; width: 100%; }
|
||||||
|
.pagination-footer :deep(.el-pagination) { justify-content: flex-start; }
|
||||||
|
}
|
||||||
|
@media (max-width: 450px) {
|
||||||
|
.organization-layout { padding-right: 12px; padding-left: 12px; }
|
||||||
|
.organization-actions .btn { width: 100%; }
|
||||||
|
.member-row { grid-template-columns: 36px minmax(0, 1fr); gap: 8px; }
|
||||||
|
.member-avatar-wrap, .member-avatar { width: 36px; height: 36px; }
|
||||||
|
}
|
||||||
|
@media (max-width: 760px) and (max-height: 600px) {
|
||||||
|
.organization-layout { grid-template-rows: repeat(2, minmax(220px, auto)); }
|
||||||
|
.organization-tree-wrap, .department-members { min-height: 220px; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page-content">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">FINANCE RECEIPT</span>
|
||||||
|
<h1>财务待收单</h1>
|
||||||
|
<p>审批通过的报销进入收单队列,财务处理结果独立记录。</p>
|
||||||
|
</div>
|
||||||
|
<div class="head-actions">
|
||||||
|
<button class="btn" type="button" :disabled="loadingState" @click="refreshQueue">刷新</button>
|
||||||
|
<router-link class="btn primary" to="/payments">查看待付款</router-link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="loadingState" class="load-wrap" role="status" aria-live="polite">
|
||||||
|
<span class="loader" aria-hidden="true"></span>
|
||||||
|
<p>正在读取收单队列…</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="hasBlockingError" class="card empty-state" role="alert">
|
||||||
|
<strong>收单队列暂时无法加载</strong>
|
||||||
|
<span>请检查网络连接后重试,系统不会以空列表代替异常数据。</span>
|
||||||
|
<button class="btn" type="button" @click="refreshQueue">重新加载</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<div v-if="hasDataNotice" class="inline-alert" role="status" aria-live="polite">
|
||||||
|
<b aria-hidden="true">i</b>
|
||||||
|
<span>数据服务暂时不可用,当前队列可能不完整。</span>
|
||||||
|
<button class="btn small" type="button" @click="refreshQueue">重试</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="finance-kpis">
|
||||||
|
<div><span>待收单</span><strong>{{ pending.length }}</strong><small>审批已完成</small></div>
|
||||||
|
<div><span>已收单</span><strong>{{ received.length }}</strong><small>等待付款执行</small></div>
|
||||||
|
<div><span>收单金额</span><strong>{{ money(total) }}</strong><small>不等同于已付款</small></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card fill-list-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>收单队列</h2><p>确认收单后,报销单进入付款处理环节。</p></div>
|
||||||
|
<span class="tag info">财务处理</span>
|
||||||
|
</div>
|
||||||
|
<div class="filter-bar">
|
||||||
|
<label class="filter-search">
|
||||||
|
<span aria-hidden="true">⌕</span>
|
||||||
|
<input v-model="query" type="search" aria-label="搜索待收单" placeholder="搜索报销单号、报销人或事项">
|
||||||
|
</label>
|
||||||
|
<span class="filter-spacer"></span>
|
||||||
|
<span class="tag info" aria-live="polite">{{ filtered.length }} 笔结果</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="filtered.length" class="table-wrap">
|
||||||
|
<table class="data-table responsive-table" aria-label="财务收单队列">
|
||||||
|
<caption class="sr-only">财务收单队列</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">报销单号</th><th scope="col">报销人 / 事项</th><th scope="col" class="amount">申请金额</th>
|
||||||
|
<th scope="col">审批状态</th><th scope="col">收单状态</th><th scope="col">付款状态</th><th scope="col">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in filtered" :key="item.id">
|
||||||
|
<td data-label="报销单号"><router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link><small>{{ item.createdAt?.slice(0, 10) || '-' }}</small></td>
|
||||||
|
<td data-label="报销人 / 事项"><strong>{{ item.applicantName }}</strong><small>{{ item.title }}</small></td>
|
||||||
|
<td data-label="申请金额" class="amount">{{ money(item.totalAmount) }}</td>
|
||||||
|
<td data-label="审批状态"><span class="tag success">{{ item.approvalStatus }}</span></td>
|
||||||
|
<td data-label="收单状态"><span class="tag" :class="tone(item.receiptStatus)">{{ item.receiptStatus }}</span></td>
|
||||||
|
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
|
||||||
|
<td data-label="操作">
|
||||||
|
<button
|
||||||
|
v-if="item.receiptStatus === '待收单'"
|
||||||
|
class="btn small primary"
|
||||||
|
type="button"
|
||||||
|
:disabled="isReceiving(item.id)"
|
||||||
|
:aria-busy="isReceiving(item.id)"
|
||||||
|
@click="receive(item)"
|
||||||
|
>{{ isReceiving(item.id) ? '处理中…' : '确认收单' }}</button>
|
||||||
|
<span v-else class="muted-copy">已完成</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="!rows.length" class="empty-state">
|
||||||
|
<strong>当前没有待收单记录</strong>
|
||||||
|
<span>审批通过的报销会自动进入这里。</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="empty-state">
|
||||||
|
<strong>没有符合条件的收单记录</strong>
|
||||||
|
<span>请调整搜索关键词后重试。</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, ref } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
|
||||||
|
const store = useWorkbenchStore()
|
||||||
|
const query = ref('')
|
||||||
|
const hasLoaded = ref(false)
|
||||||
|
const receiving = ref<Set<string>>(new Set())
|
||||||
|
const rows = computed(() => store.reimbursements.filter(item => item.approvalStatus === '审批通过'))
|
||||||
|
const pending = computed(() => rows.value.filter(item => item.receiptStatus === '待收单'))
|
||||||
|
const received = computed(() => rows.value.filter(item => item.receiptStatus === '已收单'))
|
||||||
|
const total = computed(() => rows.value.reduce((sum, item) => sum + item.totalAmount, 0))
|
||||||
|
const filtered = computed(() => {
|
||||||
|
const normalizedQuery = query.value.trim().toLowerCase()
|
||||||
|
return rows.value.filter(item => `${item.applicationNo} ${item.applicantName} ${item.title}`.toLowerCase().includes(normalizedQuery))
|
||||||
|
})
|
||||||
|
const loadingState = computed(() => store.loading || !hasLoaded.value)
|
||||||
|
const hasBlockingError = computed(() => hasLoaded.value && (store.source === 'error' || Boolean(store.financeQueueError)))
|
||||||
|
const hasDataNotice = computed(() => hasLoaded.value && Boolean(store.error) && !hasBlockingError.value)
|
||||||
|
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
|
||||||
|
const tone = (value: string) => ({ 待收单: 'pending', 已收单: 'success', 未付款: 'neutral', 部分付款: 'info', 已付款: 'success' } as Record<string, string>)[value] || 'neutral'
|
||||||
|
const receivingKey = (id: string | number) => String(id)
|
||||||
|
const isReceiving = (id: string | number) => receiving.value.has(receivingKey(id))
|
||||||
|
|
||||||
|
const refreshQueue = async () => {
|
||||||
|
hasLoaded.value = false
|
||||||
|
store.error = ''
|
||||||
|
store.financeQueueError = ''
|
||||||
|
await store.loadFinanceQueue('receipt')
|
||||||
|
hasLoaded.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const receive = async (item: ReimApplicationDetail) => {
|
||||||
|
const key = receivingKey(item.id)
|
||||||
|
if (receiving.value.has(key)) return
|
||||||
|
receiving.value = new Set(receiving.value).add(key)
|
||||||
|
try {
|
||||||
|
await store.receive(item.id)
|
||||||
|
ElMessage.success(`${item.applicationNo} 已完成财务收单`)
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error(error instanceof Error ? error.message : '收单失败,请重试')
|
||||||
|
} finally {
|
||||||
|
const next = new Set(receiving.value)
|
||||||
|
next.delete(key)
|
||||||
|
receiving.value = next
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => { void refreshQueue() })
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
<template>
|
||||||
|
<div class="integration-page">
|
||||||
|
<div class="page-head">
|
||||||
|
<div><span class="eyebrow">INTEGRATIONS</span><h1>配置管理</h1><p>管理飞书和金蝶连接。敏感配置只会在输入非空时更新。</p></div>
|
||||||
|
</div>
|
||||||
|
<div v-if="loadError" class="inline-alert danger" role="alert"><b>!</b><span>{{ loadError }}</span><button class="btn small" type="button" @click="loadConfig">重试</button></div>
|
||||||
|
<div v-if="loading" class="card load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载集成配置…</span></div>
|
||||||
|
<div v-else-if="!canView" class="card empty-state" role="alert"><strong>无权查看配置</strong><span>权限服务不可用或当前账号没有集成查看权限。</span></div>
|
||||||
|
<div v-else class="integration-grid">
|
||||||
|
<section v-for="provider in providers" :key="provider.key" class="card integration-card" :aria-labelledby="`${provider.key}-title`">
|
||||||
|
<div class="card-head"><div><span class="eyebrow">{{ provider.code }}</span><h2 :id="`${provider.key}-title`">{{ provider.label }}</h2><p>配置项由服务端动态提供。</p></div><span class="tag" :class="forms[provider.key].enabled ? 'success' : 'neutral'">{{ forms[provider.key].enabled ? '已启用' : '未启用' }}</span></div>
|
||||||
|
<div class="integration-body">
|
||||||
|
<div class="enabled-row"><div><strong>启用集成</strong><small>关闭后不会主动调用该服务。</small></div><label class="toggle"><input v-model="forms[provider.key].enabled" type="checkbox" :disabled="!canManage" :aria-label="`启用${provider.label}`"><span class="toggle-slider"></span></label></div>
|
||||||
|
<div v-if="!forms[provider.key].fields.length" class="empty-state compact-empty"><strong>暂无配置字段</strong><span>服务端尚未提供配置项。</span></div>
|
||||||
|
<div v-else class="form-grid integration-form"><div v-for="field in forms[provider.key].fields" :key="field.key" class="field"><label :for="`${provider.key}-${field.key}`">{{ field.label }} <small v-if="field.configured" class="configured-label">已配置</small></label><input v-if="field.secret" :id="`${provider.key}-${field.key}`" v-model="forms[provider.key].values[field.key]" type="password" autocomplete="new-password" :disabled="!canManage" placeholder="留空以保留原值" :aria-describedby="`${provider.key}-${field.key}-help`"><input v-else :id="`${provider.key}-${field.key}`" v-model="forms[provider.key].values[field.key]" type="text" :disabled="!canManage"><small :id="`${provider.key}-${field.key}-help`" class="form-help">{{ field.secret ? (field.configured ? '已配置,留空不会覆盖原密钥。' : '敏感值不会明文展示。') : (field.configured ? `当前值:${displayValue(field.value)}` : '尚未配置') }}</small></div></div>
|
||||||
|
</div>
|
||||||
|
<div class="modal-actions integration-actions"><span v-if="testResults[provider.key]" class="test-result" :class="testResults[provider.key]?.success ? 'success-copy' : 'danger-copy'" role="status">{{ testResults[provider.key]?.message }}</span><button class="btn" type="button" :disabled="!canTest || testing === provider.key" @click="testConnection(provider.key)">{{ testing === provider.key ? '测试中…' : '测试连接' }}</button><button class="btn primary" type="button" :disabled="!canManage || saving === provider.key" @click="saveProvider(provider.key)">{{ saving === provider.key ? '保存中…' : '保存配置' }}</button></div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, reactive, ref } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { adminApi, type IntegrationConfig, type IntegrationField } from '@/api/admin'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
|
||||||
|
type ProviderKey = 'feishu' | 'kingdee'
|
||||||
|
type ProviderCode = 'FEISHU' | 'KINGDEE'
|
||||||
|
type ProviderForm = { enabled: boolean; fields: IntegrationField[]; values: Record<string, string> }
|
||||||
|
type TestResult = { success: boolean; message: string }
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const providers: { key: ProviderKey; code: ProviderCode; label: string }[] = [{ key: 'feishu', code: 'FEISHU', label: '飞书集成' }, { key: 'kingdee', code: 'KINGDEE', label: '金蝶集成' }]
|
||||||
|
const forms = reactive<Record<ProviderKey, ProviderForm>>({ feishu: { enabled: false, fields: [], values: {} }, kingdee: { enabled: false, fields: [], values: {} } })
|
||||||
|
const loading = ref(false); const loadError = ref(''); const saving = ref<ProviderKey | ''>(''); const testing = ref<ProviderKey | ''>(''); const testResults = ref<Partial<Record<ProviderKey, TestResult>>>({})
|
||||||
|
const legacyAdmin = computed(() => ['ADMIN', 'SUPER_ADMIN'].includes(userStore.userInfo?.userType || ''))
|
||||||
|
const useLegacyFallback = computed(() => userStore.token === 'demo-local-session' || Boolean(userStore.permissionsError))
|
||||||
|
const canView = computed(() => userStore.permissionsLoaded && !userStore.permissionsError ? userStore.hasPermission('system:integration:view') : useLegacyFallback.value && legacyAdmin.value)
|
||||||
|
const canManage = computed(() => canView.value && (userStore.hasPermission('system:integration:manage') || (useLegacyFallback.value && legacyAdmin.value)))
|
||||||
|
const canTest = computed(() => canView.value && (userStore.hasPermission('system:integration:test') || (useLegacyFallback.value && legacyAdmin.value)))
|
||||||
|
const errorText = (error: unknown) => error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
|
||||||
|
const displayValue = (value: unknown) => { const text = String(value ?? '').trim(); return text || '未配置' }
|
||||||
|
const loadConfig = async () => { loading.value = true; loadError.value = ''; try { await userStore.loadPermissions(); if (!canView.value) return; const config = await adminApi.getIntegrationConfig(); applyConfig(config) } catch (error) { loadError.value = errorText(error); ElMessage.error(`配置加载失败:${loadError.value}`) } finally { loading.value = false } }
|
||||||
|
const applyConfig = (config: IntegrationConfig) => { providers.forEach(provider => { const source = config?.[provider.key]; forms[provider.key].enabled = Boolean(source?.enabled); forms[provider.key].fields = Array.isArray(source?.fields) ? source.fields : []; forms[provider.key].values = {}; forms[provider.key].fields.forEach(field => { // Never copy a secret returned by the API into a displayable form value.
|
||||||
|
if (!field.secret) forms[provider.key].values[field.key] = String(field.value ?? '')
|
||||||
|
}) }) }
|
||||||
|
const buildValues = (key: ProviderKey) => { const values: Record<string, unknown> = {}; forms[key].fields.forEach(field => { const value = forms[key].values[field.key] || ''; if (!field.secret || value.trim()) values[field.key] = value }) ; return values }
|
||||||
|
const saveProvider = async (key: ProviderKey) => { saving.value = key; try { await adminApi.updateIntegrationConfig(key === 'feishu' ? 'FEISHU' : 'KINGDEE', forms[key].enabled, buildValues(key)); forms[key].fields.forEach(field => { if (field.secret && forms[key].values[field.key]) { field.configured = true; forms[key].values[field.key] = '' } }); ElMessage.success(`${key === 'feishu' ? '飞书' : '金蝶'}配置已保存`) } catch (error) { ElMessage.error(`配置保存失败:${errorText(error)}`) } finally { saving.value = '' } }
|
||||||
|
const testConnection = async (key: ProviderKey) => { testing.value = key; testResults.value[key] = undefined; try { const result = await adminApi.testIntegration(key === 'feishu' ? 'FEISHU' : 'KINGDEE'); testResults.value[key] = { success: Boolean(result?.success), message: result?.message || (result?.success ? '连接成功' : '连接失败') }; if (result?.success) ElMessage.success(testResults.value[key]?.message || '连接成功'); else ElMessage.error(testResults.value[key]?.message || '连接失败') } catch (error) { const message = errorText(error); testResults.value[key] = { success: false, message }; ElMessage.error(`连接测试失败:${message}`) } finally { testing.value = '' } }
|
||||||
|
onMounted(() => { void loadConfig() })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.integration-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 350px), 1fr)); gap: 16px; align-items: stretch; }
|
||||||
|
.integration-card { display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.integration-body { display: flex; flex: 1; flex-direction: column; min-width: 0; padding: 0 18px; }
|
||||||
|
.integration-body > .empty-state { flex: 1; }
|
||||||
|
.enabled-row { display: flex; align-items: center; justify-content: space-between; gap: 15px; padding: 16px 0 12px; border-bottom: 1px solid var(--line); }
|
||||||
|
.enabled-row strong, .enabled-row small { display: block; }
|
||||||
|
.enabled-row strong { font-size: 12px; }
|
||||||
|
.enabled-row small { color: var(--muted); font-size: 11px; }
|
||||||
|
.integration-form { padding: 17px 0 20px; grid-template-columns: minmax(0, 1fr); gap: 13px; }
|
||||||
|
.configured-label { margin-left: 5px; color: var(--success); font-weight: 400; }
|
||||||
|
.integration-actions { align-items: center; min-height: 59px; flex-wrap: wrap; margin-top: auto; }
|
||||||
|
.test-result { min-width: 0; max-width: 100%; margin-right: auto; font-size: 11px; }
|
||||||
|
.success-copy { color: var(--success); }
|
||||||
|
.danger-copy { color: var(--danger); }
|
||||||
|
@media (max-width: 760px) { .integration-grid { grid-template-columns: 1fr; } .integration-actions { justify-content: flex-end; } .test-result { width: 100%; margin-right: 0; } }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,625 @@
|
|||||||
|
<template>
|
||||||
|
<div class="app-shell">
|
||||||
|
<a class="skip-link" href="#main-content">跳转到主内容</a>
|
||||||
|
<div class="mobile-mask" :class="{ open: sidebarOpen }" @click="sidebarOpen = false" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<aside id="primary-navigation" class="sidebar" :class="{ open: sidebarOpen }">
|
||||||
|
<div class="brand">
|
||||||
|
<span class="brand-mark" aria-hidden="true"><i></i><i></i></span>
|
||||||
|
<span>
|
||||||
|
<strong>零差云控</strong>
|
||||||
|
<small>ZEROERR</small>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="product-name">
|
||||||
|
员工报销工作台
|
||||||
|
<span>财务与报销管理</span>
|
||||||
|
</div>
|
||||||
|
<nav class="main-nav" aria-label="主导航">
|
||||||
|
<div class="nav-group" v-if="canAccess('dashboard')">
|
||||||
|
<span>工作台</span>
|
||||||
|
<router-link to="/dashboard" @click="sidebarOpen = false" :class="{ active: route.path === '/dashboard' }" :aria-current="route.path === '/dashboard' ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><House /></b> 工作台
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="nav-group" v-if="canAccess('applications')">
|
||||||
|
<span>报销管理</span>
|
||||||
|
<router-link to="/applications" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/applications') }" :aria-current="route.path.startsWith('/applications') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><DocumentCopy /></b> 我的报销 <i class="nav-count">{{ mineCount }}</i>
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="canAccess('application-create')" to="/applications/new" @click="sidebarOpen = false"><b aria-hidden="true"><Plus /></b> 发起报销</router-link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="nav-group" v-if="canAccess('finance')">
|
||||||
|
<span>财务处理</span>
|
||||||
|
<router-link v-if="canAccess('finance-receipt')" to="/finance-receipt" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/finance-receipt') }" :aria-current="route.path.startsWith('/finance-receipt') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><Tickets /></b> 财务待收单 <i class="nav-count warning">{{ receiptCount }}</i>
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="canAccess('sources')" to="/sources" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/sources') }" :aria-current="route.path.startsWith('/sources') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><Files /></b> 业务单据
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="canAccess('payments')" to="/payments" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/payments') }" :aria-current="route.path.startsWith('/payments') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><Wallet /></b> 待付款 <i class="nav-count">{{ paymentCount }}</i>
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="canAccess('logs')" to="/logs" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/logs') }" :aria-current="route.path.startsWith('/logs') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><Memo /></b> 操作日志
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="nav-group admin-nav" v-if="canAccess('master-data')">
|
||||||
|
<span>基础设置</span>
|
||||||
|
<router-link v-if="canAccess('expense-types')" to="/expense-types" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/expense-types') }" :aria-current="route.path.startsWith('/expense-types') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><CollectionTag /></b> 费用类型
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="canAccess('payees')" to="/payees" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/payees') }" :aria-current="route.path.startsWith('/payees') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><User /></b> 付款对象
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="nav-group admin-nav" v-if="canAccess('admin') || canAccess('integration') || canAccess('feishu-directory')">
|
||||||
|
<span>系统管理</span>
|
||||||
|
<router-link v-if="canAccess('admin')" to="/users" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/users') }" :aria-current="route.path.startsWith('/users') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><Setting /></b> 用户管理
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="canAccess('integration')" to="/integration-config" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/integration-config') }" :aria-current="route.path.startsWith('/integration-config') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><Connection /></b> 配置管理
|
||||||
|
</router-link>
|
||||||
|
<router-link v-if="canAccess('feishu-directory')" to="/feishu-directory" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/feishu-directory') }" :aria-current="route.path.startsWith('/feishu-directory') ? 'page' : undefined">
|
||||||
|
<b aria-hidden="true"><Connection /></b> 飞书通讯录
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
<div class="sidebar-foot">
|
||||||
|
<span class="status-dot"></span>
|
||||||
|
<div>
|
||||||
|
<strong>{{ userName }}</strong>
|
||||||
|
<small>{{ userTypeLabel }}</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<div class="main-area">
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="topbar-left">
|
||||||
|
<button class="icon-button mobile-menu" type="button" :aria-expanded="sidebarOpen" aria-controls="primary-navigation" @click="sidebarOpen = !sidebarOpen" aria-label="打开导航"><Menu /></button>
|
||||||
|
<div class="breadcrumb">
|
||||||
|
<span>报销管理</span>
|
||||||
|
<i>/</i>
|
||||||
|
<strong>{{ pageTitle }}</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="topbar-tools">
|
||||||
|
<label class="search-box"><Search aria-hidden="true" /><input v-model="search" type="search" placeholder="搜索报销单号、事项或收款人" aria-label="全局搜索" @keyup.enter="runSearch"></label>
|
||||||
|
<button class="icon-button" type="button" @click="showHelp" aria-label="查看帮助" title="帮助"><QuestionFilled /></button>
|
||||||
|
<button ref="notificationButton" class="icon-button notification" @click="showNotifications" :aria-label="notificationButtonLabel" title="通知">
|
||||||
|
<Bell aria-hidden="true" />
|
||||||
|
<span v-if="unreadNotificationCount" class="notification-count" aria-hidden="true">{{ unreadNotificationCount > 99 ? '99+' : unreadNotificationCount }}</span>
|
||||||
|
</button>
|
||||||
|
<button class="role-switch" type="button" @click="handleLogout" aria-label="退出登录">
|
||||||
|
<span class="avatar" aria-hidden="true"><UserFilled /></span>
|
||||||
|
<span><strong>{{ userName }}</strong><small>{{ userTypeLabel }}</small></span><i><SwitchButton /> 退出登录</i>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="data-sync-banner" role="status"><span class="source-pill" :class="sourceTone">{{ sourceLabel }}</span><p>{{ sourceMessage }}</p><button v-if="workbench.error || workbench.source === 'error'" class="btn small" type="button" @click="workbench.load">重新同步</button></div>
|
||||||
|
<main id="main-content" class="page-stage" aria-live="polite">
|
||||||
|
<router-view />
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<dialog
|
||||||
|
ref="notificationDialog"
|
||||||
|
class="notification-dialog"
|
||||||
|
aria-labelledby="notification-dialog-title"
|
||||||
|
aria-modal="true"
|
||||||
|
@click="handleDialogClick"
|
||||||
|
@cancel="handleDialogCancel"
|
||||||
|
@close="handleNotificationsClosed"
|
||||||
|
>
|
||||||
|
<section ref="notificationPanel" class="notification-dialog-panel" :style="notificationPanelStyle" aria-describedby="notification-dialog-description">
|
||||||
|
<header class="notification-modal-head" title="拖动通知面板" @pointerdown="startNotificationDrag">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">通知中心</span>
|
||||||
|
<h2 id="notification-dialog-title">通知</h2>
|
||||||
|
<p id="notification-dialog-description">
|
||||||
|
{{ notificationItems.length ? `共 ${notificationItems.length} 条待关注事项` : '暂无待关注事项' }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
class="modal-close"
|
||||||
|
type="button"
|
||||||
|
aria-label="关闭通知"
|
||||||
|
data-notification-autofocus
|
||||||
|
@click="closeNotifications"
|
||||||
|
><Close /></button>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div v-if="notificationItems.length" class="notification-modal-body">
|
||||||
|
<ul class="notification-list" aria-label="通知列表">
|
||||||
|
<li v-for="item in notificationItems" :key="item.id">
|
||||||
|
<button
|
||||||
|
class="notification-item"
|
||||||
|
:class="{ actionable: item.route }"
|
||||||
|
type="button"
|
||||||
|
:aria-label="`${item.title}:${item.message}${item.route ? ',点击查看详情' : ''}`"
|
||||||
|
@click="openNotification(item)"
|
||||||
|
>
|
||||||
|
<span class="notification-item-icon" :class="item.tone" aria-hidden="true"><component :is="item.icon" /></span>
|
||||||
|
<span class="notification-item-copy">
|
||||||
|
<strong>{{ item.title }}</strong>
|
||||||
|
<span>{{ item.message }}</span>
|
||||||
|
<small>{{ item.time }}</small>
|
||||||
|
</span>
|
||||||
|
<span v-if="item.route" class="notification-item-link" aria-hidden="true">查看 <ArrowRight /></span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<div v-else class="notification-empty empty-state">
|
||||||
|
<span class="notification-empty-icon" aria-hidden="true"><CircleCheckFilled /></span>
|
||||||
|
<strong>暂无未读通知</strong>
|
||||||
|
<span>新的报销进度和付款状态会显示在这里。</span>
|
||||||
|
</div>
|
||||||
|
<footer class="notification-modal-actions">
|
||||||
|
<button class="btn small" type="button" @click="closeNotifications">关闭</button>
|
||||||
|
</footer>
|
||||||
|
</section>
|
||||||
|
</dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, nextTick, onBeforeUnmount, onMounted, watch } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
import { authApi } from '@/api/auth'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
|
||||||
|
type NotificationTone = 'danger' | 'pending' | 'info' | 'success'
|
||||||
|
type NotificationItem = {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
message: string
|
||||||
|
time: string
|
||||||
|
icon: string
|
||||||
|
tone: NotificationTone
|
||||||
|
route?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const workbench = useWorkbenchStore()
|
||||||
|
const sidebarOpen = ref(false)
|
||||||
|
const search = ref('')
|
||||||
|
const notificationButton = ref<HTMLButtonElement | null>(null)
|
||||||
|
const notificationDialog = ref<HTMLDialogElement | null>(null)
|
||||||
|
const notificationPanel = ref<HTMLElement | null>(null)
|
||||||
|
const notificationItems = ref<NotificationItem[]>([])
|
||||||
|
const notificationPosition = ref({ left: 0, top: 0 })
|
||||||
|
let notificationTrigger: HTMLElement | null = null
|
||||||
|
let notificationDragOffset = { x: 0, y: 0 }
|
||||||
|
|
||||||
|
const notificationPanelStyle = computed(() => ({
|
||||||
|
left: `${notificationPosition.value.left}px`,
|
||||||
|
top: `${notificationPosition.value.top}px`,
|
||||||
|
}))
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
// 刷新时从后端获取最新的用户信息(包括角色变更)
|
||||||
|
const roleBeforeRefresh = userStore.userInfo?.userType
|
||||||
|
let roleChanged = false
|
||||||
|
if (userStore.token && userStore.token !== 'demo-local-session') {
|
||||||
|
try {
|
||||||
|
// Refresh when supported, but keep cached role when the API is offline.
|
||||||
|
const refreshRes = await userStore.refreshToken()
|
||||||
|
roleChanged = Boolean(roleBeforeRefresh && roleBeforeRefresh !== refreshRes.user?.userType)
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
await userStore.fetchUserInfo()
|
||||||
|
roleChanged = Boolean(roleBeforeRefresh && roleBeforeRefresh !== userStore.userInfo?.userType)
|
||||||
|
} catch { /* use cached data */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (roleChanged) {
|
||||||
|
// A refreshed role must not retain a page or business snapshot that was
|
||||||
|
// loaded under the previous permission set.
|
||||||
|
workbench.reset()
|
||||||
|
if (route.path !== '/dashboard') await router.replace('/dashboard')
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await userStore.loadPermissions()
|
||||||
|
} catch {
|
||||||
|
// Management navigation is deliberately fail-closed. The request
|
||||||
|
// interceptor already reports the transport/API error to the user.
|
||||||
|
}
|
||||||
|
if (!workbench.reimbursements.length) void workbench.load()
|
||||||
|
})
|
||||||
|
|
||||||
|
const userType = computed(() => userStore.userInfo?.userType || '')
|
||||||
|
const userName = computed(() => userStore.userInfo?.realName || '用户')
|
||||||
|
const userInitial = computed(() => userName.value.charAt(0) || '用')
|
||||||
|
|
||||||
|
const userTypeLabel = computed(() => {
|
||||||
|
const labels: Record<string, string> = {
|
||||||
|
'SUPER_ADMIN': '超级管理员',
|
||||||
|
'ADMIN': '系统管理员',
|
||||||
|
'FINANCE': '财务人员',
|
||||||
|
'EMPLOYEE': '员工',
|
||||||
|
}
|
||||||
|
return labels[userType.value] || userType.value || '普通用户'
|
||||||
|
})
|
||||||
|
|
||||||
|
const pageTitle = computed(() => {
|
||||||
|
const meta = route.meta?.title as string
|
||||||
|
return meta || '工作台'
|
||||||
|
})
|
||||||
|
|
||||||
|
// Permission map: which modules each userType can access
|
||||||
|
const modulePermissions: Record<string, string[]> = {
|
||||||
|
ADMIN: ['dashboard', 'applications', 'finance', 'payments', 'sources', 'logs', 'master-data', 'admin'],
|
||||||
|
SUPER_ADMIN: ['dashboard', 'applications', 'finance', 'payments', 'sources', 'logs', 'master-data', 'admin'],
|
||||||
|
FINANCE: ['dashboard', 'applications', 'finance', 'payments', 'sources', 'logs', 'master-data'],
|
||||||
|
EMPLOYEE: ['dashboard', 'applications'],
|
||||||
|
}
|
||||||
|
|
||||||
|
const permissions = computed(() => modulePermissions[userType.value] || ['dashboard'])
|
||||||
|
const legacyAdmin = computed(() => ['ADMIN', 'SUPER_ADMIN'].includes(userType.value))
|
||||||
|
const permissionByModule: Record<string, string[]> = {
|
||||||
|
dashboard: ['applications', 'reimbursement:view-own'],
|
||||||
|
applications: ['applications', 'reimbursement:view-own'],
|
||||||
|
'application-create': ['reimbursement:create'],
|
||||||
|
finance: ['receipt:manage', 'reimbursement:view-all', 'payment:register', 'approval:view'],
|
||||||
|
'finance-receipt': ['receipt:manage'],
|
||||||
|
payments: ['payment:register'],
|
||||||
|
sources: ['reimbursement:view-all'],
|
||||||
|
logs: ['approval:view'],
|
||||||
|
'master-data': ['master-data:manage'],
|
||||||
|
'expense-types': ['master-data:manage'],
|
||||||
|
payees: ['master-data:manage'],
|
||||||
|
'feishu-directory': ['system:feishu:sync', 'system:feishu:bind'],
|
||||||
|
}
|
||||||
|
const legacyModuleByRoute: Record<string, string> = {
|
||||||
|
dashboard: 'dashboard', applications: 'applications', 'application-create': 'applications',
|
||||||
|
finance: 'finance', 'finance-receipt': 'finance', payments: 'finance', sources: 'finance', logs: 'finance',
|
||||||
|
'expense-types': 'master-data', payees: 'master-data',
|
||||||
|
}
|
||||||
|
const useLegacyNavigation = computed(() => userStore.token === 'demo-local-session' || Boolean(userStore.permissionsError))
|
||||||
|
const hasSystemPermission = (code: string) => {
|
||||||
|
if (userStore.permissionsLoaded && !userStore.permissionsError) return userStore.hasPermission(code)
|
||||||
|
return useLegacyNavigation.value && legacyAdmin.value
|
||||||
|
}
|
||||||
|
const canAccess = (routeName: string) => {
|
||||||
|
if (routeName === 'admin') return hasSystemPermission('system:user:view')
|
||||||
|
if (routeName === 'integration') return hasSystemPermission('system:integration:view')
|
||||||
|
// Unlike the older navigation groups, this entry is never exposed by a
|
||||||
|
// demo/role fallback: it is granted only by the two directory permissions.
|
||||||
|
if (routeName === 'feishu-directory') {
|
||||||
|
return userStore.permissionsLoaded
|
||||||
|
&& !userStore.permissionsError
|
||||||
|
&& (permissionByModule[routeName] || []).some(code => userStore.hasPermission(code))
|
||||||
|
}
|
||||||
|
const required = permissionByModule[routeName] || [routeName]
|
||||||
|
if (userStore.permissionsLoaded && !userStore.permissionsError) return required.some(code => userStore.hasPermission(code))
|
||||||
|
return useLegacyNavigation.value && permissions.value.includes(legacyModuleByRoute[routeName] || routeName)
|
||||||
|
}
|
||||||
|
const mineCount = computed(() => workbench.reimbursements.filter(item => item.applicantName === userName.value).length)
|
||||||
|
const receiptCount = computed(() => workbench.reimbursements.filter(item => item.receiptStatus === '待收单').length)
|
||||||
|
const paymentCount = computed(() => workbench.reimbursements.filter(item => workbench.balance(item) > 0 && item.receiptStatus === '已收单').length)
|
||||||
|
const sourceLabel = computed(() => {
|
||||||
|
if (workbench.error && workbench.source !== 'fallback') return '同步异常'
|
||||||
|
return {
|
||||||
|
api: '已同步',
|
||||||
|
fallback: '使用缓存',
|
||||||
|
error: '同步异常',
|
||||||
|
connecting: '同步中',
|
||||||
|
}[workbench.source]
|
||||||
|
})
|
||||||
|
const sourceTone = computed(() => workbench.error && workbench.source !== 'fallback' ? 'error' : workbench.source)
|
||||||
|
const sourceMessage = computed(() => {
|
||||||
|
if (workbench.source === 'fallback') return '数据服务暂不可用,当前展示缓存数据。'
|
||||||
|
if (workbench.source === 'error') return '暂时无法同步业务数据,当前未展示业务记录。'
|
||||||
|
if (workbench.error) return '数据同步需要关注,请稍后重试。'
|
||||||
|
if (workbench.source === 'api') return '业务数据已更新。'
|
||||||
|
return '正在同步业务数据…'
|
||||||
|
})
|
||||||
|
const unreadNotificationCount = computed(() => Math.max(0, Math.floor(Number(workbench.notifications) || 0)))
|
||||||
|
const notificationButtonLabel = computed(() => unreadNotificationCount.value ? `打开通知(${unreadNotificationCount.value}条未读)` : '打开通知(暂无未读)')
|
||||||
|
const runSearch = () => { if (search.value.trim()) router.push({ path: '/applications', query: { q: search.value.trim() } }) }
|
||||||
|
const showHelp = () => ElMessageBox.alert('申请、审批、收单和付款是四个独立状态;金蝶来源单据只读,付款登记支持分次付款并保留幂等键。', '工作台帮助', { confirmButtonText: '知道了' })
|
||||||
|
|
||||||
|
const displayText = (value: unknown, fallback: string) => {
|
||||||
|
const result = String(value ?? '').trim()
|
||||||
|
return result && result !== 'undefined' && result !== 'null' ? result : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
const applicationName = (item: ReimApplicationDetail) => displayText(item.applicationNo, `报销单 ${displayText(item.id, '待处理')}`)
|
||||||
|
const applicationRoute = (item: ReimApplicationDetail) => {
|
||||||
|
const id = displayText(item.id, '')
|
||||||
|
return id ? `/applications/${encodeURIComponent(id)}` : '/applications'
|
||||||
|
}
|
||||||
|
const money = (value: unknown) => {
|
||||||
|
const amount = Number(value)
|
||||||
|
return `¥ ${Number.isFinite(amount) ? amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 }) : '0.00'}`
|
||||||
|
}
|
||||||
|
const notificationTime = (item: ReimApplicationDetail) => displayText(item.updatedAt || item.createdAt, '刚刚')
|
||||||
|
const financeRoute = (item: ReimApplicationDetail) => canAccess('finance') ? '/finance-receipt' : applicationRoute(item)
|
||||||
|
|
||||||
|
const buildNotifications = (count: number) => {
|
||||||
|
const rows = workbench.reimbursements
|
||||||
|
const dynamic: NotificationItem[] = []
|
||||||
|
const add = (item: NotificationItem) => { if (!dynamic.some(existing => existing.id === item.id)) dynamic.push(item) }
|
||||||
|
|
||||||
|
rows.filter(item => item.approvalStatus === '退回').forEach(item => add({
|
||||||
|
id: `returned-${displayText(item.id, applicationName(item))}`,
|
||||||
|
title: '报销需要补充材料',
|
||||||
|
message: `${applicationName(item)} 已退回:${displayText(item.returnReason, '请查看退回原因并补充材料。')}`,
|
||||||
|
time: notificationTime(item), icon: 'WarningFilled', tone: 'danger', route: applicationRoute(item),
|
||||||
|
}))
|
||||||
|
rows.filter(item => ['审批中', '已提交'].includes(item.approvalStatus) && item.approvalStatus !== '退回').forEach(item => add({
|
||||||
|
id: `approval-${displayText(item.id, applicationName(item))}`,
|
||||||
|
title: '报销审批进行中',
|
||||||
|
message: `${applicationName(item)} 正在${displayText(item.currentApprovalNode, '审批流程')},请留意审批进度。`,
|
||||||
|
time: notificationTime(item), icon: 'Refresh', tone: 'pending', route: applicationRoute(item),
|
||||||
|
}))
|
||||||
|
rows.filter(item => item.receiptStatus === '待收单').forEach(item => add({
|
||||||
|
id: `receipt-${displayText(item.id, applicationName(item))}`,
|
||||||
|
title: '有报销单待收单',
|
||||||
|
message: `${applicationName(item)} 已审批通过,等待财务收单。`,
|
||||||
|
time: notificationTime(item), icon: 'Tickets', tone: 'info', route: financeRoute(item),
|
||||||
|
}))
|
||||||
|
rows.filter(item => item.receiptStatus === '已收单' && workbench.balance(item) > 0).forEach(item => add({
|
||||||
|
id: `payment-${displayText(item.id, applicationName(item))}`,
|
||||||
|
title: '报销单待付款',
|
||||||
|
message: `${applicationName(item)} 已完成收单,待付款金额 ${money(workbench.balance(item))}。`,
|
||||||
|
time: notificationTime(item), icon: 'Wallet', tone: 'success', route: canAccess('finance') ? '/payments' : applicationRoute(item),
|
||||||
|
}))
|
||||||
|
|
||||||
|
// Only render notifications that can be traced back to a real business row.
|
||||||
|
// The API currently exposes a count but not notification details, so never
|
||||||
|
// manufacture placeholder messages just to fill the notification panel.
|
||||||
|
return dynamic.slice(0, count > 0 ? count : dynamic.length).map((item, index) => ({
|
||||||
|
...item,
|
||||||
|
id: `${item.id}-${index}`,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const clampNotificationPosition = (left: number, top: number) => {
|
||||||
|
const panel = notificationPanel.value
|
||||||
|
const width = panel?.offsetWidth || 450
|
||||||
|
const height = panel?.offsetHeight || 360
|
||||||
|
return {
|
||||||
|
left: Math.min(Math.max(12, left), Math.max(12, window.innerWidth - width - 12)),
|
||||||
|
top: Math.min(Math.max(12, top), Math.max(12, window.innerHeight - height - 12)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const positionNotificationPanel = () => {
|
||||||
|
const button = notificationButton.value
|
||||||
|
if (!button) return
|
||||||
|
const buttonRect = button.getBoundingClientRect()
|
||||||
|
const panelWidth = notificationPanel.value?.offsetWidth || 450
|
||||||
|
const preferredLeft = buttonRect.right - panelWidth
|
||||||
|
const preferredTop = buttonRect.bottom + 10
|
||||||
|
const top = preferredTop + (notificationPanel.value?.offsetHeight || 360) > window.innerHeight
|
||||||
|
? buttonRect.top - (notificationPanel.value?.offsetHeight || 360) - 10
|
||||||
|
: preferredTop
|
||||||
|
notificationPosition.value = clampNotificationPosition(preferredLeft, top)
|
||||||
|
}
|
||||||
|
|
||||||
|
const moveNotificationPanel = (event: PointerEvent) => {
|
||||||
|
notificationPosition.value = clampNotificationPosition(
|
||||||
|
event.clientX - notificationDragOffset.x,
|
||||||
|
event.clientY - notificationDragOffset.y,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const stopNotificationDrag = () => {
|
||||||
|
window.removeEventListener('pointermove', moveNotificationPanel)
|
||||||
|
window.removeEventListener('pointerup', stopNotificationDrag)
|
||||||
|
}
|
||||||
|
|
||||||
|
const startNotificationDrag = (event: PointerEvent) => {
|
||||||
|
if (event.button !== 0 || (event.target as HTMLElement).closest('button')) return
|
||||||
|
const panel = notificationPanel.value
|
||||||
|
if (!panel) return
|
||||||
|
const rect = panel.getBoundingClientRect()
|
||||||
|
notificationDragOffset = { x: event.clientX - rect.left, y: event.clientY - rect.top }
|
||||||
|
window.addEventListener('pointermove', moveNotificationPanel)
|
||||||
|
window.addEventListener('pointerup', stopNotificationDrag)
|
||||||
|
}
|
||||||
|
|
||||||
|
const restoreNotificationFocus = () => {
|
||||||
|
if (notificationTrigger?.isConnected) notificationTrigger.focus()
|
||||||
|
notificationTrigger = null
|
||||||
|
}
|
||||||
|
const handleNotificationsClosed = () => {
|
||||||
|
notificationItems.value = []
|
||||||
|
restoreNotificationFocus()
|
||||||
|
}
|
||||||
|
const closeNotifications = () => {
|
||||||
|
if (notificationDialog.value?.open) notificationDialog.value.close()
|
||||||
|
else restoreNotificationFocus()
|
||||||
|
}
|
||||||
|
const handleDialogClick = (event: MouseEvent) => {
|
||||||
|
if (event.target === event.currentTarget) closeNotifications()
|
||||||
|
}
|
||||||
|
const handleDialogCancel = () => {
|
||||||
|
// Do not prevent the native cancel event: Escape closes the dialog and restores focus via close.
|
||||||
|
}
|
||||||
|
const showNotifications = async () => {
|
||||||
|
if (notificationDialog.value?.open) return
|
||||||
|
notificationTrigger = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||||
|
notificationItems.value = buildNotifications(unreadNotificationCount.value)
|
||||||
|
positionNotificationPanel()
|
||||||
|
notificationDialog.value?.showModal()
|
||||||
|
await nextTick()
|
||||||
|
positionNotificationPanel()
|
||||||
|
notificationDialog.value?.querySelector<HTMLElement>('[data-notification-autofocus]')?.focus()
|
||||||
|
}
|
||||||
|
const openNotification = (item: NotificationItem) => {
|
||||||
|
closeNotifications()
|
||||||
|
if (item.route) void router.push(item.route)
|
||||||
|
}
|
||||||
|
|
||||||
|
const repositionOpenNotificationPanel = () => {
|
||||||
|
if (notificationDialog.value?.open) positionNotificationPanel()
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('resize', repositionOpenNotificationPanel)
|
||||||
|
onBeforeUnmount(() => {
|
||||||
|
stopNotificationDrag()
|
||||||
|
window.removeEventListener('resize', repositionOpenNotificationPanel)
|
||||||
|
})
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
if (userStore.token && userStore.token !== 'demo-local-session') void authApi.logout().catch(() => undefined)
|
||||||
|
workbench.reset()
|
||||||
|
userStore.logout()
|
||||||
|
router.push('/login')
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权访问「${String(value)}」,已返回工作台`) }, { immediate: true })
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.mobile-menu { display: none; }
|
||||||
|
@media (max-width: 900px) { .mobile-menu { display: grid; } }
|
||||||
|
|
||||||
|
.notification-glyph { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-linecap: round; stroke-linejoin: round; stroke-width: 1.7; }
|
||||||
|
.notification-count { position: absolute; top: 1px; right: -3px; min-width: 16px; height: 16px; padding: 0 4px; border: 2px solid #fff; border-radius: 99px; background: var(--danger); color: #fff; font-size: 9px; font-weight: 800; line-height: 12px; text-align: center; }
|
||||||
|
|
||||||
|
.notification-dialog {
|
||||||
|
display: block;
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
width: 100%;
|
||||||
|
max-width: none;
|
||||||
|
height: 100%;
|
||||||
|
max-height: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text);
|
||||||
|
overflow: hidden;
|
||||||
|
pointer-events: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* The author styles above must not override the browser's closed-dialog rule. */
|
||||||
|
.notification-dialog:not([open]) { display: none; }
|
||||||
|
|
||||||
|
.notification-dialog::backdrop {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-dialog-panel {
|
||||||
|
position: fixed;
|
||||||
|
display: flex;
|
||||||
|
width: min(450px, calc(100vw - 24px));
|
||||||
|
max-height: min(680px, calc(100vh - 32px));
|
||||||
|
flex-direction: column;
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: 14px;
|
||||||
|
background: #fff;
|
||||||
|
box-shadow: 0 18px 48px #0926402b, 0 3px 10px #09264012;
|
||||||
|
overflow: hidden;
|
||||||
|
pointer-events: auto;
|
||||||
|
animation: notification-pop .16s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes notification-pop {
|
||||||
|
from { opacity: 0; transform: translateY(-5px) scale(.985); }
|
||||||
|
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-modal-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 14px;
|
||||||
|
padding: 18px 21px 15px;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
background: #f8fafc;
|
||||||
|
cursor: grab;
|
||||||
|
user-select: none;
|
||||||
|
touch-action: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-modal-head:active { cursor: grabbing; }
|
||||||
|
|
||||||
|
.notification-modal-head h2 { margin-top: 4px; font-size: 19px; }
|
||||||
|
.notification-modal-head p { margin-top: 3px; color: var(--muted); font-size: 11px; }
|
||||||
|
|
||||||
|
.notification-modal-body { max-height: min(480px, calc(100vh - 190px)); padding: 0; overflow-y: auto; }
|
||||||
|
.notification-list { list-style: none; }
|
||||||
|
.notification-list li:last-child .notification-item { border-bottom: 0; }
|
||||||
|
|
||||||
|
.notification-item {
|
||||||
|
display: grid;
|
||||||
|
width: 100%;
|
||||||
|
grid-template-columns: 34px minmax(0, 1fr) auto;
|
||||||
|
align-items: start;
|
||||||
|
gap: 11px;
|
||||||
|
padding: 14px 18px;
|
||||||
|
border: 0;
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
background: #fff;
|
||||||
|
color: var(--text);
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-item.actionable { cursor: pointer; }
|
||||||
|
.notification-item.actionable:hover { background: #f7faff; }
|
||||||
|
.notification-item:focus-visible { position: relative; z-index: 1; outline: 3px solid #72adff; outline-offset: -3px; }
|
||||||
|
|
||||||
|
.notification-item-icon {
|
||||||
|
display: grid;
|
||||||
|
place-items: center;
|
||||||
|
width: 34px;
|
||||||
|
height: 34px;
|
||||||
|
border-radius: 8px;
|
||||||
|
background: var(--blue-soft);
|
||||||
|
color: var(--blue);
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 800;
|
||||||
|
}
|
||||||
|
|
||||||
|
.notification-item-icon.danger { background: var(--danger-soft); color: var(--danger); }
|
||||||
|
.notification-item-icon.pending { background: var(--warning-soft); color: var(--warning); }
|
||||||
|
.notification-item-icon.success { background: var(--success-soft); color: var(--success); }
|
||||||
|
|
||||||
|
.notification-item-copy { display: block; min-width: 0; }
|
||||||
|
.notification-item-copy strong,
|
||||||
|
.notification-item-copy span,
|
||||||
|
.notification-item-copy small { display: block; }
|
||||||
|
.notification-item-copy strong { font-size: 12px; }
|
||||||
|
.notification-item-copy span { margin-top: 2px; color: var(--body); font-size: 11px; line-height: 1.55; }
|
||||||
|
.notification-item-copy small { margin-top: 5px; color: var(--quiet); font-size: 10px; }
|
||||||
|
.notification-item-link { padding-top: 8px; color: var(--blue); font-size: 11px; white-space: nowrap; }
|
||||||
|
.notification-item-link svg { width: 14px; height: 14px; vertical-align: -3px; }
|
||||||
|
|
||||||
|
.notification-empty { padding: 38px 20px; }
|
||||||
|
.notification-empty-icon { display: grid; place-items: center; width: 34px; height: 34px; margin: 0 auto 7px; border-radius: 50%; background: var(--success-soft); color: var(--success); font-weight: 800; }
|
||||||
|
.notification-empty strong,
|
||||||
|
.notification-empty span:not(.notification-empty-icon) { display: block; text-align: center; }
|
||||||
|
.notification-empty strong { color: var(--body); font-size: 13px; }
|
||||||
|
.notification-empty span:not(.notification-empty-icon) { margin-top: 3px; color: var(--muted); font-size: 11px; }
|
||||||
|
|
||||||
|
.notification-modal-actions { display: flex; justify-content: flex-end; padding: 13px 21px; border-top: 1px solid var(--line); background: var(--surface); }
|
||||||
|
|
||||||
|
@media (max-width: 680px) {
|
||||||
|
.notification-dialog-panel { width: calc(100vw - 24px); max-height: calc(100vh - 24px); }
|
||||||
|
.notification-modal-head { padding: 16px 17px 13px; }
|
||||||
|
.notification-item { padding: 13px 15px; }
|
||||||
|
.notification-modal-actions { padding: 12px 17px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.notification-dialog-panel { animation: none; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
<template>
|
||||||
|
<main class="login-screen" aria-labelledby="loginTitle">
|
||||||
|
<div class="login-panel">
|
||||||
|
<header class="login-brand">
|
||||||
|
<span class="brand-mark" aria-hidden="true"><i></i><i></i></span>
|
||||||
|
<span>
|
||||||
|
<strong>零差云控</strong>
|
||||||
|
<small>ZEROERR · 财务管理平台</small>
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="login-layout">
|
||||||
|
<section class="login-copy" aria-describedby="loginIntro">
|
||||||
|
<span class="eyebrow">FINANCE WORKSPACE</span>
|
||||||
|
<h1 id="loginTitle">让每一笔报销,<br><b>清晰地走完全流程</b></h1>
|
||||||
|
<p id="loginIntro">统一管理报销申请、审批进度与财务处理,让每一个环节都有据可查。</p>
|
||||||
|
<div class="login-points" aria-label="平台能力">
|
||||||
|
<span><b aria-hidden="true">01</b>申请与审批状态清晰可见</span>
|
||||||
|
<span><b aria-hidden="true">02</b>收单与付款记录独立留痕</span>
|
||||||
|
<span><b aria-hidden="true">03</b>企业统一身份认证,安全访问</span>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="login-card" aria-labelledby="loginCardTitle" aria-describedby="loginCardDescription">
|
||||||
|
<div class="feishu-logo" aria-hidden="true">飞</div>
|
||||||
|
<span class="eyebrow">AUTHORIZED ENTRY</span>
|
||||||
|
<h2 id="loginCardTitle">使用飞书账号登录</h2>
|
||||||
|
<p id="loginCardDescription">通过飞书授权验证身份后即可进入系统;通讯录同步用于员工资料与业务管理,不作为登录条件。每日首次访问需重新完成授权。</p>
|
||||||
|
|
||||||
|
<div v-if="loading" class="login-loading" role="status" aria-live="polite">
|
||||||
|
<p>正在验证身份…</p>
|
||||||
|
<small>{{ loadingMessage }}</small>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else>
|
||||||
|
<div v-if="loginError" class="inline-alert danger" role="alert">
|
||||||
|
<b aria-hidden="true">!</b>
|
||||||
|
<span>{{ loginError }}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
class="btn"
|
||||||
|
type="button"
|
||||||
|
:disabled="feishuLoading"
|
||||||
|
:aria-busy="feishuLoading"
|
||||||
|
@click="handleFeishuLogin"
|
||||||
|
>
|
||||||
|
{{ feishuLoading ? '正在前往飞书…' : '飞书授权登录' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="login-card-foot">
|
||||||
|
登录信息由飞书授权提供,本平台不单独维护登录密码
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer class="login-foot">企业财务工作台 · 飞书统一身份认证</footer>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { onMounted, ref } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { authApi } from '@/api/auth'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const route = useRoute()
|
||||||
|
const userStore = useUserStore()
|
||||||
|
const workbench = useWorkbenchStore()
|
||||||
|
const feishuLoading = ref(false)
|
||||||
|
const loading = ref(true)
|
||||||
|
const loadingMessage = ref('')
|
||||||
|
const loginError = ref('')
|
||||||
|
|
||||||
|
const handleFeishuLogin = async () => {
|
||||||
|
const attempt = userStore.beginFeishuLogin()
|
||||||
|
feishuLoading.value = true
|
||||||
|
loginError.value = ''
|
||||||
|
try {
|
||||||
|
const response = await authApi.getAuthUrl()
|
||||||
|
if (!response.authUrl) throw new Error('获取飞书授权地址失败')
|
||||||
|
window.location.assign(response.authUrl)
|
||||||
|
} catch (e: any) {
|
||||||
|
// request.ts already reports HTTP/network failures; avoid duplicating those toasts.
|
||||||
|
const message = e?.message === '获取飞书授权地址失败'
|
||||||
|
? e.message
|
||||||
|
: '暂时无法连接认证服务,请稍后重试'
|
||||||
|
loginError.value = message
|
||||||
|
if (e?.message === '获取飞书授权地址失败') ElMessage.error(e.message)
|
||||||
|
userStore.clearFeishuLogin(attempt)
|
||||||
|
} finally {
|
||||||
|
feishuLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
const token = route.query.token as string | undefined
|
||||||
|
const code = route.query.code as string | undefined
|
||||||
|
const state = route.query.state as string | undefined
|
||||||
|
const error = route.query.error as string | undefined
|
||||||
|
|
||||||
|
// Do not leave OAuth credentials or one-time codes in browser history.
|
||||||
|
if (token || code || error) window.history.replaceState({}, document.title, window.location.pathname)
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
const attempt = sessionStorage.getItem('feishuOAuthAttempt')
|
||||||
|
if (!attempt || userStore.isCurrentFeishuLogin(attempt)) {
|
||||||
|
userStore.logout()
|
||||||
|
userStore.clearFeishuLogin(attempt)
|
||||||
|
}
|
||||||
|
workbench.reset()
|
||||||
|
loading.value = false
|
||||||
|
loginError.value = error
|
||||||
|
ElMessage.error(error)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (token) {
|
||||||
|
loadingMessage.value = '正在获取用户信息…'
|
||||||
|
try {
|
||||||
|
// A token callback can follow an expired session or a different user.
|
||||||
|
// Clear business data before loading the new identity to prevent data
|
||||||
|
// from the previous session flashing in lists and notifications.
|
||||||
|
workbench.reset()
|
||||||
|
await userStore.setToken(token)
|
||||||
|
ElMessage.success('登录成功')
|
||||||
|
router.replace('/dashboard')
|
||||||
|
} catch (e: any) {
|
||||||
|
userStore.logout()
|
||||||
|
workbench.reset()
|
||||||
|
loading.value = false
|
||||||
|
loginError.value = e?.message || '登录验证失败,请重新授权'
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (code) {
|
||||||
|
const attempt = sessionStorage.getItem('feishuOAuthAttempt')
|
||||||
|
loadingMessage.value = '正在交换授权码…'
|
||||||
|
try {
|
||||||
|
workbench.reset()
|
||||||
|
await userStore.feishuLogin(code, state, attempt || undefined)
|
||||||
|
ElMessage.success('登录成功')
|
||||||
|
await router.replace('/dashboard')
|
||||||
|
} catch (e: any) {
|
||||||
|
if (!attempt || userStore.isCurrentFeishuLogin(attempt)) {
|
||||||
|
userStore.logout()
|
||||||
|
userStore.clearFeishuLogin(attempt)
|
||||||
|
}
|
||||||
|
workbench.reset()
|
||||||
|
loading.value = false
|
||||||
|
loginError.value = e?.message || '登录失败,请重试'
|
||||||
|
ElMessage.error(loginError.value)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
loading.value = false
|
||||||
|
})
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page-content">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">OPERATION LOGS</span>
|
||||||
|
<h1>操作日志</h1>
|
||||||
|
<p>系统操作记录,按时间倒序排列。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card fill-list-card">
|
||||||
|
<div class="timeline" v-if="items.length > 0">
|
||||||
|
<div class="timeline-item" v-for="item in items" :key="item.id">
|
||||||
|
<div class="tl-dot" :class="item.action"></div>
|
||||||
|
<div class="tl-content">
|
||||||
|
<strong>{{ item.operator }}</strong>
|
||||||
|
<span>{{ item.action }} · {{ item.detail }}</span>
|
||||||
|
<small>{{ item.time }}</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="empty-state" v-else-if="loaded"><strong>暂无操作日志</strong></div>
|
||||||
|
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载操作日志…</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import request from '@/api/request'
|
||||||
|
const items = ref<any[]>([])
|
||||||
|
const loaded = ref(false)
|
||||||
|
onMounted(async () => { try { items.value = await request.get('/logs') || [] } catch {} finally { loaded.value = true } })
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page-content">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">PAYEES</span>
|
||||||
|
<h1>付款对象</h1>
|
||||||
|
<p>管理收款方账户信息。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card fill-list-card">
|
||||||
|
<div class="table-wrap" v-if="items.length > 0" tabindex="0" role="region" aria-label="付款对象列表"><table class="data-table">
|
||||||
|
<thead><tr><th>账户名称</th><th>银行</th><th>账号</th><th>默认</th><th>状态</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in items" :key="item.id">
|
||||||
|
<td><strong>{{ item.name }}</strong></td>
|
||||||
|
<td><small>{{ item.bankName }}</small></td>
|
||||||
|
<td><small>{{ item.bankAccountMask || '已脱敏' }}</small></td>
|
||||||
|
<td><span class="tag" :class="item.isDefault?'success':'draft'">{{ item.isDefault?'默认':'' }}</span></td>
|
||||||
|
<td><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
<div class="empty-state" v-else-if="loaded"><strong>暂无付款对象</strong></div>
|
||||||
|
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载付款对象…</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted } from 'vue'
|
||||||
|
import request from '@/api/request'
|
||||||
|
const items = ref<any[]>([])
|
||||||
|
const loaded = ref(false)
|
||||||
|
onMounted(async () => { try { items.value = await request.get('/metadata/payees') || [] } catch {} finally { loaded.value = true } })
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page-content">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">PAYMENT QUEUE</span>
|
||||||
|
<h1>待付款</h1>
|
||||||
|
<p>收单完成后进入付款队列,支持分次付款并保留付款凭据。</p>
|
||||||
|
</div>
|
||||||
|
<div class="head-actions">
|
||||||
|
<button class="btn" type="button" :disabled="loadingState" @click="refreshQueue">刷新</button>
|
||||||
|
<router-link class="btn primary" to="/finance-receipt">返回待收单</router-link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="loadingState" class="load-wrap" role="status" aria-live="polite">
|
||||||
|
<span class="loader" aria-hidden="true"></span>
|
||||||
|
<p>正在读取付款队列…</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="hasBlockingError" class="card empty-state" role="alert">
|
||||||
|
<strong>付款队列暂时无法加载</strong>
|
||||||
|
<span>请检查网络连接后重试,系统不会以空列表代替异常数据。</span>
|
||||||
|
<button class="btn" type="button" @click="refreshQueue">重新加载</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<template v-else>
|
||||||
|
<div v-if="hasDataNotice" class="inline-alert" role="status" aria-live="polite">
|
||||||
|
<b aria-hidden="true">i</b>
|
||||||
|
<span>数据服务暂时不可用,当前队列可能不完整。</span>
|
||||||
|
<button class="btn small" type="button" @click="refreshQueue">重试</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="finance-kpis">
|
||||||
|
<div><span>待付款</span><strong>{{ payable.length }}</strong><small>存在未付余额</small></div>
|
||||||
|
<div><span>待付金额</span><strong>{{ money(totalBalance) }}</strong><small>由有效付款记录派生</small></div>
|
||||||
|
<div><span>已付款</span><strong>{{ completed.length }}</strong><small>全额完成</small></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card fill-list-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<div><h2>付款登记队列</h2><p>登记结果后,付款状态自动派生并保留付款事实。</p></div>
|
||||||
|
<span class="tag info">财务处理</span>
|
||||||
|
</div>
|
||||||
|
<div class="filter-bar">
|
||||||
|
<label class="filter-search">
|
||||||
|
<span aria-hidden="true">⌕</span>
|
||||||
|
<input v-model="query" type="search" aria-label="搜索待付款" placeholder="搜索报销单号、报销人或事项">
|
||||||
|
</label>
|
||||||
|
<span class="filter-spacer"></span>
|
||||||
|
<span class="tag info" aria-live="polite">{{ filtered.length }} 笔结果</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="filtered.length" class="table-wrap">
|
||||||
|
<table class="data-table responsive-table" aria-label="付款登记队列">
|
||||||
|
<caption class="sr-only">付款登记队列</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">报销单号</th><th scope="col">报销人 / 收款人</th><th scope="col" class="amount">申请金额</th>
|
||||||
|
<th scope="col" class="amount">累计已付</th><th scope="col" class="amount">未付余额</th><th scope="col">收单状态</th><th scope="col">付款状态</th><th scope="col">操作</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in filtered" :key="item.id">
|
||||||
|
<td data-label="报销单号"><router-link class="table-action strong-link" :to="`/applications/${item.id}`">{{ item.applicationNo }}</router-link><small>{{ item.createdAt?.slice(0, 10) || '-' }}</small></td>
|
||||||
|
<td data-label="报销人 / 收款人"><strong>{{ item.applicantName }}</strong><small>{{ item.payeeName || '-' }}</small></td>
|
||||||
|
<td data-label="申请金额" class="amount">{{ money(item.totalAmount) }}</td>
|
||||||
|
<td data-label="累计已付" class="amount">{{ money(store.paidAmount(item)) }}</td>
|
||||||
|
<td data-label="未付余额" class="amount">{{ money(store.balance(item)) }}</td>
|
||||||
|
<td data-label="收单状态"><span class="tag success">{{ item.receiptStatus }}</span></td>
|
||||||
|
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
|
||||||
|
<td data-label="操作">
|
||||||
|
<button
|
||||||
|
v-if="store.balance(item) > 0"
|
||||||
|
class="btn small primary"
|
||||||
|
type="button"
|
||||||
|
:disabled="saving"
|
||||||
|
:aria-busy="saving && selected?.id === item.id"
|
||||||
|
@click="openPayment(item)"
|
||||||
|
>{{ saving && selected?.id === item.id ? '提交中…' : '登记付款' }}</button>
|
||||||
|
<span v-else class="muted-copy">已完成</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="!rows.length" class="empty-state">
|
||||||
|
<strong>当前没有待付款记录</strong>
|
||||||
|
<span>完成财务收单的报销会自动进入这里。</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="empty-state">
|
||||||
|
<strong>没有符合条件的付款记录</strong>
|
||||||
|
<span>请调整搜索关键词后重试。</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<dialog
|
||||||
|
ref="dialog"
|
||||||
|
class="payment-dialog"
|
||||||
|
aria-labelledby="payment-dialog-title"
|
||||||
|
aria-describedby="payment-dialog-description"
|
||||||
|
@close="handleDialogClose"
|
||||||
|
@click.self="closePayment"
|
||||||
|
>
|
||||||
|
<form v-if="selected" class="payment-form" @submit.prevent="submitPayment">
|
||||||
|
<div class="modal-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">PAYMENT RECORD</span>
|
||||||
|
<h2 id="payment-dialog-title">登记付款</h2>
|
||||||
|
<p id="payment-dialog-description">{{ selected.applicationNo }} · {{ selected.title }}</p>
|
||||||
|
</div>
|
||||||
|
<button class="modal-close" type="button" aria-label="关闭付款登记窗口" @click="closePayment">×</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-body">
|
||||||
|
<div class="payment-summary">
|
||||||
|
<div><span>申请金额</span><strong>{{ money(selected.totalAmount) }}</strong></div>
|
||||||
|
<div><span>累计已付</span><strong>{{ money(store.paidAmount(selected)) }}</strong></div>
|
||||||
|
<div><span>未付余额</span><strong>{{ money(store.balance(selected)) }}</strong></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-grid">
|
||||||
|
<div class="field">
|
||||||
|
<label for="pay-amount">本次付款金额 <em>*</em></label>
|
||||||
|
<input
|
||||||
|
id="pay-amount"
|
||||||
|
v-model.number="amount"
|
||||||
|
type="number"
|
||||||
|
min="0.01"
|
||||||
|
step="0.01"
|
||||||
|
inputmode="decimal"
|
||||||
|
:max="store.balance(selected)"
|
||||||
|
:aria-invalid="Boolean(formError)"
|
||||||
|
aria-describedby="pay-amount-help payment-form-error"
|
||||||
|
>
|
||||||
|
<p id="pay-amount-help" class="form-help">不超过未付余额 {{ money(store.balance(selected)) }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="field full">
|
||||||
|
<label for="pay-remark">备注</label>
|
||||||
|
<textarea id="pay-remark" v-model="remark" rows="3" maxlength="200" placeholder="可填写付款说明或外部凭据"></textarea>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p v-if="formError" id="payment-form-error" class="amount-error" role="alert">{{ formError }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="modal-actions">
|
||||||
|
<button class="btn" type="button" :disabled="saving" @click="closePayment">取消</button>
|
||||||
|
<button class="btn primary" type="submit" :disabled="saving" :aria-busy="saving">
|
||||||
|
{{ saving ? '正在保存…' : '确认登记' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||||
|
import { useWorkbenchStore } from '@/store/workbench'
|
||||||
|
|
||||||
|
const store = useWorkbenchStore()
|
||||||
|
const query = ref('')
|
||||||
|
const hasLoaded = ref(false)
|
||||||
|
const selected = ref<ReimApplicationDetail | null>(null)
|
||||||
|
const dialog = ref<HTMLDialogElement | null>(null)
|
||||||
|
const amount = ref<number | null>(0)
|
||||||
|
const remark = ref('')
|
||||||
|
const idempotencyKey = ref('')
|
||||||
|
const saving = ref(false)
|
||||||
|
const formError = ref('')
|
||||||
|
let trigger: HTMLElement | null = null
|
||||||
|
|
||||||
|
const rows = computed(() => store.reimbursements.filter(item => item.receiptStatus === '已收单'))
|
||||||
|
const payable = computed(() => rows.value.filter(item => store.balance(item) > 0))
|
||||||
|
const completed = computed(() => rows.value.filter(item => store.balance(item) <= 0))
|
||||||
|
const totalBalance = computed(() => payable.value.reduce((sum, item) => sum + store.balance(item), 0))
|
||||||
|
const filtered = computed(() => {
|
||||||
|
const normalizedQuery = query.value.trim().toLowerCase()
|
||||||
|
return rows.value.filter(item => `${item.applicationNo} ${item.applicantName} ${item.title} ${item.payeeName}`.toLowerCase().includes(normalizedQuery))
|
||||||
|
})
|
||||||
|
const loadingState = computed(() => store.loading || !hasLoaded.value)
|
||||||
|
const hasBlockingError = computed(() => hasLoaded.value && (store.source === 'error' || Boolean(store.financeQueueError)))
|
||||||
|
const hasDataNotice = computed(() => hasLoaded.value && Boolean(store.error) && !hasBlockingError.value)
|
||||||
|
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
|
||||||
|
const tone = (value: string) => ({ 未付款: 'neutral', 部分付款: 'info', 已付款: 'success' } as Record<string, string>)[value] || 'neutral'
|
||||||
|
|
||||||
|
const refreshQueue = async () => {
|
||||||
|
hasLoaded.value = false
|
||||||
|
store.error = ''
|
||||||
|
store.financeQueueError = ''
|
||||||
|
await store.loadFinanceQueue('payment')
|
||||||
|
hasLoaded.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const openPayment = async (item: ReimApplicationDetail) => {
|
||||||
|
if (saving.value) return
|
||||||
|
trigger = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||||
|
selected.value = item
|
||||||
|
amount.value = Number(store.balance(item).toFixed(2))
|
||||||
|
remark.value = ''
|
||||||
|
idempotencyKey.value = `reim-${item.id}-${Number(store.balance(item).toFixed(2)).toFixed(2)}`
|
||||||
|
formError.value = ''
|
||||||
|
if (!dialog.value) return
|
||||||
|
if (!dialog.value.open) dialog.value.showModal()
|
||||||
|
await nextTick()
|
||||||
|
document.getElementById('pay-amount')?.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
const restoreDialogFocus = () => {
|
||||||
|
const element = trigger
|
||||||
|
trigger = null
|
||||||
|
selected.value = null
|
||||||
|
if (element?.isConnected) element.focus()
|
||||||
|
}
|
||||||
|
|
||||||
|
const closePayment = () => {
|
||||||
|
if (dialog.value?.open) dialog.value.close()
|
||||||
|
restoreDialogFocus()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDialogClose = () => restoreDialogFocus()
|
||||||
|
|
||||||
|
const submitPayment = async () => {
|
||||||
|
if (!selected.value || saving.value) return
|
||||||
|
const max = store.balance(selected.value)
|
||||||
|
const enteredAmount = Number(amount.value)
|
||||||
|
if (!Number.isFinite(enteredAmount) || !(enteredAmount > 0) || enteredAmount > max + 0.005) {
|
||||||
|
formError.value = `付款金额须大于 0 且不超过未付余额 ${money(max)}`
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
saving.value = true
|
||||||
|
formError.value = ''
|
||||||
|
try {
|
||||||
|
await store.pay(selected.value.id, Number(enteredAmount.toFixed(2)), remark.value.trim(), idempotencyKey.value)
|
||||||
|
closePayment()
|
||||||
|
ElMessage.success('付款记录已登记')
|
||||||
|
} catch (error) {
|
||||||
|
formError.value = error instanceof Error ? error.message : '付款失败,请检查后重试'
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => { void refreshQueue() })
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page-content">
|
||||||
|
<div class="page-head">
|
||||||
|
<div>
|
||||||
|
<span class="eyebrow">SOURCE DOCUMENTS</span>
|
||||||
|
<h1>业务单据</h1>
|
||||||
|
<p>来自金蝶 ERP 的源单据,只读展示。</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="card fill-list-card">
|
||||||
|
<div class="filter-bar">
|
||||||
|
<label class="filter-search"><span aria-hidden="true">🔍</span><input type="search" v-model="search" placeholder="搜索单据编号" aria-label="搜索"></label>
|
||||||
|
<span class="filter-spacer"></span><span class="tag info">{{ filtered.length }} 笔</span>
|
||||||
|
</div>
|
||||||
|
<div class="table-wrap" v-if="filtered.length > 0" tabindex="0" role="region" aria-label="业务单据列表"><table class="data-table">
|
||||||
|
<thead><tr><th>单据编号</th><th>类型</th><th class="amount">金额</th><th>日期</th><th>来源</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr v-for="item in filtered" :key="item.id">
|
||||||
|
<td><strong>{{ item.sourceDocNo }}</strong></td>
|
||||||
|
<td><span class="tag">{{ item.sourceDocType }}</span></td>
|
||||||
|
<td class="amount">{{ fmt(item.amount) }}</td>
|
||||||
|
<td><small>{{ item.sourceDate }}</small></td>
|
||||||
|
<td><small>{{ item.sourceSystem }}</small></td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
<div class="empty-state" v-else-if="loaded"><strong>暂无业务单据</strong><span>金蝶 ERP 数据同步后会自动显示</span></div>
|
||||||
|
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载业务单据…</span></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted } from 'vue'
|
||||||
|
import request from '@/api/request'
|
||||||
|
const search = ref('')
|
||||||
|
const items = ref<any[]>([])
|
||||||
|
const loaded = ref(false)
|
||||||
|
onMounted(async () => { try { items.value = await request.get('/sources') || [] } catch {} finally { loaded.value = true } })
|
||||||
|
const filtered = computed(() => {
|
||||||
|
if (!search.value) return items.value
|
||||||
|
const q = search.value.toLowerCase()
|
||||||
|
return items.value.filter(i => (i.sourceDocNo || '').toLowerCase().includes(q))
|
||||||
|
})
|
||||||
|
const fmt = (v: number) => `¥ ${(v||0).toLocaleString('zh-CN',{minimumFractionDigits:2})}`
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
<template>
|
||||||
|
<div class="admin-page page-content" :class="{ 'has-group-detail': selectedGroup }">
|
||||||
|
<div class="page-head"><div><span class="eyebrow">SYSTEM MANAGEMENT</span><h1>用户管理</h1><p>统一管理用户、角色权限和飞书组织用户组。</p></div><div v-if="activeTab === 'roles' && can('system:role:manage')" class="head-actions"><button class="btn primary" type="button" @click="openRoleForm()">新建角色</button></div><div v-else-if="activeTab === 'groups' && can('system:group:manage')" class="head-actions"><button class="btn primary" type="button" @click="openGroupForm()">新建用户组</button><button v-if="selectedGroup" class="btn" type="button" @click="toggleGroupStatus(selectedGroup)">{{ selectedGroup.status === 'ACTIVE' ? '停用当前组' : '启用当前组' }}</button></div></div>
|
||||||
|
<div v-if="permissionsFailed" class="inline-alert danger" role="alert"><b>!</b><span>管理权限加载失败,管理项已隐藏。请重试后再进行操作。</span><button class="btn small" type="button" @click="retryPermissions">重试</button></div>
|
||||||
|
<nav v-if="availableTabs.length" class="tabs" aria-label="用户管理模块" role="tablist"><button v-if="can('system:user:view')" class="tab" :class="{ active: activeTab === 'users' }" type="button" :aria-selected="activeTab === 'users'" role="tab" @click="switchTab('users')">用户</button><button v-if="can('system:role:view')" class="tab" :class="{ active: activeTab === 'roles' }" type="button" :aria-selected="activeTab === 'roles'" role="tab" @click="switchTab('roles')">角色管理</button><button v-if="can('system:group:view')" class="tab" :class="{ active: activeTab === 'groups' }" type="button" :aria-selected="activeTab === 'groups'" role="tab" @click="switchTab('groups')">用户组 / 飞书绑定</button></nav>
|
||||||
|
|
||||||
|
<section v-if="activeTab === 'users' && can('system:user:view')" class="card admin-card"><div class="card-head"><div><h2>系统用户</h2><p>旧角色下拉仍可使用;多角色请打开角色分配。</p></div><span class="muted-copy">{{ users.length }} 人</span></div><div v-if="usersLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载用户…</span></div><div v-else-if="usersError" class="empty-state" role="alert"><strong>用户加载失败</strong><span>{{ usersError }}</span><button class="btn small" type="button" @click="loadUsers">重试</button></div><div v-else-if="!users.length" class="empty-state"><strong>暂无用户</strong><span>当前没有可管理的系统用户。</span></div><div v-else class="table-wrap"><table class="data-table" aria-label="系统用户列表"><thead><tr><th>员工号 / 部门</th><th>姓名</th><th>角色</th><th>状态</th><th>最后登录</th><th>操作</th></tr></thead><tbody><tr v-for="user in users" :key="user.id"><td><strong>{{ user.employeeNo || '-' }}</strong><small>{{ user.departmentName || '未分配部门' }}</small></td><td><strong>{{ user.realName || '未命名用户' }}</strong><small>{{ user.position || '' }}</small></td><td class="role-cell"><span v-if="user.roleCodes?.length" v-for="roleCode in user.roleCodes" :key="roleCode" class="tag info">{{ roleCode }}</span><span v-else class="tag neutral">{{ legacyRoleLabel(user.userType) }}</span><select class="select legacy-role" :value="legacyRole(user.userType)" :disabled="!can('system:user:manage') || statusSaving === user.id" aria-label="兼容旧角色选择" @change="updateLegacyRole(user, $event)"><option value="ADMIN">系统管理员</option><option value="FINANCE">财务人员</option><option value="EMPLOYEE">普通用户</option></select></td><td><button class="status-button" :class="user.status === 'ACTIVE' ? 'active' : 'inactive'" type="button" :disabled="!can('system:user:manage') || statusSaving === user.id" :aria-label="`${user.realName}:${user.status === 'ACTIVE' ? '停用' : '启用'}`" @click="toggleUserStatus(user)"><span class="status-dot-small" aria-hidden="true"></span>{{ user.status === 'ACTIVE' ? '正常' : '已停用' }}</button></td><td><small>{{ user.lastLoginAt || '-' }}</small></td><td><button class="table-action" type="button" :disabled="!can('system:user:manage')" @click="openUserRoles(user)">分配角色</button></td></tr></tbody></table></div></section>
|
||||||
|
|
||||||
|
<section v-if="activeTab === 'roles' && can('system:role:view')" class="card admin-card"><div class="card-head"><div><h2>角色列表</h2><p>菜单、按钮和字段权限可分别配置。</p></div><span class="muted-copy">{{ roles.length }} 个角色</span></div><div v-if="rolesLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载角色…</span></div><div v-else-if="rolesError" class="empty-state" role="alert"><strong>角色加载失败</strong><span>{{ rolesError }}</span><button class="btn small" type="button" @click="loadRoles">重试</button></div><div v-else-if="!roles.length" class="empty-state"><strong>暂无角色</strong><span>创建角色后可配置其权限。</span></div><div v-else class="table-wrap"><table class="data-table" aria-label="角色列表"><thead><tr><th>角色</th><th>说明</th><th>状态</th><th>成员数</th><th>权限数</th><th>操作</th></tr></thead><tbody><tr v-for="role in roles" :key="role.id"><td><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}</small></td><td><span class="muted-copy">{{ role.description || '-' }}</span></td><td><span class="tag" :class="role.status === 'ACTIVE' ? 'success' : 'danger'">{{ role.status === 'ACTIVE' ? '启用' : '停用' }}</span></td><td>{{ role.memberCount ?? 0 }}</td><td>{{ role.permissionCount ?? 0 }}</td><td class="actions-cell"><button class="table-action" type="button" :disabled="!can('system:role:manage')" @click="openRoleForm(role)">{{ role.builtIn ? '查看 / 编辑' : '编辑' }}</button><button v-if="!role.builtIn && can('system:role:manage')" class="table-action" type="button" @click="toggleRoleStatus(role)">{{ role.status === 'ACTIVE' ? '停用' : '启用' }}</button><button v-if="!role.builtIn && can('system:role:manage')" class="table-action danger-action" type="button" @click="deleteRole(role)">删除</button></td></tr></tbody></table></div></section>
|
||||||
|
|
||||||
|
<section v-if="activeTab === 'groups' && can('system:group:view')" class="group-layout"><div class="card admin-card"><div class="card-head"><div><h2>用户组</h2><p>每个用户组可以独立绑定人员和角色。</p></div><span class="muted-copy">{{ groups.length }} 个用户组</span></div><div v-if="groupsLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载用户组…</span></div><div v-else-if="groupsError" class="empty-state" role="alert"><strong>用户组加载失败</strong><span>{{ groupsError }}</span><button class="btn small" type="button" @click="loadGroups">重试</button></div><div v-else-if="!groups.length" class="empty-state"><strong>暂无用户组</strong><span>新建用户组后可以绑定飞书人员。</span></div><div v-else class="table-wrap"><table class="data-table" aria-label="用户组列表"><thead><tr><th>用户组</th><th>状态</th><th>成员</th><th>角色</th><th>操作</th></tr></thead><tbody><tr v-for="group in groups" :key="group.id" :class="{ selected: selectedGroup?.id === group.id }"><td><button class="link-button" type="button" @click="openGroupDetail(group)"><strong>{{ group.groupName }}</strong><small>{{ group.groupCode }}</small></button></td><td><span class="tag" :class="group.status === 'ACTIVE' ? 'success' : 'danger'">{{ group.status === 'ACTIVE' ? '启用' : '已停用' }}</span></td><td>{{ group.memberCount ?? 0 }}</td><td>{{ group.roleCount ?? 0 }}</td><td class="actions-cell"><button class="table-action" type="button" @click="openGroupDetail(group)">绑定详情</button><button class="table-action" type="button" :disabled="!can('system:group:manage')" @click="openGroupForm(group)">编辑</button><button v-if="can('system:group:manage')" class="table-action danger-action" type="button" @click="deleteGroup(group)">删除</button></td></tr></tbody></table></div></div>
|
||||||
|
<div v-if="selectedGroup" class="card group-detail"><div class="card-head"><div><span class="eyebrow">GROUP DETAIL</span><h2>{{ selectedGroup.groupName }}</h2><p>{{ selectedGroup.description || '绑定飞书组织人员和角色' }}</p></div><button class="modal-close" type="button" aria-label="关闭用户组详情" @click="selectedGroup = null">×</button></div><div v-if="groupDetailLoading" class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载绑定信息…</span></div><div v-else-if="groupDetailError" class="empty-state" role="alert"><strong>详情加载失败</strong><span>{{ groupDetailError }}</span><button class="btn small" type="button" @click="openGroupDetail(selectedGroup!)">重试</button></div><template v-else><section class="binding-section"><div class="section-title"><h2>飞书组织人员</h2><span>{{ selectedMemberIds.length }} 人已绑定</span></div><div class="filter-bar"><label class="filter-search"><span class="sr-only">关键字</span><input v-model.trim="candidateKeyword" type="search" placeholder="搜索姓名、工号或飞书 ID" aria-label="搜索候选人员"></label><label><span class="sr-only">部门</span><select v-model="candidateDepartment" class="select" aria-label="按部门筛选"><option value="">全部部门</option><option v-for="department in candidateDepartments" :key="department" :value="department">{{ department }}</option></select></label></div><div v-if="candidateLoading" class="load-wrap"><span class="loader" aria-hidden="true"></span><span>正在加载候选人员…</span></div><div v-else-if="!filteredCandidates.length" class="empty-state compact-empty"><strong>没有符合条件的候选人员</strong><span>可调整部门或关键字筛选。</span></div><div v-else class="candidate-list"><label v-for="candidate in filteredCandidates" :key="candidate.id" class="candidate-row"><input v-model="selectedMemberIds" type="checkbox" :value="candidate.id" :disabled="!can('system:group:manage')"><span class="candidate-copy"><strong>{{ candidate.realName }} <small>{{ candidate.employeeNo || '-' }}</small></strong><span>{{ candidate.departmentName || '未分配部门' }} · {{ candidate.status === 'ACTIVE' ? '在职' : '已停用' }}</span></span><span class="candidate-ids"><small>Open ID:{{ maskId(candidate.feishuOpenId) }}</small><small>User ID:{{ maskId(candidate.feishuUserId) }}</small></span></label></div><div class="binding-actions"><button class="btn primary" type="button" :disabled="!can('system:group:manage') || savingBinding === 'members'" @click="saveGroupMembers">{{ savingBinding === 'members' ? '保存中…' : '保存人员绑定' }}</button></div></section><section class="binding-section"><div class="section-title"><h2>绑定角色</h2><span>{{ selectedGroupRoleIds.length }} 个角色</span></div><div v-if="!roles.length" class="empty-state compact-empty"><strong>暂无可用角色</strong><span>需要角色查看权限才能配置用户组角色。</span></div><div v-else class="role-options"><label v-for="role in roles" :key="role.id" class="check-option"><input v-model="selectedGroupRoleIds" type="checkbox" :value="role.id" :disabled="!can('system:group:manage')"><span><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}</small></span></label></div><div class="binding-actions"><button class="btn primary" type="button" :disabled="!can('system:group:manage') || savingBinding === 'roles'" @click="saveGroupRoles">{{ savingBinding === 'roles' ? '保存中…' : '保存角色绑定' }}</button></div></section></template></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<dialog ref="userRoleDialog" class="admin-dialog" aria-labelledby="user-role-title" @click.self="closeUserRoleDialog"><form @submit.prevent="saveUserRoles"><div class="modal-head"><div><span class="eyebrow">USER ROLES</span><h2 id="user-role-title">分配用户角色</h2><p>{{ selectedUser?.realName }} · {{ selectedUser?.employeeNo }}</p></div><button class="modal-close" type="button" aria-label="关闭角色分配窗口" @click="closeUserRoleDialog">×</button></div><div class="modal-body"><div v-if="!roles.length" class="empty-state compact-empty"><strong>暂无可分配角色</strong><span>请先确认角色查看权限和角色列表。</span></div><div v-else class="role-options"><label v-for="role in roles" :key="role.id" class="check-option"><input v-model="userRoleIds" type="checkbox" :value="role.id"><span><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }} · {{ role.description || '无描述' }}</small></span></label></div></div><div class="modal-actions"><button class="btn" type="button" :disabled="userRoleSaving" @click="closeUserRoleDialog">取消</button><button class="btn primary" type="submit" :disabled="userRoleSaving || !can('system:user:manage')">{{ userRoleSaving ? '保存中…' : '保存角色' }}</button></div></form></dialog>
|
||||||
|
|
||||||
|
<dialog ref="roleDialog" class="admin-dialog wide-dialog" aria-labelledby="role-dialog-title" @click.self="closeRoleDialog"><form @submit.prevent="saveRole"><div class="modal-head"><div><span class="eyebrow">ROLE CONFIGURATION</span><h2 id="role-dialog-title">{{ editingRole ? '编辑角色' : '新建角色' }}</h2><p>权限变更保存后立即生效。</p></div><button class="modal-close" type="button" aria-label="关闭角色窗口" @click="closeRoleDialog">×</button></div><div class="modal-body"><div class="form-grid"><div class="field"><label for="role-code">角色编码 <em>*</em></label><input id="role-code" v-model.trim="roleForm.roleCode" :disabled="Boolean(editingRole)" required maxlength="50"></div><div class="field"><label for="role-name">角色名称 <em>*</em></label><input id="role-name" v-model.trim="roleForm.roleName" required maxlength="50"></div><div class="field"><label for="role-status">状态</label><select id="role-status" v-model="roleForm.status"><option value="ACTIVE">启用</option><option value="INACTIVE">停用</option></select></div><div class="field full"><label for="role-description">角色说明</label><textarea id="role-description" v-model.trim="roleForm.description" rows="2" maxlength="200"></textarea></div></div><div v-if="rolePermissionLoading" class="load-wrap compact-empty"><span class="loader" aria-hidden="true"></span><span>正在加载权限目录…</span></div><div v-else-if="rolePermissionError" class="empty-state compact-empty" role="alert"><strong>权限配置加载失败</strong><span>{{ rolePermissionError }}</span><button class="btn small" type="button" @click="loadRolePermissionData">重试</button></div><div v-else class="permission-editor"><div v-for="section in permissionSections" :key="section.kind" class="permission-column"><div class="section-title"><h2>{{ section.title }}</h2><span>勾选可用权限</span></div><div v-for="group in section.groups" :key="group.key" class="permission-group"><strong>{{ group.label }}</strong><div v-for="item in group.items" :key="item.code" class="permission-option"><template v-if="section.kind === 'field'"><span class="permission-name">{{ item.name }}<small>{{ item.code }}</small></span><span class="field-radios"><span v-for="level in fieldLevels" :key="level.value" class="radio-option"><input v-model="permissionForm.fieldPermissions[item.code]" type="radio" :name="`field-${item.code}`" :value="level.value">{{ level.label }}</span></span></template><template v-else><input v-model="permissionForm.permissionCodes" type="checkbox" :value="item.code"><span class="permission-name">{{ item.name }}<small>{{ item.code }}</small></span></template></div></div></div></div></div><div class="modal-actions"><button class="btn" type="button" :disabled="roleSaving" @click="closeRoleDialog">取消</button><button class="btn primary" type="submit" :disabled="roleSaving || !can('system:role:manage')">{{ roleSaving ? '保存中…' : '保存角色和权限' }}</button></div></form></dialog>
|
||||||
|
|
||||||
|
<dialog ref="groupDialog" class="admin-dialog" aria-labelledby="group-dialog-title" @click.self="closeGroupDialog"><form @submit.prevent="saveGroup"><div class="modal-head"><div><span class="eyebrow">USER GROUP</span><h2 id="group-dialog-title">{{ editingGroup ? '编辑用户组' : '新建用户组' }}</h2><p>用户组信息与人员、角色绑定分开保存。</p></div><button class="modal-close" type="button" aria-label="关闭用户组窗口" @click="closeGroupDialog">×</button></div><div class="modal-body"><div class="form-grid"><div class="field"><label for="group-code">组编码 <em>*</em></label><input id="group-code" v-model.trim="groupForm.groupCode" :disabled="Boolean(editingGroup)" required maxlength="50"></div><div class="field"><label for="group-name">组名称 <em>*</em></label><input id="group-name" v-model.trim="groupForm.groupName" required maxlength="80"></div><div class="field"><label for="group-status">状态</label><select id="group-status" v-model="groupForm.status"><option value="ACTIVE">启用</option><option value="INACTIVE">停用</option></select></div><div class="field full"><label for="group-description">说明</label><textarea id="group-description" v-model.trim="groupForm.description" rows="3" maxlength="200"></textarea></div></div></div><div class="modal-actions"><button class="btn" type="button" :disabled="groupSaving" @click="closeGroupDialog">取消</button><button class="btn primary" type="submit" :disabled="groupSaving || !can('system:group:manage')">{{ groupSaving ? '保存中…' : '保存用户组' }}</button></div></form></dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import { adminApi, type AdminUser, type GroupCandidate, type PermissionItem, type Role, type UserGroup } from '@/api/admin'
|
||||||
|
import { useUserStore } from '@/store/user'
|
||||||
|
|
||||||
|
type Tab = 'users' | 'roles' | 'groups'; type PermissionLevel = 'HIDDEN' | 'READ' | 'EDIT'
|
||||||
|
const userStore = useUserStore(); const activeTab = ref<Tab>('users'); const users = ref<AdminUser[]>([]); const roles = ref<Role[]>([]); const groups = ref<UserGroup[]>([]); const usersLoading = ref(false); const rolesLoading = ref(false); const groupsLoading = ref(false); const usersError = ref(''); const rolesError = ref(''); const groupsError = ref(''); const roleCatalog = ref<PermissionItem[]>([])
|
||||||
|
const permissionsFailed = computed(() => Boolean(userStore.permissionsError)); const legacyAdmin = computed(() => ['ADMIN', 'SUPER_ADMIN'].includes(userStore.userInfo?.userType || '')); const useLegacyFallback = computed(() => userStore.token === 'demo-local-session' || Boolean(userStore.permissionsError)); const can = (permission: string) => userStore.permissionsLoaded && !userStore.permissionsError ? userStore.hasPermission(permission) : useLegacyFallback.value && legacyAdmin.value; const availableTabs = computed(() => (['users', 'roles', 'groups'] as Tab[]).filter(tab => can(`system:${tab === 'users' ? 'user' : tab === 'roles' ? 'role' : 'group'}:view`)))
|
||||||
|
const errorText = (error: unknown) => error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'; const show = async (dialog: HTMLDialogElement | null) => { await nextTick(); if (dialog && !dialog.open) dialog.showModal() }; const close = (dialog: HTMLDialogElement | null) => { if (dialog?.open) dialog.close() }; const switchTab = (tab: Tab) => { activeTab.value = tab; if (tab === 'roles' && !roles.value.length) void loadRoles(); if (tab === 'groups' && !groups.value.length) void loadGroups() }
|
||||||
|
const retryPermissions = async () => { try { await userStore.loadPermissions(true); activeTab.value = availableTabs.value[0] || 'users'; await loadInitialData() } catch (error) { ElMessage.error(errorText(error)) } }
|
||||||
|
const loadUsers = async () => { usersLoading.value = true; usersError.value = ''; try { users.value = await adminApi.listUsers() || [] } catch (error) { usersError.value = errorText(error); ElMessage.error(`用户加载失败:${usersError.value}`) } finally { usersLoading.value = false } }; const loadRoles = async () => { rolesLoading.value = true; rolesError.value = ''; try { roles.value = await adminApi.listRoles() || [] } catch (error) { rolesError.value = errorText(error); ElMessage.error(`角色加载失败:${rolesError.value}`) } finally { rolesLoading.value = false } }; const loadGroups = async () => { groupsLoading.value = true; groupsError.value = ''; try { groups.value = await adminApi.listGroups() || [] } catch (error) { groupsError.value = errorText(error); ElMessage.error(`用户组加载失败:${groupsError.value}`) } finally { groupsLoading.value = false } }; const loadInitialData = async () => { const jobs: Promise<unknown>[] = []; if (can('system:user:view')) jobs.push(loadUsers()); if (can('system:role:view')) jobs.push(loadRoles()); if (can('system:group:view')) jobs.push(loadGroups()); await Promise.all(jobs) }; onMounted(async () => { try { await userStore.loadPermissions(); activeTab.value = availableTabs.value[0] || 'users'; await loadInitialData() } catch (error) { ElMessage.error(errorText(error)) } })
|
||||||
|
const legacyRole = (value?: string) => ['ADMIN', 'FINANCE', 'EMPLOYEE'].includes(value || '') ? value as string : 'EMPLOYEE'; const legacyRoleLabel = (value?: string) => ({ ADMIN: '系统管理员', FINANCE: '财务人员', EMPLOYEE: '普通用户' }[legacyRole(value)] || '普通用户'); const statusSaving = ref<number | null>(null)
|
||||||
|
const updateLegacyRole = async (user: AdminUser, event: Event) => { const previous = user.userType; const next = (event.target as HTMLSelectElement).value; statusSaving.value = user.id; try { const updated = await request.put<AdminUser>(`/auth/users/${user.id}/role`, { userType: next }); Object.assign(user, updated || { userType: next }); ElMessage.success('旧角色已更新') } catch (error) { ElMessage.error(`角色更新失败:${errorText(error)}`); if (previous !== undefined) user.userType = previous } finally { statusSaving.value = null } }; const toggleUserStatus = async (user: AdminUser) => { const next = user.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'; statusSaving.value = user.id; try { const updated = await request.put<AdminUser>(`/auth/users/${user.id}/status`, { status: next }); Object.assign(user, updated || { status: next }); ElMessage.success('状态已更新') } catch (error) { ElMessage.error(`状态更新失败:${errorText(error)}`) } finally { statusSaving.value = null } }
|
||||||
|
const userRoleDialog = ref<HTMLDialogElement | null>(null); const selectedUser = ref<AdminUser | null>(null); const userRoleIds = ref<number[]>([]); const userRoleSaving = ref(false); const openUserRoles = async (user: AdminUser) => { selectedUser.value = user; userRoleIds.value = roles.value.filter(role => user.roleCodes?.includes(role.roleCode)).map(role => role.id); await show(userRoleDialog.value) }; const closeUserRoleDialog = () => { close(userRoleDialog.value); selectedUser.value = null }; const saveUserRoles = async () => { if (!selectedUser.value) return; userRoleSaving.value = true; try { const updated = await adminApi.updateUserRoles(selectedUser.value.id, userRoleIds.value); Object.assign(selectedUser.value, updated || {}); ElMessage.success('用户角色已保存'); closeUserRoleDialog() } catch (error) { ElMessage.error(`用户角色保存失败:${errorText(error)}`) } finally { userRoleSaving.value = false } }
|
||||||
|
const roleDialog = ref<HTMLDialogElement | null>(null); const editingRole = ref<Role | null>(null); const roleSaving = ref(false); const rolePermissionLoading = ref(false); const rolePermissionError = ref(''); const roleForm = reactive({ roleCode: '', roleName: '', description: '', status: 'ACTIVE' as string }); const permissionForm = reactive<{ permissionCodes: string[]; fieldPermissions: Record<string, PermissionLevel> }>({ permissionCodes: [], fieldPermissions: {} }); const fieldLevels: { value: PermissionLevel; label: string }[] = [{ value: 'HIDDEN', label: '隐藏' }, { value: 'READ', label: '只读' }, { value: 'EDIT', label: '编辑' }]
|
||||||
|
const permissionKind = (item: PermissionItem) => { const type = String(item.type || '').toUpperCase(); return type.includes('FIELD') ? 'field' : type.includes('BUTTON') || type.includes('ACTION') ? 'button' : 'menu' }; const permissionSections = computed(() => (['menu', 'button', 'field'].map(kind => { const items = roleCatalog.value.filter(item => permissionKind(item) === kind); const map = new Map<string, PermissionItem[]>(); items.forEach(item => { const key = item.parentCode || item.resource || 'common'; map.set(key, [...(map.get(key) || []), item]) }); return { kind, title: kind === 'menu' ? '菜单权限' : kind === 'button' ? '按钮权限' : '字段权限', groups: [...map.entries()].map(([key, values]) => ({ key, label: key === 'common' ? '通用' : (roleCatalog.value.find(item => item.code === key)?.name || key), items: values })) } })).filter(section => section.groups.length)); const resetPermissionForm = () => { permissionForm.permissionCodes = []; permissionForm.fieldPermissions = {}; roleCatalog.value.filter(item => permissionKind(item) === 'field').forEach(item => { permissionForm.fieldPermissions[item.code] = 'HIDDEN' }) }
|
||||||
|
const loadRolePermissionData = async () => { rolePermissionLoading.value = true; rolePermissionError.value = ''; try { if (!roleCatalog.value.length) roleCatalog.value = await adminApi.listPermissions() || []; resetPermissionForm(); if (editingRole.value) { const current = await adminApi.getRolePermissions(editingRole.value.id); permissionForm.permissionCodes = current?.permissionCodes || []; Object.entries(current?.fieldPermissions || {}).forEach(([code, level]) => { permissionForm.fieldPermissions[code] = level }) } } catch (error) { rolePermissionError.value = errorText(error); ElMessage.error(`权限目录加载失败:${rolePermissionError.value}`) } finally { rolePermissionLoading.value = false } }; const openRoleForm = async (role?: Role) => { editingRole.value = role || null; roleForm.roleCode = role?.roleCode || ''; roleForm.roleName = role?.roleName || ''; roleForm.description = role?.description || ''; roleForm.status = role?.status || 'ACTIVE'; rolePermissionError.value = ''; resetPermissionForm(); await show(roleDialog.value); await loadRolePermissionData() }; const closeRoleDialog = () => { close(roleDialog.value); editingRole.value = null }
|
||||||
|
const saveRole = async () => { if (!roleForm.roleCode || !roleForm.roleName) return; roleSaving.value = true; try { const body = { roleCode: roleForm.roleCode, roleName: roleForm.roleName, description: roleForm.description, status: roleForm.status }; const saved = editingRole.value ? await adminApi.updateRole(editingRole.value.id, body) : await adminApi.createRole(body); if (!saved?.id) throw new Error('角色保存响应无效'); await adminApi.updateRolePermissions(saved.id, { permissionCodes: permissionForm.permissionCodes, fieldPermissions: permissionForm.fieldPermissions }); await loadRoles(); ElMessage.success('角色和权限已保存'); closeRoleDialog() } catch (error) { ElMessage.error(`角色保存失败:${errorText(error)}`) } finally { roleSaving.value = false } }; const deleteRole = async (role: Role) => { try { await ElMessageBox.confirm(`确定删除角色“${role.roleName}”吗?删除后不可恢复。`, '确认删除', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }); await adminApi.deleteRole(role.id); roles.value = roles.value.filter(item => item.id !== role.id); ElMessage.success('角色已删除') } catch (error: unknown) { if (error !== 'cancel' && error !== 'close') ElMessage.error(`角色删除失败:${errorText(error)}`) } }; const toggleRoleStatus = async (role: Role) => { try { const updated = await adminApi.updateRole(role.id, { status: role.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE' }); Object.assign(role, updated || {}); ElMessage.success('角色状态已更新') } catch (error) { ElMessage.error(`角色状态更新失败:${errorText(error)}`) } }
|
||||||
|
const groupDialog = ref<HTMLDialogElement | null>(null); const editingGroup = ref<UserGroup | null>(null); const groupSaving = ref(false); const groupForm = reactive({ groupCode: '', groupName: '', description: '', status: 'ACTIVE' as string }); const openGroupForm = async (group?: UserGroup) => { editingGroup.value = group || null; groupForm.groupCode = group?.groupCode || ''; groupForm.groupName = group?.groupName || ''; groupForm.description = group?.description || ''; groupForm.status = group?.status || 'ACTIVE'; await show(groupDialog.value) }; const closeGroupDialog = () => { close(groupDialog.value); editingGroup.value = null }; const saveGroup = async () => { if (!groupForm.groupCode || !groupForm.groupName) return; groupSaving.value = true; try { const body = { groupCode: groupForm.groupCode, groupName: groupForm.groupName, description: groupForm.description, status: groupForm.status }; const saved = editingGroup.value ? await adminApi.updateGroup(editingGroup.value.id, body) : await adminApi.createGroup(body); if (editingGroup.value) Object.assign(editingGroup.value, saved || body); else groups.value.unshift(saved); ElMessage.success('用户组已保存'); closeGroupDialog() } catch (error) { ElMessage.error(`用户组保存失败:${errorText(error)}`) } finally { groupSaving.value = false } }; const deleteGroup = async (group: UserGroup) => { try { await ElMessageBox.confirm(`确定删除用户组“${group.groupName}”吗?绑定关系也会被移除。`, '确认删除', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }); await adminApi.deleteGroup(group.id); groups.value = groups.value.filter(item => item.id !== group.id); if (selectedGroup.value?.id === group.id) selectedGroup.value = null; ElMessage.success('用户组已删除') } catch (error: unknown) { if (error !== 'cancel' && error !== 'close') ElMessage.error(`用户组删除失败:${errorText(error)}`) } }
|
||||||
|
const selectedGroup = ref<UserGroup | null>(null); const groupDetailLoading = ref(false); const groupDetailError = ref(''); const candidates = ref<GroupCandidate[]>([]); const candidateLoading = ref(false); const candidateKeyword = ref(''); const candidateDepartment = ref(''); const selectedMemberIds = ref<number[]>([]); const selectedGroupRoleIds = ref<number[]>([]); const savingBinding = ref<'members' | 'roles' | ''>(''); const candidateDepartments = computed(() => [...new Set(candidates.value.map(candidate => candidate.departmentName).filter(Boolean) as string[])]); const filteredCandidates = computed(() => candidates.value.filter(candidate => { const query = candidateKeyword.value.toLowerCase(); const text = [candidate.realName, candidate.employeeNo, candidate.departmentName, candidate.feishuOpenId, candidate.feishuUserId].join(' ').toLowerCase(); return (!query || text.includes(query)) && (!candidateDepartment.value || candidate.departmentName === candidateDepartment.value) })); const maskId = (value?: string) => { const text = String(value || '').trim(); if (!text) return '-'; if (text.length <= 4) return '••••'; return `${text.slice(0, 2)}••••${text.slice(-2)}` }
|
||||||
|
const openGroupDetail = async (group: UserGroup) => { selectedGroup.value = group; groupDetailLoading.value = true; groupDetailError.value = ''; candidateKeyword.value = ''; candidateDepartment.value = ''; try { candidateLoading.value = true; const [members, assignedRoles, people] = await Promise.all([adminApi.getGroupMembers(group.id), adminApi.getGroupRoles(group.id), adminApi.listCandidates()]); selectedMemberIds.value = members?.userIds || []; selectedGroupRoleIds.value = assignedRoles?.roleIds || []; candidates.value = people || [] } catch (error) { groupDetailError.value = errorText(error); ElMessage.error(`用户组详情加载失败:${groupDetailError.value}`) } finally { candidateLoading.value = false; groupDetailLoading.value = false } }; const saveGroupMembers = async () => { if (!selectedGroup.value) return; savingBinding.value = 'members'; try { await adminApi.updateGroupMembers(selectedGroup.value.id, selectedMemberIds.value); selectedGroup.value.memberCount = selectedMemberIds.value.length; const item = groups.value.find(group => group.id === selectedGroup.value?.id); if (item) item.memberCount = selectedMemberIds.value.length; ElMessage.success('人员绑定已保存') } catch (error) { ElMessage.error(`人员绑定保存失败:${errorText(error)}`) } finally { savingBinding.value = '' } }; const saveGroupRoles = async () => { if (!selectedGroup.value) return; savingBinding.value = 'roles'; try { await adminApi.updateGroupRoles(selectedGroup.value.id, selectedGroupRoleIds.value); selectedGroup.value.roleCount = selectedGroupRoleIds.value.length; const item = groups.value.find(group => group.id === selectedGroup.value?.id); if (item) item.roleCount = selectedGroupRoleIds.value.length; ElMessage.success('角色绑定已保存') } catch (error) { ElMessage.error(`角色绑定保存失败:${errorText(error)}`) } finally { savingBinding.value = '' } }
|
||||||
|
const toggleGroupStatus = async (group: UserGroup) => { try { const updated = await adminApi.updateGroup(group.id, { status: group.status === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE' }); Object.assign(group, updated || {}); ElMessage.success('用户组状态已更新') } catch (error) { ElMessage.error(`用户组状态更新失败:${errorText(error)}`) } }
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.admin-card{min-width:0}.role-cell{min-width:230px}.role-cell .tag{margin:2px 4px 2px 0}.legacy-role{display:block;width:150px;height:30px;margin-top:5px;padding:2px 8px;font-size:11px}.status-button{display:inline-flex;align-items:center;gap:6px;min-height:29px;padding:4px 7px;border:1px solid transparent;border-radius:5px;background:transparent;color:var(--body);font-size:11px}.status-button:hover{border-color:var(--line);background:var(--surface-raised)}.status-button.active{color:var(--success)}.status-button.inactive{color:var(--danger)}.status-dot-small{width:7px;height:7px;border-radius:50%;background:currentColor}.actions-cell{min-width:190px}.danger-action{color:var(--danger)}.group-layout{display:grid;grid-template-columns:minmax(420px,.9fr) minmax(430px,1.1fr);align-items:start;gap:16px}.group-detail{min-width:0}.group-detail .card-head{align-items:flex-start}.group-detail .card-head h2{margin-top:3px}.link-button{display:block;border:0;background:transparent;color:inherit;text-align:left}.link-button:hover strong{color:var(--blue)}.data-table tr.selected{background:var(--blue-soft)}.binding-section+.binding-section{border-top:1px solid var(--line)}.candidate-list{max-height:390px;overflow-y:auto}.candidate-row{display:flex;min-width:0;align-items:center;gap:10px;padding:11px 18px;border-bottom:1px solid var(--line);cursor:pointer}.candidate-row:hover{background:#fbfcfe}.candidate-row>input,.check-option>input,.permission-option>input{flex:none;width:16px;height:16px;accent-color:var(--blue)}.candidate-copy{min-width:145px;flex:1}.candidate-copy strong,.candidate-copy span,.candidate-ids small{display:block}.candidate-copy strong{font-size:12px}.candidate-copy strong small{display:inline;margin-left:5px;color:var(--quiet);font:10px var(--mono)}.candidate-copy span{color:var(--muted);font-size:11px}.candidate-ids{min-width:145px;color:var(--quiet);font:10px var(--mono);text-align:right}.binding-actions{display:flex;justify-content:flex-end;padding:12px 18px;border-top:1px solid var(--line);background:var(--surface-raised)}.role-options{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px;padding:16px 18px}.check-option{display:flex;min-width:0;align-items:flex-start;gap:9px;padding:10px;border:1px solid var(--line);border-radius:6px;background:#fff;cursor:pointer}.check-option:hover{border-color:#b9d2ee;background:var(--blue-soft)}.check-option span,.check-option strong,.check-option small{display:block;min-width:0}.check-option strong{font-size:12px}.check-option small{margin-top:2px;overflow:hidden;color:var(--muted);font-size:10px;text-overflow:ellipsis}.admin-dialog{width:min(650px,calc(100vw - 24px));max-height:min(90vh,820px);padding:0;border:0;border-radius:10px;overflow:auto;box-shadow:0 24px 70px rgba(16,42,67,.28)}.wide-dialog{width:min(1000px,calc(100vw - 24px))}.admin-dialog::backdrop{background:rgba(16,42,67,.52)}.admin-dialog .modal-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;padding:18px 21px;border-bottom:1px solid var(--line)}.admin-dialog .modal-head h2{margin-top:3px;font-size:17px}.admin-dialog .modal-head p{margin-top:3px;color:var(--muted);font-size:12px}.admin-dialog .modal-body{padding:0}.admin-dialog .form-grid{padding:19px 21px}.admin-dialog .modal-actions{position:sticky;bottom:0;z-index:1}.permission-editor{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:1px;background:var(--line);border-top:1px solid var(--line)}.permission-column{min-width:0;background:#fff}.permission-column .section-title{padding:13px 15px}.permission-column .section-title h2{font-size:13px}.permission-group{padding:11px 15px 5px}.permission-group>strong{display:block;margin-bottom:7px;color:var(--muted);font-size:11px}.permission-option{display:flex;min-width:0;align-items:center;gap:7px;padding:5px 0;cursor:pointer;font-size:11px}.permission-name{min-width:0;flex:1}.permission-name small{display:block;overflow:hidden;color:var(--quiet);font:10px var(--mono);text-overflow:ellipsis}.field-radios{display:flex;flex-wrap:wrap;gap:5px;color:var(--muted);font-size:10px;white-space:nowrap}.radio-option{display:inline-flex!important;align-items:center;gap:2px;cursor:pointer}.radio-option input{width:13px;height:13px;accent-color:var(--blue)}.compact-empty{min-height:100px}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(max-width:980px){.group-layout{grid-template-columns:1fr}.permission-editor{grid-template-columns:1fr}}@media(max-width:620px){.role-options{grid-template-columns:1fr}.candidate-row{align-items:flex-start}.candidate-ids{min-width:0;text-align:left}.candidate-copy{min-width:0}.admin-dialog .form-grid{grid-template-columns:1fr}}
|
||||||
|
/* Only the active list grows; dialogs retain their existing width/height. */
|
||||||
|
.admin-card,
|
||||||
|
.group-detail { display: flex; flex-direction: column; }
|
||||||
|
.admin-card { flex: 1 0 auto; }
|
||||||
|
.admin-card > .empty-state,
|
||||||
|
.admin-card > .load-wrap,
|
||||||
|
.group-detail > .empty-state,
|
||||||
|
.group-detail > .load-wrap { flex: 1 0 auto; }
|
||||||
|
.group-layout { flex: 1 0 auto; grid-template-columns: minmax(0, 1fr); align-items: stretch; }
|
||||||
|
.has-group-detail .group-layout { grid-template-columns: minmax(0, .9fr) minmax(0, 1.1fr); }
|
||||||
|
.candidate-row { flex-wrap: wrap; }
|
||||||
|
.candidate-copy { min-width: 0; }
|
||||||
|
.candidate-ids { min-width: 0; max-width: 100%; overflow-wrap: anywhere; }
|
||||||
|
.group-detail .filter-search { min-width: 0; flex: 1 1 240px; }
|
||||||
|
.group-detail .filter-bar label { max-width: 100%; }
|
||||||
|
.group-detail .select { max-width: 100%; }
|
||||||
|
@media (max-width: 1180px) {
|
||||||
|
.has-group-detail .group-layout { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
}
|
||||||
|
@media (max-width: 560px) {
|
||||||
|
.candidate-ids { flex-basis: 100%; padding-left: 26px; text-align: left; }
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
export default {
|
||||||
|
content: [
|
||||||
|
"./index.html",
|
||||||
|
"./src/**/*.{vue,js,ts,jsx,tsx}",
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
primary: {
|
||||||
|
50: '#eff6ff',
|
||||||
|
100: '#dbeafe',
|
||||||
|
200: '#bfdbfe',
|
||||||
|
300: '#93c5fd',
|
||||||
|
400: '#60a5fa',
|
||||||
|
500: '#3b82f6',
|
||||||
|
600: '#2563eb',
|
||||||
|
700: '#1d4ed8',
|
||||||
|
800: '#1e40af',
|
||||||
|
900: '#1e3a8a',
|
||||||
|
},
|
||||||
|
finance: {
|
||||||
|
blue: '#1a73e8',
|
||||||
|
green: '#0f9d58',
|
||||||
|
orange: '#f9ab00',
|
||||||
|
red: '#ea4335',
|
||||||
|
}
|
||||||
|
},
|
||||||
|
animation: {
|
||||||
|
'fade-in': 'fadeIn 0.3s ease-out',
|
||||||
|
'slide-up': 'slideUp 0.3s ease-out',
|
||||||
|
'slide-down': 'slideDown 0.3s ease-out',
|
||||||
|
'scale-in': 'scaleIn 0.2s ease-out',
|
||||||
|
'pulse-slow': 'pulse 3s infinite',
|
||||||
|
},
|
||||||
|
keyframes: {
|
||||||
|
fadeIn: {
|
||||||
|
'0%': { opacity: '0' },
|
||||||
|
'100%': { opacity: '1' },
|
||||||
|
},
|
||||||
|
slideUp: {
|
||||||
|
'0%': { transform: 'translateY(10px)', opacity: '0' },
|
||||||
|
'100%': { transform: 'translateY(0)', opacity: '1' },
|
||||||
|
},
|
||||||
|
slideDown: {
|
||||||
|
'0%': { transform: 'translateY(-10px)', opacity: '0' },
|
||||||
|
'100%': { transform: 'translateY(0)', opacity: '1' },
|
||||||
|
},
|
||||||
|
scaleIn: {
|
||||||
|
'0%': { transform: 'scale(0.95)', opacity: '0' },
|
||||||
|
'100%': { transform: 'scale(1)', opacity: '1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [],
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ES2020",
|
||||||
|
"useDefineForClassFields": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"jsx": "preserve",
|
||||||
|
"strict": true,
|
||||||
|
"noUnusedLocals": false,
|
||||||
|
"noUnusedParameters": false,
|
||||||
|
"noFallthroughCasesInSwitch": true,
|
||||||
|
"paths": {
|
||||||
|
"@/*": ["./src/*"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||||
|
"references": [{ "path": "./tsconfig.node.json" }]
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"composite": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"allowSyntheticDefaultImports": true
|
||||||
|
},
|
||||||
|
"include": ["vite.config.ts"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import path from 'path'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': path.resolve(__dirname, 'src'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': {
|
||||||
|
target: 'http://127.0.0.1:8080',
|
||||||
|
changeOrigin: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||