优化第一次
This commit is contained in:
1 parent
3a4e81a070
commit
459339719d
83 files changed
+7001
-1767
No files matched your search
+2
-2
@@ -41,7 +41,7 @@ const clearSessionAndRedirect = () => {
|
||||
|
||||
const checkDailySession = () => {
|
||||
const hadSession = Boolean(
|
||||
localStorage.getItem(TOKEN_KEY) ||
|
||||
sessionStorage.getItem(TOKEN_KEY) ||
|
||||
localStorage.getItem(USER_INFO_KEY) ||
|
||||
localStorage.getItem(AUTH_DAY_KEY) ||
|
||||
userStore.token,
|
||||
@@ -67,7 +67,7 @@ const handleStorage = (event: StorageEvent) => {
|
||||
if (storageSyncTimer !== null) window.clearTimeout(storageSyncTimer)
|
||||
storageSyncTimer = window.setTimeout(() => {
|
||||
storageSyncTimer = null
|
||||
const token = localStorage.getItem(TOKEN_KEY)
|
||||
const token = sessionStorage.getItem(TOKEN_KEY)
|
||||
const valid = userStore.ensureDailyAuth()
|
||||
if (!valid || !token) {
|
||||
clearSessionAndRedirect()
|
||||
|
||||
+206
-41
@@ -1,24 +1,7 @@
|
||||
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 type PermissionAccess = 'HIDDEN' | 'READ' | 'EDIT'
|
||||
|
||||
export interface Role {
|
||||
id: number
|
||||
@@ -31,17 +14,27 @@ export interface Role {
|
||||
permissionCount?: number
|
||||
}
|
||||
|
||||
export type RolePayload = Pick<Role, 'roleCode' | 'roleName' | 'description' | 'status'>
|
||||
|
||||
export interface PermissionItem {
|
||||
code: string
|
||||
name: string
|
||||
type: string
|
||||
/** ACTION and legacy BUTTON both represent editable operations. Unknown values remain accepted for compatibility. */
|
||||
type: 'MODULE' | 'PAGE' | 'MENU' | 'FIELD' | 'ACTION' | 'BUTTON' | (string & {})
|
||||
parentCode?: string
|
||||
resource?: string
|
||||
defaultAccess?: PermissionAccess
|
||||
}
|
||||
|
||||
export interface RolePermissions {
|
||||
permissionCodes: string[]
|
||||
fieldPermissions: Record<string, 'HIDDEN' | 'READ' | 'EDIT'>
|
||||
fieldPermissions: Record<string, PermissionAccess>
|
||||
permissionAccess: Record<string, PermissionAccess>
|
||||
}
|
||||
|
||||
export interface UpdateRolePermissionsPayload extends RolePermissions {
|
||||
/** Snapshot read before editing; server rejects stale concurrent edits with 409. */
|
||||
expectedPermissionAccess: Record<string, PermissionAccess>
|
||||
}
|
||||
|
||||
export interface UserGroup {
|
||||
@@ -50,18 +43,81 @@ export interface UserGroup {
|
||||
groupName: string
|
||||
description?: string
|
||||
status: Status | string
|
||||
memberCount?: number
|
||||
roleCount?: number
|
||||
builtIn: boolean
|
||||
membershipMode: 'DYNAMIC' | 'EXPLICIT'
|
||||
memberCount: number | null
|
||||
membershipResolved: boolean
|
||||
snapshotState?: string | null
|
||||
roleCount: number
|
||||
}
|
||||
|
||||
export type UserGroupPayload = Pick<UserGroup, 'groupCode' | 'groupName' | 'description' | 'status'>
|
||||
|
||||
export interface DirectoryIdentity {
|
||||
/** Identity alias for the directory's currentRevision. */
|
||||
generationId: string
|
||||
openId: string
|
||||
/** Legacy identity hint. Directory v1 identities are keyed by openId. */
|
||||
userId?: string | null
|
||||
}
|
||||
|
||||
export interface GroupCandidate {
|
||||
id: number
|
||||
id: number | null
|
||||
realName: string
|
||||
employeeNo?: string
|
||||
employeeNo?: string | null
|
||||
/** @deprecated Legacy candidate endpoint compatibility. */
|
||||
departmentName?: string
|
||||
departmentNames: string[]
|
||||
feishuOpenId?: string
|
||||
feishuUserId?: string
|
||||
status: string
|
||||
/** @deprecated Legacy candidate endpoint compatibility. */
|
||||
status?: string
|
||||
assignedGroupId: number | null
|
||||
assignedGroupName?: string | null
|
||||
eligible: boolean
|
||||
selectable: boolean
|
||||
directoryIdentity?: DirectoryIdentity
|
||||
}
|
||||
|
||||
export type GroupMemberSnapshotState = 'FRESH' | 'NEVER_SYNCED' | 'STALE' | 'CONTEXT_CHANGED' | 'UNAVAILABLE'
|
||||
export type DirectoryAvailabilityState = 'AVAILABLE' | 'NEVER_SYNCED' | 'UNAVAILABLE'
|
||||
export type DirectoryContextState = 'MATCH' | 'CHANGED' | 'UNKNOWN'
|
||||
|
||||
export interface GroupMemberCandidates {
|
||||
snapshotState: GroupMemberSnapshotState
|
||||
/** Optional while older backend nodes are still serving traffic. */
|
||||
availabilityState?: DirectoryAvailabilityState | null
|
||||
additionsAllowed?: boolean
|
||||
currentRevision?: string | null
|
||||
contextState?: DirectoryContextState | null
|
||||
currentMembers: GroupCandidate[]
|
||||
matches: GroupCandidate[]
|
||||
blockedMatchesPresent: boolean
|
||||
limit: number
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export interface GroupMembers {
|
||||
userIds: number[]
|
||||
dynamic: boolean
|
||||
editable: boolean
|
||||
membershipResolved: boolean
|
||||
snapshotState?: string | null
|
||||
}
|
||||
|
||||
export interface UpdateGroupMembersPayload {
|
||||
userIds: number[]
|
||||
directoryIdentities: DirectoryIdentity[]
|
||||
expectedUserIds: number[]
|
||||
}
|
||||
|
||||
export interface UpdateGroupMembersResponse {
|
||||
userIds: number[]
|
||||
}
|
||||
|
||||
export interface UpdateGroupRolesPayload {
|
||||
roleIds: number[]
|
||||
expectedRoleIds: number[]
|
||||
}
|
||||
|
||||
export interface IntegrationField {
|
||||
@@ -70,51 +126,160 @@ export interface IntegrationField {
|
||||
value?: unknown
|
||||
secret: boolean
|
||||
configured: boolean
|
||||
readOnly?: boolean
|
||||
inputType?: 'text' | 'password' | 'url' | 'boolean'
|
||||
placeholder?: string
|
||||
helpText?: string
|
||||
}
|
||||
|
||||
export interface IntegrationProvider {
|
||||
enabled: boolean
|
||||
readOnly?: boolean
|
||||
source?: string
|
||||
fields: IntegrationField[]
|
||||
}
|
||||
|
||||
export interface IntegrationConfig {
|
||||
feishu: IntegrationProvider
|
||||
kingdee: IntegrationProvider
|
||||
kingdee?: IntegrationProvider
|
||||
}
|
||||
|
||||
export interface FeishuApprovalDefinitionSyncResult {
|
||||
success?: boolean
|
||||
message?: string
|
||||
syncedAt?: string
|
||||
fetchedAt?: string
|
||||
approvalCode?: string
|
||||
eventSubscribed?: boolean
|
||||
changed?: boolean
|
||||
nodeCount?: number
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export type KingdeeSyncConfigId = number | string
|
||||
export type KingdeeSyncDataType = 'STRING' | 'INTEGER' | 'BIGINT' | 'DECIMAL' | 'DATE' | 'DATETIME' | 'BOOLEAN' | 'JSON'
|
||||
export type KingdeeSyncFilterOperator = 'EQ' | 'NE' | 'GT' | 'GE' | 'LT' | 'LE' | 'LIKE' | 'IN'
|
||||
|
||||
export interface KingdeeSyncField {
|
||||
sourceFieldKey: string
|
||||
targetColumnName: string
|
||||
fieldComment: string
|
||||
dataType: KingdeeSyncDataType
|
||||
fieldLength: number | null
|
||||
sortOrder: number
|
||||
}
|
||||
|
||||
export interface KingdeeSyncFilter {
|
||||
sourceFieldKey: string
|
||||
operator: KingdeeSyncFilterOperator
|
||||
filterValue: string
|
||||
sortOrder: number
|
||||
}
|
||||
|
||||
export interface KingdeeSyncConfigPayload {
|
||||
configName: string
|
||||
formId: string
|
||||
targetTableName: string
|
||||
targetTableComment: string
|
||||
enabled: boolean
|
||||
maxRowsPerRun: number
|
||||
fields: KingdeeSyncField[]
|
||||
filters: KingdeeSyncFilter[]
|
||||
}
|
||||
|
||||
export interface KingdeeSyncConfig extends KingdeeSyncConfigPayload {
|
||||
id: KingdeeSyncConfigId
|
||||
createdAt?: string
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
export interface KingdeeSyncPreview {
|
||||
filterString: string
|
||||
rows: Array<Record<string, unknown>>
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export type KingdeeSyncRunStatus = 'RUNNING' | 'SUCCEEDED' | 'PARTIAL' | 'FAILED'
|
||||
|
||||
export interface KingdeeSyncRun {
|
||||
id: KingdeeSyncConfigId
|
||||
fetchedCount: number | null
|
||||
insertedCount: number | null
|
||||
updatedCount: number | null
|
||||
failedCount: number | null
|
||||
status: KingdeeSyncRunStatus
|
||||
startedAt: string | null
|
||||
finishedAt: string | null
|
||||
errorMessage: string | null
|
||||
configId?: KingdeeSyncConfigId
|
||||
filterString?: string | null
|
||||
}
|
||||
|
||||
export interface KingdeePrepareTableResult {
|
||||
success?: boolean
|
||||
message?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
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> =>
|
||||
createRole: (body: RolePayload): Promise<Role> =>
|
||||
request.post('/roles', body),
|
||||
updateRole: (id: number, body: Partial<Pick<Role, 'roleCode' | 'roleName' | 'description' | 'status'>>): Promise<Role> =>
|
||||
updateRole: (id: number, body: RolePayload): 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> =>
|
||||
updateRolePermissions: (id: number, body: UpdateRolePermissionsPayload): 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> =>
|
||||
createGroup: (body: UserGroupPayload): Promise<UserGroup> =>
|
||||
request.post('/user-groups', body),
|
||||
updateGroup: (id: number, body: Partial<Pick<UserGroup, 'groupCode' | 'groupName' | 'description' | 'status'>>): Promise<UserGroup> =>
|
||||
updateGroup: (id: number, body: UserGroupPayload): 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'),
|
||||
updateGroupRoles: (id: number, body: UpdateGroupRolesPayload): Promise<void> =>
|
||||
request.put(`/user-groups/${id}/roles`, body, { suppressErrorNotification: true }),
|
||||
getGroupMembers: (id: number): Promise<GroupMembers> => request.get(`/user-groups/${id}/members`),
|
||||
updateGroupMembers: (id: number, body: UpdateGroupMembersPayload): Promise<UpdateGroupMembersResponse> =>
|
||||
request.put(`/user-groups/${id}/members`, body, { suppressErrorNotification: true }),
|
||||
listCandidates: (groupId?: number, q?: string): Promise<GroupCandidate[]> => {
|
||||
const query = q?.trim()
|
||||
const params = {
|
||||
...(groupId === undefined ? {} : { groupId }),
|
||||
...(query ? { q: query } : {}),
|
||||
}
|
||||
return request.get('/user-groups/candidates', Object.keys(params).length ? { params } : undefined)
|
||||
},
|
||||
searchGroupMemberCandidates: (groupId: number, q = ''): Promise<GroupMemberCandidates> =>
|
||||
request.get(`/user-groups/${groupId}/member-candidates`, { params: { q: q.trim() } }),
|
||||
|
||||
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 }),
|
||||
syncFeishuApprovalDefinition: (): Promise<FeishuApprovalDefinitionSyncResult> =>
|
||||
request.post('/feishu/approval/definition/sync', undefined, { suppressErrorNotification: true }),
|
||||
|
||||
listKingdeeSyncConfigs: (): Promise<KingdeeSyncConfig[]> =>
|
||||
request.get('/integrations/kingdee/sync-configs'),
|
||||
createKingdeeSyncConfig: (body: KingdeeSyncConfigPayload): Promise<KingdeeSyncConfig> =>
|
||||
request.post('/integrations/kingdee/sync-configs', body),
|
||||
getKingdeeSyncConfig: (id: KingdeeSyncConfigId): Promise<KingdeeSyncConfig> =>
|
||||
request.get(`/integrations/kingdee/sync-configs/${id}`),
|
||||
updateKingdeeSyncConfig: (id: KingdeeSyncConfigId, body: KingdeeSyncConfigPayload): Promise<KingdeeSyncConfig> =>
|
||||
request.put(`/integrations/kingdee/sync-configs/${id}`, body),
|
||||
deleteKingdeeSyncConfig: (id: KingdeeSyncConfigId): Promise<void> =>
|
||||
request.delete(`/integrations/kingdee/sync-configs/${id}`),
|
||||
previewKingdeeSyncConfig: (id: KingdeeSyncConfigId): Promise<KingdeeSyncPreview> =>
|
||||
request.post(`/integrations/kingdee/sync-configs/${id}/preview`),
|
||||
prepareKingdeeSyncTable: (id: KingdeeSyncConfigId): Promise<KingdeePrepareTableResult> =>
|
||||
request.post(`/integrations/kingdee/sync-configs/${id}/prepare-table`),
|
||||
syncKingdeeConfig: (id: KingdeeSyncConfigId): Promise<KingdeeSyncRun> =>
|
||||
request.post(`/integrations/kingdee/sync-configs/${id}/sync`),
|
||||
listKingdeeSyncRuns: (id: KingdeeSyncConfigId): Promise<KingdeeSyncRun[]> =>
|
||||
request.get(`/integrations/kingdee/sync-configs/${id}/runs`),
|
||||
}
|
||||
@@ -9,6 +9,8 @@ export interface UserProfile {
|
||||
departmentName: string
|
||||
position: string
|
||||
userType: string
|
||||
roleCodes?: string[]
|
||||
isSuperAdmin?: boolean
|
||||
status: string
|
||||
feishuStatus: string
|
||||
lastLoginAt: string
|
||||
|
||||
+1
-1
@@ -29,7 +29,7 @@ const item = (id: string, title: string, owner: string, department: string, amou
|
||||
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 }],
|
||||
expenseItems: [{ id: `${id}-1`, seqNo: 1, expenseDate: date, category, description: title, amount, attachmentIds: [] }],
|
||||
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: [],
|
||||
})
|
||||
|
||||
+38
-11
@@ -1,10 +1,34 @@
|
||||
import request from './request'
|
||||
|
||||
export type DirectorySnapshotState = 'UNAVAILABLE' | 'NEVER_SYNCED' | 'FRESH' | 'STALE' | 'CONTEXT_CHANGED'
|
||||
export type DirectoryAvailabilityState = 'AVAILABLE' | 'NEVER_SYNCED' | 'UNAVAILABLE'
|
||||
export type DirectoryContextState = 'MATCH' | 'CHANGED' | 'UNKNOWN'
|
||||
|
||||
export interface DirectoryAvailabilityContract {
|
||||
snapshotState: DirectorySnapshotState
|
||||
/** Additive fields are optional for rolling compatibility with older nodes. */
|
||||
availabilityState?: DirectoryAvailabilityState | null
|
||||
additionsAllowed?: boolean
|
||||
currentRevision?: string | null
|
||||
contextState?: DirectoryContextState | null
|
||||
}
|
||||
|
||||
export const directoryAvailability = (value: DirectoryAvailabilityContract): DirectoryAvailabilityState => {
|
||||
if (value.availabilityState === 'AVAILABLE' || value.availabilityState === 'NEVER_SYNCED' || value.availabilityState === 'UNAVAILABLE') {
|
||||
return value.availabilityState
|
||||
}
|
||||
// Older backends did not expose availability. Only their FRESH state is safe
|
||||
// to treat as usable; all other legacy states deliberately fail closed.
|
||||
return value.snapshotState === 'FRESH'
|
||||
? 'AVAILABLE'
|
||||
: value.snapshotState === 'NEVER_SYNCED' ? 'NEVER_SYNCED' : 'UNAVAILABLE'
|
||||
}
|
||||
|
||||
export interface DirectoryRun {
|
||||
runId: string
|
||||
trigger: 'MANUAL' | 'STARTUP'
|
||||
trigger: 'MANUAL' | 'STARTUP' | 'SCHEDULED'
|
||||
state: 'RUNNING' | 'SUCCEEDED' | 'FAILED'
|
||||
startedAt: string
|
||||
startedAt: string | null
|
||||
finishedAt: string | null
|
||||
complete: boolean
|
||||
applied: boolean
|
||||
@@ -13,10 +37,9 @@ export interface DirectoryRun {
|
||||
errorMessage: string | null
|
||||
}
|
||||
|
||||
export interface DirectoryStatus {
|
||||
export interface DirectoryStatus extends DirectoryAvailabilityContract {
|
||||
configured: boolean
|
||||
running: boolean
|
||||
snapshotState: 'UNAVAILABLE' | 'NEVER_SYNCED' | 'FRESH' | 'STALE' | 'CONTEXT_CHANGED'
|
||||
maxStatusAgeSeconds: number
|
||||
lastSuccessfulRunId: string | null
|
||||
lastSuccessfulAt: string | null
|
||||
@@ -36,19 +59,16 @@ export interface DirectoryDepartment {
|
||||
|
||||
export interface DirectoryOrganizationUser {
|
||||
openId: string
|
||||
userId: string
|
||||
userId: string | null
|
||||
name: string
|
||||
email: string
|
||||
mobile: string
|
||||
jobTitle: string
|
||||
employeeType: number | null
|
||||
avatarUrl: string
|
||||
employmentStatus: string
|
||||
departmentIds: string[]
|
||||
}
|
||||
|
||||
export interface DirectoryOrganization {
|
||||
snapshotState: DirectoryStatus['snapshotState']
|
||||
export interface DirectoryOrganization extends DirectoryAvailabilityContract {
|
||||
lastSuccessfulAt: string | null
|
||||
departments: DirectoryDepartment[]
|
||||
users: DirectoryOrganizationUser[]
|
||||
@@ -61,6 +81,13 @@ export const feishuDirectoryApi = {
|
||||
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 }),
|
||||
/** Departments (+ optional full users). Default omits users so the shell paints quickly. */
|
||||
organization: (signal?: AbortSignal, includeUsers = false): Promise<DirectoryOrganization> =>
|
||||
request.get('/feishu/directory/organization', { signal, params: { includeUsers } }),
|
||||
/** Members for one department tree; used after the organization shell is ready. */
|
||||
organizationMembers: (departmentId: string, signal?: AbortSignal, includeDescendants = true): Promise<DirectoryOrganization> =>
|
||||
request.get('/feishu/directory/organization/members', {
|
||||
signal,
|
||||
params: { departmentId, includeDescendants },
|
||||
}),
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import request from './request'
|
||||
|
||||
export interface KingdeeAccountBinding {
|
||||
userId: number
|
||||
realName: string
|
||||
employeeNo?: string | null
|
||||
status?: string | null
|
||||
bound: boolean
|
||||
kingdeeUsername?: string | null
|
||||
boundAt?: string | null
|
||||
updatedAt?: string | null
|
||||
boundBy?: number | null
|
||||
}
|
||||
|
||||
export const kingdeeAccountsApi = {
|
||||
list: (): Promise<KingdeeAccountBinding[]> => request.get('/kingdee/account-bindings'),
|
||||
me: (): Promise<KingdeeAccountBinding> => request.get('/kingdee/account-bindings/me'),
|
||||
bind: (userId: number, body: { kingdeeUsername: string; kingdeePassword: string; verifyLogin?: boolean }): Promise<KingdeeAccountBinding> =>
|
||||
request.put(`/kingdee/account-bindings/${userId}`, body),
|
||||
unbind: (userId: number): Promise<void> => request.delete(`/kingdee/account-bindings/${userId}`),
|
||||
test: (userId: number): Promise<{ success: boolean; message: string }> =>
|
||||
request.post(`/kingdee/account-bindings/${userId}/test`),
|
||||
}
|
||||
+120
-4
@@ -65,6 +65,57 @@ export interface ReimApplicationDetail {
|
||||
payments: PaymentRecord[]
|
||||
paidAmountSnapshot?: number
|
||||
remainingAmountSnapshot?: number
|
||||
formSnapshot?: ReimbursementFormSnapshot
|
||||
}
|
||||
|
||||
export type ReimbursementFormMode = 'FEISHU' | 'LOCAL'
|
||||
export type ReimbursementFormSnapshotMode = ReimbursementFormMode | 'LEGACY'
|
||||
export type ReimbursementFormFieldType = 'TEXT' | 'TEXTAREA' | 'DECIMAL' | 'DATE' | 'SINGLE_SELECT' | 'MULTI_SELECT' | 'CONTACT' | 'DEPARTMENT' | 'DISPLAY' | 'EXPENSE_ITEMS' | 'ATTACHMENT' | 'FORMULA'
|
||||
export type ReimbursementFormFieldBinding = 'APPLICATION_NO' | 'TITLE' | 'APPLICANT_NAME' | 'APPLICANT_CONTACT' | 'APPLICANT_DEPARTMENT' | 'DEPARTMENT' | 'EXPENSE_TYPE' | 'TOTAL_AMOUNT' | 'DESCRIPTION' | 'SOURCE_DOC_NO' | 'EXPENSE_ITEMS' | 'EXPENSE_DATE' | 'EXPENSE_CATEGORY' | 'EXPENSE_DESCRIPTION' | 'EXPENSE_AMOUNT' | 'EXPENSE_ATTACHMENT' | 'CUSTOM'
|
||||
|
||||
export interface ReimbursementFormOption {
|
||||
value: string
|
||||
label: string
|
||||
}
|
||||
|
||||
export interface ReimbursementFormField {
|
||||
id: string
|
||||
customId?: string
|
||||
valueKey: string
|
||||
providerType?: string
|
||||
type: ReimbursementFormFieldType
|
||||
binding: ReimbursementFormFieldBinding
|
||||
label: string
|
||||
required: boolean
|
||||
readOnly: boolean
|
||||
currency?: string
|
||||
maxLength?: number
|
||||
options: ReimbursementFormOption[]
|
||||
children: ReimbursementFormField[]
|
||||
}
|
||||
|
||||
export interface ReimbursementFormDefinition {
|
||||
mode: ReimbursementFormMode
|
||||
approvalCode?: string
|
||||
definitionFingerprint?: string
|
||||
formFingerprint?: string
|
||||
fetchedAt?: string
|
||||
fields: ReimbursementFormField[]
|
||||
}
|
||||
|
||||
export interface ExpenseTypeMetadata {
|
||||
id: number
|
||||
code: string
|
||||
name: string
|
||||
category: string
|
||||
description: string
|
||||
}
|
||||
|
||||
export interface ReimbursementFormSnapshot {
|
||||
mode: ReimbursementFormSnapshotMode
|
||||
fingerprint?: string
|
||||
fields: ReimbursementFormField[]
|
||||
values: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ExpenseItem {
|
||||
@@ -74,6 +125,16 @@ export interface ExpenseItem {
|
||||
category: string
|
||||
description?: string
|
||||
amount: number
|
||||
attachmentIds: Array<number | string>
|
||||
attachments?: ReimbursementFormAttachment[]
|
||||
attachmentMetadata?: ReimbursementFormAttachment[]
|
||||
}
|
||||
|
||||
export interface ReimbursementFormAttachment {
|
||||
id: number | string
|
||||
fileName: string
|
||||
contentType: string
|
||||
fileSize: number
|
||||
}
|
||||
|
||||
export interface CreateApplicationRequest {
|
||||
@@ -85,6 +146,38 @@ export interface CreateApplicationRequest {
|
||||
payeeName: string
|
||||
payeeBankId: number
|
||||
items: ExpenseItem[]
|
||||
formFingerprint?: string
|
||||
formValues?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type ApprovalRouteSource = 'FEISHU' | 'LOCAL'
|
||||
|
||||
export interface ApprovalRouteNode {
|
||||
order: number
|
||||
nodeKey: string
|
||||
nodeName: string
|
||||
nodeType?: string
|
||||
approvalMode?: string
|
||||
approverLabels: string[]
|
||||
dynamic: boolean
|
||||
}
|
||||
|
||||
export interface ApprovalRoutePreview {
|
||||
applicationId: number | string
|
||||
source: ApprovalRouteSource
|
||||
nodes: ApprovalRouteNode[]
|
||||
routeFingerprint: string
|
||||
snapshotFingerprint?: string
|
||||
previewToken: string
|
||||
expiresAt: string
|
||||
snapshotFetchedAt?: string
|
||||
staleSnapshot: boolean
|
||||
exact: boolean
|
||||
warning?: string
|
||||
}
|
||||
|
||||
export interface SubmitReimbursementRequest {
|
||||
previewToken: string
|
||||
}
|
||||
|
||||
export interface Invoice {
|
||||
@@ -100,8 +193,11 @@ export interface Invoice {
|
||||
export interface Attachment {
|
||||
id: number | string
|
||||
fileName: string
|
||||
fileType: string
|
||||
fileUrl: string
|
||||
fileType?: string
|
||||
contentType?: string
|
||||
fileSize?: number
|
||||
fileUrl?: string
|
||||
expenseItemId?: number | string
|
||||
}
|
||||
|
||||
export interface ApprovalRecord {
|
||||
@@ -130,6 +226,23 @@ export interface PaymentRecord {
|
||||
}
|
||||
|
||||
export const reimbursementApi = {
|
||||
getFormDefinition: (): Promise<ReimbursementFormDefinition> =>
|
||||
request.get('/v1/reimbursements/form-definition', { suppressErrorNotification: true }),
|
||||
|
||||
getExpenseTypes: (): Promise<ExpenseTypeMetadata[]> =>
|
||||
request.get('/metadata/expense-types', { suppressErrorNotification: true }),
|
||||
|
||||
uploadFormAttachment: (file: File, formFingerprint: string, controlId: string): Promise<ReimbursementFormAttachment> => {
|
||||
const data = new FormData()
|
||||
data.append('file', file)
|
||||
data.append('formFingerprint', formFingerprint)
|
||||
data.append('controlId', controlId)
|
||||
return request.post('/v1/reimbursements/form-attachments', data, { headers: { 'Content-Type': 'multipart/form-data' }, suppressErrorNotification: true })
|
||||
},
|
||||
|
||||
deleteFormAttachment: (id: number | string): Promise<void> =>
|
||||
request.delete(`/v1/reimbursements/form-attachments/${encodeURIComponent(String(id))}`, { suppressErrorNotification: true }),
|
||||
|
||||
getWorkbench: (): Promise<any> =>
|
||||
request.get('/v1/reimbursements/workbench'),
|
||||
|
||||
@@ -148,8 +261,11 @@ export const reimbursementApi = {
|
||||
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`),
|
||||
getRoutePreview: (id: number | string): Promise<ApprovalRoutePreview> =>
|
||||
request.get(`/v1/reimbursements/${id}/route-preview`),
|
||||
|
||||
submit: (id: number | string, data: SubmitReimbursementRequest): Promise<ReimApplicationDetail> =>
|
||||
request.post(`/v1/reimbursements/${id}/submit`, data),
|
||||
|
||||
receive: (id: number | string): Promise<ReimApplicationDetail> =>
|
||||
request.post(`/v1/reimbursements/${id}/receive`),
|
||||
|
||||
+24
-14
@@ -3,13 +3,18 @@ import type { AxiosRequestConfig } from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import router from '@/router'
|
||||
|
||||
type ClientRequestConfig = AxiosRequestConfig & { suppressErrorNotification?: boolean }
|
||||
|
||||
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>
|
||||
get<T = unknown>(url: string, config?: ClientRequestConfig): Promise<T>
|
||||
post<T = unknown>(url: string, data?: unknown, config?: ClientRequestConfig): Promise<T>
|
||||
put<T = unknown>(url: string, data?: unknown, config?: ClientRequestConfig): Promise<T>
|
||||
delete<T = unknown>(url: string, config?: ClientRequestConfig): Promise<T>
|
||||
}
|
||||
|
||||
const suppressErrorNotification = (config: unknown) =>
|
||||
Boolean((config as { suppressErrorNotification?: boolean } | undefined)?.suppressErrorNotification)
|
||||
|
||||
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.
|
||||
@@ -22,8 +27,12 @@ const axiosClient = axios.create({
|
||||
})
|
||||
|
||||
const clearSessionAndRedirect = () => {
|
||||
localStorage.removeItem('token')
|
||||
sessionStorage.removeItem('token')
|
||||
localStorage.removeItem('token') // remove credentials left by pre-hardening builds
|
||||
localStorage.removeItem('userInfo')
|
||||
localStorage.removeItem('finance.auth-day')
|
||||
sessionStorage.removeItem('token')
|
||||
sessionStorage.removeItem('userInfo')
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
void router.push('/login')
|
||||
}
|
||||
@@ -36,7 +45,7 @@ const requestToken = (config: unknown): string | undefined => {
|
||||
|
||||
const clearOnlyIfRequestOwnsSession = (config: unknown) => {
|
||||
const issuedToken = requestToken(config)
|
||||
if (issuedToken && localStorage.getItem('token') === issuedToken) clearSessionAndRedirect()
|
||||
if (issuedToken && sessionStorage.getItem('token') === issuedToken) clearSessionAndRedirect()
|
||||
}
|
||||
|
||||
let lastNotification = ''
|
||||
@@ -53,7 +62,7 @@ const notifyOnce = (message: string, type: 'error' | 'warning' | 'info' = 'error
|
||||
// Request interceptor - attach JWT token
|
||||
axiosClient.interceptors.request.use(
|
||||
(config) => {
|
||||
const token = localStorage.getItem('token')
|
||||
const token = sessionStorage.getItem('token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
@@ -74,7 +83,7 @@ axiosClient.interceptors.response.use(
|
||||
|
||||
if (res.code !== 200) {
|
||||
if (res.code === 401) clearOnlyIfRequestOwnsSession(response.config)
|
||||
notifyOnce(res.message || '请求失败')
|
||||
if (!suppressErrorNotification(response.config)) notifyOnce(res.message || '请求失败')
|
||||
return Promise.reject(new Error(res.message || '请求失败'))
|
||||
}
|
||||
return res.data
|
||||
@@ -82,24 +91,25 @@ axiosClient.interceptors.response.use(
|
||||
(error) => {
|
||||
if (error.response) {
|
||||
const { status, data } = error.response
|
||||
const silent = suppressErrorNotification(error.config)
|
||||
switch (status) {
|
||||
case 401:
|
||||
clearOnlyIfRequestOwnsSession(error.config)
|
||||
notifyOnce('登录已过期,请重新登录')
|
||||
if (!silent) notifyOnce('登录已过期,请重新登录')
|
||||
break
|
||||
case 403:
|
||||
notifyOnce('权限不足')
|
||||
if (!silent) notifyOnce('权限不足')
|
||||
break
|
||||
case 404:
|
||||
notifyOnce('请求的资源不存在')
|
||||
if (!silent) notifyOnce('请求的资源不存在')
|
||||
break
|
||||
case 409:
|
||||
notifyOnce(data?.message || '业务冲突')
|
||||
if (!silent) notifyOnce(data?.message || '业务冲突')
|
||||
break
|
||||
default:
|
||||
notifyOnce(data?.message || '服务器错误')
|
||||
if (!silent) notifyOnce(data?.message || '服务器错误')
|
||||
}
|
||||
} else {
|
||||
} else if (!suppressErrorNotification(error.config)) {
|
||||
notifyOnce('网络连接失败')
|
||||
}
|
||||
return Promise.reject(error)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import request from './request'
|
||||
|
||||
export type ScheduledTaskStatus = 'IDLE' | 'RUNNING'
|
||||
export type ScheduledRunTrigger = 'MANUAL' | 'STARTUP' | 'SCHEDULED'
|
||||
export type ScheduledRunState = 'QUEUED' | 'RUNNING' | 'SUCCEEDED' | 'FAILED'
|
||||
export type ScheduledIntervalHours = 1 | 2 | 3 | 6 | 12 | 24
|
||||
|
||||
export interface ScheduledTask {
|
||||
code: string
|
||||
name: string
|
||||
enabled: boolean
|
||||
intervalHours: ScheduledIntervalHours
|
||||
timeZone: string
|
||||
nextDueAt: string | null
|
||||
lastClaimedAt: string | null
|
||||
version: number
|
||||
status: ScheduledTaskStatus
|
||||
}
|
||||
|
||||
export interface ScheduledRunCounts {
|
||||
departments: number
|
||||
usersSeen: number
|
||||
eligible: number
|
||||
excluded: number
|
||||
created: number
|
||||
updated: number
|
||||
ineligible: number
|
||||
outOfScope: number
|
||||
}
|
||||
|
||||
export interface ScheduledTaskRun {
|
||||
runId: string
|
||||
trigger: ScheduledRunTrigger
|
||||
state: ScheduledRunState
|
||||
queuedAt: string
|
||||
startedAt: string | null
|
||||
finishedAt: string | null
|
||||
attempts: number
|
||||
complete: boolean
|
||||
applied: boolean
|
||||
counts: ScheduledRunCounts
|
||||
errorCode: string | null
|
||||
errorMessage: string | null
|
||||
}
|
||||
|
||||
export interface ScheduledRunPage {
|
||||
items: ScheduledTaskRun[]
|
||||
page: number
|
||||
size: number
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface UpdateScheduledTaskRequest {
|
||||
enabled: boolean
|
||||
intervalHours: ScheduledIntervalHours
|
||||
version: number
|
||||
}
|
||||
|
||||
export const SCHEDULED_TASK_REQUEST_TIMEOUT = 15_000
|
||||
export const SCHEDULED_TASK_EXECUTE_TIMEOUT = 20_000
|
||||
|
||||
const pathFor = (code: string) => `/scheduled-tasks/${encodeURIComponent(code)}`
|
||||
|
||||
export const scheduledTasksApi = {
|
||||
list: (signal?: AbortSignal): Promise<ScheduledTask[]> =>
|
||||
request.get('/scheduled-tasks', { signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT }),
|
||||
detail: (code: string, signal?: AbortSignal): Promise<ScheduledTask> =>
|
||||
request.get(pathFor(code), { signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT }),
|
||||
updateSchedule: (code: string, body: UpdateScheduledTaskRequest, signal?: AbortSignal): Promise<ScheduledTask> =>
|
||||
request.put(`${pathFor(code)}/schedule`, body, { signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT, suppressErrorNotification: true }),
|
||||
execute: (code: string, signal?: AbortSignal): Promise<ScheduledTaskRun> =>
|
||||
request.post(`${pathFor(code)}/execute`, undefined, { signal, timeout: SCHEDULED_TASK_EXECUTE_TIMEOUT, suppressErrorNotification: true }),
|
||||
runs: (code: string, page = 0, size = 20, signal?: AbortSignal): Promise<ScheduledRunPage> =>
|
||||
request.get(`${pathFor(code)}/runs`, { params: { page, size }, signal, timeout: SCHEDULED_TASK_REQUEST_TIMEOUT }),
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 6.1 KiB |
+1105
-407
File diff suppressed because it is too large.
@@ -1,8 +1,9 @@
|
||||
<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><h2 id="directory-title">飞书通讯录同步</h2><p>同步飞书员工资料与目录状态;不作为 OAuth 登录条件;同步失败会保留当前目录</p></div>
|
||||
<div class="directory-actions">
|
||||
<router-link v-if="canManageSchedule" class="btn small" to="/scheduled-tasks">管理自动同步</router-link>
|
||||
<button class="btn small" type="button" :disabled="loading || submitting" @click="refreshStatus">{{ loading ? '查询中…' : '刷新状态' }}</button>
|
||||
<button v-if="canSync" class="btn primary" type="button" :disabled="syncDisabled" :aria-busy="submitting" @click="sync">{{ submitting || status?.running ? '同步中…' : '同步飞书通讯录' }}</button>
|
||||
</div>
|
||||
@@ -15,14 +16,16 @@
|
||||
<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>
|
||||
<div><dt>当前目录</dt><dd>{{ availabilityLabels[currentAvailability] }}</dd></div>
|
||||
<div><dt>上次成功更新 <span class="time-zone-label">本地时间</span></dt><dd>{{ formatLocalDateTime(status.lastSuccessfulAt, '暂无') }}</dd></div>
|
||||
<div><dt>当前版本</dt><dd>{{ status.currentRevision || status.lastSuccessfulRunId || '暂无' }}</dd></div>
|
||||
<div><dt>配置上下文</dt><dd>{{ contextLabels[currentContext] }}</dd></div>
|
||||
</dl>
|
||||
<p v-if="status.snapshotState === 'STALE' || status.snapshotState === 'CONTEXT_CHANGED'">快照已过期或应用上下文已变化,请重新同步以更新目录资料与业务候选人。</p>
|
||||
<p v-if="currentContext === 'CHANGED'" class="directory-warning" role="status">应用配置上下文已变化,这是更新提示,不会停用已经可用的当前目录;可同步以更新资料。</p>
|
||||
<p v-else-if="status.snapshotState === 'STALE'" class="directory-warning" role="status">服务返回旧版 STALE 状态;{{ currentAvailability === 'AVAILABLE' ? '当前目录仍可继续使用,建议同步更新资料。' : '当前服务未确认目录可用,请同步后再添加成员。' }}</p>
|
||||
</template>
|
||||
<template v-if="run">
|
||||
<p>最近运行:{{ run.trigger === 'STARTUP' ? '启动同步' : '手动同步' }} · {{ stateLabels[run.state] }} · {{ run.applied ? '已提交' : '未提交,不覆盖上次结果' }}</p>
|
||||
<p>最近运行:{{ triggerLabels[run.trigger] }} · {{ stateLabels[run.state] }} · {{ run.applied ? '已提交' : '未提交,保留当前目录' }}</p>
|
||||
<p class="muted-copy">运行时间(本地时间):{{ formatLocalDateTime(run.startedAt) }} — {{ formatLocalDateTime(run.finishedAt, '尚未结束') }} · 运行 ID:{{ run.runId }}</p>
|
||||
<p v-if="run.state === 'FAILED' || run.errorMessage" class="directory-failure" role="alert">{{ run.errorCode || '同步失败' }}:{{ run.errorMessage || '同步未完成,请检查配置后重试。' }}</p>
|
||||
<dl class="directory-counts"><div v-for="(label, key) in countLabels" :key="key"><dt>{{ label }}</dt><dd>{{ run.counts[key] }}</dd></div></dl>
|
||||
@@ -34,27 +37,34 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onBeforeUnmount, ref } from 'vue'
|
||||
import { feishuDirectoryApi, type DirectoryRun, type DirectoryStatus } from '@/api/feishuDirectory'
|
||||
import { directoryAvailability, feishuDirectoryApi, type DirectoryContextState, 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 canSync = computed(() => userStore.canEdit('system.feishu.directory.sync'))
|
||||
const canRead = computed(() => userStore.canRead('page.feishu-directory'))
|
||||
const canManageSchedule = computed(() => userStore.canRead('page.scheduled-tasks'))
|
||||
const status = ref<DirectoryStatus | null>(null)
|
||||
const run = ref<DirectoryRun | null>(null)
|
||||
const loading = ref(false)
|
||||
const submitting = ref(false)
|
||||
const uncertain = ref(true)
|
||||
const error = ref('')
|
||||
const currentAvailability = computed(() => status.value ? directoryAvailability(status.value) : 'UNAVAILABLE')
|
||||
const currentContext = computed<DirectoryContextState>(() => {
|
||||
if (status.value?.contextState === 'MATCH' || status.value?.contextState === 'CHANGED' || status.value?.contextState === 'UNKNOWN') return status.value.contextState
|
||||
return status.value?.snapshotState === 'CONTEXT_CHANGED' ? 'CHANGED' : 'UNKNOWN'
|
||||
})
|
||||
const syncDisabled = computed(() => !canSync.value || loading.value || submitting.value || uncertain.value || !status.value?.configured || status.value.running)
|
||||
const controller = new AbortController()
|
||||
let disposed = false
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let observedSuccess: string | null | undefined
|
||||
const snapshotLabels = { UNAVAILABLE: '不可用', NEVER_SYNCED: '尚未同步', FRESH: '有效', STALE: '已过期', CONTEXT_CHANGED: '应用上下文已变化' }
|
||||
const availabilityLabels = { AVAILABLE: '可用', NEVER_SYNCED: '尚未同步', UNAVAILABLE: '不可用' }
|
||||
const contextLabels: Record<DirectoryContextState, string> = { MATCH: '一致', CHANGED: '已变化(仅提示)', UNKNOWN: '未知' }
|
||||
const stateLabels = { RUNNING: '运行中', SUCCEEDED: '成功', FAILED: '失败' }
|
||||
const triggerLabels: Record<DirectoryRun['trigger'], string> = { MANUAL: '手动同步', STARTUP: '启动同步', SCHEDULED: '自动同步' }
|
||||
const countLabels = { departments: '部门', usersSeen: '扫描员工', excluded: '排除', created: '新增用户', updated: '更新用户', outOfScope: '可见范围外' }
|
||||
|
||||
// Date getters intentionally use the browser's local timezone instead of
|
||||
@@ -130,11 +140,12 @@ onBeforeUnmount(() => { disposed = true; clearTimeout(timer); controller.abort()
|
||||
.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 { padding: 0 22px 20px; font-size: 12px; color: var(--muted); }
|
||||
.directory-body p { margin: 10px 0; }
|
||||
.directory-meta, .directory-counts { display: grid; gap: 12px; margin: 12px 0 0; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); }
|
||||
.directory-counts { grid-template-columns: repeat(auto-fit, minmax(100px, 1fr)); }
|
||||
dt { color: var(--muted); } dd { margin: 4px 0 0; color: var(--body); }
|
||||
.time-zone-label { color: var(--quiet); font-size: 10px; font-weight: 400; white-space: nowrap; }
|
||||
.directory-failure { color: var(--danger); }
|
||||
.directory-warning { color: var(--warning); }
|
||||
</style>
|
||||
@@ -0,0 +1,262 @@
|
||||
<template>
|
||||
<div class="kingdee-bind-panel" :class="{ embedded: embedded }">
|
||||
<div v-if="loadError" class="inline-alert danger" role="alert">
|
||||
<b>!</b><span>{{ loadError }}</span>
|
||||
<button class="btn small" type="button" @click="load">重试</button>
|
||||
</div>
|
||||
|
||||
<div class="card fill-list-card primary-list-card" :class="{ 'panel-card': embedded }">
|
||||
<div class="filter-bar">
|
||||
<label v-if="canViewAll" class="filter-search">
|
||||
<span aria-hidden="true">🔍</span>
|
||||
<input v-model="search" type="search" placeholder="搜索姓名、工号或金蝶账号" aria-label="搜索财务人员">
|
||||
</label>
|
||||
<span v-else class="filter-hint">当前权限:仅查看本人</span>
|
||||
<span class="filter-spacer"></span>
|
||||
<span class="tag info">{{ filtered.length }} 人</span>
|
||||
<span class="tag" :class="boundCount ? 'success' : 'neutral'">已绑定 {{ boundCount }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="load-wrap" role="status">
|
||||
<span class="loader" aria-hidden="true"></span><span>正在加载绑定列表…</span>
|
||||
</div>
|
||||
<div v-else-if="!loadError && filtered.length" class="table-wrap" tabindex="0" role="region" aria-label="金蝶账号绑定列表">
|
||||
<table class="data-table responsive-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>财务人员</th>
|
||||
<th>工号</th>
|
||||
<th>金蝶账号</th>
|
||||
<th>绑定状态</th>
|
||||
<th>操作</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in paginatedItems" :key="item.userId">
|
||||
<td data-label="财务人员">
|
||||
<strong>{{ item.realName }}</strong>
|
||||
<small v-if="item.userId === meId" class="self-mark">本人</small>
|
||||
</td>
|
||||
<td data-label="工号"><small>{{ item.employeeNo || '—' }}</small></td>
|
||||
<td data-label="金蝶账号"><small>{{ item.kingdeeUsername || '—' }}</small></td>
|
||||
<td data-label="绑定状态">
|
||||
<span class="tag" :class="item.bound ? 'success' : 'neutral'">{{ item.bound ? '已绑定' : '未绑定' }}</span>
|
||||
</td>
|
||||
<td data-label="操作" class="actions-cell">
|
||||
<button v-if="canBindRow(item)" class="table-action" type="button" @click="openBind(item)">
|
||||
{{ item.bound ? '重新绑定' : '绑定' }}
|
||||
</button>
|
||||
<button v-if="canBindRow(item) && item.bound" class="table-action" type="button" :disabled="testingId === item.userId" @click="testBinding(item)">
|
||||
{{ testingId === item.userId ? '验证中…' : '验证' }}
|
||||
</button>
|
||||
<button v-if="canUnbindRow(item) && item.bound" class="table-action danger-action" type="button" @click="unbind(item)">解绑</button>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-else-if="!loading && !loadError" class="empty-state">
|
||||
<strong>{{ canViewAll ? '暂无财务人员' : '暂无本人记录' }}</strong>
|
||||
<span>{{ canViewAll ? '请先为用户分配「财务」角色,或授予「变更金蝶财务单据」权限。' : '当前账号不在可绑定范围内,或尚无权限。' }}</span>
|
||||
</div>
|
||||
<AppListPagination
|
||||
v-if="!loading && !loadError && filtered.length && canViewAll"
|
||||
v-model:page="page"
|
||||
v-model:page-size="pageSize"
|
||||
:total="filtered.length"
|
||||
aria-label="金蝶账号绑定列表分页"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<dialog ref="bindDialog" v-dialog-drag class="app-dialog" aria-labelledby="kingdee-bind-title" @cancel.prevent="closeBind">
|
||||
<form @submit.prevent="saveBind">
|
||||
<div class="modal-head" data-dialog-drag-handle>
|
||||
<div>
|
||||
<span class="eyebrow">BIND KINGDEE ACCOUNT</span>
|
||||
<h2 id="kingdee-bind-title">绑定金蝶账号 · {{ editing?.realName }}</h2>
|
||||
<p>填写该人员在金蝶云星空的登录用户名与密码;保存前默认验证登录。</p>
|
||||
</div>
|
||||
<button class="modal-close" type="button" aria-label="关闭" :disabled="saving" @click="closeBind">×</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="form-grid">
|
||||
<div class="field">
|
||||
<label for="kingdee-username">金蝶用户名 <em>*</em></label>
|
||||
<input id="kingdee-username" v-model.trim="form.kingdeeUsername" required autocomplete="username" :disabled="saving">
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="kingdee-password">金蝶密码 <em>*</em></label>
|
||||
<input id="kingdee-password" v-model="form.kingdeePassword" type="password" required autocomplete="new-password" :disabled="saving" :placeholder="editing?.bound ? '请重新输入密码' : '请输入金蝶密码'">
|
||||
</div>
|
||||
<label class="check-option full">
|
||||
<input v-model="form.verifyLogin" type="checkbox" :disabled="saving">
|
||||
<span>保存前验证金蝶登录</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button class="btn" type="button" :disabled="saving" @click="closeBind">取消</button>
|
||||
<button class="btn primary" type="submit" :disabled="saving">{{ saving ? '保存中…' : '保存绑定' }}</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 AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
import { kingdeeAccountsApi, type KingdeeAccountBinding } from '@/api/kingdeeAccounts'
|
||||
import { useUserStore } from '@/store/user'
|
||||
|
||||
defineProps<{ embedded?: boolean }>()
|
||||
|
||||
const userStore = useUserStore()
|
||||
const meId = computed(() => Number(userStore.userInfo?.id || 0) || null)
|
||||
const canViewAll = computed(() => userStore.canRead('finance.kingdee.account.view-all'))
|
||||
const canBindAll = computed(() => userStore.canEdit('finance.kingdee.account.bind'))
|
||||
const canBindOwn = computed(() => userStore.canEdit('finance.kingdee.account.bind-own'))
|
||||
const canUnbindAll = computed(() => userStore.canEdit('finance.kingdee.account.unbind'))
|
||||
const canUnbindOwn = computed(() => userStore.canEdit('finance.kingdee.account.unbind-own'))
|
||||
|
||||
const canBindRow = (item: KingdeeAccountBinding) =>
|
||||
canBindAll.value || (canBindOwn.value && item.userId === meId.value)
|
||||
const canUnbindRow = (item: KingdeeAccountBinding) =>
|
||||
canUnbindAll.value || (canUnbindOwn.value && item.userId === meId.value)
|
||||
|
||||
const items = ref<KingdeeAccountBinding[]>([])
|
||||
const loading = ref(false)
|
||||
const loadError = ref('')
|
||||
const search = ref('')
|
||||
const saving = ref(false)
|
||||
const testingId = ref<number | null>(null)
|
||||
const bindDialog = ref<HTMLDialogElement | null>(null)
|
||||
const editing = ref<KingdeeAccountBinding | null>(null)
|
||||
const form = reactive({ kingdeeUsername: '', kingdeePassword: '', verifyLogin: true })
|
||||
|
||||
const errorText = (error: unknown) => {
|
||||
const responseMessage = (error as { response?: { data?: { message?: unknown } } })?.response?.data?.message
|
||||
if (typeof responseMessage === 'string' && responseMessage.trim()) return responseMessage
|
||||
return error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
|
||||
}
|
||||
|
||||
const filtered = computed(() => {
|
||||
const q = search.value.trim().toLowerCase()
|
||||
if (!q) return items.value
|
||||
return items.value.filter(item =>
|
||||
[item.realName, item.employeeNo, item.kingdeeUsername]
|
||||
.some(value => String(value || '').toLowerCase().includes(q)))
|
||||
})
|
||||
const boundCount = computed(() => items.value.filter(item => item.bound).length)
|
||||
const { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [search] })
|
||||
|
||||
const load = async () => {
|
||||
loading.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
await userStore.loadPermissions()
|
||||
items.value = await kingdeeAccountsApi.list() || []
|
||||
} catch (error) {
|
||||
loadError.value = errorText(error)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const openBind = async (item: KingdeeAccountBinding) => {
|
||||
if (!canBindRow(item)) return
|
||||
editing.value = item
|
||||
form.kingdeeUsername = item.kingdeeUsername || ''
|
||||
form.kingdeePassword = ''
|
||||
form.verifyLogin = true
|
||||
await nextTick()
|
||||
bindDialog.value?.showModal()
|
||||
}
|
||||
|
||||
const closeBind = () => {
|
||||
if (saving.value) return
|
||||
bindDialog.value?.close()
|
||||
editing.value = null
|
||||
}
|
||||
|
||||
const saveBind = async () => {
|
||||
if (!editing.value || !canBindRow(editing.value) || saving.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const saved = await kingdeeAccountsApi.bind(editing.value.userId, {
|
||||
kingdeeUsername: form.kingdeeUsername,
|
||||
kingdeePassword: form.kingdeePassword,
|
||||
verifyLogin: form.verifyLogin,
|
||||
})
|
||||
const index = items.value.findIndex(item => item.userId === saved.userId)
|
||||
if (index >= 0) items.value[index] = saved
|
||||
else items.value.push(saved)
|
||||
ElMessage.success('金蝶账号已绑定')
|
||||
closeBind()
|
||||
} catch (error) {
|
||||
ElMessage.error(`绑定失败:${errorText(error)}`)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const testBinding = async (item: KingdeeAccountBinding) => {
|
||||
if (!canBindRow(item) || testingId.value != null) return
|
||||
testingId.value = item.userId
|
||||
try {
|
||||
const result = await kingdeeAccountsApi.test(item.userId)
|
||||
if (result?.success) ElMessage.success(result.message || '验证成功')
|
||||
else ElMessage.error(result?.message || '验证失败')
|
||||
} catch (error) {
|
||||
ElMessage.error(`验证失败:${errorText(error)}`)
|
||||
} finally {
|
||||
testingId.value = null
|
||||
}
|
||||
}
|
||||
|
||||
const unbind = async (item: KingdeeAccountBinding) => {
|
||||
if (!canUnbindRow(item)) return
|
||||
try {
|
||||
await ElMessageBox.confirm(`确认解绑 ${item.realName} 的金蝶账号?解绑后该员工将无法变更金蝶财务单据。`, '解绑确认', {
|
||||
type: 'warning',
|
||||
confirmButtonText: '解绑',
|
||||
cancelButtonText: '取消',
|
||||
})
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await kingdeeAccountsApi.unbind(item.userId)
|
||||
const index = items.value.findIndex(row => row.userId === item.userId)
|
||||
if (index >= 0) {
|
||||
items.value[index] = {
|
||||
...items.value[index],
|
||||
bound: false,
|
||||
kingdeeUsername: null,
|
||||
boundAt: null,
|
||||
updatedAt: null,
|
||||
boundBy: null,
|
||||
}
|
||||
}
|
||||
ElMessage.success('已解绑')
|
||||
} catch (error) {
|
||||
ElMessage.error(`解绑失败:${errorText(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => { void load() })
|
||||
|
||||
defineExpose({ reload: load })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.kingdee-bind-panel.embedded .panel-card {
|
||||
box-shadow: none;
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
.filter-hint { color: var(--muted); font-size: 12px; }
|
||||
.self-mark { margin-left: 6px; color: var(--muted); font-size: 11px; }
|
||||
.check-option.full { grid-column: 1 / -1; display: flex; align-items: center; gap: 8px; margin-top: 4px; }
|
||||
</style>
|
||||
@@ -0,0 +1,522 @@
|
||||
<template>
|
||||
<section class="sync-panel primary-list-card" aria-labelledby="kingdee-sync-title">
|
||||
<div class="sync-head">
|
||||
<div>
|
||||
<span class="eyebrow">KINGDEE SYNC</span>
|
||||
<h3 id="kingdee-sync-title">金蝶单据同步规则</h3>
|
||||
<p>配置单据字段映射、过滤条件和同步目标表;过滤条件只接受结构化值,不接受原始 SQL。</p>
|
||||
</div>
|
||||
<button v-if="canCreate" class="btn primary small" type="button" @click="openCreate">新建同步规则</button>
|
||||
</div>
|
||||
|
||||
<div v-if="!canView" class="sync-empty" role="alert">
|
||||
<strong>无权查看同步规则</strong><span>当前账号没有集成查看权限。</span>
|
||||
</div>
|
||||
<div v-else-if="loading" class="sync-loading" role="status" aria-live="polite"><span class="loader" aria-hidden="true"></span>正在加载同步规则…</div>
|
||||
<div v-else-if="loadError" class="inline-alert danger sync-alert" role="alert"><span>{{ loadError }}</span><button class="btn small" type="button" @click="loadConfigs">重试</button></div>
|
||||
<template v-else>
|
||||
<div v-if="!configs.length" class="sync-empty"><strong>暂无同步规则</strong><span>新建规则后,可以创建目标表并执行单据同步。</span></div>
|
||||
<div v-else class="table-scroll" role="region" aria-label="金蝶同步规则列表" tabindex="0">
|
||||
<el-table :data="pagedConfigs" row-key="id" size="small" empty-text="暂无同步规则">
|
||||
<el-table-column prop="configName" label="配置名称" min-width="150" />
|
||||
<el-table-column prop="formId" label="formId" min-width="140" />
|
||||
<el-table-column prop="targetTableName" label="目标表" min-width="150" />
|
||||
<el-table-column label="字段 / 过滤" width="105">
|
||||
<template #default="scope">{{ scope.row.fields.length }} / {{ scope.row.filters.length }}</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="状态" width="90">
|
||||
<template #default="scope"><el-tag :type="scope.row.enabled ? 'success' : 'info'" size="small">{{ scope.row.enabled ? '已启用' : '已停用' }}</el-tag></template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" fixed="right" width="155">
|
||||
<template #default="scope">
|
||||
<div class="row-actions">
|
||||
<el-button v-if="canView" link type="primary" size="small" @click="openEdit(scope.row.id)">{{ canUpdate ? '编辑' : '查看' }}</el-button>
|
||||
<el-button v-if="canDelete" link type="danger" size="small" @click="deleteConfig(scope.row)">删除</el-button>
|
||||
<span v-if="!canUpdate && !canDelete" class="muted-copy">只读</span>
|
||||
</div>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
</div>
|
||||
<AppListPagination v-if="configs.length" v-model:page="currentPage" v-model:page-size="pageSize" :total="configs.length" aria-label="金蝶同步规则分页" />
|
||||
</template>
|
||||
|
||||
<el-dialog ref="dialogRef" v-model="dialogVisible" :aria-label="editingId === null ? '新建金蝶同步规则' : '编辑金蝶同步规则'" width="min(1080px, 96vw)" align-center :draggable="desktopDialogDrag" :before-close="beforeKingdeeDialogClose" :close-on-click-modal="!dialogBusy" :close-on-press-escape="!dialogBusy" :show-close="!dialogBusy" destroy-on-close class="kingdee-sync-dialog" @closed="resetKingdeeDialogPosition">
|
||||
<template #header>
|
||||
<div class="dialog-title-block">
|
||||
<span class="eyebrow">KINGDEE SYNC RULE</span>
|
||||
<h2>{{ editingId === null ? '新建金蝶同步规则' : '编辑金蝶同步规则' }}</h2>
|
||||
<p>配置来源单据、目标表及字段映射;结构变更请在同步前完成目标表校验。</p>
|
||||
</div>
|
||||
</template>
|
||||
<div v-if="detailLoading" class="sync-loading" role="status"><span class="loader" aria-hidden="true"></span>正在加载规则详情…</div>
|
||||
<div v-else class="dialog-content">
|
||||
<div v-if="detailError" class="inline-alert danger" role="alert"><span>{{ detailError }}</span></div>
|
||||
<el-form v-else ref="formRef" :model="draft" label-position="top" @submit.prevent>
|
||||
<div v-if="validationError" class="form-error" role="alert">{{ validationError }}</div>
|
||||
<div class="sync-form-grid">
|
||||
<el-form-item label="单据名称" required :error="fieldError('configName')"><el-input v-model="draft.configName" :disabled="!canManage" maxlength="100" show-word-limit placeholder="例如:销售订单" /></el-form-item>
|
||||
<el-form-item label="金蝶单据标识(formId)" required :error="fieldError('formId')"><el-input v-model="draft.formId" :disabled="!canManage" maxlength="100" placeholder="例如:SAL_SaleOrder" /></el-form-item>
|
||||
<el-form-item label="数据库表名" required :error="fieldError('targetTableName')"><el-input v-model="draft.targetTableName" :disabled="!canManage" maxlength="63" placeholder="例如:kd_sale_order" /></el-form-item>
|
||||
<el-form-item label="表注释名"><el-input v-model="draft.targetTableComment" :disabled="!canManage" maxlength="200" placeholder="可选" /></el-form-item>
|
||||
<el-form-item label="启用"><el-switch v-model="draft.enabled" :disabled="!canManage" active-text="启用" inactive-text="停用" /></el-form-item>
|
||||
<el-form-item label="最大同步行数" required :error="fieldError('maxRowsPerRun')"><el-input-number v-model="draft.maxRowsPerRun" :disabled="!canManage" :min="1" :max="100000" controls-position="right" /></el-form-item>
|
||||
</div>
|
||||
|
||||
<div class="subsection-head"><div><h4>字段映射</h4><p>必须包含 FBillNo 作为不可变来源主键;排序按列表顺序提交。</p></div><el-button v-if="canManage" type="primary" plain size="small" @click="addField">新增字段</el-button></div>
|
||||
<div v-if="fieldError('fields')" class="form-error compact-error" role="alert">{{ fieldError('fields') }}</div>
|
||||
<div class="mapping-list">
|
||||
<div v-for="(field, index) in draft.fields" :key="field._key" class="mapping-row">
|
||||
<el-form-item label="源字段标识" required><el-input v-model="field.sourceFieldKey" :disabled="!canManage" placeholder="如:FMaterialId" /></el-form-item>
|
||||
<el-form-item label="数据库字段名" required><el-input v-model="field.targetColumnName" :disabled="!canManage" placeholder="如:material_id" /></el-form-item>
|
||||
<el-form-item label="字段注释"><el-input v-model="field.fieldComment" :disabled="!canManage" placeholder="可选" /></el-form-item>
|
||||
<el-form-item label="类型" required><el-select v-model="field.dataType" :disabled="!canManage" placeholder="选择类型" @change="onDataTypeChange(field)"><el-option v-for="type in dataTypes" :key="type" :label="type" :value="type" /></el-select></el-form-item>
|
||||
<el-form-item label="长度"><el-input-number v-model="field.fieldLength" :disabled="!canManage || field.dataType !== 'STRING'" :min="1" :max="10000" controls-position="right" placeholder="可选" /></el-form-item>
|
||||
<el-button v-if="canManage" class="remove-row" link type="danger" :disabled="draft.fields.length <= 1" :aria-label="`删除第${index + 1}条字段`" @click="removeField(index)">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="subsection-head filter-head"><div><h4>过滤条件</h4><p>服务端会将结构化条件转换为查询条件,请勿填写 SQL 片段。</p></div><el-button v-if="canManage" type="primary" plain size="small" @click="addFilter">新增过滤</el-button></div>
|
||||
<div class="filter-list">
|
||||
<div v-for="(filter, index) in draft.filters" :key="filter._key" class="filter-row">
|
||||
<el-form-item label="源字段标识"><el-input v-model="filter.sourceFieldKey" :disabled="!canManage" placeholder="如:FDocumentStatus" /></el-form-item>
|
||||
<el-form-item label="操作符"><el-select v-model="filter.operator" :disabled="!canManage"><el-option v-for="operator in operators" :key="operator.value" :label="operator.label" :value="operator.value" /></el-select></el-form-item>
|
||||
<el-form-item label="过滤值"><el-input v-model="filter.filterValue" :disabled="!canManage" placeholder="结构化值,如:A,B" /></el-form-item>
|
||||
<el-button v-if="canManage" class="remove-row" link type="danger" :aria-label="`删除第${index + 1}条过滤条件`" @click="removeFilter(index)">删除</el-button>
|
||||
</div>
|
||||
<div v-if="!draft.filters.length" class="muted-copy filter-empty">未配置过滤条件,将按金蝶接口返回规则执行。</div>
|
||||
</div>
|
||||
</el-form>
|
||||
|
||||
<div v-if="!detailLoading && !detailError" class="detail-actions" aria-label="同步规则操作">
|
||||
<el-button type="primary" :disabled="!canManage || actionLoading === 'save'" :loading="actionLoading === 'save'" @click="saveConfig">保存配置</el-button>
|
||||
<el-button v-if="canPrepare" :disabled="editingId === null || Boolean(actionLoading)" :loading="actionLoading === 'prepare'" @click="prepareTable">创建/校验目标表</el-button>
|
||||
<el-button v-if="canPreview" :disabled="editingId === null || Boolean(actionLoading)" :loading="actionLoading === 'preview'" @click="previewData">预览数据</el-button>
|
||||
<el-button type="success" :disabled="syncDisabled" :loading="syncInProgress" @click="syncNow">{{ activeRun ? '同步运行中' : '立即同步' }}</el-button>
|
||||
</div>
|
||||
|
||||
<div v-if="prepareResult" class="result-note" :class="prepareResult.success === false ? 'result-danger' : 'result-success'" role="status">{{ prepareResult.message || (prepareResult.success === false ? '目标表处理失败' : '目标表已创建或校验通过') }}</div>
|
||||
<section v-if="previewResult" class="result-section" aria-labelledby="preview-result-title">
|
||||
<div class="result-title"><h4 id="preview-result-title">预览结果</h4><el-tag v-if="previewResult.truncated" type="warning" size="small">结果已截断</el-tag></div>
|
||||
<p class="result-meta">过滤条件:{{ previewResult.filterString || '无' }} · 返回 {{ previewResult.rows.length }} 行</p>
|
||||
<div v-if="!previewResult.rows.length" class="muted-copy">暂无符合条件的数据。</div>
|
||||
<div v-else class="table-scroll preview-table" role="region" aria-label="同步数据预览" tabindex="0"><el-table :data="previewResult.rows" size="small"><el-table-column v-for="column in previewColumns" :key="column" :prop="column" :label="column" min-width="140"><template #default="scope">{{ formatCell(scope.row[column]) }}</template></el-table-column></el-table></div>
|
||||
</section>
|
||||
<div v-if="runNotice" class="result-note" :class="runNoticeDanger ? 'result-danger' : 'result-pending'" :role="runNoticeDanger ? 'alert' : 'status'" aria-live="polite">
|
||||
<span>{{ runNotice }}</span><el-button v-if="pollingTimedOut" link type="primary" size="small" :loading="runLoading" @click="refreshRunStatus">刷新运行状态</el-button>
|
||||
</div>
|
||||
<section v-if="latestRun || runs.length" class="result-section" aria-labelledby="run-result-title">
|
||||
<div class="result-title"><h4 id="run-result-title">运行结果</h4><span v-if="runLoading" class="muted-copy" role="status">正在查询状态…</span></div>
|
||||
<div v-if="latestRun" class="run-summary" role="status" aria-live="polite"><span>状态:{{ latestRun.status }}</span><span>fetched:{{ latestRun.fetchedCount ?? 0 }}</span><span>inserted:{{ latestRun.insertedCount ?? 0 }}</span><span>updated:{{ latestRun.updatedCount ?? 0 }}</span><span>failed:{{ latestRun.failedCount ?? 0 }}</span><span v-if="latestRun.errorMessage" class="run-error">{{ latestRun.errorMessage }}</span></div>
|
||||
<div v-if="runs.length" class="table-scroll run-table" role="region" aria-label="历史运行结果" tabindex="0"><el-table :data="runs" size="small"><el-table-column prop="status" label="status" width="110" /><el-table-column prop="fetchedCount" label="fetched" width="95" /><el-table-column prop="insertedCount" label="inserted" width="95" /><el-table-column prop="updatedCount" label="updated" width="95" /><el-table-column prop="failedCount" label="failed" width="85" /><el-table-column label="运行时间" min-width="180"><template #default="scope">{{ formatDate(scope.row.startedAt) }}</template></el-table-column></el-table></div>
|
||||
</section>
|
||||
</div>
|
||||
<template #footer><el-button :disabled="dialogBusy" @click="requestKingdeeDialogClose">关闭</el-button></template>
|
||||
</el-dialog>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
|
||||
import { adminApi, type KingdeePrepareTableResult, type KingdeeSyncConfig, type KingdeeSyncConfigId, type KingdeeSyncConfigPayload, type KingdeeSyncDataType, type KingdeeSyncFilterOperator, type KingdeeSyncPreview, type KingdeeSyncRun } from '@/api/admin'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
|
||||
type DraftField = KingdeeSyncConfigPayload['fields'][number] & { _key: string }
|
||||
type DraftFilter = KingdeeSyncConfigPayload['filters'][number] & { _key: string }
|
||||
type KingdeeSyncDraft = Omit<KingdeeSyncConfigPayload, 'fields' | 'filters'> & { fields: DraftField[]; filters: DraftFilter[] }
|
||||
type Action = '' | 'save' | 'prepare' | 'preview' | 'sync'
|
||||
type DialogPositionInstance = { resetPosition: () => void }
|
||||
|
||||
const props = withDefaults(defineProps<{ canView: boolean; canCreate: boolean; canUpdate: boolean; canDelete: boolean; canPrepare: boolean; canPreview: boolean; canSync: boolean }>(), { canView: false, canCreate: false, canUpdate: false, canDelete: false, canPrepare: false, canPreview: false, canSync: false })
|
||||
const dataTypes: KingdeeSyncDataType[] = ['STRING', 'INTEGER', 'BIGINT', 'DECIMAL', 'DATE', 'DATETIME', 'BOOLEAN', 'JSON']
|
||||
const operators: Array<{ value: KingdeeSyncFilterOperator; label: string }> = [
|
||||
{ value: 'EQ', label: '等于(EQ)' }, { value: 'NE', label: '不等于(NE)' }, { value: 'GT', label: '大于(GT)' }, { value: 'GE', label: '大于等于(GE)' },
|
||||
{ value: 'LT', label: '小于(LT)' }, { value: 'LE', label: '小于等于(LE)' }, { value: 'LIKE', label: '包含(LIKE)' }, { value: 'IN', label: '集合(IN)' },
|
||||
]
|
||||
const configs = ref<KingdeeSyncConfig[]>([])
|
||||
const loading = ref(false)
|
||||
const loaded = ref(false)
|
||||
const loadError = ref('')
|
||||
const dialogVisible = ref(false)
|
||||
const dialogRef = ref<DialogPositionInstance>()
|
||||
const desktopDragMedia = window.matchMedia('(min-width: 761px)')
|
||||
const desktopDialogDrag = ref(desktopDragMedia.matches)
|
||||
const resetKingdeeDialogPosition = () => { dialogRef.value?.resetPosition() }
|
||||
const updateDesktopDialogDrag = (event: MediaQueryListEvent) => { desktopDialogDrag.value = event.matches;if(!event.matches)resetKingdeeDialogPosition() }
|
||||
desktopDragMedia.addEventListener('change', updateDesktopDialogDrag)
|
||||
window.addEventListener('resize', resetKingdeeDialogPosition)
|
||||
const editingId = ref<KingdeeSyncConfigId | null>(null)
|
||||
const detailLoading = ref(false)
|
||||
const detailError = ref('')
|
||||
const formRef = ref<FormInstance>()
|
||||
const draft = ref<KingdeeSyncDraft>(emptyDraft())
|
||||
const validationError = ref('')
|
||||
const actionLoading = ref<Action>('')
|
||||
const prepareResult = ref<KingdeePrepareTableResult | null>(null)
|
||||
const previewResult = ref<KingdeeSyncPreview | null>(null)
|
||||
const latestRun = ref<KingdeeSyncRun | null>(null)
|
||||
const runs = ref<KingdeeSyncRun[]>([])
|
||||
const runLoading = ref(false)
|
||||
const runNotice = ref('')
|
||||
const runNoticeDanger = ref(false)
|
||||
const pollingTimedOut = ref(false)
|
||||
const pollingRunId = ref<KingdeeSyncConfigId | null>(null)
|
||||
const syncUncertain = ref(false)
|
||||
const POLL_FAST_INTERVAL_MS = 2000
|
||||
const POLL_SLOW_INTERVAL_MS = 5000
|
||||
const POLL_BACKOFF_AFTER_MS = 30 * 1000
|
||||
const POLL_TIMEOUT_MS = 31 * 60 * 1000
|
||||
const terminalStatuses = new Set(['SUCCEEDED', 'PARTIAL', 'FAILED'])
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let pollStartedAt = 0
|
||||
let pollDeadline = 0
|
||||
let runContext = 0
|
||||
let pollingBaseline = new Set<string>()
|
||||
let configLoadGeneration = 0
|
||||
let configRefreshQueued = false
|
||||
let configLoadPromise: Promise<void> | null = null
|
||||
|
||||
const { page: currentPage, pageSize, paginatedItems: pagedConfigs } = useListPagination(configs)
|
||||
const previewColumns = computed(() => {
|
||||
const columns = new Set<string>()
|
||||
previewResult.value?.rows.forEach(row => Object.keys(row).forEach(key => columns.add(key)))
|
||||
return Array.from(columns)
|
||||
})
|
||||
const activeRun = computed(() => runs.value.find(run => run.status === 'RUNNING') || (latestRun.value?.status === 'RUNNING' ? latestRun.value : null))
|
||||
const canManage = computed(() => editingId.value === null ? props.canCreate : props.canUpdate)
|
||||
const syncInProgress = computed(() => actionLoading.value === 'sync' || Boolean(activeRun.value) || syncUncertain.value)
|
||||
const syncDisabled = computed(() => !props.canSync || editingId.value === null || Boolean(actionLoading.value) || Boolean(activeRun.value) || syncUncertain.value)
|
||||
const dialogBusy = computed(() => detailLoading.value || runLoading.value || Boolean(actionLoading.value) || syncInProgress.value)
|
||||
|
||||
function beforeKingdeeDialogClose(done: () => void) { if (!dialogBusy.value) done() }
|
||||
function requestKingdeeDialogClose() { if (!dialogBusy.value) dialogVisible.value = false }
|
||||
|
||||
function key(prefix: string) { return `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}` }
|
||||
function emptyField(): DraftField { return { _key: key('field'), sourceFieldKey: '', targetColumnName: '', fieldComment: '', dataType: 'STRING', fieldLength: null, sortOrder: 0 } }
|
||||
function emptyFilter(): DraftFilter { return { _key: key('filter'), sourceFieldKey: '', operator: 'EQ', filterValue: '', sortOrder: 0 } }
|
||||
function emptyDraft(): KingdeeSyncDraft { return { configName: '', formId: '', targetTableName: '', targetTableComment: '', enabled: true, maxRowsPerRun: 1000, fields: [emptyField()], filters: [] } }
|
||||
function normalizeDraft(config: Partial<KingdeeSyncConfig>): KingdeeSyncDraft {
|
||||
return {
|
||||
configName: String(config.configName || ''), formId: String(config.formId || ''), targetTableName: String(config.targetTableName || ''), targetTableComment: String(config.targetTableComment || ''),
|
||||
enabled: config.enabled !== false, maxRowsPerRun: Number(config.maxRowsPerRun) || 1000,
|
||||
fields: (Array.isArray(config.fields) && config.fields.length ? config.fields : [emptyField()]).map((field, index) => ({ ...field, _key: key('field'), fieldComment: field.fieldComment || '', fieldLength: field.fieldLength ?? null, sortOrder: index })),
|
||||
filters: (Array.isArray(config.filters) ? config.filters : []).map((filter, index) => ({ ...filter, _key: key('filter'), filterValue: String(filter.filterValue || ''), sortOrder: index })),
|
||||
}
|
||||
}
|
||||
function stopRunTracking() {
|
||||
if (pollTimer) clearTimeout(pollTimer)
|
||||
pollTimer = undefined
|
||||
pollingRunId.value = null
|
||||
pollStartedAt = 0
|
||||
pollDeadline = 0
|
||||
}
|
||||
function resetResults() {
|
||||
stopRunTracking(); prepareResult.value = null; previewResult.value = null; latestRun.value = null; runs.value = []; validationError.value = ''; detailError.value = ''
|
||||
runNotice.value = ''; runNoticeDanger.value = false; pollingTimedOut.value = false; syncUncertain.value = false
|
||||
}
|
||||
|
||||
function loadConfigs(): Promise<void> {
|
||||
if (!props.canView) return Promise.resolve()
|
||||
// Every request invalidates an older response. Calls made while a request is
|
||||
// in flight are coalesced into exactly one subsequent refresh.
|
||||
configLoadGeneration += 1
|
||||
configRefreshQueued = true
|
||||
if (!configLoadPromise) {
|
||||
loading.value = true
|
||||
configLoadPromise = drainConfigLoads().finally(() => {
|
||||
loading.value = false
|
||||
configLoadPromise = null
|
||||
})
|
||||
}
|
||||
return configLoadPromise
|
||||
}
|
||||
async function drainConfigLoads() {
|
||||
while (configRefreshQueued && props.canView) {
|
||||
configRefreshQueued = false
|
||||
const generation = configLoadGeneration
|
||||
loadError.value = ''
|
||||
try {
|
||||
const result = await adminApi.listKingdeeSyncConfigs()
|
||||
if (generation !== configLoadGeneration || !props.canView) continue
|
||||
configs.value = Array.isArray(result) ? result : []
|
||||
loaded.value = true
|
||||
if (currentPage.value > Math.max(1, Math.ceil(configs.value.length / pageSize.value))) currentPage.value = 1
|
||||
} catch (error) {
|
||||
if (generation === configLoadGeneration && props.canView) loadError.value = errorText(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
watch(() => props.canView, value => {
|
||||
if (value && !loaded.value) void loadConfigs()
|
||||
else if (!value) { configLoadGeneration += 1; configRefreshQueued = false }
|
||||
}, { immediate: true })
|
||||
|
||||
function openCreate() { if (!props.canCreate) return; runContext += 1; editingId.value = null; draft.value = emptyDraft(); resetResults(); dialogVisible.value = true }
|
||||
async function openEdit(id: KingdeeSyncConfigId) {
|
||||
if (!props.canView) return
|
||||
const context = ++runContext
|
||||
editingId.value = id; draft.value = emptyDraft(); resetResults(); dialogVisible.value = true; detailLoading.value = true
|
||||
try {
|
||||
const config = await adminApi.getKingdeeSyncConfig(id)
|
||||
if (!isCurrentRunContext(id, context)) return
|
||||
draft.value = normalizeDraft(config)
|
||||
await loadRuns(id, context)
|
||||
} catch (error) { if (isCurrentRunContext(id, context)) detailError.value = errorText(error) }
|
||||
finally { if (isCurrentRunContext(id, context)) detailLoading.value = false }
|
||||
}
|
||||
async function deleteConfig(config: KingdeeSyncConfig) {
|
||||
if (!props.canDelete) return
|
||||
try { await ElMessageBox.confirm(`确定删除同步规则“${config.configName}”吗?`, '删除确认', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }) }
|
||||
catch { return }
|
||||
try { await adminApi.deleteKingdeeSyncConfig(config.id); ElMessage.success('同步规则已删除'); await loadConfigs() }
|
||||
catch (error) { ElMessage.error(`删除失败:${errorText(error)}`) }
|
||||
}
|
||||
function addField() { if (canManage.value) draft.value.fields.push(emptyField()) }
|
||||
function removeField(index: number) { if (canManage.value && draft.value.fields.length > 1) draft.value.fields.splice(index, 1) }
|
||||
function onDataTypeChange(field: DraftField) { if (field.dataType !== 'STRING') field.fieldLength = null }
|
||||
function addFilter() { if (canManage.value) draft.value.filters.push(emptyFilter()) }
|
||||
function removeFilter(index: number) { if (canManage.value) draft.value.filters.splice(index, 1) }
|
||||
function fieldError(field: string) {
|
||||
if (!validationError.value) return ''
|
||||
if (field === 'fields' && validationError.value.includes('字段')) return validationError.value
|
||||
if (field === 'configName' && validationError.value.includes('单据名称')) return validationError.value
|
||||
if (field === 'formId' && validationError.value.includes('formId')) return validationError.value
|
||||
if (field === 'targetTableName' && validationError.value.includes('数据库表名')) return validationError.value
|
||||
if (field === 'maxRowsPerRun' && validationError.value.includes('最大同步行数')) return validationError.value
|
||||
return ''
|
||||
}
|
||||
function validateDraft() {
|
||||
const value = draft.value
|
||||
if (!value.configName.trim()) validationError.value = '请填写单据名称。'
|
||||
else if (!value.formId.trim()) validationError.value = '请填写金蝶单据标识(formId)。'
|
||||
else if (!value.targetTableName.trim()) validationError.value = '请填写数据库表名。'
|
||||
else if (!Number.isInteger(value.maxRowsPerRun) || value.maxRowsPerRun < 1 || value.maxRowsPerRun > 100000) validationError.value = '最大同步行数必须是1到100000之间的整数。'
|
||||
else if (!value.fields.length) validationError.value = '至少配置一条字段映射。'
|
||||
else if (value.fields.some(field => !field.sourceFieldKey.trim() || !field.targetColumnName.trim())) validationError.value = '请填写每条字段映射的源字段标识和数据库字段名。'
|
||||
else if (!value.fields.some(field => field.sourceFieldKey.trim().toLowerCase() === 'fbillno')) validationError.value = '字段映射必须包含 FBillNo 作为不可变来源主键。'
|
||||
else if (value.fields.some(field => !dataTypes.includes(field.dataType))) validationError.value = '字段类型不在允许范围内。'
|
||||
else if (value.filters.some(filter => !filter.sourceFieldKey.trim() || !filter.filterValue.trim())) validationError.value = '请完整填写过滤条件的源字段标识和过滤值。'
|
||||
else if (value.filters.some(filter => !operators.some(item => item.value === filter.operator))) validationError.value = '过滤条件操作符不在允许范围内。'
|
||||
else validationError.value = ''
|
||||
return !validationError.value
|
||||
}
|
||||
function buildPayload(): KingdeeSyncConfigPayload {
|
||||
return {
|
||||
configName: draft.value.configName.trim(), formId: draft.value.formId.trim(), targetTableName: draft.value.targetTableName.trim(), targetTableComment: draft.value.targetTableComment.trim(), enabled: draft.value.enabled, maxRowsPerRun: draft.value.maxRowsPerRun,
|
||||
fields: draft.value.fields.map((field, index) => ({ sourceFieldKey: field.sourceFieldKey.trim(), targetColumnName: field.targetColumnName.trim(), fieldComment: field.fieldComment.trim(), dataType: field.dataType, fieldLength: field.fieldLength === null ? null : Number(field.fieldLength), sortOrder: index })),
|
||||
filters: draft.value.filters.map((filter, index) => ({ sourceFieldKey: filter.sourceFieldKey.trim(), operator: filter.operator, filterValue: filter.filterValue.trim(), sortOrder: index })),
|
||||
}
|
||||
}
|
||||
async function saveConfig() {
|
||||
if (!canManage.value || actionLoading.value || !validateDraft()) return
|
||||
const id = editingId.value
|
||||
const context = runContext
|
||||
let currentId = id
|
||||
const payload = buildPayload()
|
||||
actionLoading.value = 'save'
|
||||
try {
|
||||
const result = id === null ? await adminApi.createKingdeeSyncConfig(payload) : await adminApi.updateKingdeeSyncConfig(id, payload)
|
||||
if (!isCurrentActionContext(id, context)) return
|
||||
currentId = result.id
|
||||
editingId.value = result.id; draft.value = normalizeDraft(result); ElMessage.success('同步规则已保存'); await loadConfigs()
|
||||
} catch (error) {
|
||||
if (isCurrentActionContext(id, context)) ElMessage.error(`保存失败:${errorText(error)}`)
|
||||
} finally {
|
||||
if (isCurrentActionContext(currentId, context)) actionLoading.value = ''
|
||||
}
|
||||
}
|
||||
async function prepareTable() {
|
||||
if (!props.canPrepare || editingId.value === null || actionLoading.value) return
|
||||
const id = editingId.value
|
||||
const context = runContext
|
||||
actionLoading.value = 'prepare'; prepareResult.value = null
|
||||
try {
|
||||
const result = await adminApi.prepareKingdeeSyncTable(id)
|
||||
if (!isCurrentActionContext(id, context)) return
|
||||
prepareResult.value = result || { success: true, message: '目标表已创建或校验通过' }
|
||||
ElMessage.success(prepareResult.value.message || '目标表已创建或校验通过')
|
||||
} catch (error) {
|
||||
if (!isCurrentActionContext(id, context)) return
|
||||
prepareResult.value = { success: false, message: errorText(error) }; ElMessage.error(`目标表处理失败:${errorText(error)}`)
|
||||
} finally { if (isCurrentActionContext(id, context)) actionLoading.value = '' }
|
||||
}
|
||||
async function previewData() {
|
||||
if (!props.canPreview || editingId.value === null || actionLoading.value) return
|
||||
const id = editingId.value
|
||||
const context = runContext
|
||||
actionLoading.value = 'preview'; previewResult.value = null
|
||||
try {
|
||||
const result = await adminApi.previewKingdeeSyncConfig(id)
|
||||
if (!isCurrentActionContext(id, context)) return
|
||||
previewResult.value = result; ElMessage.success('数据预览已完成')
|
||||
} catch (error) {
|
||||
if (isCurrentActionContext(id, context)) ElMessage.error(`预览失败:${errorText(error)}`)
|
||||
} finally { if (isCurrentActionContext(id, context)) actionLoading.value = '' }
|
||||
}
|
||||
async function syncNow() {
|
||||
if (syncDisabled.value || editingId.value === null) return
|
||||
const id = editingId.value
|
||||
const context = runContext
|
||||
const baseline = new Set(runs.value.map(run => String(run.id)))
|
||||
actionLoading.value = 'sync'; pollingTimedOut.value = false; runNotice.value = ''; runNoticeDanger.value = false
|
||||
try {
|
||||
const submittedRun = await adminApi.syncKingdeeConfig(id)
|
||||
if (!isCurrentRunContext(id, context)) return
|
||||
latestRun.value = submittedRun
|
||||
runs.value = [submittedRun, ...runs.value.filter(run => String(run.id) !== String(submittedRun.id))]
|
||||
if (submittedRun.status === 'RUNNING') {
|
||||
runNotice.value = '同步任务已提交,正在后台运行。'
|
||||
beginPolling(id, submittedRun.id, context, baseline)
|
||||
} else {
|
||||
finishRun(submittedRun)
|
||||
}
|
||||
} catch {
|
||||
if (!isCurrentRunContext(id, context)) return
|
||||
// A client timeout does not prove that the server rejected the task. Keep
|
||||
// submission disabled while run history is used to reconcile the outcome.
|
||||
syncUncertain.value = true
|
||||
runNotice.value = '同步请求结果未确认,正在查询服务器运行状态,请勿重复提交。'
|
||||
ElMessage.warning('同步请求结果未确认,正在查询运行状态')
|
||||
const history = await fetchRuns(id, context)
|
||||
if (!history || !isCurrentRunContext(id, context)) return
|
||||
const running = history.find(run => run.status === 'RUNNING')
|
||||
if (running) beginPolling(id, running.id, context, baseline)
|
||||
else beginPolling(id, null, context, baseline)
|
||||
} finally { if (isCurrentRunContext(id, context)) actionLoading.value = '' }
|
||||
}
|
||||
function isCurrentRunContext(id: KingdeeSyncConfigId, context: number) {
|
||||
return isCurrentActionContext(id, context)
|
||||
}
|
||||
function isCurrentActionContext(id: KingdeeSyncConfigId | null, context: number) {
|
||||
return dialogVisible.value && context === runContext && (id === null ? editingId.value === null : String(editingId.value) === String(id))
|
||||
}
|
||||
async function fetchRuns(id: KingdeeSyncConfigId, context: number) {
|
||||
runLoading.value = true
|
||||
try {
|
||||
const result = await adminApi.listKingdeeSyncRuns(id)
|
||||
if (!isCurrentRunContext(id, context)) return null
|
||||
runs.value = Array.isArray(result) ? result : []
|
||||
latestRun.value = runs.value[0] || null
|
||||
return runs.value
|
||||
} catch {
|
||||
if (isCurrentRunContext(id, context)) runNotice.value = '暂时无法查询运行状态,将自动重试。'
|
||||
return null
|
||||
} finally { if (isCurrentRunContext(id, context)) runLoading.value = false }
|
||||
}
|
||||
async function loadRuns(id: KingdeeSyncConfigId, context = runContext) {
|
||||
const history = await fetchRuns(id, context)
|
||||
if (!history || !isCurrentRunContext(id, context)) return
|
||||
const running = history.find(run => run.status === 'RUNNING')
|
||||
if (running) {
|
||||
runNotice.value = '检测到正在运行的同步任务,正在查询状态。'
|
||||
beginPolling(id, running.id, context, new Set(history.map(run => String(run.id))))
|
||||
} else {
|
||||
syncUncertain.value = false
|
||||
}
|
||||
}
|
||||
function beginPolling(id: KingdeeSyncConfigId, runId: KingdeeSyncConfigId | null, context: number, baseline: Set<string>) {
|
||||
stopRunTracking()
|
||||
pollingRunId.value = runId
|
||||
pollingBaseline = baseline
|
||||
pollStartedAt = Date.now()
|
||||
pollDeadline = pollStartedAt + POLL_TIMEOUT_MS
|
||||
syncUncertain.value = syncUncertain.value || runId === null
|
||||
schedulePoll(id, context)
|
||||
}
|
||||
function schedulePoll(id: KingdeeSyncConfigId, context: number) {
|
||||
if (!isCurrentRunContext(id, context)) return
|
||||
const remaining = pollDeadline - Date.now()
|
||||
if (remaining <= 0) { handlePollingTimeout(); return }
|
||||
const interval = Date.now() - pollStartedAt >= POLL_BACKOFF_AFTER_MS ? POLL_SLOW_INTERVAL_MS : POLL_FAST_INTERVAL_MS
|
||||
pollTimer = setTimeout(() => void pollRuns(id, context), Math.min(interval, remaining))
|
||||
}
|
||||
async function pollRuns(id: KingdeeSyncConfigId, context: number) {
|
||||
pollTimer = undefined
|
||||
if (!isCurrentRunContext(id, context)) return
|
||||
if (Date.now() >= pollDeadline) { handlePollingTimeout(); return }
|
||||
const history = await fetchRuns(id, context)
|
||||
if (!isCurrentRunContext(id, context)) return
|
||||
if (history) {
|
||||
let tracked = pollingRunId.value === null ? undefined : history.find(run => String(run.id) === String(pollingRunId.value))
|
||||
if (!tracked && pollingRunId.value === null) tracked = history.find(run => run.status === 'RUNNING') || history.find(run => !pollingBaseline.has(String(run.id)))
|
||||
if (tracked?.status === 'RUNNING') {
|
||||
pollingRunId.value = tracked.id; syncUncertain.value = false; runNotice.value = '同步任务正在后台运行。'
|
||||
} else if (tracked && terminalStatuses.has(tracked.status)) {
|
||||
latestRun.value = tracked; stopRunTracking(); syncUncertain.value = false; finishRun(tracked); return
|
||||
}
|
||||
}
|
||||
schedulePoll(id, context)
|
||||
}
|
||||
function finishRun(run: KingdeeSyncRun) {
|
||||
if (run.status === 'SUCCEEDED') { runNotice.value = '同步任务已成功完成。'; runNoticeDanger.value = false; ElMessage.success('同步任务已完成') }
|
||||
else if (run.status === 'PARTIAL') { runNotice.value = `同步任务部分完成${run.errorMessage ? `:${run.errorMessage}` : '。'}`; runNoticeDanger.value = true; ElMessage.warning('同步任务部分完成') }
|
||||
else if (run.status === 'FAILED') { runNotice.value = `同步任务失败${run.errorMessage ? `:${run.errorMessage}` : '。'}`; runNoticeDanger.value = true; ElMessage.error('同步任务失败') }
|
||||
}
|
||||
function handlePollingTimeout() {
|
||||
stopRunTracking(); pollingTimedOut.value = true
|
||||
runNotice.value = '运行状态查询已超时;这不代表同步任务失败,请刷新状态确认结果。'
|
||||
runNoticeDanger.value = false
|
||||
}
|
||||
async function refreshRunStatus() {
|
||||
if (editingId.value === null || runLoading.value) return
|
||||
const id = editingId.value; const context = runContext
|
||||
pollingTimedOut.value = false; runNotice.value = ''
|
||||
const history = await fetchRuns(id, context)
|
||||
if (!history || !isCurrentRunContext(id, context)) return
|
||||
const running = history.find(run => run.status === 'RUNNING')
|
||||
syncUncertain.value = false
|
||||
if (running) { runNotice.value = '同步任务正在后台运行。'; beginPolling(id, running.id, context, new Set(history.map(run => String(run.id)))) }
|
||||
else if (history[0] && terminalStatuses.has(history[0].status)) finishRun(history[0])
|
||||
}
|
||||
watch(dialogVisible, visible => {
|
||||
if (!visible) { runContext += 1; stopRunTracking(); actionLoading.value = ''; syncUncertain.value = false }
|
||||
})
|
||||
onBeforeUnmount(() => { runContext += 1; stopRunTracking(); desktopDragMedia.removeEventListener('change', updateDesktopDialogDrag);window.removeEventListener('resize', resetKingdeeDialogPosition) })
|
||||
function formatCell(value: unknown) { return typeof value === 'object' && value !== null ? JSON.stringify(value) : String(value ?? '') }
|
||||
function formatDate(value: unknown) { const date = new Date(typeof value === 'string' || typeof value === 'number' ? value : ''); return Number.isFinite(date.getTime()) ? date.toLocaleString() : '—' }
|
||||
function errorText(error: unknown) { return error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。' }
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.sync-panel { min-width: 0; margin: 18px 0 4px; padding: 16px 0 0; border-top: 1px solid var(--line); }
|
||||
.sync-head { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 12px; padding: 0 0 14px; }
|
||||
.sync-head > div { min-width: 0; flex: 1 1 320px; }
|
||||
.sync-head h3 { margin-top: 2px; font-size: 16px; }
|
||||
.sync-head p { margin-top: 4px; color: var(--muted); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.sync-empty, .sync-loading { display: flex; min-height: 78px; align-items: center; justify-content: center; gap: 8px; padding: 18px; color: var(--muted); text-align: center; }
|
||||
.sync-empty { flex-direction: column; border: 1px dashed var(--line-strong); border-radius: var(--radius); }
|
||||
.sync-empty strong { color: var(--body); }
|
||||
.sync-alert { margin: 0 0 12px; }
|
||||
.table-scroll { width: 100%; overflow-x: auto; }
|
||||
.table-scroll :deep(.el-table) { min-width: 720px; }
|
||||
.row-actions { display: flex; align-items: center; gap: 2px; white-space: nowrap; }
|
||||
.dialog-content { min-width: 0; padding: 0 1px 2px; }
|
||||
.sync-form-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0 14px; }
|
||||
.mapping-list, .filter-list { display: grid; gap: 10px; }
|
||||
.mapping-row { display: grid; grid-template-columns: minmax(130px, 1.2fr) minmax(130px, 1.2fr) minmax(120px, 1fr) minmax(125px, .8fr) minmax(100px, .7fr) auto; align-items: start; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; background: #fafbfd; }
|
||||
.filter-row { display: grid; grid-template-columns: minmax(160px, 1fr) minmax(150px, .8fr) minmax(180px, 1.3fr) auto; align-items: start; gap: 8px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; background: #fafbfd; }
|
||||
.mapping-row :deep(.el-form-item), .filter-row :deep(.el-form-item) { margin-bottom: 0; }
|
||||
.remove-row { margin-top: 30px; }
|
||||
.subsection-head { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; margin: 16px 0 10px; padding-top: 15px; border-top: 1px solid var(--line); }
|
||||
.subsection-head h4, .result-title h4 { color: var(--text); font-size: 13px; }
|
||||
.subsection-head p, .result-meta { color: var(--muted); font-size: 11px; }
|
||||
.filter-head { margin-top: 8px; }
|
||||
.filter-empty { padding: 10px; border: 1px dashed var(--line-strong); border-radius: var(--radius); }
|
||||
.form-error { margin-bottom: 12px; color: var(--danger); font-size: 12px; }
|
||||
.compact-error { margin-top: -2px; }
|
||||
.detail-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 18px; padding: 14px; border: 1px solid #cdddea; border-radius: 6px; background: #f4f8fc; }
|
||||
.result-note { margin-top: 12px; padding: 8px 10px; border-radius: 5px; font-size: 12px; }
|
||||
.result-success { color: var(--success); background: var(--success-soft); }
|
||||
.result-danger { color: var(--danger); background: var(--danger-soft); }
|
||||
.result-pending { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--body); background: var(--surface-raised); border: 1px solid var(--line); }
|
||||
.result-section { margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--line); }
|
||||
.result-title { display: flex; align-items: center; gap: 8px; margin-bottom: 6px; }
|
||||
.result-meta { margin-bottom: 8px; overflow-wrap: anywhere; }
|
||||
.preview-table :deep(.el-table), .run-table :deep(.el-table) { min-width: 520px; }
|
||||
.run-summary { display: flex; flex-wrap: wrap; gap: 8px 18px; margin: 8px 0; color: var(--body); font: 12px var(--mono); }
|
||||
.run-error { flex-basis: 100%; color: var(--danger); overflow-wrap: anywhere; }
|
||||
@media (max-width: 860px) { .sync-form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } .mapping-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } .filter-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } .remove-row { margin-top: 0; justify-self: start; } }
|
||||
@media (max-width: 560px) { .sync-form-grid { grid-template-columns: 1fr; } .mapping-row, .filter-row { grid-template-columns: 1fr; padding: 10px; } .detail-actions { align-items: stretch; flex-direction: column; } .detail-actions :deep(.el-button) { width: 100%; min-height: 44px; margin-left: 0; } }
|
||||
</style>
|
||||
@@ -1,50 +1,641 @@
|
||||
<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="application-form">
|
||||
<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 && !definitionError" class="inline-alert danger" role="alert"><b>!</b><span>{{ loadError }}</span></div>
|
||||
<div v-if="!loading && attachmentIntegrityError" class="inline-alert danger" role="alert"><b>!</b><span>{{ attachmentIntegrityError }}</span></div>
|
||||
<div v-if="staleDefinition" class="inline-alert danger conflict-alert" role="alert"><b>409</b><span><strong>审批模板已更新,当前内容不能保存或提交</strong><br>当前页面仍保留原模板及全部输入。升级前不会删除或改写任何值。</span><button v-if="definition?.mode === 'FEISHU'" class="btn small" type="button" :disabled="migratingDefinition" :aria-busy="migratingDefinition" @click="migrateStaleDefinition">{{ migratingDefinition ? '正在读取最新模板…' : '升级到最新模板并核对' }}</button></div>
|
||||
<div v-if="migrationNotice" class="inline-alert migration-alert" role="status"><b>↑</b><span><strong>草稿已升级到当前飞书审批模板</strong><br>{{ migrationNotice }}</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 v-if="loading" class="card load-wrap" role="status" aria-live="polite"><span class="loader" aria-hidden="true"></span><span>正在读取飞书报销模板…</span></div>
|
||||
<div v-else-if="definitionError" class="card definition-state" role="alert"><strong>模板暂时无法加载</strong><span>{{ definitionError }}</span><div><button class="btn" type="button" @click="loadPage">重新检查</button><router-link class="btn" to="/applications">返回我的报销</router-link></div></div>
|
||||
|
||||
<form v-else class="form-page" @submit.prevent="save(true)">
|
||||
<div v-if="isFeishu" class="definition-bar" aria-label="飞书表单模板信息"><strong>飞书审批表单</strong><span>版本 {{ shortFingerprint }}</span><span v-if="definition?.fetchedAt">同步于 {{ formatDateTime(definition.fetchedAt) }}</span></div>
|
||||
<section v-if="isFeishu" class="section-card" aria-labelledby="feishu-form-title">
|
||||
<div class="section-title"><h2 id="feishu-form-title">飞书审批信息</h2><span>按模板顺序 · * 为必填项</span></div>
|
||||
<FeishuFormFields :fields="activeFields" :form-values="formValues" :form="form" :derived="derivedValues" :show-errors="showValidationErrors" :items-total="itemsTotal" :amount-matches="amountMatches" :expense-types="expenseTypes" :form-fingerprint="pinnedFingerprint" @add-item="addItem" @remove-item="removeItem" @upload-state-change="attachmentRevision++" />
|
||||
</section>
|
||||
|
||||
<section v-if="hasSupplementFields" class="section-card" :class="{ 'section-gap': isFeishu }" aria-labelledby="finance-supplement-title">
|
||||
<div class="section-title"><h2 id="finance-supplement-title">财务补充信息</h2><span>审批与付款必需 · * 为必填项</span></div>
|
||||
<div class="form-grid">
|
||||
<div v-if="missingBinding('TITLE')" class="field"><label for="title">报销事项 <em>*</em></label><input id="title" v-model.trim="form.title" required maxlength="100"></div>
|
||||
<div v-if="missingBinding('EXPENSE_TYPE')" class="field"><label for="expense-type">费用类型 <em>*</em></label><select id="expense-type" v-model.number="form.expenseTypeId" required @change="syncExpenseType"><option value="" disabled>请选择</option><option v-for="type in expenseTypes" :key="type.id" :value="type.id">{{ type.name }}</option></select></div>
|
||||
<div v-if="missingBinding('TOTAL_AMOUNT') && showField('application:amount')" class="field"><label for="amount">报销金额(元) <em>*</em></label><input id="amount" v-model.number="form.totalAmount" type="number" min="0.01" step="0.01" :readonly="readonlyField('application:amount')" required><small v-if="readonlyField('application:amount')" class="form-help">当前字段只读</small></div>
|
||||
<div v-if="missingBinding('DESCRIPTION')" 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 v-if="showField('application:payeeName')" class="field"><label for="payee">收款人 <em>*</em></label><input id="payee" v-model.trim="form.payeeName" :readonly="readonlyField('application:payeeName')" maxlength="100" required><small v-if="readonlyField('application:payeeName')" class="form-help">当前字段只读</small></div>
|
||||
<div v-if="showField('application:bankAccount')" class="field"><label for="bank">收款账户 ID <em>*</em></label><input id="bank" v-model.number="form.payeeBankId" type="number" min="1" step="1" :readonly="readonlyField('application:bankAccount')" required><small class="form-help">{{ readonlyField('application:bankAccount') ? '当前字段只读;账户信息不会明文展示。' : '后端按账户 ID 关联,详情页只显示脱敏账号。' }}</small></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="missingBinding('EXPENSE_ITEMS')" class="section-card section-gap" aria-labelledby="expense-items-title">
|
||||
<div class="section-title"><h2 id="expense-items-title">费用明细</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}`"
|
||||
:value="localAmountText(item)"
|
||||
type="text"
|
||||
inputmode="decimal"
|
||||
autocomplete="off"
|
||||
placeholder="0.00"
|
||||
required
|
||||
:aria-invalid="showValidationErrors && Boolean(itemAmountError(item))"
|
||||
@input="setLocalItemAmount(item, $event)"
|
||||
@blur="normalizeLocalItemAmount(item)"
|
||||
>
|
||||
<small v-if="showValidationErrors && itemAmountError(item)" class="field-error" role="alert">! {{ itemAmountError(item) }}</small>
|
||||
<small v-else class="form-help">请填写大于 0 的金额,最多两位小数,上限 99,999,999.99 元</small>
|
||||
</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>
|
||||
<small v-if="form.totalAmount > 0 && !amountMatches" class="field-error" role="status">明细合计须与申请金额一致,请核对各行金额。</small>
|
||||
</section>
|
||||
|
||||
<div v-if="canWriteApplication" class="form-actions"><button class="btn" type="button" :disabled="saving || staleDefinition || hasAttachmentBlocks" :title="hasAttachmentBlocks ? attachmentBlockMessage : undefined" @click="save(false)">{{ saving ? '保存中…' : '保存草稿' }}</button><button v-if="canSubmit" class="btn primary" type="submit" :disabled="saving || staleDefinition || hasUnsupported || hasAttachmentBlocks" :title="hasAttachmentBlocks ? attachmentBlockMessage : undefined" :aria-busy="saving">{{ saving ? '处理中…' : '提交报销' }}</button></div>
|
||||
</form>
|
||||
|
||||
<dialog ref="previewDialog" v-dialog-drag class="app-dialog route-dialog" aria-modal="true" aria-labelledby="route-dialog-title" aria-describedby="route-dialog-description" @cancel="handleDialogCancel" @click="handleBackdropClick">
|
||||
<div class="app-dialog__panel route-dialog-panel">
|
||||
<header class="route-dialog-head" data-dialog-drag-handle>
|
||||
<div><span class="eyebrow">APPROVAL PREVIEW</span><h2 id="route-dialog-title">确认审批路线</h2><p id="route-dialog-description">以下为预计审批路径,实际审批人可能在提交时由飞书确定。</p></div>
|
||||
<button class="modal-close" type="button" aria-label="关闭审批路线预览" :disabled="submitting" @click="closePreview">×</button>
|
||||
</header>
|
||||
|
||||
<div class="route-dialog-body">
|
||||
<dl class="route-summary" aria-label="报销摘要"><div><dt>报销事项</dt><dd>{{ form.title }}</dd></div><div><dt>费用类型</dt><dd>{{ form.category }}</dd></div><div><dt>报销金额</dt><dd>{{ money(form.totalAmount) }}</dd></div></dl>
|
||||
|
||||
<div v-if="previewLoading" class="route-state" role="status" aria-live="polite"><span class="loader" aria-hidden="true"></span><span>正在获取预计审批路径…</span></div>
|
||||
<div v-else-if="previewError" class="route-state route-error" role="alert"><strong>审批路线预览失败</strong><span>{{ previewError }}</span><button ref="retryButton" class="btn small" type="button" :disabled="previewLoading || submitting" @click="requestPreview">重新预览</button></div>
|
||||
<template v-else-if="preview">
|
||||
<div class="route-meta"><span class="tag">{{ preview.source === 'FEISHU' ? 'FEISHU · 飞书' : 'LOCAL · 本地流程' }}</span><span>{{ preview.exact ? '按当前配置精确预览' : '提交时可能动态调整' }}</span><span v-if="preview.snapshotFetchedAt">最后同步时间:{{ formatDateTime(preview.snapshotFetchedAt) }}</span></div>
|
||||
<div v-if="preview.staleSnapshot || preview.warning" class="route-warning" role="status" aria-live="polite"><strong>路线提示</strong><span>{{ preview.warning || '通讯录或审批配置快照可能不是最新状态,请确认后提交。' }}</span></div>
|
||||
<h3>预计审批路径</h3>
|
||||
<ol v-if="orderedNodes.length" class="route-list" aria-label="预计审批路径节点">
|
||||
<li v-for="node in orderedNodes" :key="`${node.order}-${node.nodeKey}`">
|
||||
<span class="route-order" aria-hidden="true">{{ node.order }}</span>
|
||||
<div><strong>{{ node.nodeName }}</strong><small v-if="node.nodeType || node.approvalMode">{{ [node.nodeType, node.approvalMode].filter(Boolean).join(' · ') }}</small><ul v-if="node.approverLabels.length" class="approver-list" aria-label="审批人"><li v-for="label in node.approverLabels" :key="label">{{ label }}</li></ul><p v-if="node.dynamic" class="dynamic-approver"><strong>动态审批人</strong><span>提交时由飞书确定</span></p><p v-else-if="!node.approverLabels.length" class="quiet-copy">未提供审批人信息</p></div>
|
||||
</li>
|
||||
</ol>
|
||||
<div v-else class="route-state" role="status"><strong>暂无审批节点</strong><span>当前预览未返回审批节点,请返回修改或重新预览。</span></div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<footer class="route-dialog-actions"><button class="btn" type="button" :disabled="submitting" @click="closePreview">返回修改</button><button v-if="canSubmit" class="btn primary" type="button" :disabled="!preview || previewLoading || submitting || hasAttachmentBlocks" :aria-busy="submitting" @click="confirmSubmit">{{ submitting ? '提交中…' : '确认提交' }}</button></footer>
|
||||
</div>
|
||||
</dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { CreateApplicationRequest, ExpenseItem } from '@/api/reimbursement'
|
||||
import { reimbursementApi, type ApprovalRoutePreview, type CreateApplicationRequest, type ExpenseItem, type ExpenseTypeMetadata, type ReimbursementFormAttachment, type ReimbursementFormDefinition, type ReimbursementFormField } from '@/api/reimbursement'
|
||||
import FeishuFormFields from '@/components/reimbursement/FeishuFormFields.vue'
|
||||
import { attachmentIdsMissingMetadata, expenseItemAttachmentMetadata, hydratedAttachmentIds } from '@/modules/reimbursementAttachments'
|
||||
import { useUserStore } from '@/store/user'
|
||||
import { useWorkbenchStore } from '@/store/workbench'
|
||||
import { inspectMoneyAmount, moneyAmountMessage, normalizeMoneyAmount } from '@/utils/moneyAmount'
|
||||
|
||||
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()] })
|
||||
interface AttachmentEntry extends ReimbursementFormAttachment { localKey: string; status: 'uploaded' | 'pending' | 'failed' | 'deleting'; error?: string }
|
||||
interface FormItem extends ExpenseItem { key: number; description: string; attachmentFiles: AttachmentEntry[] }
|
||||
|
||||
// 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 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 submitting = ref(false)
|
||||
const loadError = ref('')
|
||||
const definitionError = ref('')
|
||||
const definition = ref<ReimbursementFormDefinition | null>(null)
|
||||
const expenseTypes = ref<ExpenseTypeMetadata[]>([])
|
||||
const activeFields = ref<ReimbursementFormField[]>([])
|
||||
const activeMode = ref<'FEISHU' | 'LOCAL'>('LOCAL')
|
||||
const pinnedFingerprint = ref<string>()
|
||||
const formValues = reactive<Record<string, unknown>>({})
|
||||
const staleDefinition = ref(false)
|
||||
const migrationNotice = ref('')
|
||||
const migratingDefinition = ref(false)
|
||||
const showValidationErrors = ref(false)
|
||||
const previewDialog = ref<HTMLDialogElement | null>(null)
|
||||
const retryButton = ref<HTMLButtonElement | null>(null)
|
||||
const preview = ref<ApprovalRoutePreview | null>(null)
|
||||
const previewLoading = ref(false)
|
||||
const previewError = ref('')
|
||||
const persistedApplicationId = ref<string | number>('')
|
||||
const attachmentRevision = ref(0)
|
||||
let previewRequestVersion = 0
|
||||
let nextKey = 1
|
||||
|
||||
const userName = computed(() => userStore.userInfo?.realName || store.user?.realName || '用户')
|
||||
const department = computed(() => userStore.userInfo?.departmentName || store.user?.departmentName || '—')
|
||||
const newItem = (value?: Partial<ExpenseItem>, applicationAttachments: Parameters<typeof expenseItemAttachmentMetadata>[1] = []): FormItem => {
|
||||
const files = expenseItemAttachmentMetadata(value, applicationAttachments)
|
||||
const attachmentIds = hydratedAttachmentIds(value, files)
|
||||
return { 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, attachmentIds, attachmentFiles: files.map(file => ({ ...file, localKey: `saved-${file.id}`, status: 'uploaded' })) }
|
||||
}
|
||||
const form = reactive({ title: '', expenseTypeId: undefined as number | undefined, category: '', totalAmount: 0, description: '', payeeName: '', payeeBankId: undefined as number | undefined, items: [newItem()] })
|
||||
|
||||
const canWriteApplication = computed(() => userStore.canEdit(id.value ? 'reimbursement.application.edit' : 'reimbursement.application.create'))
|
||||
const canSubmit = computed(() => userStore.canEdit('reimbursement.application.submit'))
|
||||
const fieldLevel = (code: string): FieldLevel => userStore.access(code)
|
||||
const showField = (code: string) => fieldLevel(code) !== 'HIDDEN'
|
||||
const readonlyField = (code: string) => fieldLevel(code) === 'READ'
|
||||
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 localAmountDrafts = reactive<Record<number, string>>({})
|
||||
const localAmountSource = (item: FormItem) => (localAmountDrafts[item.key] != null ? localAmountDrafts[item.key] : (item.amount > 0 ? item.amount : ''))
|
||||
const localAmountText = (item: FormItem) => (localAmountDrafts[item.key] != null ? localAmountDrafts[item.key] : (item.amount > 0 ? String(item.amount) : ''))
|
||||
const setLocalItemAmount = (item: FormItem, event: Event) => {
|
||||
const text = (event.target as HTMLInputElement).value.trimStart()
|
||||
localAmountDrafts[item.key] = text
|
||||
const issue = inspectMoneyAmount(text)
|
||||
if (!issue) item.amount = normalizeMoneyAmount(text)
|
||||
else if (!text.trim()) item.amount = 0
|
||||
else {
|
||||
const parsed = Number(text)
|
||||
item.amount = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0
|
||||
}
|
||||
}
|
||||
const normalizeLocalItemAmount = (item: FormItem) => {
|
||||
const text = localAmountDrafts[item.key]
|
||||
if (text == null) return
|
||||
if (!inspectMoneyAmount(text)) {
|
||||
item.amount = normalizeMoneyAmount(text)
|
||||
delete localAmountDrafts[item.key]
|
||||
}
|
||||
}
|
||||
const itemAmountError = (item: FormItem) => {
|
||||
const issue = inspectMoneyAmount(localAmountSource(item))
|
||||
return issue ? moneyAmountMessage(issue, '金额') : ''
|
||||
}
|
||||
const orderedNodes = computed(() => [...(preview.value?.nodes || [])].sort((a, b) => a.order - b.order))
|
||||
const isFeishu = computed(() => activeMode.value === 'FEISHU')
|
||||
const canonicalWriterTypes: Partial<Record<ReimbursementFormField['binding'], ReimbursementFormField['type'][]>> = {
|
||||
TITLE: ['TEXT', 'TEXTAREA'], EXPENSE_TYPE: ['SINGLE_SELECT'], TOTAL_AMOUNT: ['DECIMAL'], DESCRIPTION: ['TEXT', 'TEXTAREA'],
|
||||
}
|
||||
const expenseChildBindings = new Set<ReimbursementFormField['binding']>(['EXPENSE_DATE', 'EXPENSE_CATEGORY', 'EXPENSE_DESCRIPTION', 'EXPENSE_AMOUNT', 'EXPENSE_ATTACHMENT'])
|
||||
const compatibleExpenseChild = (child: ReimbursementFormField) => {
|
||||
if (child.type === 'DISPLAY') return !child.required
|
||||
if (child.binding === 'EXPENSE_DATE') return child.type === 'DATE'
|
||||
if (child.binding === 'EXPENSE_CATEGORY') return child.type === 'TEXT' || child.type === 'SINGLE_SELECT'
|
||||
if (child.binding === 'EXPENSE_DESCRIPTION') return child.type === 'TEXT' || child.type === 'TEXTAREA'
|
||||
if (child.binding === 'EXPENSE_AMOUNT') return child.type === 'DECIMAL'
|
||||
if (child.binding === 'EXPENSE_ATTACHMENT') return child.type === 'ATTACHMENT'
|
||||
return false
|
||||
}
|
||||
const validExpenseChild = (child: ReimbursementFormField) => !child.readOnly && child.type !== 'DISPLAY' && compatibleExpenseChild(child)
|
||||
const writableCanonicalField = (field: ReimbursementFormField) => {
|
||||
if (field.binding === 'TOTAL_AMOUNT' && field.type === 'FORMULA') return true
|
||||
if (field.readOnly || field.type === 'DISPLAY') return false
|
||||
if (field.binding === 'EXPENSE_ITEMS') return field.type === 'EXPENSE_ITEMS'
|
||||
&& ['EXPENSE_DATE', 'EXPENSE_DESCRIPTION', 'EXPENSE_AMOUNT'].every(binding => field.children.some(child => child.binding === binding && validExpenseChild(child)))
|
||||
return Boolean(canonicalWriterTypes[field.binding]?.includes(field.type))
|
||||
}
|
||||
const renderedBindings = computed(() => new Set(activeFields.value.filter(writableCanonicalField).map(field => field.binding)))
|
||||
const rowReasonCaptured = computed(() => activeFields.value.some(field => field.type === 'EXPENSE_ITEMS' && field.binding === 'EXPENSE_ITEMS' && field.children.some(child => child.binding === 'EXPENSE_DESCRIPTION' && validExpenseChild(child))))
|
||||
const missingBinding = (binding: string) => !isFeishu.value || (!(['TITLE', 'DESCRIPTION'].includes(binding) && rowReasonCaptured.value) && !renderedBindings.value.has(binding as ReimbursementFormField['binding']))
|
||||
const hasSupplementFields = computed(() => ['TITLE', 'EXPENSE_TYPE', 'TOTAL_AMOUNT', 'DESCRIPTION'].some(missingBinding) || showField('application:payeeName') || showField('application:bankAccount'))
|
||||
const shortFingerprint = computed(() => pinnedFingerprint.value?.slice(0, 8) || '未知')
|
||||
const hasUnsupported = computed(() => activeFields.value.some(field => {
|
||||
if (field.type === 'CONTACT') return field.binding !== 'APPLICANT_CONTACT'
|
||||
if (field.type === 'DEPARTMENT' || field.binding === 'APPLICANT_DEPARTMENT') return field.type !== 'DEPARTMENT' || field.binding !== 'APPLICANT_DEPARTMENT'
|
||||
if (!['TEXT', 'TEXTAREA', 'DECIMAL', 'DATE', 'SINGLE_SELECT', 'MULTI_SELECT', 'DISPLAY', 'EXPENSE_ITEMS', 'FORMULA'].includes(field.type)) return true
|
||||
if (field.type !== 'EXPENSE_ITEMS' && field.binding !== 'EXPENSE_ITEMS') return false
|
||||
return field.children.some(child => !(child.type === 'DISPLAY' && !child.required) && (!expenseChildBindings.has(child.binding) || !compatibleExpenseChild(child)))
|
||||
}))
|
||||
const attachmentFields = computed(() => activeFields.value.filter(field => field.type === 'EXPENSE_ITEMS' && field.binding === 'EXPENSE_ITEMS').flatMap(field => field.children.filter(child => child.type === 'ATTACHMENT' && child.binding === 'EXPENSE_ATTACHMENT')))
|
||||
const attachmentRequired = computed(() => attachmentFields.value.some(field => field.required))
|
||||
const attachmentIntegrityError = computed(() => {
|
||||
void attachmentRevision.value
|
||||
const missing = form.items.flatMap(item => attachmentIdsMissingMetadata(item.attachmentIds, item.attachmentFiles))
|
||||
return missing.length ? `附件信息不完整(ID:${missing.join('、')}),请刷新详情;如仍异常,请联系管理员处理后再保存。` : ''
|
||||
})
|
||||
const attachmentBlockMessage = computed(() => attachmentIntegrityError.value || '请先处理正在上传、移除中或失败的附件')
|
||||
const hasAttachmentBlocks = computed(() => {
|
||||
void attachmentRevision.value
|
||||
return Boolean(attachmentIntegrityError.value) || form.items.some(item => item.attachmentFiles.some(file => file.status === 'pending' || file.status === 'failed' || file.status === 'deleting'))
|
||||
})
|
||||
const derivedValues = computed<Record<string, string>>(() => ({ APPLICATION_NO: existing.value?.applicationNo || '保存后生成', APPLICANT_NAME: userName.value, APPLICANT_CONTACT: userName.value, APPLICANT_DEPARTMENT: department.value, DEPARTMENT: department.value, REIMBURSEMENT_DATE: existing.value?.createdAt?.slice(0, 10) || new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(new Date()), SOURCE_DOC_NO: existing.value?.sourceDocNo || '—' }))
|
||||
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
|
||||
const formatDateTime = (value: string) => { const date = new Date(value); return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false }) }
|
||||
|
||||
const hydrate = () => {
|
||||
const item = existing.value
|
||||
if (!item) { form.payeeName = userName.value; return }
|
||||
persistedApplicationId.value = item.id
|
||||
form.title = item.title
|
||||
form.expenseTypeId = item.expenseTypeId || undefined
|
||||
form.category = item.expenseTypeName || item.category
|
||||
form.totalAmount = item.totalAmount
|
||||
form.description = item.description
|
||||
form.payeeName = item.payeeName || userName.value
|
||||
form.payeeBankId = item.payeeBankId || undefined
|
||||
form.items = item.expenseItems.length ? item.expenseItems.map(expense => newItem(expense, item.attachments)) : [newItem({ amount: item.totalAmount, category: item.category, description: item.title })]
|
||||
if (item.formSnapshot?.mode === 'FEISHU') {
|
||||
activeMode.value = 'FEISHU'
|
||||
pinnedFingerprint.value = item.formSnapshot.fingerprint
|
||||
activeFields.value = item.formSnapshot.fields || []
|
||||
Object.assign(formValues, item.formSnapshot.values || {})
|
||||
activeFields.value.filter(field => field.binding === 'APPLICANT_CONTACT' || field.binding === 'APPLICANT_DEPARTMENT').forEach(field => delete formValues[field.valueKey])
|
||||
}
|
||||
}
|
||||
const localDefinition = (): ReimbursementFormDefinition => ({ mode: 'LOCAL', fields: [] })
|
||||
/** One short retry — sync may still be flushing the snapshot when the create page opens. */
|
||||
const loadFormDefinitionWithRetry = async (): Promise<ReimbursementFormDefinition> => {
|
||||
try {
|
||||
return await reimbursementApi.getFormDefinition()
|
||||
} catch (firstError) {
|
||||
await new Promise(resolve => setTimeout(resolve, 600))
|
||||
try {
|
||||
return await reimbursementApi.getFormDefinition()
|
||||
} catch {
|
||||
throw firstError
|
||||
}
|
||||
}
|
||||
}
|
||||
const loadPage = async () => {
|
||||
loading.value = true
|
||||
definitionError.value = ''
|
||||
loadError.value = ''
|
||||
staleDefinition.value = false
|
||||
migrationNotice.value = ''
|
||||
Object.keys(formValues).forEach(key => delete formValues[key])
|
||||
try {
|
||||
if (id.value) {
|
||||
const detail = await store.loadDetail(id.value, { strict: true })
|
||||
if (store.source === 'api' && !detail?.formSnapshot) throw new Error('报销详情缺少表单快照,无法安全编辑,请刷新或联系管理员。')
|
||||
if (store.source === 'api' && detail?.formSnapshot && !['FEISHU', 'LOCAL', 'LEGACY'].includes(detail.formSnapshot.mode)) throw new Error('报销详情的表单快照模式无效,无法安全编辑。')
|
||||
} else if (!store.reimbursements.length) await store.load()
|
||||
hydrate()
|
||||
if (id.value && !existing.value) throw new Error('未找到该报销单,无法编辑')
|
||||
const [definitionResult, expenseTypesResult] = await Promise.allSettled([loadFormDefinitionWithRetry(), reimbursementApi.getExpenseTypes()])
|
||||
if (expenseTypesResult.status === 'rejected') throw expenseTypesResult.reason
|
||||
expenseTypes.value = expenseTypesResult.value
|
||||
if (definitionResult.status === 'fulfilled') definition.value = definitionResult.value
|
||||
else if (store.source === 'fallback') definition.value = localDefinition()
|
||||
else throw definitionResult.reason
|
||||
if (!definition.value || !Array.isArray(definition.value.fields)) throw new Error('审批模板响应格式无效,请联系管理员重新同步')
|
||||
if (!Array.isArray(expenseTypes.value) || !expenseTypes.value.length) throw new Error('没有可用费用类型,无法填写报销。')
|
||||
const snapshot = existing.value?.formSnapshot
|
||||
if (definition.value.mode === 'FEISHU' && (!definition.value.fields.length || !definition.value.formFingerprint)) {
|
||||
if (!definition.value.fields.length) throw new Error('审批模板没有可用字段,请联系管理员重新同步')
|
||||
throw new Error('审批模板缺少表单版本,无法安全保存,请联系管理员重新同步')
|
||||
}
|
||||
if (!id.value && definition.value.mode === 'FEISHU') {
|
||||
activeFields.value = definition.value.fields
|
||||
activeMode.value = 'FEISHU'
|
||||
pinnedFingerprint.value = definition.value.formFingerprint
|
||||
} else if (snapshot?.mode === 'FEISHU') {
|
||||
const currentFingerprint = definition.value.formFingerprint
|
||||
staleDefinition.value = definition.value.mode !== 'FEISHU' || !snapshot.fingerprint || !currentFingerprint || snapshot.fingerprint !== currentFingerprint
|
||||
} else if (id.value && (snapshot?.mode === 'LOCAL' || snapshot?.mode === 'LEGACY') && definition.value.mode === 'FEISHU') {
|
||||
activeFields.value = definition.value.fields
|
||||
activeMode.value = 'FEISHU'
|
||||
pinnedFingerprint.value = definition.value.formFingerprint
|
||||
Object.keys(formValues).forEach(key => delete formValues[key])
|
||||
migrationNotice.value = '原有报销、付款和费用明细已保留;新模板自定义字段从空值开始,请逐项核对并填写后再保存。'
|
||||
} else {
|
||||
activeFields.value = []
|
||||
activeMode.value = 'LOCAL'
|
||||
pinnedFingerprint.value = undefined
|
||||
}
|
||||
} catch (error) {
|
||||
definitionError.value = errorMessage(error, '无法读取审批模板,请稍后重试。')
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
const addItem = () => form.items.push(newItem({ category: form.category }))
|
||||
const removeItem = async (index: number) => {
|
||||
const item = form.items[index]
|
||||
if (!item || item.attachmentFiles.some(file => file.status === 'pending' || file.status === 'deleting')) return
|
||||
loadError.value = ''
|
||||
for (const attachmentId of [...item.attachmentIds]) {
|
||||
const metadata = item.attachmentFiles.find(file => String(file.id) === String(attachmentId))
|
||||
if (metadata) {
|
||||
metadata.status = 'deleting'
|
||||
metadata.error = undefined
|
||||
attachmentRevision.value++
|
||||
}
|
||||
try {
|
||||
await reimbursementApi.deleteFormAttachment(attachmentId)
|
||||
item.attachmentIds = item.attachmentIds.filter(id => String(id) !== String(attachmentId))
|
||||
item.attachmentFiles = item.attachmentFiles.filter(file => String(file.id) !== String(attachmentId))
|
||||
attachmentRevision.value++
|
||||
} catch (error) {
|
||||
if (metadata) {
|
||||
metadata.status = 'failed'
|
||||
metadata.error = errorMessage(error, '附件移除失败,请重试')
|
||||
}
|
||||
loadError.value = `附件“${metadata?.fileName || attachmentId}”删除失败;此前已删除的附件不会恢复,本条明细及剩余附件已保留,请重试移除。`
|
||||
attachmentRevision.value++
|
||||
return
|
||||
}
|
||||
}
|
||||
form.items.splice(index, 1)
|
||||
}
|
||||
const syncExpenseType = () => { const type = expenseTypes.value.find(entry => entry.id === form.expenseTypeId); form.category = type?.category || type?.name || ''; form.items.forEach(item => { item.category = form.category }) }
|
||||
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 })
|
||||
const errorMessage = (error: unknown, fallback: string) => {
|
||||
const responseMessage = (error as { response?: { data?: { message?: unknown } } })?.response?.data?.message
|
||||
if (typeof responseMessage === 'string' && responseMessage.trim()) return responseMessage.trim()
|
||||
return error instanceof Error && error.message ? error.message : fallback
|
||||
}
|
||||
const isConflict = (error: unknown) => (error as { response?: { status?: number } } | null)?.response?.status === 409
|
||||
const conflictMessage = (error: unknown) => String((error as { response?: { data?: { message?: unknown } } } | null)?.response?.data?.message || '')
|
||||
const isFormConflict = (error: unknown) => isConflict(error) && /表单|模板|fingerprint/i.test(conflictMessage(error))
|
||||
const compatibleCustomType = (oldField: ReimbursementFormField, currentField: ReimbursementFormField) => {
|
||||
if (oldField.type === currentField.type) return true
|
||||
const textTypes = new Set<ReimbursementFormField['type']>(['TEXT', 'TEXTAREA'])
|
||||
return textTypes.has(oldField.type) && textTypes.has(currentField.type)
|
||||
}
|
||||
const migrateStaleDefinition = async () => {
|
||||
if (!staleDefinition.value || migratingDefinition.value) return
|
||||
migratingDefinition.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
const latest = await reimbursementApi.getFormDefinition()
|
||||
if (latest.mode !== 'FEISHU' || !latest.formFingerprint || !Array.isArray(latest.fields) || !latest.fields.length) throw new Error('当前没有可迁移的飞书审批模板,请联系管理员检查同步状态。')
|
||||
const oldCustomFields = new Map(activeFields.value.filter(field => field.binding === 'CUSTOM').map(field => [field.valueKey, field]))
|
||||
const previousValues = { ...formValues }
|
||||
const preserved: Record<string, unknown> = {}
|
||||
latest.fields.filter(field => field.binding === 'CUSTOM').forEach(field => {
|
||||
const oldField = oldCustomFields.get(field.valueKey)
|
||||
if (oldField && compatibleCustomType(oldField, field) && Object.prototype.hasOwnProperty.call(previousValues, field.valueKey)) preserved[field.valueKey] = previousValues[field.valueKey]
|
||||
})
|
||||
Object.keys(formValues).forEach(key => delete formValues[key])
|
||||
Object.assign(formValues, preserved)
|
||||
definition.value = latest
|
||||
activeFields.value = latest.fields
|
||||
activeMode.value = 'FEISHU'
|
||||
pinnedFingerprint.value = latest.formFingerprint
|
||||
staleDefinition.value = false
|
||||
showValidationErrors.value = false
|
||||
migrationNotice.value = '报销、付款和费用明细保持不变;仅保留了键与类型兼容的自定义值,已移除或类型变化的字段未迁移。请核对全部字段后再手动保存。'
|
||||
} catch (error) {
|
||||
loadError.value = errorMessage(error, '无法读取最新审批模板,原模板和值未发生变化。')
|
||||
} finally {
|
||||
migratingDefinition.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const invalidatePreview = (closeDialog = false) => {
|
||||
previewRequestVersion += 1
|
||||
preview.value = null
|
||||
previewError.value = ''
|
||||
previewLoading.value = false
|
||||
if (closeDialog && previewDialog.value?.open) previewDialog.value.close()
|
||||
}
|
||||
const openPreview = async () => {
|
||||
if (!previewDialog.value?.open) previewDialog.value?.showModal()
|
||||
await nextTick()
|
||||
}
|
||||
const closePreview = () => {
|
||||
if (submitting.value) return
|
||||
invalidatePreview(true)
|
||||
}
|
||||
const handleDialogCancel = (event: Event) => {
|
||||
event.preventDefault()
|
||||
closePreview()
|
||||
}
|
||||
const handleBackdropClick = (event: MouseEvent) => {
|
||||
if (event.target === previewDialog.value) closePreview()
|
||||
}
|
||||
const requestPreview = async () => {
|
||||
if (previewLoading.value || submitting.value || !persistedApplicationId.value) return
|
||||
const version = ++previewRequestVersion
|
||||
preview.value = null
|
||||
previewError.value = ''
|
||||
previewLoading.value = true
|
||||
try {
|
||||
const result = await store.previewRoute(persistedApplicationId.value)
|
||||
if (version === previewRequestVersion) preview.value = result
|
||||
} catch (error) {
|
||||
if (version === previewRequestVersion) {
|
||||
if (isFormConflict(error)) {
|
||||
staleDefinition.value = true
|
||||
loadError.value = '审批模板已更新(409)。已保留当前输入,请刷新后按最新模板重新核对。'
|
||||
previewDialog.value?.close()
|
||||
} else previewError.value = errorMessage(error, '无法获取预计审批路径,请重试。')
|
||||
}
|
||||
} finally {
|
||||
if (version === previewRequestVersion) previewLoading.value = false
|
||||
}
|
||||
await nextTick()
|
||||
if (previewError.value) retryButton.value?.focus()
|
||||
}
|
||||
|
||||
const submittedCustomValues = () => Object.fromEntries(activeFields.value
|
||||
.filter(field => field.binding === 'CUSTOM' && !field.readOnly && field.type !== 'CONTACT' && field.type !== 'DISPLAY' && field.type !== 'EXPENSE_ITEMS')
|
||||
.map(field => [field.valueKey, formValues[field.valueKey]]))
|
||||
const payload = (): CreateApplicationRequest => ({
|
||||
title: form.title,
|
||||
expenseTypeId: form.expenseTypeId!,
|
||||
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: normalizeMoneyAmount(item.amount), attachmentIds: [...item.attachmentIds] })),
|
||||
...(isFeishu.value ? { formFingerprint: pinnedFingerprint.value, formValues: submittedCustomValues() } : {}),
|
||||
})
|
||||
const validate = () => {
|
||||
if (staleDefinition.value) return '审批模板已更新,请刷新后重新核对并录入。'
|
||||
if (hasUnsupported.value) return '审批模板包含当前系统不支持的控件,无法保存或提交,请联系管理员。'
|
||||
if (attachmentIntegrityError.value) return attachmentIntegrityError.value
|
||||
if (hasAttachmentBlocks.value) return '请等待附件上传或移除完成,并处理上传失败的文件。'
|
||||
if (attachmentRequired.value && form.items.some(item => !item.attachmentIds.length)) return '请为每条费用明细上传必填附件。'
|
||||
const hiddenRequired = [permissionBlock('application:amount', '报销金额', form.totalAmount), permissionBlock('application:payeeName', '收款人', form.payeeName), permissionBlock('application:bankAccount', '收款账户', form.payeeBankId)].find(Boolean)
|
||||
if (hiddenRequired) return hiddenRequired
|
||||
const missingCustom = activeFields.value.find(field => field.binding === 'CUSTOM' && field.required && !field.readOnly && (formValues[field.valueKey] == null || formValues[field.valueKey] === '' || (Array.isArray(formValues[field.valueKey]) && !(formValues[field.valueKey] as unknown[]).length)))
|
||||
if (missingCustom) return `请填写飞书表单必填项“${missingCustom.label}”`
|
||||
const invalidDecimal = activeFields.value.find(field => field.binding === 'CUSTOM' && field.type === 'DECIMAL' && !field.readOnly && formValues[field.valueKey] != null && formValues[field.valueKey] !== '' && !/^-?\d+(\.\d+)?$/.test(String(formValues[field.valueKey])))
|
||||
if (invalidDecimal) return `飞书表单字段“${invalidDecimal.label}”须为有效数字`
|
||||
const badAmountIndex = form.items.findIndex(item => inspectMoneyAmount(localAmountSource(item) || item.amount))
|
||||
if (badAmountIndex >= 0) {
|
||||
const item = form.items[badAmountIndex]
|
||||
const issue = inspectMoneyAmount(localAmountSource(item) || item.amount)!
|
||||
return `第 ${badAmountIndex + 1} 条费用明细:${moneyAmountMessage(issue, '金额')}`
|
||||
}
|
||||
const totalIssue = inspectMoneyAmount(form.totalAmount > 0 ? form.totalAmount : '')
|
||||
if (totalIssue) return moneyAmountMessage(totalIssue, '申请金额')
|
||||
if (!form.title || !form.description || !form.expenseTypeId || !form.category || !form.payeeName || !form.payeeBankId || !form.items.length) return '请完善必填信息后再保存'
|
||||
if (form.items.some(item => !item.expenseDate || !item.category || !item.description)) return '请完善费用明细的日期、类别和说明'
|
||||
if (!amountMatches.value) return '明细合计须与申请金额一致,请核对各行金额'
|
||||
return ''
|
||||
}
|
||||
const save = async (submit: boolean) => {
|
||||
if (!canWriteApplication.value || (submit && !canSubmit.value)) return
|
||||
if (saving.value || submitting.value) return
|
||||
showValidationErrors.value = true
|
||||
loadError.value = validate()
|
||||
if (loadError.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const isNewDraft = !persistedApplicationId.value
|
||||
const saved = await store.save(payload(), persistedApplicationId.value || undefined)
|
||||
persistedApplicationId.value = saved.id
|
||||
showValidationErrors.value = false
|
||||
if (!submit) {
|
||||
ElMessage.success('草稿已保存')
|
||||
await router.replace(`/applications/${saved.id}`)
|
||||
return
|
||||
}
|
||||
// Persist the edit URL before previewing so reload/close resumes this draft.
|
||||
// The same form component is reused, and the dialog is opened only after navigation settles.
|
||||
if (isNewDraft) await router.replace(`/applications/${saved.id}/edit`)
|
||||
await openPreview()
|
||||
await requestPreview()
|
||||
} catch (error) {
|
||||
if (isConflict(error)) {
|
||||
staleDefinition.value = true
|
||||
loadError.value = '审批模板已更新(409)。已保留当前输入,请刷新后按最新模板重新核对。'
|
||||
} else loadError.value = errorMessage(error, '保存报销草稿失败,请重试。')
|
||||
ElMessage.error(loadError.value)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
const confirmSubmit = async () => {
|
||||
if (!canSubmit.value || submitting.value || !preview.value || !persistedApplicationId.value) return
|
||||
const token = preview.value.previewToken
|
||||
submitting.value = true
|
||||
previewError.value = ''
|
||||
try {
|
||||
await store.submit(persistedApplicationId.value, token)
|
||||
ElMessage.success('报销已提交')
|
||||
previewDialog.value?.close()
|
||||
await router.replace(`/applications/${persistedApplicationId.value}`)
|
||||
} catch (error) {
|
||||
if (isFormConflict(error)) {
|
||||
staleDefinition.value = true
|
||||
loadError.value = '审批模板已更新(409)。已保留当前输入,请刷新后按最新模板重新核对。'
|
||||
previewDialog.value?.close()
|
||||
} else if (isConflict(error)) {
|
||||
invalidatePreview(false)
|
||||
previewError.value = '审批路线已变化或预览已过期,请重新预览后再提交。'
|
||||
} else {
|
||||
previewError.value = errorMessage(error, '提交失败,请保留当前页面并重试。')
|
||||
}
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
await nextTick()
|
||||
if (previewError.value) retryButton.value?.focus()
|
||||
}
|
||||
|
||||
watch(() => JSON.stringify({ form, formValues }), () => {
|
||||
if (preview.value && !submitting.value) invalidatePreview(false)
|
||||
})
|
||||
watch([itemsTotal, () => activeFields.value], () => {
|
||||
if (activeFields.value.some(field => field.binding === 'TOTAL_AMOUNT' && field.type === 'FORMULA')) form.totalAmount = Number(itemsTotal.value.toFixed(2))
|
||||
}, { deep: true, immediate: true })
|
||||
watch([rowReasonCaptured, () => form.items.map(item => item.description).join('\u0000')], () => {
|
||||
if (!rowReasonCaptured.value) return
|
||||
const reasons = form.items.map(item => item.description.trim()).filter(Boolean)
|
||||
form.title = (reasons[0] || '').slice(0, 100)
|
||||
form.description = reasons.join(';').slice(0, 500)
|
||||
}, { immediate: true })
|
||||
|
||||
onMounted(loadPage)
|
||||
</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%; } }
|
||||
.application-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 18px;
|
||||
}
|
||||
.application-form :deep(.page-head) { margin-bottom: 0; }
|
||||
.application-form :deep(.step-rail) { margin: 0; }
|
||||
.application-form :deep(.inline-alert) { margin: 0; }
|
||||
.form-page { display: flex; flex-direction: column; gap: 16px; }
|
||||
.form-page .section-card { margin: 0; }
|
||||
.form-page .section-gap { margin-top: 0; }
|
||||
.form-page :deep(.form-grid) {
|
||||
gap: 16px 20px;
|
||||
padding: 20px 22px 22px;
|
||||
}
|
||||
.form-page :deep(.field) { gap: 8px; }
|
||||
.definition-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 18px;
|
||||
margin: 0;
|
||||
padding: 14px 18px;
|
||||
border: 1px solid #bfd3e8;
|
||||
border-radius: 8px;
|
||||
background: var(--blue-soft);
|
||||
color: var(--blue);
|
||||
font-size: 12px;
|
||||
}
|
||||
.definition-state { display: flex; min-height: 220px; align-items: center; justify-content: center; flex-direction: column; gap: 14px; padding: 36px; text-align: center; }
|
||||
.definition-state > div { display: flex; gap: 10px; }
|
||||
.conflict-alert { align-items: center; }
|
||||
.conflict-alert .btn { flex: 0 0 auto; margin-left: auto; }
|
||||
.migration-alert { border-color: #b9d7c4; background: var(--success-soft); color: var(--success); }
|
||||
.form-actions { display: flex; justify-content: flex-end; gap: 12px; padding: 8px 0 4px; }
|
||||
.route-dialog { width: min(680px, calc(100vw - 32px)); max-width: 100%; max-height: calc(100dvh - 32px); }
|
||||
.route-dialog-panel { display: flex; min-width: 0; max-height: calc(100dvh - 32px); flex-direction: column; }
|
||||
.route-dialog-body { min-width: 0; padding: 20px 24px; overflow-x: hidden; overflow-y: auto; }
|
||||
.route-summary { display: grid; grid-template-columns: minmax(0, 1.5fr) minmax(0, .8fr) minmax(0, .8fr); gap: 1px; margin: 0 0 18px; overflow: hidden; border: 1px solid #d7e0e8; border-radius: 6px; background: var(--line); }
|
||||
.route-summary div { min-width: 0; padding: 11px 12px; background: var(--surface-raised); }
|
||||
.route-summary dt { color: var(--quiet); font-size: 10px; }
|
||||
.route-summary dd { margin: 3px 0 0; overflow-wrap: anywhere; font-size: 12px; font-weight: 600; }
|
||||
.route-state { display: flex; min-height: 150px; align-items: center; justify-content: center; flex-direction: column; gap: 9px; padding: 22px; border: 1px dashed var(--line-strong); border-radius: 6px; background: var(--surface-raised); color: var(--muted); text-align: center; }
|
||||
.route-error { border-style: solid; border-color: #e5bfbc; background: var(--danger-soft); color: var(--danger); }
|
||||
.route-meta { display: flex; align-items: center; flex-wrap: wrap; gap: 9px; margin-bottom: 12px; color: var(--muted); font-size: 11px; }
|
||||
.route-warning { display: flex; flex-direction: column; gap: 4px; margin: 0 0 16px; padding: 11px 13px; border: 1px solid #f1cf8d; border-radius: 7px; background: #fff9e9; color: #805a16; overflow-wrap: anywhere; font-size: 11px; }
|
||||
.route-warning small { opacity: .85; }
|
||||
.route-dialog-body h3 { margin: 0 0 10px; font-size: 13px; }
|
||||
.route-list { display: flex; margin: 0; padding: 0; flex-direction: column; gap: 9px; list-style: none; }
|
||||
.route-list > li { position: relative; display: grid; min-width: 0; grid-template-columns: 28px minmax(0, 1fr); gap: 11px; padding: 12px; border: 1px solid var(--line); border-radius: 6px; background: #fff; }
|
||||
.route-list > li::before { position: absolute; top: 0; bottom: 0; left: 0; width: 3px; background: #bfd3e8; content: ""; }
|
||||
.route-order { display: grid; width: 28px; height: 28px; place-items: center; border-radius: 50%; background: var(--blue-soft); color: var(--blue); font: 600 11px var(--mono); }
|
||||
.route-list strong, .route-list small { display: block; overflow-wrap: anywhere; }
|
||||
.route-list small { margin-top: 3px; color: var(--quiet); font-size: 10px; }
|
||||
.approver-list { display: flex; flex-wrap: wrap; gap: 5px; margin: 8px 0 0; padding: 0; list-style: none; }
|
||||
.approver-list li { max-width: 100%; padding: 3px 7px; border-radius: 4px; background: var(--blue-soft); color: var(--blue); overflow-wrap: anywhere; font-size: 10px; }
|
||||
.dynamic-approver { display: flex; align-items: baseline; flex-wrap: wrap; gap: 6px; margin: 8px 0 0; color: var(--muted); font-size: 11px; }
|
||||
.dynamic-approver strong { color: var(--body); }
|
||||
.quiet-copy { margin: 7px 0 0; color: var(--quiet); font-size: 11px; }
|
||||
.route-dialog-actions { display: flex; justify-content: flex-end; gap: 9px; padding: 13px 24px; border-top: 1px solid var(--line); background: var(--surface-raised); }
|
||||
@media (max-width: 560px) {
|
||||
.definition-state > div { width: 100%; flex-direction: column; }
|
||||
.conflict-alert { align-items: flex-start; }
|
||||
.conflict-alert .btn { width: 100%; margin-left: 0; }
|
||||
.form-actions { flex-direction: column-reverse; }
|
||||
.form-actions .btn { width: 100%; }
|
||||
.route-dialog { width: calc(100vw - 20px); max-height: calc(100dvh - 20px); }
|
||||
.route-dialog-panel { max-height: calc(100dvh - 20px); }
|
||||
.route-dialog-body { padding-right: 17px; padding-left: 17px; }
|
||||
.route-summary { grid-template-columns: 1fr; }
|
||||
.route-dialog-actions { flex-direction: column-reverse; }
|
||||
.route-dialog-actions .btn { width: 100%; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .route-dialog { scroll-behavior: auto; } }
|
||||
</style>
|
||||
@@ -0,0 +1,138 @@
|
||||
<template>
|
||||
<section class="permission-editor" aria-labelledby="permission-editor-title">
|
||||
<header class="editor-head">
|
||||
<div><h3 id="permission-editor-title">细粒度权限</h3><p>模块 → 页面 → 按钮分层授权;字段权限独立配置,目录异常时禁止保存。</p></div>
|
||||
<label class="permission-search"><span class="sr-only">搜索权限</span><input v-model="query" type="search" placeholder="搜索名称或编码" aria-label="搜索权限名称或编码"></label>
|
||||
</header>
|
||||
<div class="permission-summary" role="status"><strong>授权摘要</strong><span>{{ summary }}</span></div>
|
||||
<div v-if="!mayConfigure" class="permission-readonly" role="note">当前账号只能查看权限配置,不能修改。</div>
|
||||
<div class="permission-rules"><strong>权限粒度</strong><span>页面 READ 表示可查看、EDIT 表示可编辑;按钮 EDIT 表示允许执行该操作。字段 READ/EDIT 分别为只读/可编辑,HIDDEN 均为无权。模块/页面勾选仅批量设置菜单与按钮,不触碰字段;搜索时批量框禁用以免改动隐藏项,可单独编辑可见项。</span></div>
|
||||
<div v-if="catalogError" class="inline-alert danger" role="alert">{{ catalogError }}</div>
|
||||
|
||||
<div class="permission-columns">
|
||||
<section class="permission-column menu-column" aria-labelledby="menu-permission-title">
|
||||
<div class="column-head"><div><h3 id="menu-permission-title">菜单与按钮权限</h3><p>按模块 → 页面 → 按钮配置</p></div><span>{{ menuResultCount }} 项</span></div>
|
||||
<div v-if="!visibleMenuRoots.length" class="empty-state compact-empty"><strong>未找到菜单或按钮</strong><span>请调整搜索关键字。</span></div>
|
||||
<div v-for="module in visibleMenuRoots" :key="module.code" class="module-card">
|
||||
<label class="branch-title">
|
||||
<input type="checkbox" :checked="state(module).checked" :indeterminate.prop="state(module).indeterminate" :disabled="!mayConfigure || Boolean(normalizedQuery) || Boolean(catalogError)" :title="catalogError || (normalizedQuery ? '搜索筛选期间禁止批量修改,以保护隐藏权限' : undefined)" @change="toggle(module, $event)">
|
||||
<span><strong>{{ module.name }}</strong><code>{{ module.code }}</code></span>
|
||||
</label>
|
||||
<div class="page-grid">
|
||||
<article v-for="page in menuPages(module)" :key="page.code" class="page-card">
|
||||
<label class="branch-title page-title">
|
||||
<input type="checkbox" :checked="state(page).checked" :indeterminate.prop="state(page).indeterminate" :disabled="!mayConfigure || Boolean(normalizedQuery) || Boolean(catalogError)" :title="catalogError || (normalizedQuery ? '搜索筛选期间禁止批量修改,以保护隐藏权限' : undefined)" @change="toggle(page, $event)">
|
||||
<span><strong>{{ page.name }}</strong><code>{{ page.code }}</code></span>
|
||||
</label>
|
||||
<div v-if="actions(page, module).length" class="action-list" aria-label="关键动作">
|
||||
<label v-for="item in actions(page, module)" :key="item.code"><input type="checkbox" :checked="level(item.code) === 'EDIT'" :disabled="!mayConfigure || Boolean(catalogError)" @change="set(item.code, ($event.target as HTMLInputElement).checked ? 'EDIT' : 'HIDDEN')"><span>{{ item.name }}<code>{{ item.code }}</code></span></label>
|
||||
</div>
|
||||
<div v-else class="page-empty">该页面无匹配按钮</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="permission-column field-column" aria-labelledby="field-permission-title">
|
||||
<div class="column-head"><div><h3 id="field-permission-title">表单字段权限</h3><p>按所属模块 / 页面配置</p></div><span>{{ fieldResultCount }} 个字段</span></div>
|
||||
<div v-if="!visibleFieldGroups.length" class="empty-state compact-empty"><strong>未找到表单字段</strong><span>当前目录没有匹配字段,或请调整搜索关键字。</span></div>
|
||||
<section v-for="module in visibleFieldGroups" :key="module.code" class="field-module">
|
||||
<header><strong>{{ module.name }}</strong><code>{{ module.code }}</code></header>
|
||||
<article v-for="page in module.pages" :key="page.code" class="field-page">
|
||||
<div class="field-page-title"><strong>{{ page.name }}</strong><code>{{ page.code }}</code></div>
|
||||
<div class="field-list">
|
||||
<label v-for="item in page.fields" :key="item.code"><span>{{ item.name }}<code>{{ item.code }}</code></span><select :value="level(item.code)" :aria-label="`${item.name}字段权限`" :disabled="!mayConfigure || Boolean(catalogError)" @change="set(item.code, ($event.target as HTMLSelectElement).value as PermissionAccess)"><option value="HIDDEN">隐藏</option><option value="READ">只读</option><option value="EDIT">编辑</option></select></label>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section v-if="compatibility.length" class="compatibility-card" aria-labelledby="compat-title"><h4 id="compat-title">兼容权限</h4><p>以下权限不在当前目录中,保存时会原样保留,避免静默丢失。</p><ul><li v-for="item in compatibility" :key="item.code"><code>{{ item.code }}</code><select :value="item.level" :aria-label="`${item.code}兼容权限`" :disabled="!mayConfigure || Boolean(catalogError)" @change="set(item.code, ($event.target as HTMLSelectElement).value as PermissionAccess)"><option value="HIDDEN">隐藏</option><option value="READ">只读</option><option value="EDIT">编辑</option></select></li></ul></section>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue'
|
||||
import type { PermissionAccess, PermissionItem } from '@/api/admin'
|
||||
import { branchState, buildPermissionForest, descendants, permissionKind, toggleBranch, validatePermissionCatalog, type PermissionBranch } from '@/composables/permissionEditor'
|
||||
import { useUserStore } from '@/store/user'
|
||||
|
||||
type FieldPage = { code: string; name: string; fields: PermissionBranch[] }
|
||||
type FieldModule = { code: string; name: string; pages: FieldPage[] }
|
||||
|
||||
const props = defineProps<{ catalog: PermissionItem[]; modelValue: Record<string, PermissionAccess> }>()
|
||||
const emit = defineEmits<{ 'update:modelValue': [Record<string, PermissionAccess>] }>()
|
||||
const userStore = useUserStore()
|
||||
const mayConfigure = computed(() => userStore.canEdit('system.role.permission.configure'))
|
||||
const query = ref('')
|
||||
const catalogError = computed(() => validatePermissionCatalog(props.catalog))
|
||||
const forest = computed(() => buildPermissionForest(props.catalog))
|
||||
const known = computed(() => new Set(props.catalog.map(item => item.code)))
|
||||
const compatibility = computed(() => Object.entries(props.modelValue).filter(([code]) => !known.value.has(code)).map(([code, level]) => ({ code, level })))
|
||||
const normalizedQuery = computed(() => query.value.trim().toLocaleLowerCase())
|
||||
const textMatches = (item: Pick<PermissionItem, 'name' | 'code'>) => !normalizedQuery.value || `${item.name} ${item.code}`.toLocaleLowerCase().includes(normalizedQuery.value)
|
||||
const nested = (branch: PermissionBranch) => descendants(branch).slice(1)
|
||||
const menuMatches = (branch: PermissionBranch): boolean => (permissionKind(branch) !== 'field' && textMatches(branch)) || branch.children.some(menuMatches)
|
||||
const visibleMenuRoots = computed(() => forest.value.filter(menuMatches))
|
||||
const menuPages = (module: PermissionBranch) => module.children.filter(page => permissionKind(page) !== 'field' && (textMatches(module) || menuMatches(page)))
|
||||
const actions = (page: PermissionBranch, module: PermissionBranch) => nested(page).filter(item => permissionKind(item) === 'action' && (textMatches(module) || textMatches(page) || textMatches(item)))
|
||||
|
||||
const allFieldGroups = computed<FieldModule[]>(() => forest.value.map(module => ({
|
||||
code: module.code,
|
||||
name: module.name,
|
||||
pages: module.children.map(page => ({ code: page.code, name: page.name, fields: nested(page).filter(item => permissionKind(item) === 'field') })).filter(page => page.fields.length),
|
||||
})).filter(module => module.pages.length))
|
||||
const visibleFieldGroups = computed<FieldModule[]>(() => allFieldGroups.value.map(module => {
|
||||
const moduleMatch = textMatches(module)
|
||||
const pages = module.pages.map(page => {
|
||||
const contextMatch = moduleMatch || textMatches(page)
|
||||
return { ...page, fields: contextMatch ? page.fields : page.fields.filter(textMatches) }
|
||||
}).filter(page => page.fields.length)
|
||||
return { ...module, pages }
|
||||
}).filter(module => module.pages.length))
|
||||
|
||||
const level = (code: string): PermissionAccess => props.modelValue[code] || 'HIDDEN'
|
||||
const set = (code: string, value: PermissionAccess) => { if (mayConfigure.value && !catalogError.value) emit('update:modelValue', { ...props.modelValue, [code]: value }) }
|
||||
const state = (branch: PermissionBranch) => branchState(branch, props.modelValue)
|
||||
const toggle = (branch: PermissionBranch, event: Event) => { if (mayConfigure.value && !normalizedQuery.value && !catalogError.value) emit('update:modelValue', toggleBranch(branch, (event.target as HTMLInputElement).checked, props.modelValue)) }
|
||||
const menuResultCount = computed(() => visibleMenuRoots.value.reduce((count, module) => count + 1 + menuPages(module).reduce((pageCount, page) => pageCount + 1 + actions(page, module).length, 0), 0))
|
||||
const fieldResultCount = computed(() => visibleFieldGroups.value.reduce((count, module) => count + module.pages.reduce((pageCount, page) => pageCount + page.fields.length, 0), 0))
|
||||
const summary = computed(() => {
|
||||
const entries = Object.entries(props.modelValue).filter(([, value]) => value !== 'HIDDEN')
|
||||
const edit = entries.filter(([, value]) => value === 'EDIT').length
|
||||
const read = entries.filter(([, value]) => value === 'READ').length
|
||||
return `${entries.length} 项已授权(${read} 项只读,${edit} 项可编辑)`
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.permission-editor{display:grid;gap:14px}.editor-head{display:flex;align-items:end;justify-content:space-between;gap:16px}.editor-head h3,.column-head h3{font-size:15px}.editor-head p,.column-head p,.permission-rules,.compatibility-card p{color:var(--muted);font-size:11px}.permission-search{width:min(320px,100%)}.permission-search input{width:100%}.permission-summary,.permission-rules{display:flex;gap:10px;padding:10px 12px;border:1px solid var(--line);border-radius:7px;background:var(--surface)}.permission-columns{display:grid;grid-template-columns:minmax(0,2fr) minmax(280px,1fr);align-items:start;gap:14px}.permission-column{display:grid;min-width:0;gap:10px}.column-head{display:flex;align-items:end;justify-content:space-between;gap:10px;padding:0 2px}.column-head>span{color:var(--muted);font-size:11px;white-space:nowrap}.module-card,.field-module{border:1px solid var(--line);border-radius:9px;background:#fff;overflow:hidden}.branch-title{display:flex;align-items:center;gap:9px;padding:12px 14px;cursor:pointer}.branch-title>span,.action-list label>span,.field-list label>span{display:grid;min-width:0;gap:2px}.branch-title code,.action-list code,.field-list code,.field-module code,.compatibility-card code{color:var(--quiet);font:10px var(--mono);overflow-wrap:anywhere}.page-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;padding:0 12px 12px}.page-card{min-width:0;border:1px solid var(--line);border-radius:7px;background:var(--surface-raised)}.page-title{border-bottom:1px solid var(--line)}.action-list,.field-list{display:grid;gap:1px;padding:8px}.action-list label,.field-list label{display:flex;align-items:center;gap:8px;padding:7px;border-radius:5px;font-size:11px}.action-list label:hover,.field-list label:hover{background:var(--blue-soft)}.page-empty{padding:9px 12px;color:var(--quiet);font-size:10px}.field-module>header{display:grid;gap:2px;padding:11px 12px;border-bottom:1px solid var(--line);background:var(--surface)}.field-page+.field-page{border-top:1px solid var(--line)}.field-page-title{display:grid;gap:2px;padding:9px 12px 3px}.field-list label{justify-content:space-between}.field-list select,.compatibility-card select{min-width:84px;padding:6px}.compatibility-card{padding:13px;border:1px dashed var(--warning);border-radius:8px;background:var(--warning-soft)}.compatibility-card ul{display:grid;gap:6px;margin-top:8px;padding:0;list-style:none}.compatibility-card li{display:flex;align-items:center;justify-content:space-between;gap:10px}
|
||||
@media(max-width:900px){.permission-columns{grid-template-columns:1fr}.editor-head{align-items:stretch;flex-direction:column}.permission-search{width:100%}.page-grid{grid-template-columns:1fr}.permission-summary,.permission-rules{flex-direction:column}}
|
||||
@media(max-width:560px){.field-list label{align-items:stretch;flex-direction:column}.field-list select{width:100%;min-height:44px;font-size:16px}}
|
||||
|
||||
/* The editor sits inside the role section shell; use spacing and tone instead
|
||||
of another outer border so the large dialog does not become box-within-box. */
|
||||
.permission-editor { gap: 12px; padding: 14px 16px 16px; }
|
||||
.editor-head { align-items: center; }
|
||||
.editor-head h3 { color: var(--navy); font-size: 14px; }
|
||||
.permission-search input { min-height: 38px; padding: 7px 10px; border: 1px solid var(--line-strong); border-radius: 6px; background: #fff; color: var(--text); }
|
||||
.permission-summary, .permission-rules { align-items: baseline; border: 0; border-radius: 5px; }
|
||||
.permission-summary { border-left: 3px solid var(--blue); background: var(--blue-soft); color: var(--body); }
|
||||
.permission-readonly { padding: 9px 12px; border-left: 3px solid var(--warning); background: #fff8e8; color: var(--muted); font-size: 11px; }
|
||||
.permission-summary strong, .permission-rules strong { flex: none; color: var(--navy); font-size: 11px; }
|
||||
.permission-rules { padding-top: 8px; padding-bottom: 8px; background: #f7f9fb; }
|
||||
.permission-columns { grid-template-columns: minmax(0, 1.55fr) minmax(300px, 1fr); gap: 16px; }
|
||||
.permission-column { align-content: start; }
|
||||
.column-head { min-height: 42px; align-items: center; padding: 0 1px 8px; border-bottom: 1px solid var(--line); }
|
||||
.column-head h3 { color: var(--navy); font-size: 13px; }
|
||||
.module-card, .field-module { border-color: #d7e0e8; border-radius: 6px; box-shadow: 0 1px 2px rgba(16, 42, 67, .03); }
|
||||
.branch-title { padding: 10px 12px; }
|
||||
.page-grid { gap: 8px; padding: 0 10px 10px; }
|
||||
.page-card { border-color: #e2e7ec; border-radius: 5px; background: #fafbfd; }
|
||||
.action-list label, .field-list label { min-height: 38px; }
|
||||
.action-list label:hover, .field-list label:hover { background: #f0f6fd; }
|
||||
.field-list select { min-height: 34px; border: 1px solid var(--line-strong); border-radius: 5px; background: #fff; color: var(--body); }
|
||||
@media(max-width:900px){.permission-editor{padding:13px}.permission-columns{grid-template-columns:1fr}.editor-head{gap:10px}}
|
||||
@media(max-width:560px){.permission-editor{padding:11px}.permission-summary,.permission-rules{gap:4px}.column-head{align-items:flex-start}.page-grid{padding-right:8px;padding-left:8px}}
|
||||
</style>
|
||||
@@ -0,0 +1,47 @@
|
||||
<template>
|
||||
<nav class="app-list-pagination" :aria-label="ariaLabel">
|
||||
<p class="app-list-pagination__summary" aria-live="polite">{{ summary }}</p>
|
||||
<el-pagination
|
||||
v-model:current-page="currentPage"
|
||||
v-model:page-size="currentPageSize"
|
||||
:page-sizes="pageSizes"
|
||||
:total="total"
|
||||
:disabled="disabled"
|
||||
:pager-count="5"
|
||||
layout="sizes, prev, pager, next, jumper"
|
||||
small
|
||||
background
|
||||
/>
|
||||
</nav>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
page: number
|
||||
pageSize: number
|
||||
total: number
|
||||
disabled?: boolean
|
||||
ariaLabel?: string
|
||||
pageSizes?: number[]
|
||||
}>(), {
|
||||
disabled: false,
|
||||
ariaLabel: '列表分页',
|
||||
pageSizes: () => [10, 20, 50],
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:page': [value: number]
|
||||
'update:pageSize': [value: number]
|
||||
}>()
|
||||
|
||||
const currentPage = computed({ get: () => props.page, set: value => emit('update:page', value) })
|
||||
const currentPageSize = computed({ get: () => props.pageSize, set: value => emit('update:pageSize', value) })
|
||||
const summary = computed(() => {
|
||||
if (!props.total) return '共 0 条'
|
||||
const start = (props.page - 1) * props.pageSize + 1
|
||||
const end = Math.min(props.total, props.page * props.pageSize)
|
||||
return `第 ${start}–${end} 条,共 ${props.total} 条`
|
||||
})
|
||||
</script>
|
||||
@@ -0,0 +1,560 @@
|
||||
<template>
|
||||
<div class="feishu-fields">
|
||||
<template v-for="field in fields" :key="field.id">
|
||||
<section v-if="field.type === 'EXPENSE_ITEMS' && field.binding === 'EXPENSE_ITEMS'" class="dynamic-field expense-field" :aria-labelledby="`${controlId(field)}-label`">
|
||||
<div class="section-title compact-title">
|
||||
<h3 :id="`${controlId(field)}-label`">{{ field.label }} <em v-if="field.required">*</em></h3>
|
||||
<button v-if="!field.readOnly" class="btn small" type="button" @click="$emit('add-item')">+ 添加明细</button>
|
||||
</div>
|
||||
<div v-if="expenseFieldUnsupported(field)" class="unsupported-field expense-child-warning" role="alert">
|
||||
<strong>费用明细结构暂不支持</strong><span>模板包含无法识别或不兼容的明细列,已停止猜测字段含义,请联系管理员重新同步模板。</span>
|
||||
</div>
|
||||
<div class="expense-items">
|
||||
<fieldset v-for="(item, index) in form.items" :key="item.key" class="expense-item">
|
||||
<legend class="sr-only">{{ field.label }}第 {{ index + 1 }} 条</legend>
|
||||
<div v-for="column in itemColumns(field)" :key="column.key" class="field" :class="{ 'attachment-field': column.key === 'attachmentIds' }">
|
||||
<label :for="`${controlId(field)}-${item.key}-${column.key}`">{{ column.label }} <em v-if="column.required">*</em></label>
|
||||
<template v-if="column.key === 'attachmentIds'">
|
||||
<input
|
||||
:id="`${controlId(field)}-${item.key}-${column.key}`"
|
||||
class="attachment-input" type="file" multiple :accept="attachmentAccept"
|
||||
:disabled="field.readOnly || column.readOnly || itemHasPendingUploads(item)"
|
||||
:aria-required="column.required" :aria-invalid="attachmentHasError(item, column.required)"
|
||||
:aria-describedby="attachmentDescriptionIds(field, item, column.required)"
|
||||
@change="uploadAttachments(item, column.child, $event)"
|
||||
>
|
||||
<small :id="`${controlId(field)}-${item.key}-attachment-help`" class="form-help">支持 PDF、PNG/JPEG、DOC/DOCX、XLS/XLSX,单个文件不超过 50MB;可一次选择多个文件并依次上传。</small>
|
||||
<ul v-if="item.attachmentFiles.length" class="attachment-list" :aria-label="`第 ${index + 1} 条费用明细附件`" aria-live="polite">
|
||||
<li v-for="attachment in item.attachmentFiles" :key="attachment.localKey" :class="`is-${attachment.status}`">
|
||||
<div><strong>{{ attachment.fileName }}</strong><small>{{ attachmentStatus(attachment) }}</small></div>
|
||||
<button v-if="!field.readOnly && attachment.status !== 'pending'" class="attachment-remove" type="button" :disabled="attachment.status === 'deleting'" :aria-label="`移除附件 ${attachment.fileName}`" @click="removeAttachment(item, attachment)">{{ attachment.status === 'deleting' ? '移除中…' : '移除' }}</button>
|
||||
</li>
|
||||
</ul>
|
||||
<small v-if="attachmentError(item, column.required)" :id="`${controlId(field)}-${item.key}-attachment-error`" class="field-error" role="alert">! {{ attachmentError(item, column.required) }}</small>
|
||||
</template>
|
||||
<select
|
||||
v-else-if="column.type === 'SINGLE_SELECT'"
|
||||
:id="`${controlId(field)}-${item.key}-${column.key}`"
|
||||
:value="item[column.key]"
|
||||
:required="column.required && !field.readOnly"
|
||||
:disabled="field.readOnly || column.readOnly"
|
||||
@change="setItemValue(item, column.key, $event)"
|
||||
><option value="">请选择</option><option v-for="option in column.options" :key="option.value" :value="option.label">{{ option.label }}</option></select>
|
||||
<textarea
|
||||
v-else-if="column.type === 'TEXTAREA'"
|
||||
:id="`${controlId(field)}-${item.key}-${column.key}`" :value="String(item[column.key] ?? '')" rows="2"
|
||||
:maxlength="column.maxLength" :required="column.required && !field.readOnly" :readonly="field.readOnly || column.readOnly"
|
||||
@input="setItemValue(item, column.key, $event)"
|
||||
></textarea>
|
||||
<div v-else-if="column.type === 'DECIMAL'" class="amount-control-wrap">
|
||||
<div class="amount-control">
|
||||
<input
|
||||
:id="`${controlId(field)}-${item.key}-${column.key}`"
|
||||
:value="amountInputText(item)"
|
||||
type="text"
|
||||
inputmode="decimal"
|
||||
autocomplete="off"
|
||||
placeholder="0.00"
|
||||
:required="column.required && !field.readOnly"
|
||||
:readonly="field.readOnly || column.readOnly"
|
||||
:aria-invalid="amountHasError(item, column.required)"
|
||||
:aria-describedby="amountDescriptionIds(field, item, column)"
|
||||
@input="setItemAmount(item, $event)"
|
||||
@blur="normalizeItemAmount(item)"
|
||||
>
|
||||
<select
|
||||
v-if="currencyOptions(column.child).length"
|
||||
:aria-label="`${column.label}币种`"
|
||||
:value="rowCurrency(column.child, index)"
|
||||
:disabled="field.readOnly || column.readOnly"
|
||||
@change="setRowCurrency(column.child, index, $event)"
|
||||
>
|
||||
<option v-for="option in currencyOptions(column.child)" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<small v-if="amountHasError(item, column.required)" :id="`${controlId(field)}-${item.key}-amount-error`" class="field-error" role="alert">! {{ amountError(item, column.label, column.required) }}</small>
|
||||
<small v-else :id="`${controlId(field)}-${item.key}-amount-help`" class="form-help">请填写大于 0 的金额,最多两位小数,上限 99,999,999.99 元</small>
|
||||
</div>
|
||||
<input v-else
|
||||
:id="`${controlId(field)}-${item.key}-${column.key}`" :value="item[column.key]"
|
||||
:type="column.type === 'DATE' ? 'date' : 'text'"
|
||||
:maxlength="column.maxLength" :required="column.required && !field.readOnly" :readonly="field.readOnly || column.readOnly"
|
||||
@input="setItemValue(item, column.key, $event)">
|
||||
</div>
|
||||
<button v-if="!field.readOnly && form.items.length > 1" class="remove-item" type="button" :disabled="itemHasPendingUploads(item)" :aria-label="`删除第 ${index + 1} 条费用明细`" @click="$emit('remove-item', index)">删除</button>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="amount-summary" :class="{ 'amount-mismatch': form.totalAmount > 0 && !amountMatches }">
|
||||
<span>明细合计</span><strong>{{ money(itemsTotal) }}</strong><span>申请金额 {{ money(form.totalAmount) }}</span>
|
||||
</div>
|
||||
<small v-if="form.totalAmount > 0 && !amountMatches" class="field-error amount-mismatch-tip" role="status">明细合计须与申请金额一致,请核对各行金额。</small>
|
||||
</section>
|
||||
|
||||
<div v-else-if="field.type === 'DISPLAY'" class="dynamic-field display-field" role="note">
|
||||
<strong>{{ field.label }}</strong><p>{{ displayValue(field) }}</p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="isApplicantContact(field)" class="field dynamic-field applicant-contact">
|
||||
<label :for="controlId(field)">{{ field.label }} <em v-if="field.required">*</em></label>
|
||||
<input :id="controlId(field)" :value="applicantContactLabel" readonly :aria-describedby="`${controlId(field)}-help`">
|
||||
<small :id="`${controlId(field)}-help`" class="form-help">当前申请人,由系统自动带入且不会作为自定义值提交</small>
|
||||
</div>
|
||||
|
||||
<div v-else-if="isApplicantDepartment(field)" class="field dynamic-field applicant-department">
|
||||
<label :for="controlId(field)">{{ field.label }} <em v-if="field.required">*</em></label>
|
||||
<div class="department-picker" @focusout="departmentOpen = false">
|
||||
<input
|
||||
:id="controlId(field)"
|
||||
v-model="departmentQuery"
|
||||
type="search"
|
||||
autocomplete="off"
|
||||
:placeholder="selectedDepartmentName(field) || '搜索飞书部门'"
|
||||
:aria-describedby="`${controlId(field)}-help`"
|
||||
@focus="departmentOpen = true"
|
||||
@input="departmentOpen = true"
|
||||
>
|
||||
<ul v-if="departmentOpen" class="department-menu" role="listbox">
|
||||
<li v-for="department in filteredDepartments" :key="department.id">
|
||||
<button type="button" @mousedown.prevent="chooseDepartment(field, department)">{{ department.name }}</button>
|
||||
</li>
|
||||
<li v-if="!filteredDepartments.length" class="department-empty">没有匹配的部门</li>
|
||||
</ul>
|
||||
</div>
|
||||
<small :id="`${controlId(field)}-help`" class="form-help">可搜索并选择飞书组织架构中的部门。未改选时仍使用申请人当前部门。</small>
|
||||
</div>
|
||||
|
||||
<div v-else-if="isRuntimeUnsupported(field)" class="dynamic-field unsupported-field" role="alert">
|
||||
<strong>暂不支持「{{ field.label }}」类型</strong><span>该控件无法在本系统编辑,请联系管理员。</span>
|
||||
</div>
|
||||
|
||||
<div v-else class="field dynamic-field" :class="{ full: field.type === 'TEXTAREA' }">
|
||||
<label :for="controlId(field)">{{ field.label }} <em v-if="field.required">*</em></label>
|
||||
<template v-if="!canEditField(field)">
|
||||
<textarea v-if="field.type === 'TEXTAREA'" :id="controlId(field)" :value="String(fieldValue(field) ?? '')" readonly rows="3" :aria-describedby="`${controlId(field)}-help`"></textarea>
|
||||
<input v-else :id="controlId(field)" :value="displayValue(field)" readonly :aria-describedby="`${controlId(field)}-help`">
|
||||
<small :id="`${controlId(field)}-help`" class="form-help">{{ field.type === 'FORMULA' ? '由费用明细自动计算,只读' : '只读信息,不会作为自定义值提交' }}</small>
|
||||
</template>
|
||||
<textarea
|
||||
v-else-if="field.type === 'TEXTAREA'"
|
||||
:id="controlId(field)" :value="String(fieldValue(field) ?? '')" rows="3"
|
||||
:maxlength="field.maxLength" :required="field.required" :aria-required="field.required"
|
||||
:aria-invalid="hasError(field)" :aria-describedby="hasError(field) ? `${controlId(field)}-error` : undefined"
|
||||
@input="setFieldValue(field, ($event.target as HTMLTextAreaElement).value)"
|
||||
></textarea>
|
||||
<select
|
||||
v-else-if="field.type === 'SINGLE_SELECT'"
|
||||
:id="controlId(field)" :value="String(fieldValue(field) ?? '')" :required="field.required" :aria-required="field.required"
|
||||
:aria-invalid="hasError(field)" :aria-describedby="hasError(field) ? `${controlId(field)}-error` : undefined"
|
||||
@change="setFieldValue(field, ($event.target as HTMLSelectElement).value)"
|
||||
>
|
||||
<option value="">请选择</option><option v-for="option in field.options" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
<select
|
||||
v-else-if="field.type === 'MULTI_SELECT'"
|
||||
:id="controlId(field)" :value="arrayValue(field)" multiple :required="field.required" :aria-required="field.required"
|
||||
:aria-invalid="hasError(field)" :aria-describedby="hasError(field) ? `${controlId(field)}-error` : `${controlId(field)}-help`"
|
||||
@change="setMultiValue(field, $event)"
|
||||
>
|
||||
<option v-for="option in field.options" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
<div v-else-if="field.type === 'DECIMAL'" class="amount-control">
|
||||
<input
|
||||
:id="controlId(field)" :value="fieldValue(field) as string | number | undefined"
|
||||
type="text" inputmode="decimal" :maxlength="field.maxLength"
|
||||
:required="field.required" :aria-required="field.required" :aria-invalid="hasError(field)"
|
||||
:aria-describedby="hasError(field) ? `${controlId(field)}-error` : `${controlId(field)}-help`"
|
||||
@input="setFieldValue(field, ($event.target as HTMLInputElement).value)"
|
||||
>
|
||||
<select
|
||||
v-if="currencyOptions(field).length"
|
||||
:aria-label="`${field.label}币种`"
|
||||
:value="fieldCurrency(field)"
|
||||
@change="setFieldCurrency(field, $event)"
|
||||
>
|
||||
<option v-for="option in currencyOptions(field)" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<input
|
||||
v-else
|
||||
:id="controlId(field)" :value="fieldValue(field) as string | number | undefined"
|
||||
:type="field.type === 'DATE' ? 'date' : 'text'"
|
||||
:maxlength="field.maxLength"
|
||||
:required="field.required" :aria-required="field.required" :aria-invalid="hasError(field)"
|
||||
:aria-describedby="hasError(field) ? `${controlId(field)}-error` : undefined"
|
||||
@input="setFieldValue(field, ($event.target as HTMLInputElement).value)"
|
||||
>
|
||||
<small v-if="field.type === 'MULTI_SELECT'" :id="`${controlId(field)}-help`" class="form-help">按住 Ctrl(macOS 使用 Command)可多选</small>
|
||||
<small v-if="field.type === 'DECIMAL' && field.binding === 'TOTAL_AMOUNT' && !hasError(field)" :id="`${controlId(field)}-help`" class="form-help">请填写大于 0 的金额,最多两位小数,上限 99,999,999.99 元</small>
|
||||
<small v-else-if="field.type === 'DECIMAL' && !hasError(field)" :id="`${controlId(field)}-help`" class="form-help">请输入有效数字</small>
|
||||
<small v-if="hasError(field)" :id="`${controlId(field)}-error`" class="field-error" role="alert">! {{ fieldError(field) }}</small>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { reimbursementApi, type ExpenseItem, type ExpenseTypeMetadata, type ReimbursementFormAttachment, type ReimbursementFormField, type ReimbursementFormOption } from '@/api/reimbursement'
|
||||
import { feishuDirectoryApi } from '@/api/feishuDirectory'
|
||||
import { ATTACHMENT_ACCEPT, attachmentFileValidationError, attachmentIdsMissingMetadata } from '@/modules/reimbursementAttachments'
|
||||
import { inspectMoneyAmount, moneyAmountMessage, normalizeMoneyAmount } from '@/utils/moneyAmount'
|
||||
|
||||
type ItemKey = 'expenseDate' | 'category' | 'description' | 'amount' | 'attachmentIds'
|
||||
type AttachmentStatus = 'uploaded' | 'pending' | 'failed' | 'deleting'
|
||||
interface AttachmentEntry extends Partial<ReimbursementFormAttachment> { localKey: string; fileName: string; status: AttachmentStatus; error?: string }
|
||||
interface FormItem extends ExpenseItem { key: number; description: string; attachmentFiles: AttachmentEntry[] }
|
||||
interface FormModel { title: string; expenseTypeId?: number; category: string; totalAmount: number; description: string; items: FormItem[] }
|
||||
|
||||
const props = defineProps<{
|
||||
fields: ReimbursementFormField[]
|
||||
formValues: Record<string, unknown>
|
||||
form: FormModel
|
||||
derived: Record<string, string>
|
||||
showErrors: boolean
|
||||
itemsTotal: number
|
||||
amountMatches: boolean
|
||||
expenseTypes: ExpenseTypeMetadata[]
|
||||
formFingerprint?: string
|
||||
}>()
|
||||
const emit = defineEmits<{ (event: 'add-item'): void; (event: 'remove-item', index: number): void; (event: 'upload-state-change'): void }>()
|
||||
|
||||
const derivedBindings = new Set(['APPLICATION_NO', 'APPLICANT_NAME', 'APPLICANT_CONTACT', 'APPLICANT_DEPARTMENT', 'DEPARTMENT', 'SOURCE_DOC_NO'])
|
||||
const supportedTypes = new Set(['TEXT', 'TEXTAREA', 'DECIMAL', 'DATE', 'SINGLE_SELECT', 'MULTI_SELECT'])
|
||||
const knownTypes = new Set([...supportedTypes, 'DISPLAY', 'EXPENSE_ITEMS', 'FORMULA'])
|
||||
const canonicalEditorTypes: Partial<Record<ReimbursementFormField['binding'], ReimbursementFormField['type'][]>> = {
|
||||
TITLE: ['TEXT', 'TEXTAREA'], EXPENSE_TYPE: ['SINGLE_SELECT'], TOTAL_AMOUNT: ['DECIMAL'], DESCRIPTION: ['TEXT', 'TEXTAREA'],
|
||||
}
|
||||
const safeId = (value: string) => value.replace(/[^a-zA-Z0-9_-]/g, '-')
|
||||
const controlId = (field: ReimbursementFormField) => `feishu-${safeId(field.id)}`
|
||||
const isApplicantContact = (field: ReimbursementFormField) => field.type === 'CONTACT' && field.binding === 'APPLICANT_CONTACT'
|
||||
const isApplicantDepartment = (field: ReimbursementFormField) => field.type === 'DEPARTMENT' && field.binding === 'APPLICANT_DEPARTMENT'
|
||||
const isRuntimeUnsupported = (field: ReimbursementFormField) => {
|
||||
if (field.type === 'DEPARTMENT' || field.binding === 'APPLICANT_DEPARTMENT') return !isApplicantDepartment(field)
|
||||
return !knownTypes.has(field.type) && !isApplicantContact(field)
|
||||
}
|
||||
const applicantContactLabel = computed(() => props.derived.APPLICANT_CONTACT || props.derived.APPLICANT_NAME || '—')
|
||||
const applicantDepartmentLabel = computed(() => props.derived.APPLICANT_DEPARTMENT || '—')
|
||||
const canEditField = (field: ReimbursementFormField) => {
|
||||
if (field.readOnly || derivedBindings.has(field.binding) || !supportedTypes.has(field.type)) return false
|
||||
if (field.binding === 'CUSTOM') return true
|
||||
return Boolean(canonicalEditorTypes[field.binding]?.includes(field.type))
|
||||
}
|
||||
const isEmpty = (value: unknown) => value == null || value === '' || (Array.isArray(value) && value.length === 0)
|
||||
const fieldError = (field: ReimbursementFormField) => {
|
||||
if (field.binding === 'EXPENSE_TYPE' && props.form.category && !props.form.expenseTypeId) return `${field.label}无法与系统费用类型唯一匹配,请联系管理员检查模板选项`
|
||||
if (field.required && isEmpty(fieldValue(field))) return `${field.label}为必填项`
|
||||
if (field.type === 'DECIMAL' && !isEmpty(fieldValue(field))) {
|
||||
if (field.binding === 'TOTAL_AMOUNT') {
|
||||
const issue = inspectMoneyAmount(fieldValue(field))
|
||||
if (issue && issue !== 'empty') return moneyAmountMessage(issue, field.label)
|
||||
} else if (!/^-?\d+(\.\d+)?$/.test(String(fieldValue(field)))) {
|
||||
return `${field.label}须为有效数字,例如 128.50`
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
const hasError = (field: ReimbursementFormField) => props.showErrors && canEditField(field) && Boolean(fieldError(field))
|
||||
const arrayValue = (field: ReimbursementFormField) => Array.isArray(fieldValue(field)) ? fieldValue(field) as string[] : []
|
||||
const money = (value: number) => `¥ ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`
|
||||
const unique = (matches: ExpenseTypeMetadata[]) => matches.length === 1 ? matches[0] : undefined
|
||||
const matchExpenseType = (option: ReimbursementFormOption | undefined): ExpenseTypeMetadata | undefined => {
|
||||
if (!option) return undefined
|
||||
if (/^\d+$/.test(option.value)) {
|
||||
const byId = unique(props.expenseTypes.filter(type => type.id === Number(option.value)))
|
||||
if (byId) return byId
|
||||
}
|
||||
const byCode = unique(props.expenseTypes.filter(type => type.code === option.value))
|
||||
if (byCode) return byCode
|
||||
return unique(props.expenseTypes.filter(type => type.name === option.label))
|
||||
}
|
||||
|
||||
const fieldValue = (field: ReimbursementFormField): unknown => {
|
||||
if (field.binding === 'APPLICANT_CONTACT') return applicantContactLabel.value
|
||||
if (field.binding === 'APPLICANT_DEPARTMENT') return applicantDepartmentLabel.value
|
||||
if (field.binding === 'CUSTOM') return props.formValues[field.valueKey]
|
||||
if (field.binding === 'TITLE') return props.form.title
|
||||
if (field.binding === 'EXPENSE_TYPE') {
|
||||
if (field.type !== 'SINGLE_SELECT') return props.form.category
|
||||
return field.options.find(option => matchExpenseType(option)?.id === props.form.expenseTypeId)?.value
|
||||
|| ''
|
||||
}
|
||||
if (field.binding === 'TOTAL_AMOUNT') return props.itemsTotal
|
||||
if (field.binding === 'DESCRIPTION') return props.form.description
|
||||
return props.derived[field.binding] || ''
|
||||
}
|
||||
const displayValue = (field: ReimbursementFormField) => {
|
||||
const value = fieldValue(field)
|
||||
if (Array.isArray(value)) return value.map(entry => field.options.find(option => option.value === String(entry))?.label || String(entry)).join('、') || '—'
|
||||
if (field.type === 'FORMULA' && field.binding === 'TOTAL_AMOUNT') return `${field.currency || 'CNY'} ${Number(value || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
|
||||
if (field.type === 'SINGLE_SELECT') return field.options.find(option => option.value === String(value))?.label || String(value || '—')
|
||||
return String(value ?? '') || '—'
|
||||
}
|
||||
const setFieldValue = (field: ReimbursementFormField, value: string) => {
|
||||
if (!canEditField(field)) return
|
||||
if (field.binding === 'CUSTOM') props.formValues[field.valueKey] = value
|
||||
else if (field.binding === 'TITLE') props.form.title = value
|
||||
else if (field.binding === 'EXPENSE_TYPE') {
|
||||
const option = field.options.find(entry => entry.value === value)
|
||||
const matched = matchExpenseType(option)
|
||||
props.form.expenseTypeId = matched?.id
|
||||
props.form.category = matched?.category || option?.label || ''
|
||||
} else if (field.binding === 'TOTAL_AMOUNT') props.form.totalAmount = Number(value) || 0
|
||||
else if (field.binding === 'DESCRIPTION') props.form.description = value
|
||||
}
|
||||
const setMultiValue = (field: ReimbursementFormField, event: Event) => {
|
||||
if (field.binding !== 'CUSTOM' || field.readOnly) return
|
||||
props.formValues[field.valueKey] = [...(event.target as HTMLSelectElement).selectedOptions].map(option => option.value)
|
||||
}
|
||||
const childBindingKeys: Partial<Record<ReimbursementFormField['binding'], ItemKey>> = {
|
||||
EXPENSE_DATE: 'expenseDate', EXPENSE_CATEGORY: 'category', EXPENSE_DESCRIPTION: 'description', EXPENSE_AMOUNT: 'amount', EXPENSE_ATTACHMENT: 'attachmentIds',
|
||||
}
|
||||
const supportedChildTypes: Record<ItemKey, Set<ReimbursementFormField['type']>> = {
|
||||
expenseDate: new Set(['DATE']), category: new Set(['TEXT', 'SINGLE_SELECT']), description: new Set(['TEXT', 'TEXTAREA']), amount: new Set(['DECIMAL']), attachmentIds: new Set(['ATTACHMENT']),
|
||||
}
|
||||
const expenseFieldUnsupported = (field: ReimbursementFormField) => field.children.some(child => {
|
||||
if (child.type === 'DISPLAY' && !child.required) return false
|
||||
const key = childBindingKeys[child.binding]
|
||||
return !key || !supportedChildTypes[key].has(child.type)
|
||||
})
|
||||
const itemColumns = (field: ReimbursementFormField) => {
|
||||
const ordered: { key: ItemKey; label: string; required: boolean; readOnly: boolean; type: ReimbursementFormField['type']; maxLength?: number; options: ReimbursementFormField['options']; child: ReimbursementFormField }[] = []
|
||||
field.children.forEach(child => {
|
||||
if (child.type === 'DISPLAY' && !child.required) return
|
||||
const key = childBindingKeys[child.binding]
|
||||
if (key && supportedChildTypes[key].has(child.type) && !ordered.some(column => column.key === key)) ordered.push({ key, label: child.label, required: child.required, readOnly: child.readOnly, type: child.type, maxLength: child.maxLength, options: child.options, child })
|
||||
})
|
||||
return ordered
|
||||
}
|
||||
const setItemValue = (item: FormItem, key: ItemKey, event: Event) => {
|
||||
if (key === 'attachmentIds' || key === 'amount') return
|
||||
item[key] = (event.target as HTMLInputElement).value
|
||||
}
|
||||
const amountDrafts = reactive<Record<number, string>>({})
|
||||
const amountSource = (item: FormItem) => (amountDrafts[item.key] != null ? amountDrafts[item.key] : (item.amount > 0 ? item.amount : ''))
|
||||
const amountInputText = (item: FormItem) => {
|
||||
if (amountDrafts[item.key] != null) return amountDrafts[item.key]
|
||||
return item.amount > 0 ? String(item.amount) : ''
|
||||
}
|
||||
const setItemAmount = (item: FormItem, event: Event) => {
|
||||
const text = (event.target as HTMLInputElement).value.trimStart()
|
||||
amountDrafts[item.key] = text
|
||||
const issue = inspectMoneyAmount(text)
|
||||
if (!issue) item.amount = normalizeMoneyAmount(text)
|
||||
else if (!text.trim()) item.amount = 0
|
||||
else {
|
||||
const parsed = Number(text)
|
||||
item.amount = Number.isFinite(parsed) && parsed >= 0 ? parsed : 0
|
||||
}
|
||||
}
|
||||
const normalizeItemAmount = (item: FormItem) => {
|
||||
const text = amountDrafts[item.key]
|
||||
if (text == null) return
|
||||
if (!inspectMoneyAmount(text)) {
|
||||
item.amount = normalizeMoneyAmount(text)
|
||||
delete amountDrafts[item.key]
|
||||
}
|
||||
}
|
||||
const amountError = (item: FormItem, label: string, required: boolean) => {
|
||||
const issue = inspectMoneyAmount(amountSource(item))
|
||||
if (!issue) return ''
|
||||
if (issue === 'empty' && !required) return ''
|
||||
return moneyAmountMessage(issue, label)
|
||||
}
|
||||
const amountHasError = (item: FormItem, required: boolean) => props.showErrors && Boolean(amountError(item, '金额', required))
|
||||
const amountDescriptionIds = (field: ReimbursementFormField, item: FormItem, column: { required: boolean }) =>
|
||||
amountHasError(item, column.required)
|
||||
? `${controlId(field)}-${item.key}-amount-error`
|
||||
: `${controlId(field)}-${item.key}-amount-help`
|
||||
const currencyKey = (field: ReimbursementFormField) => `__currency__${field.valueKey}`
|
||||
const currencyOptions = (field: ReimbursementFormField) => field.options?.length ? field.options : (field.currency ? [{ value: field.currency, label: field.currency }] : [])
|
||||
const fieldCurrency = (field: ReimbursementFormField) => String(props.formValues[currencyKey(field)] || field.currency || currencyOptions(field)[0]?.value || 'CNY')
|
||||
const setFieldCurrency = (field: ReimbursementFormField, event: Event) => { props.formValues[currencyKey(field)] = (event.target as HTMLSelectElement).value }
|
||||
const rowCurrency = (field: ReimbursementFormField, index: number) => {
|
||||
const stored = props.formValues[currencyKey(field)]
|
||||
return Array.isArray(stored) && stored[index] ? String(stored[index]) : (field.currency || currencyOptions(field)[0]?.value || 'CNY')
|
||||
}
|
||||
const setRowCurrency = (field: ReimbursementFormField, index: number, event: Event) => {
|
||||
const next = Array.isArray(props.formValues[currencyKey(field)]) ? [...props.formValues[currencyKey(field)] as string[]] : []
|
||||
next[index] = (event.target as HTMLSelectElement).value
|
||||
props.formValues[currencyKey(field)] = next
|
||||
}
|
||||
const departments = ref<{ id: string; name: string }[]>([])
|
||||
const departmentQuery = ref('')
|
||||
const departmentOpen = ref(false)
|
||||
const filteredDepartments = computed(() => {
|
||||
const keyword = departmentQuery.value.trim().toLowerCase()
|
||||
return departments.value.filter(department => !keyword || department.name.toLowerCase().includes(keyword)).slice(0, 30)
|
||||
})
|
||||
const selectedDepartmentName = (field: ReimbursementFormField) => {
|
||||
const id = String(props.formValues[field.valueKey] || '')
|
||||
return departments.value.find(department => department.id === id)?.name || ''
|
||||
}
|
||||
const chooseDepartment = (field: ReimbursementFormField, department: { id: string; name: string }) => {
|
||||
props.formValues[field.valueKey] = department.id
|
||||
departmentQuery.value = department.name
|
||||
departmentOpen.value = false
|
||||
}
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const organization = await feishuDirectoryApi.organization()
|
||||
departments.value = (organization.departments || []).map(department => ({ id: department.id, name: department.name }))
|
||||
} catch { departments.value = [] }
|
||||
})
|
||||
|
||||
const attachmentAccept = ATTACHMENT_ACCEPT
|
||||
const itemHasPendingUploads = (item: FormItem) => item.attachmentFiles.some(file => file.status === 'pending' || file.status === 'deleting')
|
||||
const attachmentError = (item: FormItem, required: boolean) => {
|
||||
const failed = item.attachmentFiles.find(file => file.status === 'failed')
|
||||
if (failed) return failed.error || `${failed.fileName}上传失败,请移除后重新选择`
|
||||
const missing = attachmentIdsMissingMetadata(item.attachmentIds, item.attachmentFiles)
|
||||
if (missing.length) return `附件信息不完整(ID:${missing.join('、')}),请刷新详情;如仍异常,请联系管理员处理`
|
||||
if (props.showErrors && required && !item.attachmentIds.length) return '该条费用明细必须上传附件'
|
||||
return ''
|
||||
}
|
||||
const attachmentHasError = (item: FormItem, required: boolean) => Boolean(attachmentError(item, required))
|
||||
const attachmentDescriptionIds = (field: ReimbursementFormField, item: FormItem, required: boolean) => [
|
||||
`${controlId(field)}-${item.key}-attachment-help`,
|
||||
attachmentHasError(item, required) ? `${controlId(field)}-${item.key}-attachment-error` : '',
|
||||
].filter(Boolean).join(' ')
|
||||
const attachmentStatus = (attachment: AttachmentEntry) => {
|
||||
if (attachment.status === 'pending') return '正在上传…'
|
||||
if (attachment.status === 'deleting') return '正在移除…'
|
||||
if (attachment.status === 'failed') return attachment.error || '上传失败'
|
||||
const size = Number(attachment.fileSize || 0)
|
||||
return size ? `已上传 · ${(size / 1024 / 1024).toFixed(size >= 1024 * 1024 ? 1 : 2)} MB` : '已上传'
|
||||
}
|
||||
const uploadAttachments = async (item: FormItem, child: ReimbursementFormField, event: Event) => {
|
||||
const input = event.target as HTMLInputElement
|
||||
const files = [...(input.files || [])]
|
||||
input.value = ''
|
||||
for (const file of files) {
|
||||
const localKey = `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
const invalid = attachmentFileValidationError(file)
|
||||
const entry: AttachmentEntry = { localKey, fileName: file.name, fileSize: file.size, contentType: file.type, status: invalid ? 'failed' : 'pending', error: invalid }
|
||||
item.attachmentFiles.push(entry)
|
||||
emit('upload-state-change')
|
||||
if (invalid) continue
|
||||
try {
|
||||
if (!props.formFingerprint) throw new Error('表单版本缺失,无法上传附件')
|
||||
const uploaded = await reimbursementApi.uploadFormAttachment(file, props.formFingerprint, child.id)
|
||||
Object.assign(entry, uploaded, { status: 'uploaded', error: undefined })
|
||||
if (!item.attachmentIds.some(id => String(id) === String(uploaded.id))) item.attachmentIds.push(uploaded.id)
|
||||
} catch (error) {
|
||||
entry.status = 'failed'
|
||||
entry.error = error instanceof Error && error.message ? error.message : '上传失败,请移除后重试'
|
||||
}
|
||||
emit('upload-state-change')
|
||||
}
|
||||
}
|
||||
const removeAttachment = async (item: FormItem, attachment: AttachmentEntry) => {
|
||||
if (attachment.status === 'pending' || attachment.status === 'deleting') return
|
||||
if (attachment.id == null) {
|
||||
item.attachmentFiles = item.attachmentFiles.filter(file => file.localKey !== attachment.localKey)
|
||||
emit('upload-state-change')
|
||||
return
|
||||
}
|
||||
attachment.status = 'deleting'
|
||||
attachment.error = undefined
|
||||
emit('upload-state-change')
|
||||
try {
|
||||
await reimbursementApi.deleteFormAttachment(attachment.id)
|
||||
item.attachmentIds = item.attachmentIds.filter(id => String(id) !== String(attachment.id))
|
||||
item.attachmentFiles = item.attachmentFiles.filter(file => file.localKey !== attachment.localKey)
|
||||
} catch (error) {
|
||||
attachment.status = 'failed'
|
||||
attachment.error = error instanceof Error && error.message ? error.message : '附件移除失败,请重试'
|
||||
}
|
||||
emit('upload-state-change')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.feishu-fields {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 16px 20px;
|
||||
padding: 20px 22px 22px;
|
||||
}
|
||||
.dynamic-field { min-width: 0; }
|
||||
.expense-field,
|
||||
.display-field,
|
||||
.unsupported-field { grid-column: 1 / -1; }
|
||||
.expense-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
margin: 8px 0 0;
|
||||
padding: 20px 0 0;
|
||||
border-top: 1px solid var(--line);
|
||||
}
|
||||
.expense-field .expense-items { padding: 0; }
|
||||
.expense-field .expense-item {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 16px 20px;
|
||||
align-items: start;
|
||||
padding: 16px;
|
||||
}
|
||||
.expense-field .expense-item > .field { min-width: 0; }
|
||||
.expense-field .expense-item > .attachment-field { grid-column: 1 / -1; }
|
||||
.expense-field .remove-item { grid-column: 1 / -1; justify-self: end; margin-top: 0; }
|
||||
.expense-field .amount-summary { margin: 4px 0 0; }
|
||||
.amount-control-wrap { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
|
||||
.amount-control { display: grid; grid-template-columns: minmax(0, 1fr) 108px; gap: 8px; align-items: center; }
|
||||
.amount-control select { min-height: var(--control-height); }
|
||||
.amount-mismatch-tip { display: block; margin-top: 6px; }
|
||||
.department-picker { position: relative; }
|
||||
.department-menu { position: absolute; z-index: 5; top: calc(100% + 4px); right: 0; left: 0; max-height: 240px; margin: 0; padding: 6px; overflow: auto; list-style: none; border: 1px solid var(--line); border-radius: 6px; background: #fff; box-shadow: var(--card-shadow); }
|
||||
.department-menu button { width: 100%; padding: 8px 10px; border: 0; border-radius: 4px; background: transparent; text-align: left; }
|
||||
.department-menu button:hover { background: var(--blue-soft); color: var(--blue); }
|
||||
.department-empty { padding: 8px 10px; color: var(--muted); }
|
||||
.compact-title {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border-bottom: 0;
|
||||
}
|
||||
.compact-title h3 { margin: 0; font-size: 15px; }
|
||||
.compact-title em { color: var(--danger); font-style: normal; }
|
||||
.display-field,
|
||||
.unsupported-field {
|
||||
padding: 16px 18px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.display-field p { margin: 8px 0 0; color: var(--muted); white-space: pre-wrap; line-height: 1.65; }
|
||||
.unsupported-field { display: flex; flex-direction: column; gap: 6px; border-color: #e5bfbc; background: var(--danger-soft); color: var(--danger); }
|
||||
.expense-child-warning { margin: 0; }
|
||||
.field-error { color: var(--danger); }
|
||||
.field [aria-invalid="true"] { border-color: var(--danger); }
|
||||
.attachment-field { grid-column: 1 / -1; }
|
||||
.attachment-input { padding: 10px; }
|
||||
.attachment-list { display: flex; margin: 10px 0 0; padding: 0; flex-direction: column; gap: 8px; list-style: none; }
|
||||
.attachment-list li {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 14px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
background: var(--surface);
|
||||
}
|
||||
.attachment-list li > div { min-width: 0; }
|
||||
.attachment-list strong,
|
||||
.attachment-list small { display: block; overflow-wrap: anywhere; }
|
||||
.attachment-list small { margin-top: 3px; color: var(--quiet); }
|
||||
.attachment-list .is-failed { border-color: #e5bfbc; background: var(--danger-soft); }
|
||||
.attachment-list .is-failed small { color: var(--danger); }
|
||||
.attachment-remove { border: 0; background: transparent; color: var(--danger); cursor: pointer; font: inherit; }
|
||||
.attachment-remove:disabled { cursor: wait; opacity: .6; }
|
||||
select[multiple] { min-height: 104px; }
|
||||
.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: 680px) {
|
||||
.feishu-fields { grid-template-columns: 1fr; gap: 18px; padding: 16px; }
|
||||
.dynamic-field { grid-column: 1; }
|
||||
.expense-field .expense-item { grid-template-columns: 1fr; }
|
||||
.amount-control { grid-template-columns: 1fr; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { PermissionItem } from '@/api/admin'
|
||||
import { buildPermissionForest, hasUnsavedRoleDraft, hydrateRolePermissions, permissionKind, toggleBranch, validatePermissionCatalog } from './permissionEditor'
|
||||
|
||||
const item = (code: string, type: string, parentCode?: string): PermissionItem => ({ code, name: code, type, parentCode })
|
||||
|
||||
describe('permission editor catalog safety', () => {
|
||||
it('rejects empty and duplicate codes, self parents and cycles', () => {
|
||||
expect(validatePermissionCatalog([item('', 'PAGE')])).toContain('空编码')
|
||||
expect(validatePermissionCatalog([item('x', 'PAGE'), item('x', 'ACTION')])).toContain('重复编码')
|
||||
expect(validatePermissionCatalog([item('x', 'PAGE', 'x')])).toContain('自身')
|
||||
expect(validatePermissionCatalog([item('a', 'PAGE', 'b'), item('b', 'PAGE', 'a')])).toContain('循环')
|
||||
})
|
||||
|
||||
it('retains orphan legacy entries as roots and keeps unknown types compatible', () => {
|
||||
const forest = buildPermissionForest([item('legacy', 'OLD', 'missing')])
|
||||
expect(forest).toHaveLength(1)
|
||||
expect(permissionKind(forest[0])).toBe('action')
|
||||
expect(permissionKind(item('button', 'BUTTON'))).toBe('action')
|
||||
})
|
||||
|
||||
it('bulk changes the complete unfiltered menu tree but never fields', () => {
|
||||
const [module] = buildPermissionForest([item('module.a', 'MODULE'), item('page.a', 'PAGE', 'module.a'), item('button.a', 'ACTION', 'page.a'), item('field.a', 'FIELD', 'page.a')])
|
||||
const updated = toggleBranch(module, true, {})
|
||||
expect(updated).toEqual({ 'module.a': 'READ', 'page.a': 'READ', 'button.a': 'EDIT' })
|
||||
})
|
||||
|
||||
it('can protect hidden search results while allowing matched branch items', () => {
|
||||
const [module] = buildPermissionForest([item('module.a', 'MODULE'), item('page.a', 'PAGE', 'module.a'), item('button.visible', 'ACTION', 'page.a'), item('button.hidden', 'ACTION', 'page.a')])
|
||||
const updated = toggleBranch(module, true, {}, new Set(['module.a', 'page.a', 'button.visible']))
|
||||
expect(updated).toEqual({ 'module.a': 'READ', 'page.a': 'READ', 'button.visible': 'EDIT' })
|
||||
})
|
||||
|
||||
it('rejects missing/malformed role payload instead of granting empty permissions', () => {
|
||||
expect(() => hydrateRolePermissions(undefined)).toThrow('缺失或格式无效')
|
||||
expect(() => hydrateRolePermissions({ permissionAccess: [] as unknown as Record<string, 'READ'> })).toThrow('格式无效')
|
||||
})
|
||||
|
||||
it('strictly validates every permission map entry and code list member', () => {
|
||||
expect(() => hydrateRolePermissions({ permissionCodes: [1] as unknown as string[] })).toThrow('字符串数组')
|
||||
expect(() => hydrateRolePermissions({ permissionAccess: { '': 'READ' } })).toThrow('无效编码或权限值')
|
||||
expect(() => hydrateRolePermissions({ permissionAccess: { x: 'ALLOW' as never } })).toThrow('无效编码或权限值')
|
||||
expect(() => hydrateRolePermissions({ fieldPermissions: { x: null as never } })).toThrow('无效编码或权限值')
|
||||
})
|
||||
|
||||
it('tracks form and permission changes against baselines and retains retry drafts', () => {
|
||||
const savedForm = { roleCode: 'new', roleName: '新角色' }
|
||||
const permissionBase = JSON.stringify({})
|
||||
expect(hasUnsavedRoleDraft(savedForm, { x: 'EDIT' }, JSON.stringify(savedForm), permissionBase)).toBe(true)
|
||||
expect(hasUnsavedRoleDraft(savedForm, { x: 'EDIT' }, JSON.stringify(savedForm), JSON.stringify({ x: 'EDIT' }))).toBe(false)
|
||||
expect(hasUnsavedRoleDraft({ ...savedForm, roleName: '改名' }, { x: 'EDIT' }, JSON.stringify(savedForm), JSON.stringify({ x: 'EDIT' }))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { PermissionAccess, PermissionItem, RolePermissions } from '@/api/admin'
|
||||
|
||||
export type PermissionBranch = PermissionItem & { children: PermissionBranch[] }
|
||||
|
||||
export const hasUnsavedRoleDraft = (form: unknown, permissions: unknown, formBaseline: string, permissionBaseline: string): boolean => JSON.stringify(form) !== formBaseline || JSON.stringify(permissions) !== permissionBaseline
|
||||
|
||||
export const validatePermissionCatalog = (catalog: PermissionItem[]): string | null => {
|
||||
if (!Array.isArray(catalog) || catalog.length === 0) return '权限目录为空,无法安全编辑角色权限。'
|
||||
const codes = new Set<string>()
|
||||
for (const item of catalog) {
|
||||
if (!item || typeof item.code !== 'string' || !item.code.trim() || item.code.trim() !== item.code) return '权限目录存在空编码或无效空格,已禁止保存。'
|
||||
if (typeof item.name !== 'string' || !item.name.trim()) return `权限「${item.code}」缺少名称,已禁止保存。`
|
||||
if (item.parentCode !== undefined && item.parentCode !== null && typeof item.parentCode !== 'string') return `权限「${item.code}」的父级编码格式无效,已禁止保存。`
|
||||
if (codes.has(item.code)) return `权限目录存在重复编码「${item.code}」,已禁止保存。`
|
||||
codes.add(item.code)
|
||||
}
|
||||
const parents = new Map(catalog.map(item => [item.code, item.parentCode]))
|
||||
for (const item of catalog) if (item.parentCode === item.code) return `权限「${item.code}」不能以自身为父级,已禁止保存。`
|
||||
for (const item of catalog) {
|
||||
const path = new Set<string>([item.code])
|
||||
let parent = item.parentCode
|
||||
while (parent && parents.has(parent)) {
|
||||
if (path.has(parent)) return `权限「${item.code}」的父级关系存在循环(涉及「${parent}」),已禁止保存。`
|
||||
path.add(parent)
|
||||
parent = parents.get(parent)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export const permissionKind = (item: PermissionItem) => {
|
||||
const type = String(item.type || '').trim().toUpperCase()
|
||||
// Explicit backend types are authoritative. In particular, BUTTON codes may
|
||||
// use the legacy `application:*` namespace also used by old field codes.
|
||||
if (type === 'FIELD') return 'field'
|
||||
if (type === 'ACTION' || type === 'BUTTON') return 'action'
|
||||
if (type === 'MODULE') return 'module'
|
||||
if (type === 'PAGE') return 'page'
|
||||
if (type === 'MENU') return item.code.startsWith('module.') || !item.parentCode ? 'module' : 'page'
|
||||
// Code inference is compatibility-only for missing or unknown types.
|
||||
if (item.code.startsWith('application:')) return 'field'
|
||||
if (!item.code.startsWith('module.') && !item.code.startsWith('page.')) return 'action'
|
||||
return item.code.startsWith('module.') ? 'module' : 'page'
|
||||
}
|
||||
|
||||
export const buildPermissionForest = (catalog: PermissionItem[]): PermissionBranch[] => {
|
||||
const branches = new Map(catalog.map(item => [item.code, { ...item, children: [] as PermissionBranch[] }]))
|
||||
const roots: PermissionBranch[] = []
|
||||
branches.forEach(branch => {
|
||||
const parent = branch.parentCode ? branches.get(branch.parentCode) : undefined
|
||||
if (parent) parent.children.push(branch)
|
||||
else roots.push(branch)
|
||||
})
|
||||
const sort = (items: PermissionBranch[]) => items.sort((a, b) => a.code.localeCompare(b.code, 'zh-CN')).forEach(item => sort(item.children))
|
||||
sort(roots)
|
||||
return roots
|
||||
}
|
||||
|
||||
export const descendants = (branch: PermissionBranch): PermissionBranch[] => [branch, ...branch.children.flatMap(descendants)]
|
||||
|
||||
export const branchState = (branch: PermissionBranch, access: Record<string, PermissionAccess>) => {
|
||||
const selectable = descendants(branch).filter(item => permissionKind(item) !== 'field')
|
||||
const selected = selectable.filter(item => (access[item.code] || 'HIDDEN') !== 'HIDDEN').length
|
||||
return { checked: Boolean(selectable.length) && selected === selectable.length, indeterminate: selected > 0 && selected < selectable.length }
|
||||
}
|
||||
|
||||
export const toggleBranch = (branch: PermissionBranch, checked: boolean, source: Record<string, PermissionAccess>, allowedCodes?: Set<string>) => {
|
||||
const next = { ...source }
|
||||
descendants(branch).forEach(item => {
|
||||
if (allowedCodes && !allowedCodes.has(item.code)) return
|
||||
const kind = permissionKind(item)
|
||||
// Menu bulk actions never mutate field grants. Fields are managed in their
|
||||
// own column and retain their explicit HIDDEN/READ/EDIT value.
|
||||
if (kind === 'field') return
|
||||
next[item.code] = checked ? (kind === 'action' ? 'EDIT' : 'READ') : 'HIDDEN'
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
export const matchesPermission = (branch: PermissionBranch, query: string): boolean => {
|
||||
const value = query.trim().toLocaleLowerCase()
|
||||
return !value || `${branch.name} ${branch.code}`.toLocaleLowerCase().includes(value) || branch.children.some(child => matchesPermission(child, value))
|
||||
}
|
||||
|
||||
export const hydrateRolePermissions = (value: Partial<RolePermissions> | undefined) => {
|
||||
if (!value || typeof value !== 'object' || (!Array.isArray(value.permissionCodes) && !isAccessMap(value.permissionAccess) && !isAccessMap(value.fieldPermissions))) throw new Error('角色权限响应缺失或格式无效,已禁止保存。')
|
||||
if ((value.permissionCodes !== undefined && !Array.isArray(value.permissionCodes)) || (value.permissionAccess !== undefined && !isAccessMap(value.permissionAccess)) || (value.fieldPermissions !== undefined && !isAccessMap(value.fieldPermissions))) throw new Error('角色权限响应格式无效,已禁止保存。')
|
||||
if (value.permissionCodes !== undefined && !(value.permissionCodes as unknown[]).every(code => typeof code === 'string' && code.trim().length > 0)) throw new Error('角色权限编码列表必须是非空字符串数组,已禁止保存。')
|
||||
for (const [mapName, map] of [['permissionAccess', value.permissionAccess], ['fieldPermissions', value.fieldPermissions]] as const) {
|
||||
if (map === undefined) continue
|
||||
for (const [code, level] of Object.entries(map)) {
|
||||
if (!code.trim() || !['HIDDEN', 'READ', 'EDIT'].includes(String(level))) throw new Error(`角色权限${mapName}包含无效编码或权限值,已禁止保存。`)
|
||||
}
|
||||
}
|
||||
const access: Record<string, PermissionAccess> = { ...(value?.permissionAccess || {}) }
|
||||
if (!value?.permissionAccess) (value?.permissionCodes || []).forEach(code => { access[code] = 'EDIT' })
|
||||
Object.entries(value?.fieldPermissions || {}).forEach(([code, level]) => { access[code] = level })
|
||||
return access
|
||||
}
|
||||
|
||||
const isAccessMap = (value: unknown): value is Record<string, PermissionAccess> => Boolean(value && typeof value === 'object' && !Array.isArray(value))
|
||||
|
||||
export const serializeRolePermissions = (access: Record<string, PermissionAccess>, catalog: PermissionItem[]): RolePermissions => {
|
||||
const fields = new Set(catalog.filter(item => permissionKind(item) === 'field').map(item => item.code))
|
||||
// Explicit HIDDEN values are revocations and must survive a round-trip.
|
||||
const permissionAccess = { ...access }
|
||||
const fieldPermissions = Object.fromEntries(Object.entries(access).filter(([code]) => fields.has(code))) as Record<string, PermissionAccess>
|
||||
return { permissionAccess, permissionCodes: Object.entries(permissionAccess).filter(([code, level]) => !fields.has(code) && level !== 'HIDDEN').map(([code]) => code), fieldPermissions }
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { computed, ref, toValue, watch, type MaybeRefOrGetter, type WatchSource } from 'vue'
|
||||
|
||||
export const LIST_PAGE_SIZES = [10, 20, 50] as const
|
||||
const DEFAULT_LIST_PAGE_SIZE = 20
|
||||
|
||||
export function useListPagination<T>(
|
||||
source: MaybeRefOrGetter<readonly T[]>,
|
||||
options: { resetSources?: WatchSource[]; initialPageSize?: number } = {},
|
||||
) {
|
||||
const page = ref(1)
|
||||
const requestedSize = Number(options.initialPageSize)
|
||||
const pageSize = ref<number>(LIST_PAGE_SIZES.includes(requestedSize as 10 | 20 | 50) ? requestedSize : DEFAULT_LIST_PAGE_SIZE)
|
||||
const items = computed(() => toValue(source) || [])
|
||||
const total = computed(() => items.value.length)
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
|
||||
const clampPage = () => {
|
||||
page.value = Math.min(Math.max(1, Math.trunc(Number(page.value) || 1)), totalPages.value)
|
||||
}
|
||||
const resetPage = () => { page.value = 1 }
|
||||
const paginatedItems = computed(() => {
|
||||
const start = (page.value - 1) * pageSize.value
|
||||
return items.value.slice(start, start + pageSize.value)
|
||||
})
|
||||
|
||||
watch(pageSize, resetPage, { flush: 'sync' })
|
||||
watch(total, clampPage, { flush: 'sync' })
|
||||
if (options.resetSources?.length) watch(options.resetSources, resetPage, { flush: 'sync' })
|
||||
|
||||
return { page, pageSize, total, totalPages, paginatedItems, resetPage, clampPage }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { DirectoryIdentity, GroupCandidate, UserGroup } from '@/api/admin'
|
||||
|
||||
export const isDefaultGroup = (group?: UserGroup | null) =>
|
||||
Boolean(group && (group.groupCode === 'DEFAULT_EMPLOYEE' || group.membershipMode === 'DYNAMIC'))
|
||||
|
||||
export const isSuperAdminGroup = (group?: UserGroup | null) =>
|
||||
group?.groupCode === 'SUPER_ADMIN_GROUP'
|
||||
|
||||
export const sortUserGroups = (groups: UserGroup[]) =>
|
||||
[...groups].sort((left, right) => {
|
||||
const rank = (group: UserGroup) => isDefaultGroup(group) ? 0 : isSuperAdminGroup(group) ? 1 : 2
|
||||
return rank(left) - rank(right)
|
||||
})
|
||||
|
||||
export const memberCountText = (count: number | null) => count === null ? '无法确认' : String(count)
|
||||
|
||||
export const belongsToCurrentGroup = (candidate: GroupCandidate, groupId: number) =>
|
||||
candidate.assignedGroupId === groupId
|
||||
|
||||
export const candidateDisabled = (candidate: GroupCandidate, groupId: number) =>
|
||||
!candidate.selectable || candidate.assignedGroupId !== null
|
||||
|
||||
export type MemberSelectionKey = string
|
||||
|
||||
export const localMemberKey = (id: number): MemberSelectionKey => `local:${id}`
|
||||
|
||||
export const directoryIdentityKey = (identity: DirectoryIdentity): MemberSelectionKey =>
|
||||
`directory:${JSON.stringify([identity.generationId, identity.openId])}`
|
||||
|
||||
export const directoryIdentityPayload = (identity: DirectoryIdentity): DirectoryIdentity => ({
|
||||
generationId: identity.generationId,
|
||||
openId: identity.openId,
|
||||
...(identity.userId == null ? {} : { userId: identity.userId }),
|
||||
})
|
||||
|
||||
export const candidateKey = (candidate: GroupCandidate, baselineIds: ReadonlySet<number>): MemberSelectionKey => {
|
||||
if (candidate.id !== null && baselineIds.has(candidate.id)) return localMemberKey(candidate.id)
|
||||
if (candidate.directoryIdentity) return directoryIdentityKey(candidate.directoryIdentity)
|
||||
if (candidate.id !== null) return `readonly-local:${candidate.id}`
|
||||
return `readonly-directory:${JSON.stringify([candidate.realName, candidate.employeeNo ?? '', candidate.departmentNames ?? []])}`
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { Directive } from 'vue'
|
||||
|
||||
type DragState = {
|
||||
cleanupPointer?: () => void
|
||||
observer: MutationObserver
|
||||
onResize: () => void
|
||||
onClose: () => void
|
||||
}
|
||||
|
||||
const states = new WeakMap<HTMLDialogElement, DragState>()
|
||||
const gap = 12
|
||||
const interactiveSelector = 'button,input,select,textarea,a,[contenteditable="true"],[role="button"]'
|
||||
const handleSelector = '[data-dialog-drag-handle],.modal-head,.route-dialog-head,.notification-modal-head'
|
||||
const dragEnabled = () => window.matchMedia('(min-width: 761px)').matches
|
||||
|
||||
const resetPosition = (dialog: HTMLDialogElement) => {
|
||||
dialog.style.removeProperty('left')
|
||||
dialog.style.removeProperty('top')
|
||||
dialog.style.removeProperty('right')
|
||||
dialog.style.removeProperty('bottom')
|
||||
dialog.style.removeProperty('margin')
|
||||
dialog.dataset.dialogDragged = 'false'
|
||||
}
|
||||
|
||||
const constrainPosition = (dialog: HTMLDialogElement) => {
|
||||
if (!dialog.open || dialog.dataset.dialogDragged !== 'true') return
|
||||
const rect = dialog.getBoundingClientRect()
|
||||
const handle = dialog.querySelector<HTMLElement>(handleSelector)
|
||||
const titleHeight = Math.max(44, handle?.getBoundingClientRect().height || 0)
|
||||
const maxLeft = Math.max(gap, window.innerWidth - rect.width - gap)
|
||||
const maxTop = Math.max(gap, window.innerHeight - Math.min(rect.height, titleHeight) - gap)
|
||||
const left = Math.min(Math.max(gap, rect.left), maxLeft)
|
||||
const top = Math.min(Math.max(gap, rect.top), maxTop)
|
||||
dialog.style.left = `${left}px`
|
||||
dialog.style.top = `${top}px`
|
||||
}
|
||||
|
||||
export const dialogDrag: Directive<HTMLDialogElement> = {
|
||||
mounted(dialog) {
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
if (!dialog.open || !dragEnabled() || event.button !== 0 || !['mouse', 'pen'].includes(event.pointerType)) return
|
||||
const target = event.target as HTMLElement
|
||||
const handle = target.closest<HTMLElement>(handleSelector)
|
||||
if (!handle || !dialog.contains(handle) || target.closest(interactiveSelector)) return
|
||||
const state = states.get(dialog)
|
||||
if (!state) return
|
||||
state.cleanupPointer?.()
|
||||
|
||||
const rect = dialog.getBoundingClientRect()
|
||||
const offsetX = event.clientX - rect.left
|
||||
const offsetY = event.clientY - rect.top
|
||||
dialog.style.margin = '0'
|
||||
dialog.style.right = 'auto'
|
||||
dialog.style.bottom = 'auto'
|
||||
dialog.style.left = `${rect.left}px`
|
||||
dialog.style.top = `${rect.top}px`
|
||||
dialog.dataset.dialogDragged = 'true'
|
||||
dialog.classList.add('is-dialog-dragging')
|
||||
handle.setPointerCapture(event.pointerId)
|
||||
|
||||
const move = (moveEvent: PointerEvent) => {
|
||||
if (moveEvent.pointerId !== event.pointerId) return
|
||||
const width = dialog.offsetWidth
|
||||
const height = dialog.offsetHeight
|
||||
const titleHeight = Math.max(44, handle.offsetHeight)
|
||||
const maxLeft = Math.max(gap, window.innerWidth - width - gap)
|
||||
const maxTop = Math.max(gap, window.innerHeight - Math.min(height, titleHeight) - gap)
|
||||
dialog.style.left = `${Math.min(Math.max(gap, moveEvent.clientX - offsetX), maxLeft)}px`
|
||||
dialog.style.top = `${Math.min(Math.max(gap, moveEvent.clientY - offsetY), maxTop)}px`
|
||||
}
|
||||
let stopped = false
|
||||
const stop = () => {
|
||||
if (stopped) return
|
||||
stopped = true
|
||||
handle.removeEventListener('pointermove', move)
|
||||
handle.removeEventListener('pointerup', stop)
|
||||
handle.removeEventListener('pointercancel', stop)
|
||||
handle.removeEventListener('lostpointercapture', stop)
|
||||
try {
|
||||
if (handle.hasPointerCapture(event.pointerId)) handle.releasePointerCapture(event.pointerId)
|
||||
} catch { /* capture may already have been released by the browser */ }
|
||||
dialog.classList.remove('is-dialog-dragging')
|
||||
if (state.cleanupPointer === stop) state.cleanupPointer = undefined
|
||||
constrainPosition(dialog)
|
||||
}
|
||||
state.cleanupPointer = stop
|
||||
handle.addEventListener('pointermove', move)
|
||||
handle.addEventListener('pointerup', stop)
|
||||
handle.addEventListener('pointercancel', stop)
|
||||
handle.addEventListener('lostpointercapture', stop)
|
||||
event.preventDefault()
|
||||
}
|
||||
|
||||
const onClose = () => {
|
||||
const state = states.get(dialog)
|
||||
state?.cleanupPointer?.()
|
||||
dialog.classList.remove('is-dialog-dragging')
|
||||
resetPosition(dialog)
|
||||
}
|
||||
const onResize = () => dragEnabled() ? constrainPosition(dialog) : resetPosition(dialog)
|
||||
const observer = new MutationObserver(() => {
|
||||
if (dialog.open) resetPosition(dialog)
|
||||
else onClose()
|
||||
})
|
||||
const state: DragState = { observer, onResize, onClose }
|
||||
states.set(dialog, state)
|
||||
dialog.addEventListener('pointerdown', onPointerDown)
|
||||
dialog.addEventListener('close', onClose)
|
||||
window.addEventListener('resize', onResize)
|
||||
observer.observe(dialog, { attributes: true, attributeFilter: ['open'] })
|
||||
;(dialog as HTMLDialogElement & { __dialogDragPointerDown?: (event: PointerEvent) => void }).__dialogDragPointerDown = onPointerDown
|
||||
},
|
||||
unmounted(dialog) {
|
||||
const state = states.get(dialog)
|
||||
const element = dialog as HTMLDialogElement & { __dialogDragPointerDown?: (event: PointerEvent) => void }
|
||||
if (element.__dialogDragPointerDown) dialog.removeEventListener('pointerdown', element.__dialogDragPointerDown)
|
||||
state?.cleanupPointer?.()
|
||||
state?.observer.disconnect()
|
||||
if (state) {
|
||||
dialog.removeEventListener('close', state.onClose)
|
||||
window.removeEventListener('resize', state.onResize)
|
||||
}
|
||||
states.delete(dialog)
|
||||
},
|
||||
}
|
||||
@@ -1,373 +0,0 @@
|
||||
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'), /通讯录同步用于员工资料与业务管理,不作为登录条件/)
|
||||
})
|
||||
@@ -1,95 +0,0 @@
|
||||
// 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')
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import 'element-plus/dist/index.css'
|
||||
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
|
||||
import App from './App.vue'
|
||||
import router from './router'
|
||||
import { dialogDrag } from './directives/dialogDrag'
|
||||
import './assets/main.css'
|
||||
|
||||
const app = createApp(App)
|
||||
@@ -18,4 +19,5 @@ for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
|
||||
app.use(createPinia())
|
||||
app.use(router)
|
||||
app.use(ElementPlus, { locale: zhCn })
|
||||
app.directive('dialog-drag', dialogDrag)
|
||||
app.mount('#app')
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
MAX_ATTACHMENT_SIZE,
|
||||
attachmentFileValidationError,
|
||||
attachmentIdsMissingMetadata,
|
||||
expenseItemAttachmentMetadata,
|
||||
hydratedAttachmentIds,
|
||||
} from './reimbursementAttachments'
|
||||
|
||||
describe('attachment file policy', () => {
|
||||
it.each(['receipt.pdf', 'scan.PNG', 'photo.jpeg', 'memo.doc', 'memo.docx', 'sheet.xls', 'sheet.xlsx'])(
|
||||
'accepts supported file %s up to and including 50MB',
|
||||
name => expect(attachmentFileValidationError({ name, size: MAX_ATTACHMENT_SIZE })).toBe(''),
|
||||
)
|
||||
|
||||
it('rejects unsupported extensions and files over 50MB', () => {
|
||||
expect(attachmentFileValidationError({ name: 'archive.zip', size: 20 })).toContain('不支持')
|
||||
expect(attachmentFileValidationError({ name: 'large.pdf', size: MAX_ATTACHMENT_SIZE + 1 })).toContain('超过 50MB')
|
||||
})
|
||||
})
|
||||
|
||||
describe('saved attachment hydration', () => {
|
||||
const item = {
|
||||
id: 42,
|
||||
attachmentIds: [7, 8, 9],
|
||||
attachments: [{ id: 7, fileName: 'per-item.pdf', contentType: 'application/pdf', fileSize: 100 }],
|
||||
}
|
||||
const topLevel = [
|
||||
{ id: 8, expenseItemId: '42', fileName: 'legacy.jpg', fileType: 'image/jpeg', fileSize: 200 },
|
||||
{ id: 10, expenseItemId: 99, fileName: 'other-row.pdf', fileType: 'application/pdf', fileSize: 300 },
|
||||
]
|
||||
|
||||
it('combines per-item metadata with matching legacy top-level metadata only', () => {
|
||||
const metadata = expenseItemAttachmentMetadata(item, topLevel)
|
||||
expect(metadata).toEqual([
|
||||
item.attachments[0],
|
||||
{ id: 8, fileName: 'legacy.jpg', contentType: 'image/jpeg', fileSize: 200 },
|
||||
])
|
||||
expect(hydratedAttachmentIds(item, metadata)).toEqual([7, 8, 9])
|
||||
expect(attachmentIdsMissingMetadata(item.attachmentIds, metadata)).toEqual([9])
|
||||
})
|
||||
|
||||
it('derives ids from visible metadata when an older detail omits attachmentIds', () => {
|
||||
const metadata = expenseItemAttachmentMetadata({ id: 42 }, topLevel)
|
||||
expect(hydratedAttachmentIds({ id: 42 }, metadata)).toEqual([8])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { ExpenseItem, ReimbursementFormAttachment } from '@/api/reimbursement'
|
||||
|
||||
export const MAX_ATTACHMENT_SIZE = 50 * 1024 * 1024
|
||||
export const ATTACHMENT_ACCEPT = '.pdf,.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx,application/pdf,image/png,image/jpeg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
|
||||
|
||||
const acceptedExtensions = new Set(['pdf', 'png', 'jpg', 'jpeg', 'doc', 'docx', 'xls', 'xlsx'])
|
||||
|
||||
export interface AttachmentMetadataCandidate {
|
||||
id?: number | string
|
||||
fileName?: string
|
||||
contentType?: string
|
||||
fileType?: string
|
||||
fileSize?: number
|
||||
expenseItemId?: number | string
|
||||
}
|
||||
|
||||
export interface AttachmentFileCandidate {
|
||||
name: string
|
||||
size: number
|
||||
}
|
||||
|
||||
const normalizeAttachment = (file: AttachmentMetadataCandidate): ReimbursementFormAttachment | null => {
|
||||
if (file?.id == null || !file.fileName) return null
|
||||
return {
|
||||
id: file.id,
|
||||
fileName: file.fileName,
|
||||
contentType: file.contentType || file.fileType || '',
|
||||
fileSize: Number(file.fileSize || 0),
|
||||
}
|
||||
}
|
||||
|
||||
/** Combines current per-item metadata with legacy application-level metadata. */
|
||||
export const expenseItemAttachmentMetadata = (
|
||||
item?: Partial<ExpenseItem>,
|
||||
applicationAttachments: AttachmentMetadataCandidate[] = [],
|
||||
): ReimbursementFormAttachment[] => {
|
||||
const itemId = item?.id
|
||||
const legacyMatches = itemId == null
|
||||
? []
|
||||
: applicationAttachments.filter(file => file?.expenseItemId != null && String(file.expenseItemId) === String(itemId))
|
||||
const candidates: AttachmentMetadataCandidate[] = [
|
||||
...(item?.attachments || []),
|
||||
...(item?.attachmentMetadata || []),
|
||||
...legacyMatches,
|
||||
]
|
||||
const unique = new Map<string, ReimbursementFormAttachment>()
|
||||
candidates.forEach(candidate => {
|
||||
const file = normalizeAttachment(candidate)
|
||||
if (file && !unique.has(String(file.id))) unique.set(String(file.id), file)
|
||||
})
|
||||
return [...unique.values()]
|
||||
}
|
||||
|
||||
export const hydratedAttachmentIds = (
|
||||
item: Partial<ExpenseItem> | undefined,
|
||||
metadata: ReimbursementFormAttachment[],
|
||||
): Array<number | string> => {
|
||||
const unique = new Map<string, number | string>()
|
||||
const ids = [...(item?.attachmentIds || []), ...metadata.map(file => file.id)]
|
||||
ids.forEach(id => unique.set(String(id), id))
|
||||
return [...unique.values()]
|
||||
}
|
||||
|
||||
export const attachmentIdsMissingMetadata = (
|
||||
attachmentIds: Array<number | string>,
|
||||
metadata: Array<{ id?: number | string }>,
|
||||
): Array<number | string> => {
|
||||
const visibleIds = new Set(metadata.filter(file => file.id != null).map(file => String(file.id)))
|
||||
return attachmentIds.filter(id => !visibleIds.has(String(id)))
|
||||
}
|
||||
|
||||
export const attachmentFileValidationError = (file: AttachmentFileCandidate): string => {
|
||||
const extension = file.name.split('.').pop()?.toLowerCase() || ''
|
||||
if (!acceptedExtensions.has(extension)) return '不支持该文件类型,请选择 PDF、PNG/JPEG、DOC/DOCX 或 XLS/XLSX 文件'
|
||||
if (file.size > MAX_ATTACHMENT_SIZE) return '文件超过 50MB,无法上传'
|
||||
return ''
|
||||
}
|
||||
+40
-40
@@ -21,85 +21,91 @@ const routes: RouteRecordRaw[] = [
|
||||
path: 'dashboard',
|
||||
name: 'Dashboard',
|
||||
component: () => import('@/views/Dashboard.vue'),
|
||||
meta: { title: '工作台', permission: ['applications', 'reimbursement:view-own'] },
|
||||
meta: { title: '工作台', permission: 'page.dashboard' },
|
||||
},
|
||||
{
|
||||
path: 'applications',
|
||||
name: 'Applications',
|
||||
component: () => import('@/views/Applications.vue'),
|
||||
meta: { title: '我的报销', permission: ['applications', 'reimbursement:view-own'], roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '我的报销', permission: 'page.applications' },
|
||||
},
|
||||
{
|
||||
path: 'applications/new',
|
||||
name: 'ApplicationNew',
|
||||
component: () => import('@/components/ReimbursementForm.vue'),
|
||||
meta: { title: '发起报销', permission: 'reimbursement:create', roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '发起报销', permission: 'page.application-create' },
|
||||
},
|
||||
{
|
||||
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'] },
|
||||
meta: { title: '报销单详情', hidden: true, permission: 'page.applications' },
|
||||
},
|
||||
{
|
||||
path: 'applications/:id/edit',
|
||||
name: 'ApplicationEdit',
|
||||
component: () => import('@/components/ReimbursementForm.vue'),
|
||||
meta: { title: '编辑报销', hidden: true, permission: 'reimbursement:create', roles: ['EMPLOYEE', 'FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '编辑报销', hidden: true, permission: 'page.application-edit' },
|
||||
},
|
||||
{
|
||||
path: 'finance-receipt',
|
||||
name: 'FinanceReceipt',
|
||||
component: () => import('@/views/FinanceReceipt.vue'),
|
||||
meta: { title: '财务待收单', permission: 'receipt:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '财务待收单', permission: 'page.finance-receipt' },
|
||||
},
|
||||
{
|
||||
path: 'sources',
|
||||
name: 'Sources',
|
||||
component: () => import('@/views/Sources.vue'),
|
||||
meta: { title: '业务单据', permission: 'reimbursement:view-all', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '业务单据', permission: 'page.source-documents' },
|
||||
},
|
||||
{
|
||||
path: 'payments',
|
||||
name: 'Payments',
|
||||
component: () => import('@/views/Payments.vue'),
|
||||
meta: { title: '待付款', permission: 'payment:register', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '待付款', permission: 'page.payments' },
|
||||
},
|
||||
{
|
||||
path: 'kingdee-accounts',
|
||||
redirect: { path: '/integration-config', query: { tab: 'kingdee' } },
|
||||
},
|
||||
{
|
||||
path: 'logs',
|
||||
name: 'Logs',
|
||||
component: () => import('@/views/Logs.vue'),
|
||||
meta: { title: '操作日志', permission: 'approval:view', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '操作日志', permission: 'page.operation-log' },
|
||||
},
|
||||
{
|
||||
path: 'expense-types',
|
||||
name: 'ExpenseTypes',
|
||||
component: () => import('@/views/ExpenseTypes.vue'),
|
||||
meta: { title: '费用类型', permission: 'master-data:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '费用类型', permission: 'page.expense-types' },
|
||||
},
|
||||
{
|
||||
path: 'payees',
|
||||
name: 'Payees',
|
||||
component: () => import('@/views/Payees.vue'),
|
||||
meta: { title: '付款对象', permission: 'master-data:manage', roles: ['FINANCE', 'ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '付款对象', permission: 'page.payees' },
|
||||
},
|
||||
{
|
||||
path: 'users',
|
||||
name: 'Users',
|
||||
component: () => import('@/views/Users.vue'),
|
||||
meta: { title: '用户管理', permission: 'system:user:view', roles: ['ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '人员与角色', permission: ['page.groups', 'page.roles', 'page.feishu-directory'] },
|
||||
},
|
||||
{
|
||||
path: 'feishu-directory',
|
||||
name: 'FeishuDirectory',
|
||||
component: () => import('@/views/FeishuDirectory.vue'),
|
||||
meta: { title: '飞书通讯录', permission: ['system:feishu:sync', 'system:feishu:bind'] },
|
||||
redirect: { path: '/users', query: { tab: 'directory' } },
|
||||
},
|
||||
{
|
||||
path: 'scheduled-tasks',
|
||||
redirect: { path: '/integration-config', query: { tab: 'scheduled-tasks' } },
|
||||
},
|
||||
{
|
||||
path: 'integration-config',
|
||||
name: 'IntegrationConfig',
|
||||
component: () => import('@/views/IntegrationConfig.vue'),
|
||||
meta: { title: '配置管理', permission: 'system:integration:view', roles: ['ADMIN', 'SUPER_ADMIN'] },
|
||||
meta: { title: '配置管理', permission: ['page.integration-config', 'page.kingdee-account-binding', 'page.scheduled-tasks'] },
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -111,7 +117,7 @@ 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 hadSession = Boolean(sessionStorage.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()
|
||||
|
||||
@@ -133,38 +139,32 @@ router.beforeEach(async (to, _from, next) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (to.path === '/login' && token && !isOAuthCallback) return next('/dashboard')
|
||||
if (to.path === '/login' && token && !isOAuthCallback && !to.query.permissionError && !to.query.denied) 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)) {
|
||||
if (requiredPermissions.length > 0) {
|
||||
try {
|
||||
await userStore.loadPermissions()
|
||||
} catch {
|
||||
if (!requiredRoles.includes(userType)) {
|
||||
return next({ path: '/dashboard', query: { denied: String(to.meta.title || '该页面') } })
|
||||
}
|
||||
return next({ path: '/login', query: { permissionError: '1' } })
|
||||
}
|
||||
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 || '该页面') } })
|
||||
if (!requiredPermissions.some(permission => userStore.canRead(permission))) {
|
||||
const candidates = [
|
||||
['/dashboard', 'page.dashboard'], ['/applications', 'page.applications'],
|
||||
['/finance-receipt', 'page.finance-receipt'], ['/sources', 'page.source-documents'],
|
||||
['/payments', 'page.payments'],
|
||||
['/logs', 'page.operation-log'],
|
||||
['/expense-types', 'page.expense-types'], ['/payees', 'page.payees'],
|
||||
['/users', ['page.groups', 'page.roles', 'page.feishu-directory']],
|
||||
['/integration-config', ['page.integration-config', 'page.kingdee-account-binding', 'page.scheduled-tasks']],
|
||||
] as Array<[string, string | string[]]>
|
||||
const first = candidates.find(([, code]) => (Array.isArray(code) ? code : [code]).some(userStore.canRead))?.[0]
|
||||
if (!first) return next({ path: '/login', query: { denied: '无可访问页面' } })
|
||||
if (first === to.path) return next(false)
|
||||
return next({ path: first, query: { denied: String(to.meta.title || '该页面') } })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
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 }
|
||||
})
|
||||
+97
-26
@@ -2,6 +2,7 @@ import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { authApi, type UserProfile } from '@/api/auth'
|
||||
import request from '@/api/request'
|
||||
import type { PermissionAccess } from '@/api/admin'
|
||||
import {
|
||||
AUTH_DAY_KEY,
|
||||
DEMO_SESSION_TOKEN,
|
||||
@@ -26,19 +27,40 @@ 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)}`
|
||||
if (typeof crypto === 'undefined' || typeof crypto.getRandomValues !== 'function') {
|
||||
throw new Error('当前浏览器不支持安全的登录校验,请使用 HTTPS 后重试')
|
||||
}
|
||||
const bytes = crypto.getRandomValues(new Uint8Array(16))
|
||||
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const token = ref(localStorage.getItem(TOKEN_KEY) || '')
|
||||
// Keep bearer credentials scoped to this browser tab/session, not durable localStorage.
|
||||
const token = ref(sessionStorage.getItem(TOKEN_KEY) || '')
|
||||
const userInfo = ref<UserProfile | null>(readStoredUser())
|
||||
const permissionCodes = ref<string[]>([])
|
||||
const fieldPermissions = ref<Record<string, 'HIDDEN' | 'READ' | 'EDIT'>>({})
|
||||
const roleCodes = ref<string[]>([])
|
||||
const fieldPermissions = ref<Record<string, PermissionAccess>>({})
|
||||
const permissionAccess = ref<Record<string, PermissionAccess>>({})
|
||||
const permissionsLoaded = ref(false)
|
||||
const permissionsError = ref('')
|
||||
let permissionRequest: Promise<void> | null = null
|
||||
let permissionGeneration = 0
|
||||
let sessionVersion = 0
|
||||
|
||||
const clearPermissions = (invalidateRequests = true) => {
|
||||
if (invalidateRequests) {
|
||||
permissionGeneration += 1
|
||||
permissionRequest = null
|
||||
}
|
||||
permissionCodes.value = []
|
||||
roleCodes.value = []
|
||||
fieldPermissions.value = {}
|
||||
permissionAccess.value = {}
|
||||
permissionsLoaded.value = false
|
||||
permissionsError.value = ''
|
||||
}
|
||||
|
||||
const isLoggedIn = computed(() => !!token.value)
|
||||
const isFinance = computed(() => ['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(userInfo.value?.userType || ''))
|
||||
|
||||
@@ -53,9 +75,11 @@ export const useUserStore = defineStore('user', () => {
|
||||
const completeLogin = (jwt: string, user: UserProfile) => {
|
||||
if (!jwt || !isValidUser(user)) throw new Error('登录响应缺少有效身份信息')
|
||||
sessionVersion += 1
|
||||
clearPermissions()
|
||||
token.value = jwt
|
||||
userInfo.value = user
|
||||
localStorage.setItem(TOKEN_KEY, jwt)
|
||||
sessionStorage.setItem(TOKEN_KEY, jwt)
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))
|
||||
saveAuthDay()
|
||||
}
|
||||
@@ -96,9 +120,11 @@ export const useUserStore = defineStore('user', () => {
|
||||
const setToken = async (jwt: string) => {
|
||||
if (!jwt) throw new Error('登录响应缺少有效令牌')
|
||||
sessionVersion += 1
|
||||
clearPermissions()
|
||||
token.value = jwt
|
||||
userInfo.value = null
|
||||
localStorage.setItem(TOKEN_KEY, jwt)
|
||||
sessionStorage.setItem(TOKEN_KEY, jwt)
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(USER_INFO_KEY)
|
||||
await fetchUserInfo()
|
||||
// fetchUserInfo validates the callback token and user before this marker
|
||||
@@ -111,7 +137,7 @@ export const useUserStore = defineStore('user', () => {
|
||||
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) {
|
||||
if (requestVersion !== sessionVersion || token.value !== requestToken || sessionStorage.getItem(TOKEN_KEY) !== requestToken) {
|
||||
throw new Error('登录状态已更新,请重新登录')
|
||||
}
|
||||
completeLogin(response.token, response.user)
|
||||
@@ -120,7 +146,7 @@ export const useUserStore = defineStore('user', () => {
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
const requestVersion = sessionVersion
|
||||
const requestToken = token.value || localStorage.getItem(TOKEN_KEY) || ''
|
||||
const requestToken = token.value || sessionStorage.getItem(TOKEN_KEY) || ''
|
||||
if (!requestToken) {
|
||||
logout()
|
||||
throw new Error('未登录')
|
||||
@@ -128,7 +154,7 @@ export const useUserStore = defineStore('user', () => {
|
||||
|
||||
try {
|
||||
const user = await authApi.getUserInfo()
|
||||
if (requestVersion !== sessionVersion || token.value !== requestToken || localStorage.getItem(TOKEN_KEY) !== requestToken) {
|
||||
if (requestVersion !== sessionVersion || token.value !== requestToken || sessionStorage.getItem(TOKEN_KEY) !== requestToken) {
|
||||
throw new Error('登录状态已更新,请重新加载页面')
|
||||
}
|
||||
if (!isValidUser(user)) throw new Error('用户信息无效')
|
||||
@@ -137,7 +163,7 @@ export const useUserStore = defineStore('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()
|
||||
if (requestVersion === sessionVersion && token.value === requestToken && sessionStorage.getItem(TOKEN_KEY) === requestToken) logout()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -148,16 +174,17 @@ export const useUserStore = defineStore('user', () => {
|
||||
* migration when it already has a complete locally-verified user object.
|
||||
*/
|
||||
const ensureDailyAuth = (): boolean => {
|
||||
const storedToken = localStorage.getItem(TOKEN_KEY) || ''
|
||||
const storedToken = sessionStorage.getItem(TOKEN_KEY) || ''
|
||||
const storedDay = localStorage.getItem(AUTH_DAY_KEY)
|
||||
const storedUser = readStoredUser()
|
||||
|
||||
if (!storedToken) {
|
||||
const hadState = Boolean(token.value || userInfo.value || storedUser || storedDay)
|
||||
const hadState = Boolean(token.value || userInfo.value || storedUser || storedDay || permissionsLoaded.value || permissionRequest)
|
||||
token.value = ''
|
||||
userInfo.value = null
|
||||
if (hadState) {
|
||||
sessionVersion += 1
|
||||
clearPermissions()
|
||||
clearStoredSession()
|
||||
}
|
||||
return false
|
||||
@@ -167,6 +194,10 @@ export const useUserStore = defineStore('user', () => {
|
||||
// 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)) {
|
||||
if (token.value !== storedToken) {
|
||||
sessionVersion += 1
|
||||
clearPermissions()
|
||||
}
|
||||
token.value = storedToken
|
||||
userInfo.value = storedUser
|
||||
saveAuthDay()
|
||||
@@ -175,12 +206,17 @@ export const useUserStore = defineStore('user', () => {
|
||||
|
||||
if (storedDay !== getBusinessDay()) {
|
||||
sessionVersion += 1
|
||||
clearPermissions()
|
||||
clearStoredSession()
|
||||
token.value = ''
|
||||
userInfo.value = null
|
||||
return false
|
||||
}
|
||||
|
||||
if (token.value !== storedToken) {
|
||||
sessionVersion += 1
|
||||
clearPermissions()
|
||||
}
|
||||
token.value = storedToken
|
||||
userInfo.value = storedUser
|
||||
return true
|
||||
@@ -188,43 +224,72 @@ export const useUserStore = defineStore('user', () => {
|
||||
|
||||
const logout = () => {
|
||||
sessionVersion += 1
|
||||
clearPermissions()
|
||||
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 = ''
|
||||
const requestGeneration = ++permissionGeneration
|
||||
const requestSessionVersion = sessionVersion
|
||||
const requestToken = token.value
|
||||
clearPermissions(false)
|
||||
let currentRequest!: Promise<void>
|
||||
const isCurrentRequest = () => requestGeneration === permissionGeneration
|
||||
&& requestSessionVersion === sessionVersion
|
||||
&& requestToken === token.value
|
||||
currentRequest = (async () => {
|
||||
try {
|
||||
const result = await request.get<{
|
||||
roleCodes?: string[]
|
||||
permissionCodes?: string[]
|
||||
fieldPermissions?: Record<string, 'HIDDEN' | 'READ' | 'EDIT'>
|
||||
fieldPermissions?: Record<string, PermissionAccess>
|
||||
permissionAccess?: Record<string, PermissionAccess>
|
||||
}>('/roles/current-permissions')
|
||||
permissionCodes.value = Array.isArray(result?.permissionCodes) ? result.permissionCodes : []
|
||||
fieldPermissions.value = result?.fieldPermissions || {}
|
||||
if (!isCurrentRequest()) return
|
||||
const nextPermissionCodes = Array.isArray(result?.permissionCodes) ? result.permissionCodes : []
|
||||
const nextRoleCodes = Array.isArray(result?.roleCodes) ? result.roleCodes : []
|
||||
const validLevel = (value: unknown): value is PermissionAccess => value === 'HIDDEN' || value === 'READ' || value === 'EDIT'
|
||||
const nextFieldPermissions = Object.fromEntries(Object.entries(result?.fieldPermissions || {}).filter((entry): entry is [string, PermissionAccess] => validLevel(entry[1])))
|
||||
const suppliedAccess = Object.fromEntries(Object.entries(result?.permissionAccess || {}).filter((entry): entry is [string, PermissionAccess] => validLevel(entry[1])))
|
||||
// Old responses carry only granted codes and field levels. Project them
|
||||
// into the new access model without granting anything that was absent.
|
||||
const hasAccessContract = Boolean(result && Object.prototype.hasOwnProperty.call(result, 'permissionAccess'))
|
||||
const nextPermissionAccess = hasAccessContract
|
||||
? suppliedAccess
|
||||
: {
|
||||
...Object.fromEntries(nextPermissionCodes.map(code => [code, 'EDIT' as PermissionAccess])),
|
||||
...nextFieldPermissions,
|
||||
}
|
||||
if (!isCurrentRequest()) return
|
||||
permissionCodes.value = nextPermissionCodes
|
||||
roleCodes.value = nextRoleCodes
|
||||
fieldPermissions.value = nextFieldPermissions
|
||||
permissionAccess.value = nextPermissionAccess
|
||||
permissionsLoaded.value = true
|
||||
} catch (error) {
|
||||
permissionCodes.value = []
|
||||
fieldPermissions.value = {}
|
||||
permissionsLoaded.value = false
|
||||
if (!isCurrentRequest()) return
|
||||
clearPermissions(false)
|
||||
permissionsError.value = error instanceof Error ? error.message : '权限加载失败'
|
||||
throw error
|
||||
} finally {
|
||||
permissionRequest = null
|
||||
if (isCurrentRequest() && permissionRequest === currentRequest) permissionRequest = null
|
||||
}
|
||||
})()
|
||||
return permissionRequest
|
||||
permissionRequest = currentRequest
|
||||
return currentRequest
|
||||
}
|
||||
|
||||
const hasPermission = (code: string) => permissionsLoaded.value && !permissionsError.value && permissionCodes.value.includes(code)
|
||||
const access = (code: string): PermissionAccess => permissionsLoaded.value && !permissionsError.value
|
||||
? (permissionAccess.value[code] || 'HIDDEN')
|
||||
: 'HIDDEN'
|
||||
const canRead = (code: string) => access(code) === 'READ' || access(code) === 'EDIT'
|
||||
const canEdit = (code: string) => access(code) === 'EDIT'
|
||||
const canAny = (codes: string[]) => codes.some(canRead)
|
||||
const hasPermission = canRead
|
||||
|
||||
return {
|
||||
token,
|
||||
@@ -241,11 +306,17 @@ export const useUserStore = defineStore('user', () => {
|
||||
fetchUserInfo,
|
||||
ensureDailyAuth,
|
||||
permissionCodes,
|
||||
roleCodes,
|
||||
fieldPermissions,
|
||||
permissionAccess,
|
||||
permissionsLoaded,
|
||||
permissionsError,
|
||||
loadPermissions,
|
||||
hasPermission,
|
||||
access,
|
||||
canRead,
|
||||
canEdit,
|
||||
canAny,
|
||||
logout,
|
||||
}
|
||||
})
|
||||
+26
-7
@@ -1,6 +1,6 @@
|
||||
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 { accountsPayableApi, cashierApi, reimbursementApi, type ApprovalRoutePreview, 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'
|
||||
@@ -93,7 +93,7 @@ export const useWorkbenchStore = defineStore('workbench', () => {
|
||||
}
|
||||
}
|
||||
const loadList = async () => { if (reimbursements.value.length) return; await load() }
|
||||
const loadDetail = async (id: string | number) => {
|
||||
const loadDetail = async (id: string | number, options?: { strict?: boolean }) => {
|
||||
const requestVersion = sessionVersion
|
||||
await loadList()
|
||||
if (requestVersion !== sessionVersion) return null
|
||||
@@ -102,12 +102,15 @@ export const useWorkbenchStore = defineStore('workbench', () => {
|
||||
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)
|
||||
reimbursements.value = reimbursements.value.some(item => String(item.id) === String(id))
|
||||
? reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item)
|
||||
: [...reimbursements.value, normalized]
|
||||
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 {
|
||||
} catch (error) {
|
||||
if (options?.strict) throw error
|
||||
return getById(id)
|
||||
}
|
||||
}
|
||||
@@ -149,10 +152,26 @@ export const useWorkbenchStore = defineStore('workbench', () => {
|
||||
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 previewRoute = async (id: string | number): Promise<ApprovalRoutePreview> => {
|
||||
if (source.value !== 'fallback') return reimbursementApi.getRoutePreview(id)
|
||||
const item = getById(id)
|
||||
if (!item) throw new Error('报销单不存在')
|
||||
return {
|
||||
applicationId: id,
|
||||
source: 'LOCAL',
|
||||
nodes: [{ order: 1, nodeKey: 'department-manager', nodeName: '部门负责人审批', approverLabels: ['部门负责人'], dynamic: false }],
|
||||
routeFingerprint: `local-${id}`,
|
||||
previewToken: `local-preview-${id}-${Date.now()}`,
|
||||
expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),
|
||||
staleSnapshot: false,
|
||||
exact: false,
|
||||
warning: '当前为本地开发数据,预计审批路径仅用于界面演示。',
|
||||
}
|
||||
}
|
||||
const submit = async (id: string | number, previewToken: string) => { const requestVersion = sessionVersion; if (!previewToken) throw new Error('审批路线预览已失效,请重新预览'); 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, { previewToken }), 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 }
|
||||
const loginFallback = (employeeNo?: string) => { reset(); const result = fallbackLogin(employeeNo); user.value = result.user; sessionStorage.setItem('token', result.token); localStorage.removeItem('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, previewRoute, submit, receive, pay, loginFallback, reset, refreshPaymentStatuses }
|
||||
})
|
||||
@@ -33,9 +33,12 @@ export const saveAuthDay = (day = getBusinessDay()) => {
|
||||
}
|
||||
|
||||
export const clearStoredSession = () => {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
sessionStorage.removeItem(TOKEN_KEY)
|
||||
localStorage.removeItem(TOKEN_KEY) // purge credentials persisted by older builds
|
||||
localStorage.removeItem(USER_INFO_KEY)
|
||||
localStorage.removeItem(AUTH_DAY_KEY)
|
||||
// Also clear credentials from any sessionStorage-based intermediate builds.
|
||||
sessionStorage.removeItem(USER_INFO_KEY)
|
||||
}
|
||||
|
||||
const millisecondsUntilNextBusinessDay = () => {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Money amount rules aligned with DECIMAL(18,2) and normal reimbursement UX. */
|
||||
export const MONEY_MAX = 99_999_999.99
|
||||
export const MONEY_MIN = 0.01
|
||||
const MONEY_PATTERN = /^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/
|
||||
|
||||
export type MoneyAmountIssue =
|
||||
| 'empty'
|
||||
| 'invalid'
|
||||
| 'non_positive'
|
||||
| 'too_many_decimals'
|
||||
| 'too_large'
|
||||
|
||||
const MESSAGES: Record<MoneyAmountIssue, string> = {
|
||||
empty: '请填写金额',
|
||||
invalid: '金额须为有效数字,例如 128.50',
|
||||
non_positive: '金额须大于 0',
|
||||
too_many_decimals: '金额最多保留两位小数',
|
||||
too_large: `单笔金额不能超过 ${MONEY_MAX.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} 元`,
|
||||
}
|
||||
|
||||
export const moneyAmountMessage = (issue: MoneyAmountIssue, label = '金额') => {
|
||||
if (issue === 'empty') return `请填写${label}`
|
||||
if (issue === 'invalid') return `${label}须为有效数字,例如 128.50`
|
||||
if (issue === 'non_positive') return `${label}须大于 0`
|
||||
if (issue === 'too_many_decimals') return `${label}最多保留两位小数`
|
||||
if (issue === 'too_large') {
|
||||
return `${label}不能超过 ${MONEY_MAX.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })} 元`
|
||||
}
|
||||
return MESSAGES[issue]
|
||||
}
|
||||
|
||||
/** Inspect a typed amount (input string or numeric model). */
|
||||
export const inspectMoneyAmount = (value: unknown): MoneyAmountIssue | null => {
|
||||
if (value == null || value === '') return 'empty'
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isFinite(value)) return 'invalid'
|
||||
if (value <= 0) return 'non_positive'
|
||||
if (Math.round(value * 100) / 100 !== value) return 'too_many_decimals'
|
||||
if (value > MONEY_MAX) return 'too_large'
|
||||
return null
|
||||
}
|
||||
const text = String(value).trim()
|
||||
if (!text) return 'empty'
|
||||
if (/[eE]/.test(text) || !/^-?\d/.test(text)) return 'invalid'
|
||||
if (text.startsWith('-')) return 'non_positive'
|
||||
if (!/^\d+(\.\d+)?$/.test(text)) return 'invalid'
|
||||
if (text.includes('.') && text.split('.')[1].length > 2) return 'too_many_decimals'
|
||||
if (!MONEY_PATTERN.test(text)) return 'invalid'
|
||||
const amount = Number(text)
|
||||
if (!Number.isFinite(amount)) return 'invalid'
|
||||
if (amount <= 0) return 'non_positive'
|
||||
if (amount > MONEY_MAX) return 'too_large'
|
||||
return null
|
||||
}
|
||||
|
||||
export const normalizeMoneyAmount = (value: unknown): number => {
|
||||
const issue = inspectMoneyAmount(value)
|
||||
if (issue) return 0
|
||||
const amount = typeof value === 'number' ? value : Number(String(value).trim())
|
||||
return Math.round(amount * 100) / 100
|
||||
}
|
||||
+154
-12
@@ -1,27 +1,169 @@
|
||||
<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 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 && userStore.canEdit('reimbursement.application.edit') && userStore.canRead('page.application-edit')" class="btn primary" :to="editRoute">{{ item?.approvalStatus === '退回' ? '补充信息' : '编辑草稿' }}</router-link></div></div>
|
||||
<div v-if="detailLoading" class="load-wrap" role="status"><span class="loader"></span><p>正在读取报销详情…</p></div>
|
||||
<div v-else-if="detailError" class="card empty-state" role="alert"><strong>报销详情加载失败</strong><span>{{ detailError }}</span><button class="btn" type="button" @click="loadDetail">重新加载</button><router-link class="btn" to="/applications">返回我的报销</router-link></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 v-if="item.approvalStatus === '退回'" class="inline-alert danger" role="alert"><b>!</b><span><strong>审批退回,需补充信息</strong><br>{{ item.returnReason || '请查看审批意见' }}</span><router-link v-if="userStore.canEdit('reimbursement.application.edit') && userStore.canRead('page.application-edit')" 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 v-if="hasFeishuSnapshot" class="section-card" aria-labelledby="feishu-snapshot-title">
|
||||
<div class="section-title"><div><span class="eyebrow">HISTORICAL SNAPSHOT</span><h2 id="feishu-snapshot-title">飞书审批表单</h2></div><span>提交版本 {{ item.formSnapshot?.fingerprint?.slice(0, 8) || '未知' }} · 历史快照</span></div>
|
||||
<dl class="snapshot-fields">
|
||||
<template v-for="field in item.formSnapshot?.fields || []" :key="field.id">
|
||||
<div v-if="field.type !== 'EXPENSE_ITEMS' && field.binding !== 'EXPENSE_ITEMS'" class="snapshot-field" :class="{ full: field.type === 'TEXTAREA' || field.type === 'DISPLAY' }">
|
||||
<dt>{{ field.label }}</dt><dd :class="{ 'preserve-lines': field.type === 'TEXTAREA' || field.type === 'DISPLAY' }">{{ snapshotDisplay(field) }}</dd>
|
||||
</div>
|
||||
<div v-else class="snapshot-field full expense-snapshot">
|
||||
<dt>{{ field.label }}</dt>
|
||||
<dd><div v-if="hasUnknownExpenseChild(field)" class="snapshot-warning" role="note">该历史明细包含当前版本无法识别的列,仅展示有明确绑定的列。</div><div v-if="expenseRows(field).length && detailColumns(field).length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th v-for="column in detailColumns(field)" :key="column.valueKey" :class="{ amount: column.binding === 'EXPENSE_AMOUNT' }">{{ column.label }}</th></tr></thead><tbody><tr v-for="(expense, rowIndex) in expenseRows(field)" :key="rowIndex"><td v-for="column in detailColumns(field)" :key="column.valueKey" :data-label="column.label" :class="{ amount: column.binding === 'EXPENSE_AMOUNT' }">{{ expenseCell(expense, column, rowIndex) }}</td></tr></tbody></table></div><span v-else>—</span></dd>
|
||||
</div>
|
||||
</template>
|
||||
</dl>
|
||||
</section>
|
||||
|
||||
<section v-if="!hasFeishuSnapshot" 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 v-else class="section-card finance-facts"><div class="section-title"><h2>财务与付款信息</h2><span>系统记录</span></div><div class="source-grid"><div><span>收款人</span><strong>{{ item.payeeName || '—' }}</strong></div><div><span>收款账户</span><strong>{{ item.bankAccountMask || '已脱敏' }}</strong></div><div><span>开户银行</span><strong>{{ item.bankName || '—' }}</strong></div><div><span>申请日期</span><strong>{{ item.createdAt?.slice(0, 10) || '—' }}</strong></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 v-if="!snapshotHasExpenses" 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>附件</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="附件">{{ expenseAttachmentNames(expense) }}</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></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">FILE</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))})
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import type { ExpenseItem, ReimbursementFormAttachment, ReimbursementFormField } from '@/api/reimbursement'
|
||||
import { useUserStore } from '@/store/user'
|
||||
import { useWorkbenchStore } from '@/store/workbench'
|
||||
|
||||
type ExpenseKey = 'expenseDate' | 'category' | 'description' | 'amount'
|
||||
type SnapshotRow = Record<string, unknown>
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const store = useWorkbenchStore()
|
||||
const userStore = useUserStore()
|
||||
const detailLoading = ref(true)
|
||||
const detailError = ref('')
|
||||
const detailReady = ref(false)
|
||||
const item = computed(() => detailReady.value ? store.getById(String(route.params.id)) : null)
|
||||
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 hasFeishuSnapshot = computed(() => item.value?.formSnapshot?.mode === 'FEISHU')
|
||||
const snapshotHasExpenses = computed(() => hasFeishuSnapshot.value && item.value?.formSnapshot?.fields.some(field => field.binding === 'EXPENSE_ITEMS' || field.type === 'EXPENSE_ITEMS'))
|
||||
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'
|
||||
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 || '待办理' }] })
|
||||
|
||||
const boundValue = (field: ReimbursementFormField): unknown => {
|
||||
const current = item.value
|
||||
if (!current) return undefined
|
||||
const snapshotValues = current.formSnapshot?.values
|
||||
if (snapshotValues && Object.prototype.hasOwnProperty.call(snapshotValues, field.valueKey)) return snapshotValues[field.valueKey]
|
||||
const values: Record<string, unknown> = { APPLICATION_NO: current.applicationNo, TITLE: current.title, APPLICANT_NAME: current.applicantName, APPLICANT_CONTACT: current.applicantName, APPLICANT_DEPARTMENT: current.departmentName, DEPARTMENT: current.departmentName, EXPENSE_TYPE: current.expenseTypeName || current.category, TOTAL_AMOUNT: current.totalAmount, DESCRIPTION: current.description, SOURCE_DOC_NO: current.sourceDocNo }
|
||||
return values[field.binding]
|
||||
}
|
||||
const contactDisplayLabel = (value: unknown) => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return '—'
|
||||
const contact = value as { display_label?: unknown; label?: unknown }
|
||||
const label = contact.display_label ?? contact.label
|
||||
return typeof label === 'string' && label.trim() ? label.trim() : '—'
|
||||
}
|
||||
const departmentDisplayLabel = (value: unknown) => {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return '—'
|
||||
const label = (value as { display_label?: unknown }).display_label
|
||||
return typeof label === 'string' && label.trim() ? label.trim() : '—'
|
||||
}
|
||||
const snapshotDisplay = (field: ReimbursementFormField) => {
|
||||
const value = boundValue(field)
|
||||
if (value == null || value === '') return field.type === 'DISPLAY' ? field.label : '—'
|
||||
if (field.type === 'CONTACT') {
|
||||
const snapshotValues = item.value?.formSnapshot?.values
|
||||
const hasSnapshotValue = Boolean(snapshotValues && Object.prototype.hasOwnProperty.call(snapshotValues, field.valueKey))
|
||||
return hasSnapshotValue ? contactDisplayLabel(value) : (field.binding === 'APPLICANT_CONTACT' ? item.value?.applicantName || '—' : '—')
|
||||
}
|
||||
if (field.type === 'DEPARTMENT') return departmentDisplayLabel(value)
|
||||
if (field.binding === 'TOTAL_AMOUNT' || field.type === 'DECIMAL') return money(Number(value))
|
||||
if (Array.isArray(value)) return value.map(entry => field.options.find(option => option.value === String(entry))?.label || String(entry)).join('、') || '—'
|
||||
if (field.type === 'SINGLE_SELECT') return field.options.find(option => option.value === String(value))?.label || String(value)
|
||||
if (typeof value === 'object') return departmentDisplayLabel(value)
|
||||
return String(value)
|
||||
}
|
||||
const expenseBindingKeys: Partial<Record<ReimbursementFormField['binding'], ExpenseKey>> = { EXPENSE_DATE: 'expenseDate', EXPENSE_CATEGORY: 'category', EXPENSE_DESCRIPTION: 'description', EXPENSE_AMOUNT: 'amount' }
|
||||
const isExpenseDetailColumn = (child: ReimbursementFormField) => Boolean(expenseBindingKeys[child.binding]) || (child.binding === 'EXPENSE_ATTACHMENT' && child.type === 'ATTACHMENT')
|
||||
const detailColumns = (field: ReimbursementFormField) => field.children.filter(child => child.type !== 'DISPLAY' && isExpenseDetailColumn(child))
|
||||
const hasUnknownExpenseChild = (field: ReimbursementFormField) => field.children.some(child => child.type !== 'DISPLAY' && !isExpenseDetailColumn(child))
|
||||
const expenseRows = (field: ReimbursementFormField): SnapshotRow[] => {
|
||||
const saved = item.value?.formSnapshot?.values?.[field.valueKey]
|
||||
const columns = detailColumns(field)
|
||||
if (Array.isArray(saved) && saved.every(row => row && typeof row === 'object' && !Array.isArray(row) && columns.every(child => Object.prototype.hasOwnProperty.call(row, child.valueKey)))) return saved as SnapshotRow[]
|
||||
return (item.value?.expenseItems || []).map(expense => Object.fromEntries(detailColumns(field).map(child => {
|
||||
const key = expenseBindingKeys[child.binding]
|
||||
return [child.valueKey, key ? expense[key] : child.binding === 'EXPENSE_ATTACHMENT' ? expense.attachments || expense.attachmentMetadata || expense.attachmentIds : undefined]
|
||||
})))
|
||||
}
|
||||
const safeAttachmentMetadata = (expense?: Partial<ExpenseItem>): ReimbursementFormAttachment[] => {
|
||||
const files = [...(expense?.attachments || []), ...(expense?.attachmentMetadata || [])]
|
||||
const unique = new Map<string, ReimbursementFormAttachment>()
|
||||
files.forEach(file => { if (file?.id != null && file.fileName) unique.set(String(file.id), file) })
|
||||
return [...unique.values()]
|
||||
}
|
||||
const expenseAttachmentNames = (expense?: Partial<ExpenseItem>) => safeAttachmentMetadata(expense).map(file => file.fileName).join('、') || '—'
|
||||
const snapshotAttachmentNames = (value: unknown, rowIndex: number) => {
|
||||
const values = Array.isArray(value) ? value : value == null ? [] : [value]
|
||||
const directNames = values.map(entry => typeof entry === 'object' && entry && 'fileName' in entry ? String((entry as { fileName: unknown }).fileName || '') : '').filter(Boolean)
|
||||
if (directNames.length) return directNames.join('、')
|
||||
const detailExpense = item.value?.expenseItems[rowIndex]
|
||||
const metadata = safeAttachmentMetadata(detailExpense)
|
||||
if (!values.length) return metadata.map(file => file.fileName).join('、') || '—'
|
||||
const ids = new Set(values.map(value => String(typeof value === 'object' && value && 'id' in value ? (value as { id: unknown }).id : value)))
|
||||
return metadata.filter(file => ids.has(String(file.id))).map(file => file.fileName).join('、') || '—'
|
||||
}
|
||||
const expenseCell = (expense: SnapshotRow, child: ReimbursementFormField, rowIndex: number) => {
|
||||
const value = expense[child.valueKey]
|
||||
if (child.binding === 'EXPENSE_ATTACHMENT') return snapshotAttachmentNames(value, rowIndex)
|
||||
if (value == null || value === '') return '—'
|
||||
if (child.binding === 'EXPENSE_AMOUNT') return money(Number(value))
|
||||
if (child.type === 'SINGLE_SELECT') return child.options.find(option => option.value === String(value))?.label || String(value)
|
||||
return String(value)
|
||||
}
|
||||
const loadDetail = async () => {
|
||||
detailLoading.value = true
|
||||
detailError.value = ''
|
||||
detailReady.value = false
|
||||
try {
|
||||
const detail = await store.loadDetail(String(route.params.id), { strict: true })
|
||||
if (store.source === 'api' && !detail?.formSnapshot) throw new Error('服务端详情缺少表单快照,已停止使用列表摘要替代历史详情。')
|
||||
if (!detail) throw new Error('未找到该报销单或当前无权查看。')
|
||||
detailReady.value = true
|
||||
} catch (error) {
|
||||
detailError.value = error instanceof Error && error.message ? error.message : '无法读取权威报销详情,请稍后重试。'
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
onMounted(loadDetail)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.snapshot-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1px; margin: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 6px; background: var(--line); }
|
||||
.snapshot-field { min-width: 0; padding: 12px 14px; background: #fff; }
|
||||
.snapshot-field.full { grid-column: 1 / -1; }
|
||||
.snapshot-field dt { margin-bottom: 5px; color: var(--quiet); font-size: 11px; font-weight: 700; }
|
||||
.snapshot-field dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.snapshot-field .preserve-lines { white-space: pre-wrap; }
|
||||
.expense-snapshot dd { margin-top: 9px; }
|
||||
.snapshot-warning { margin-bottom: 9px; padding: 8px 10px; border: 1px solid #f1cf8d; border-radius: 6px; background: #fff9e9; color: #805a16; font-size: 11px; }
|
||||
.finance-facts .source-grid { margin-top: 0; }
|
||||
@media (max-width: 680px) { .snapshot-fields { grid-template-columns: 1fr; } .snapshot-field.full { grid-column: 1; } }
|
||||
</style>
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="page-content">
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">MY EXPENSES</span>
|
||||
@@ -8,7 +8,7 @@
|
||||
</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>
|
||||
<router-link v-if="canCreate" class="btn primary" to="/applications/new">+ 发起报销</router-link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
<button class="btn small" type="button" @click="reload">重试</button>
|
||||
</div>
|
||||
|
||||
<div class="card fill-list-card">
|
||||
<div class="card fill-list-card primary-list-card">
|
||||
<div class="tabs" role="tablist" aria-label="报销列表筛选">
|
||||
<button
|
||||
v-for="tab in tabs"
|
||||
@@ -91,7 +91,7 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in filtered" :key="item.id">
|
||||
<tr v-for="item in paginatedItems" :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>
|
||||
@@ -114,18 +114,19 @@
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</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>
|
||||
<router-link v-if="canCreate" 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>
|
||||
<AppListPagination v-if="filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="报销申请列表分页" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -133,9 +134,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
import { useUserStore } from '@/store/user'
|
||||
import { useWorkbenchStore } from '@/store/workbench'
|
||||
|
||||
@@ -151,6 +154,7 @@ const applicationFilter = ref('')
|
||||
const approvalFilter = ref('')
|
||||
const hasLoaded = ref(Boolean(store.reimbursements.length))
|
||||
const applicationsPanelId = 'applications-list-panel'
|
||||
const canCreate = computed(() => userStore.canEdit('reimbursement.application.create') && userStore.canRead('page.application-create'))
|
||||
|
||||
const tabs: ApplicationTab[] = [
|
||||
{ key: 'all', label: '全部' },
|
||||
@@ -187,6 +191,13 @@ const filtered = computed(() => {
|
||||
matchesTab(item, currentTab.value)
|
||||
))
|
||||
})
|
||||
const { page, pageSize, paginatedItems } = useListPagination(filtered, {
|
||||
resetSources: [query, currentTab, applicationFilter, approvalFilter],
|
||||
})
|
||||
watch(() => route.query.q, value => {
|
||||
const nextQuery = String(value || '')
|
||||
if (query.value !== nextQuery) query.value = nextQuery
|
||||
}, { flush: 'sync' })
|
||||
|
||||
const loadingState = computed(() => store.loading || !hasLoaded.value)
|
||||
const hasBlockingError = computed(() => hasLoaded.value && store.source === 'error')
|
||||
@@ -206,7 +217,7 @@ const clearFilters = () => {
|
||||
currentTab.value = 'all'
|
||||
}
|
||||
|
||||
const editable = (item: ReimApplicationDetail) => isMine(item) && (item.applicationStatus === '草稿' || item.approvalStatus === '退回')
|
||||
const editable = (item: ReimApplicationDetail) => userStore.canEdit('reimbursement.application.edit') && userStore.canRead('page.application-edit') && 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',
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
</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>
|
||||
<router-link v-if="userStore.canRead('page.finance-receipt')" class="btn" to="/finance-receipt">查看待收单</router-link>
|
||||
<router-link v-if="userStore.canRead('page.payments')" 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>
|
||||
<router-link v-if="userStore.canEdit('reimbursement.application.create') && userStore.canRead('page.application-create')" class="btn primary" to="/applications/new"><Plus /> 发起报销</router-link>
|
||||
<router-link v-if="userStore.canRead('page.applications')" class="btn" to="/applications">查看我的报销</router-link>
|
||||
</template>
|
||||
<button class="btn" type="button" :disabled="store.loading || financeQueueLoading" @click="refresh">
|
||||
<Refresh /> 刷新数据
|
||||
@@ -233,8 +233,7 @@ 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 isFinance = computed(() => userStore.canAny(['page.finance-receipt', 'page.source-documents', 'page.payments', 'page.operation-log']))
|
||||
const mine = computed(() => isFinance.value
|
||||
? store.reimbursements
|
||||
: store.reimbursements.filter(item => item.applicantName === userName.value))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="page-content">
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">EXPENSE TYPES</span>
|
||||
@@ -7,27 +7,34 @@
|
||||
<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">
|
||||
<div class="card fill-list-card primary-list-card">
|
||||
<div class="table-wrap" v-if="loaded && !error && items.length > 0" tabindex="0" role="region" aria-label="费用类型列表"><table class="data-table responsive-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 v-for="item in paginatedItems" :key="item.id">
|
||||
<td data-label="编码"><small>{{ item.code }}</small></td>
|
||||
<td data-label="名称"><strong>{{ item.name }}</strong></td>
|
||||
<td data-label="分类"><span class="tag">{{ item.category }}</span></td>
|
||||
<td data-label="状态"><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<div v-else-if="error" class="empty-state" role="alert"><strong>费用类型加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></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>
|
||||
<AppListPagination v-if="loaded && !error && items.length" v-model:page="page" v-model:page-size="pageSize" :total="items.length" aria-label="费用类型列表分页" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import request from '@/api/request'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
const items = ref<any[]>([])
|
||||
const loaded = ref(false)
|
||||
onMounted(async () => { try { items.value = await request.get('/metadata/expense-types') || [] } catch {} finally { loaded.value = true } })
|
||||
const error = ref('')
|
||||
const { page, pageSize, paginatedItems } = useListPagination(items)
|
||||
const load = async () => { loaded.value = false; error.value = ''; try { items.value = await request.get('/metadata/expense-types') || [] } catch (e) { error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。' } finally { loaded.value = true } }
|
||||
onMounted(load)
|
||||
</script>
|
||||
+144
-109
@@ -1,8 +1,8 @@
|
||||
<template>
|
||||
<div class="directory-page page-content">
|
||||
<div class="directory-page" :class="{ 'page-content route-list-page': !embedded, 'directory-embedded': embedded }">
|
||||
<FeishuDirectoryPanel @committed="refreshOrganization" />
|
||||
|
||||
<section class="card organization-card" aria-labelledby="organization-title">
|
||||
<section class="card organization-card primary-list-card" aria-labelledby="organization-title">
|
||||
<div class="card-head organization-head">
|
||||
<div>
|
||||
<span class="eyebrow">ORGANIZATION</span>
|
||||
@@ -10,7 +10,7 @@
|
||||
<p>选择部门查看该部门及下级部门的飞书员工资料。</p>
|
||||
</div>
|
||||
<div class="organization-actions">
|
||||
<span v-if="organization" class="muted-copy">快照状态:{{ snapshotLabels[organization.snapshotState] }}</span>
|
||||
<span v-if="organization" class="muted-copy">当前目录:{{ availabilityLabels[organization.availabilityState] }}</span>
|
||||
<button class="btn small" type="button" :disabled="organizationLoading || !canRead" @click="refreshOrganization">{{ organizationLoading ? '加载中…' : '刷新组织架构' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -28,17 +28,19 @@
|
||||
<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 v-else-if="!hasAvailableDirectory" class="empty-state organization-state">
|
||||
<strong>{{ organization?.availabilityState === 'UNAVAILABLE' ? '当前目录不可用' : '暂无组织架构' }}</strong>
|
||||
<span>{{ organization?.availabilityState === '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>
|
||||
<span>最近成功更新(本地时间):{{ formatLocalDateTime(organization?.lastSuccessfulAt, '暂无') }}</span>
|
||||
<span>当前版本:{{ organization?.currentRevision || '暂无' }}</span>
|
||||
<span>{{ departments.length }} 个部门 · {{ totalMemberCount }} 名员工</span>
|
||||
</div>
|
||||
<p v-if="organization?.snapshotState === 'STALE' || organization?.snapshotState === 'CONTEXT_CHANGED'" class="inline-note" role="status">当前展示的是过期或上下文已变化的快照,请同步后再作为最新目录使用。</p>
|
||||
<p v-if="organization?.contextState === 'CHANGED'" class="inline-note" role="status">应用配置上下文已变化,仅作为诊断提示;当前目录仍可继续使用,可同步以更新资料。</p>
|
||||
<p v-else-if="organization?.snapshotState === 'STALE'" class="inline-note" role="status">服务返回旧版 STALE 状态;当前目录已确认可用,仍可继续使用。</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 }">
|
||||
@@ -56,9 +58,18 @@
|
||||
<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>
|
||||
<span>{{ membersLoading ? '加载中…' : `${selectedUsers.length} 人` }}</span>
|
||||
</div>
|
||||
<div v-if="!selectedUsers.length" class="empty-state compact-empty">
|
||||
<div v-if="membersLoading" class="load-wrap compact-empty" role="status" aria-live="polite">
|
||||
<span class="loader" aria-hidden="true"></span>
|
||||
<span>正在加载部门员工…</span>
|
||||
</div>
|
||||
<div v-else-if="membersError" class="empty-state compact-empty" role="alert">
|
||||
<strong>员工加载失败</strong>
|
||||
<span>{{ membersError }}</span>
|
||||
<button class="btn small" type="button" @click="refreshMembers">重试</button>
|
||||
</div>
|
||||
<div v-else-if="!selectedUsers.length" class="empty-state compact-empty">
|
||||
<strong>该部门暂无员工</strong>
|
||||
<span>请选择其他部门查看员工。</span>
|
||||
</div>
|
||||
@@ -71,27 +82,14 @@
|
||||
<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><dt>职位</dt><dd>{{ user.jobTitle }}</dd></div>
|
||||
<div><dt>邮箱</dt><dd>{{ user.email }}</dd></div>
|
||||
<div><dt>手机</dt><dd>{{ user.mobile }}</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>
|
||||
<AppListPagination v-if="!membersLoading && !membersError && selectedUsers.length" v-model:page="selectedPage" v-model:page-size="pageSize" :total="selectedUsers.length" aria-label="部门员工列表分页" />
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
@@ -101,32 +99,39 @@
|
||||
<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 AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
import { directoryAvailability, feishuDirectoryApi, type DirectoryAvailabilityState, type DirectoryContextState, type DirectoryDepartment, type DirectoryOrganization, type DirectoryOrganizationUser, type DirectorySnapshotState } from '@/api/feishuDirectory'
|
||||
import { useUserStore } from '@/store/user'
|
||||
|
||||
withDefaults(defineProps<{ embedded?: boolean }>(), { embedded: false })
|
||||
|
||||
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[] }
|
||||
type SafeOrganizationUser = Pick<DirectoryOrganizationUser, 'userId' | 'openId' | 'name' | 'email' | 'mobile' | 'jobTitle' | 'avatarUrl' | 'departmentIds'> & { internalKey: string }
|
||||
type SafeOrganization = Omit<DirectoryOrganization, 'users' | 'availabilityState' | 'contextState' | 'currentRevision'> & {
|
||||
users: SafeOrganizationUser[]
|
||||
availabilityState: DirectoryAvailabilityState
|
||||
contextState: DirectoryContextState
|
||||
currentRevision: string | null
|
||||
}
|
||||
|
||||
const userStore = useUserStore()
|
||||
const canRead = computed(() => (
|
||||
userStore.permissionsLoaded
|
||||
&& !userStore.permissionsError
|
||||
&& (userStore.hasPermission('system:feishu:sync') || userStore.hasPermission('system:feishu:bind'))
|
||||
))
|
||||
const canRead = computed(() => userStore.canRead('page.feishu-directory'))
|
||||
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 memberUsers = ref<SafeOrganizationUser[]>([])
|
||||
const membersLoading = ref(false)
|
||||
const membersError = ref('')
|
||||
const availabilityLabels: Record<DirectoryAvailabilityState, string> = { AVAILABLE: '可用', NEVER_SYNCED: '尚未同步', UNAVAILABLE: '不可用' }
|
||||
const disposed = ref(false)
|
||||
let organizationController: AbortController | null = null
|
||||
let organizationRequest = 0
|
||||
let membersController: AbortController | null = null
|
||||
let membersRequest = 0
|
||||
|
||||
const formatLocalDateTime = (value: unknown, fallback = '—') => {
|
||||
const date = value instanceof Date
|
||||
@@ -175,10 +180,6 @@ const compareDepartmentOrder = (left: string, right: string) => {
|
||||
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>()
|
||||
@@ -212,28 +213,43 @@ const normalizeOrganization = (value: unknown): SafeOrganization => {
|
||||
const email = text(candidate.email, '--')
|
||||
const mobile = text(candidate.mobile, '--')
|
||||
users.push({
|
||||
internalKey: userId || openId || `${name}-${email}-${mobile}`,
|
||||
internalKey: openId || userId || `${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']
|
||||
? source.snapshotState as DirectorySnapshotState
|
||||
: 'UNAVAILABLE'
|
||||
return { snapshotState, lastSuccessfulAt: source.lastSuccessfulAt || null, departments, users }
|
||||
const availabilityState = directoryAvailability({ snapshotState, availabilityState: source.availabilityState })
|
||||
const contextState: DirectoryContextState = source.contextState === 'MATCH' || source.contextState === 'CHANGED' || source.contextState === 'UNKNOWN'
|
||||
? source.contextState
|
||||
: snapshotState === 'CONTEXT_CHANGED' ? 'CHANGED' : 'UNKNOWN'
|
||||
return {
|
||||
snapshotState,
|
||||
availabilityState,
|
||||
contextState,
|
||||
currentRevision: text(source.currentRevision) || null,
|
||||
lastSuccessfulAt: source.lastSuccessfulAt || null,
|
||||
departments,
|
||||
users,
|
||||
}
|
||||
}
|
||||
|
||||
const departments = computed(() => organization.value?.departments || [])
|
||||
const users = computed(() => organization.value?.users || [])
|
||||
const totalMemberCount = computed(() => {
|
||||
const ids = new Set(departments.value.map(department => department.id))
|
||||
return departments.value
|
||||
.filter(department => !department.parentId || department.parentId === '0' || !ids.has(department.parentId))
|
||||
.reduce((sum, department) => sum + department.memberCount, 0)
|
||||
})
|
||||
const departmentNodes = computed(() => {
|
||||
const nodes = new Map<string, DepartmentNode>()
|
||||
departments.value.forEach(department => nodes.set(department.id, { ...department, children: [] }))
|
||||
@@ -267,17 +283,6 @@ const departmentIndex = computed(() => {
|
||||
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 => {
|
||||
@@ -288,54 +293,24 @@ const visibleDepartments = computed<VisibleDepartment[]>(() => {
|
||||
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)
|
||||
})
|
||||
departments.value.forEach(department => counts.set(department.id, department.memberCount))
|
||||
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 selectedUsers = computed<SafeOrganizationUser[]>(() => memberUsers.value)
|
||||
const { page: selectedPage, pageSize, totalPages, paginatedItems: paginatedSelectedUsers, clampPage } = useListPagination(selectedUsers, { resetSources: [selectedDepartmentId] })
|
||||
const hasAvailableDirectory = computed(() => organization.value?.availabilityState === 'AVAILABLE')
|
||||
|
||||
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)
|
||||
selectedPage.value = page
|
||||
clampPage()
|
||||
}
|
||||
const handlePageSizeChange = (size: number) => {
|
||||
const nextSize = Number(size)
|
||||
pageSize.value = pageSizes.includes(nextSize) ? nextSize : pageSizes[0]
|
||||
pageSize.value = [10, 20, 50].includes(Number(size)) ? Number(size) : 10
|
||||
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)
|
||||
@@ -374,19 +349,54 @@ const applyOrganization = (value: unknown) => {
|
||||
if (!selectedDepartmentId.value || !knownIds.has(selectedDepartmentId.value)) selectedDepartmentId.value = roots[0]?.id || null
|
||||
}
|
||||
|
||||
const refreshMembers = async () => {
|
||||
if (!canRead.value || disposed.value || !selectedDepartmentId.value || !hasAvailableDirectory.value) {
|
||||
memberUsers.value = []
|
||||
membersError.value = ''
|
||||
membersLoading.value = false
|
||||
return
|
||||
}
|
||||
const departmentId = selectedDepartmentId.value
|
||||
const requestId = ++membersRequest
|
||||
membersController?.abort()
|
||||
const controller = new AbortController()
|
||||
membersController = controller
|
||||
membersLoading.value = true
|
||||
membersError.value = ''
|
||||
selectedPage.value = 1
|
||||
try {
|
||||
const next = await feishuDirectoryApi.organizationMembers(departmentId, controller.signal, true)
|
||||
if (disposed.value || requestId !== membersRequest) return
|
||||
memberUsers.value = normalizeOrganization(next).users
|
||||
} catch (error) {
|
||||
if (disposed.value || requestId !== membersRequest || controller.signal.aborted) return
|
||||
memberUsers.value = []
|
||||
membersError.value = error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
|
||||
} finally {
|
||||
if (requestId === membersRequest) membersLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const refreshOrganization = async () => {
|
||||
if (!canRead.value || disposed.value) return
|
||||
selectedPage.value = 1
|
||||
const requestId = ++organizationRequest
|
||||
organizationController?.abort()
|
||||
membersController?.abort()
|
||||
membersRequest += 1
|
||||
const controller = new AbortController()
|
||||
organizationController = controller
|
||||
organizationLoading.value = true
|
||||
organizationError.value = ''
|
||||
memberUsers.value = []
|
||||
membersError.value = ''
|
||||
try {
|
||||
const next = await feishuDirectoryApi.organization(controller.signal)
|
||||
const next = await feishuDirectoryApi.organization(controller.signal, false)
|
||||
if (disposed.value || requestId !== organizationRequest) return
|
||||
const previousDepartmentId = selectedDepartmentId.value
|
||||
applyOrganization(next)
|
||||
// watch handles department changes; same selection still needs a fresh member fetch.
|
||||
if (selectedDepartmentId.value === previousDepartmentId) void refreshMembers()
|
||||
} catch (error) {
|
||||
if (disposed.value || requestId !== organizationRequest || controller.signal.aborted) return
|
||||
organizationError.value = error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
|
||||
@@ -395,17 +405,41 @@ const refreshOrganization = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
watch(selectedDepartmentId, () => { void refreshMembers() })
|
||||
|
||||
onMounted(() => { void refreshOrganization() })
|
||||
onBeforeUnmount(() => {
|
||||
disposed.value = true
|
||||
organizationRequest += 1
|
||||
membersRequest += 1
|
||||
organizationController?.abort()
|
||||
membersController?.abort()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.directory-page { min-height: 100%; min-width: 0; }
|
||||
.directory-page > .directory-panel { margin-top: 0; }
|
||||
.directory-page { display: flex; min-height: 100%; min-width: 0; flex: 1 1 auto; flex-direction: column; }
|
||||
.directory-page > .directory-panel { margin-top: 0; flex: 0 0 auto; }
|
||||
.directory-embedded {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
flex: 1 1 auto;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.directory-embedded .organization-card {
|
||||
margin-top: 0;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
}
|
||||
.directory-embedded .organization-layout {
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
.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; }
|
||||
@@ -413,8 +447,11 @@ onBeforeUnmount(() => {
|
||||
.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-layout { display: grid; flex: 1 1 auto; height: auto; min-height: 420px; min-width: 0; align-items: stretch; grid-template-columns: minmax(220px, .8fr) minmax(300px, 1.2fr); gap: 18px; padding: 0 22px 22px; }
|
||||
.directory-embedded .organization-layout { min-height: 0; }
|
||||
.organization-tree-wrap, .department-members { display: flex; min-width: 0; min-height: 320px; height: 100%; flex-direction: column; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-raised); overflow: hidden; }
|
||||
.directory-embedded .organization-tree-wrap,
|
||||
.directory-embedded .department-members { min-height: 0; }
|
||||
.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; }
|
||||
@@ -446,15 +483,13 @@ onBeforeUnmount(() => {
|
||||
.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; }
|
||||
.directory-embedded .organization-layout { grid-template-rows: minmax(0, .4fr) minmax(0, .6fr); }
|
||||
.directory-embedded .organization-tree-wrap,
|
||||
.directory-embedded .department-members { min-height: 0; }
|
||||
.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; }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="page-content">
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">FINANCE RECEIPT</span>
|
||||
@@ -36,7 +36,7 @@
|
||||
<div><span>收单金额</span><strong>{{ money(total) }}</strong><small>不等同于已付款</small></div>
|
||||
</div>
|
||||
|
||||
<div class="card fill-list-card">
|
||||
<div class="card fill-list-card primary-list-card">
|
||||
<div class="card-head">
|
||||
<div><h2>收单队列</h2><p>确认收单后,报销单进入付款处理环节。</p></div>
|
||||
<span class="tag info">财务处理</span>
|
||||
@@ -60,7 +60,7 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in filtered" :key="item.id">
|
||||
<tr v-for="item in paginatedItems" :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>
|
||||
@@ -69,14 +69,16 @@
|
||||
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
|
||||
<td data-label="操作">
|
||||
<button
|
||||
v-if="item.receiptStatus === '待收单'"
|
||||
v-if="item.receiptStatus === '待收单' && canConfirm"
|
||||
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>
|
||||
<span v-else-if="item.receiptStatus === '待收单'" class="muted-copy">无确认权限</span>
|
||||
<span v-else-if="item.receiptStatus === '已收单'" class="muted-copy">已完成</span>
|
||||
<span v-else class="muted-copy">无需处理</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -90,6 +92,7 @@
|
||||
<strong>没有符合条件的收单记录</strong>
|
||||
<span>请调整搜索关键词后重试。</span>
|
||||
</div>
|
||||
<AppListPagination v-if="filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="财务收单队列分页" />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
@@ -99,9 +102,14 @@
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
import { useWorkbenchStore } from '@/store/workbench'
|
||||
import { useUserStore } from '@/store/user'
|
||||
|
||||
const store = useWorkbenchStore()
|
||||
const userStore = useUserStore()
|
||||
const canConfirm = computed(() => userStore.canEdit('finance.receipt.confirm'))
|
||||
const query = ref('')
|
||||
const hasLoaded = ref(false)
|
||||
const receiving = ref<Set<string>>(new Set())
|
||||
@@ -113,6 +121,7 @@ const filtered = computed(() => {
|
||||
const normalizedQuery = query.value.trim().toLowerCase()
|
||||
return rows.value.filter(item => `${item.applicationNo} ${item.applicantName} ${item.title}`.toLowerCase().includes(normalizedQuery))
|
||||
})
|
||||
const { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [query] })
|
||||
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)
|
||||
@@ -130,6 +139,7 @@ const refreshQueue = async () => {
|
||||
}
|
||||
|
||||
const receive = async (item: ReimApplicationDetail) => {
|
||||
if (!canConfirm.value) return
|
||||
const key = receivingKey(item.id)
|
||||
if (receiving.value.has(key)) return
|
||||
receiving.value = new Set(receiving.value).add(key)
|
||||
|
||||
+326
-47
@@ -1,70 +1,349 @@
|
||||
<template>
|
||||
<div class="integration-page">
|
||||
<div class="page-head">
|
||||
<div><span class="eyebrow">INTEGRATIONS</span><h1>配置管理</h1><p>管理飞书和金蝶连接。敏感配置只会在输入非空时更新。</p></div>
|
||||
<div>
|
||||
<span class="eyebrow">SYSTEM GOVERNANCE</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 v-if="!canOpenPage" class="card empty-state" role="alert">
|
||||
<strong>无权查看配置</strong>
|
||||
<span>当前账号没有配置管理、金蝶账号绑定或自动任务权限,可在「人员与角色」中分配。</span>
|
||||
</div>
|
||||
<template v-else>
|
||||
<nav v-if="visibleTabs.length > 1" class="tabs integration-tabs" role="tablist" aria-label="配置分栏">
|
||||
<button
|
||||
v-for="tab in visibleTabs"
|
||||
:id="`config-tab-${tab.key}`"
|
||||
:key="tab.key"
|
||||
class="tab"
|
||||
:class="{ active: activeTab === tab.key }"
|
||||
type="button"
|
||||
role="tab"
|
||||
:aria-selected="activeTab === tab.key"
|
||||
:aria-controls="`config-panel-${tab.key}`"
|
||||
@click="selectTab(tab.key)"
|
||||
>{{ tab.label }}</button>
|
||||
</nav>
|
||||
|
||||
<div
|
||||
v-show="activeTab === 'feishu'"
|
||||
id="config-panel-feishu"
|
||||
role="tabpanel"
|
||||
aria-labelledby="config-tab-feishu"
|
||||
>
|
||||
<div v-if="!canViewFeishu" class="card empty-state" role="alert">
|
||||
<strong>无权查看飞书配置</strong>
|
||||
<span>需要「配置管理」页面权限。</span>
|
||||
</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>
|
||||
<template v-else>
|
||||
<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>
|
||||
<template v-else>
|
||||
<div class="inline-note integration-note">
|
||||
保存审批定义编码后,点击「验证并同步飞书审批」拉取流程定义并订阅事件,保障飞书审批状态变更后本系统实时更新。
|
||||
</div>
|
||||
<section class="card integration-card" aria-labelledby="feishu-approval-title">
|
||||
<div class="card-head">
|
||||
<div>
|
||||
<span class="eyebrow">FEISHU</span>
|
||||
<h2 id="feishu-approval-title">飞书审批配置</h2>
|
||||
<p>仅配置审批定义编码;应用凭证与事件回调密钥在 application.yml / 环境变量中维护。</p>
|
||||
</div>
|
||||
<span class="tag" :class="feishuEnabled ? 'success' : 'neutral'">{{ feishuEnabled ? '飞书已启用' : '飞书未启用' }}</span>
|
||||
</div>
|
||||
<div class="integration-body">
|
||||
<div class="form-grid integration-form">
|
||||
<div class="field">
|
||||
<label for="feishu-approvalCode">审批定义编码 <em>*</em></label>
|
||||
<input
|
||||
id="feishu-approvalCode"
|
||||
v-model.trim="approvalCode"
|
||||
type="text"
|
||||
:disabled="!canManage || saving || approvalSyncing"
|
||||
placeholder="例如:8A0D2B3C-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
|
||||
autocomplete="off"
|
||||
aria-describedby="feishu-approvalCode-help"
|
||||
>
|
||||
<small id="feishu-approvalCode-help" class="field-hint">
|
||||
在飞书审批管理后台查看目标报销流程的 approval_code(审批定义 Code)。
|
||||
<template v-if="configSource">当前来源:{{ configSource === 'database' ? '已保存到本系统' : '后端配置文件' }}。</template>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="integration-tool">
|
||||
<div>
|
||||
<strong>验证并同步飞书审批</strong>
|
||||
<small>校验该审批定义可用,同步流程节点到本系统,并订阅此审批的事件以实现状态实时更新。</small>
|
||||
<span
|
||||
v-if="approvalSyncStatus"
|
||||
class="sync-status"
|
||||
:class="approvalSyncStatus.success ? 'success-copy' : 'danger-copy'"
|
||||
:role="approvalSyncStatus.success ? 'status' : 'alert'"
|
||||
aria-live="polite"
|
||||
>{{ approvalSyncStatus.message }}</span>
|
||||
</div>
|
||||
<button
|
||||
v-if="canApprovalSync"
|
||||
class="btn small"
|
||||
type="button"
|
||||
:disabled="approvalSyncing || saving || !approvalCode"
|
||||
:aria-busy="approvalSyncing"
|
||||
@click="syncApprovalDefinition"
|
||||
>{{ approvalSyncing ? '验证中…' : '验证并同步飞书审批' }}</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-actions integration-actions">
|
||||
<span v-if="saveHint" class="test-result" :class="saveHint.success ? 'success-copy' : 'danger-copy'" role="status">{{ saveHint.message }}</span>
|
||||
<button
|
||||
v-if="canManage"
|
||||
class="btn primary"
|
||||
type="button"
|
||||
:disabled="saving || approvalSyncing || !approvalCode"
|
||||
:aria-busy="saving"
|
||||
@click="saveApprovalCode"
|
||||
>{{ saving ? '保存中…' : '保存审批编码' }}</button>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-show="activeTab === 'kingdee'"
|
||||
id="config-panel-kingdee"
|
||||
role="tabpanel"
|
||||
aria-labelledby="config-tab-kingdee"
|
||||
>
|
||||
<div v-if="!canViewKingdee" class="card empty-state" role="alert">
|
||||
<strong>无权查看金蝶账号绑定</strong>
|
||||
<span>需要「金蝶账号绑定」权限,可在角色中分配给财务或其他角色。</span>
|
||||
</div>
|
||||
<template v-else>
|
||||
<div class="inline-note integration-note">
|
||||
在「人员与角色」中可分别配置:查看本人/全部、绑定本人/全部、解绑本人/全部。财务默认仅本人;系统同步仍使用配置文件中的金蝶系统账号。
|
||||
</div>
|
||||
<KingdeeAccountBindingPanel embedded />
|
||||
</template>
|
||||
</div>
|
||||
<div
|
||||
v-show="activeTab === 'scheduled-tasks'"
|
||||
id="config-panel-scheduled-tasks"
|
||||
role="tabpanel"
|
||||
aria-labelledby="config-tab-scheduled-tasks"
|
||||
tabindex="0"
|
||||
>
|
||||
<ScheduledTasks v-if="canViewScheduledTasks && activeTab === 'scheduled-tasks'" embedded />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { adminApi, type IntegrationConfig, type IntegrationField } from '@/api/admin'
|
||||
import { adminApi } from '@/api/admin'
|
||||
import KingdeeAccountBindingPanel from '@/components/KingdeeAccountBindingPanel.vue'
|
||||
import { useUserStore } from '@/store/user'
|
||||
import ScheduledTasks from '@/views/ScheduledTasks.vue'
|
||||
|
||||
type StatusHint = { success: boolean; message: string }
|
||||
type TabKey = 'feishu' | 'kingdee' | 'scheduled-tasks'
|
||||
|
||||
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() })
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
|
||||
const loading = ref(false)
|
||||
const loadError = ref('')
|
||||
const saving = ref(false)
|
||||
const approvalSyncing = ref(false)
|
||||
const approvalCode = ref('')
|
||||
const feishuEnabled = ref(false)
|
||||
const configSource = ref('')
|
||||
const approvalSyncStatus = ref<StatusHint | null>(null)
|
||||
const saveHint = ref<StatusHint | null>(null)
|
||||
const activeTab = ref<TabKey>('feishu')
|
||||
const feishuLoaded = ref(false)
|
||||
|
||||
const canViewFeishu = computed(() => userStore.canRead('page.integration-config'))
|
||||
const canViewKingdee = computed(() => userStore.canRead('page.kingdee-account-binding'))
|
||||
const canViewScheduledTasks = computed(() => userStore.canRead('page.scheduled-tasks'))
|
||||
const canOpenPage = computed(() => canViewFeishu.value || canViewKingdee.value || canViewScheduledTasks.value)
|
||||
const canManage = computed(() => userStore.canEdit('system.integration.config.update'))
|
||||
const canApprovalSync = computed(() => userStore.canEdit('system.integration.feishu.approval.sync'))
|
||||
|
||||
const visibleTabs = computed(() => {
|
||||
const tabs: { key: TabKey; label: string }[] = []
|
||||
// Config managers always see both sections; finance-only users see Kingdee.
|
||||
if (canViewFeishu.value) {
|
||||
tabs.push({ key: 'feishu', label: '飞书审批配置' })
|
||||
}
|
||||
if (canViewKingdee.value) tabs.push({ key: 'kingdee', label: '金蝶账号绑定' })
|
||||
if (canViewScheduledTasks.value) tabs.push({ key: 'scheduled-tasks', label: '自动任务' })
|
||||
return tabs
|
||||
})
|
||||
|
||||
const errorText = (error: unknown) => {
|
||||
const responseMessage = (error as { response?: { data?: { message?: unknown } } })?.response?.data?.message
|
||||
if (typeof responseMessage === 'string' && responseMessage.trim()) return responseMessage
|
||||
return error instanceof Error && error.message ? error.message : '请求失败,请稍后重试。'
|
||||
}
|
||||
|
||||
const approvalSyncErrorText = (error: unknown) => {
|
||||
const response = (error as { response?: { status?: number; data?: { message?: unknown } } } | null)?.response
|
||||
const responseMessage = typeof response?.data?.message === 'string' ? response.data.message.trim() : ''
|
||||
const thrownMessage = error instanceof Error ? error.message.trim() : ''
|
||||
if (response?.status === 401 || response?.status === 403) {
|
||||
return [responseMessage, thrownMessage].find(message => /权限|授权|无权|登录|认证/.test(message))
|
||||
|| '权限不足或登录已过期,请重新登录后重试。'
|
||||
}
|
||||
if (response?.status === 400 || response?.status === 409 || response?.status === 502) {
|
||||
return responseMessage || thrownMessage || '验证失败,请检查审批定义编码与飞书应用配置后重试。'
|
||||
}
|
||||
if (!response?.status && thrownMessage) return thrownMessage
|
||||
return '验证失败,请检查审批定义编码与飞书应用配置后重试。'
|
||||
}
|
||||
|
||||
const selectTab = (key: TabKey) => {
|
||||
activeTab.value = key
|
||||
const query = { ...route.query, tab: key }
|
||||
void router.replace({ query })
|
||||
}
|
||||
|
||||
const resolveTabFromRoute = () => {
|
||||
const raw = String(route.query.tab || '').trim().toLowerCase()
|
||||
if (raw === 'kingdee' && canViewKingdee.value) {
|
||||
activeTab.value = 'kingdee'
|
||||
return
|
||||
}
|
||||
if (raw === 'feishu' && canViewFeishu.value) {
|
||||
activeTab.value = 'feishu'
|
||||
return
|
||||
}
|
||||
if (raw === 'scheduled-tasks' && canViewScheduledTasks.value) {
|
||||
activeTab.value = 'scheduled-tasks'
|
||||
return
|
||||
}
|
||||
activeTab.value = visibleTabs.value[0]?.key || 'feishu'
|
||||
}
|
||||
|
||||
const loadConfig = async () => {
|
||||
if (!canViewFeishu.value) return
|
||||
loading.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
const config = await adminApi.getIntegrationConfig()
|
||||
const feishu = config?.feishu
|
||||
feishuEnabled.value = Boolean(feishu?.enabled)
|
||||
configSource.value = feishu?.source || ''
|
||||
const field = (Array.isArray(feishu?.fields) ? feishu.fields : [])
|
||||
.find(item => item.key === 'approvalCode')
|
||||
approvalCode.value = String(field?.value ?? '').trim()
|
||||
feishuLoaded.value = true
|
||||
} catch (error) {
|
||||
loadError.value = errorText(error)
|
||||
ElMessage.error(`配置加载失败:${loadError.value}`)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const saveApprovalCode = async () => {
|
||||
if (!canManage.value || saving.value || approvalSyncing.value) return
|
||||
const code = approvalCode.value.trim()
|
||||
if (!code) {
|
||||
ElMessage.warning('请填写审批定义编码')
|
||||
return
|
||||
}
|
||||
saving.value = true
|
||||
saveHint.value = null
|
||||
try {
|
||||
await adminApi.updateIntegrationConfig('FEISHU', true, { approvalCode: code })
|
||||
approvalCode.value = code
|
||||
configSource.value = 'database'
|
||||
saveHint.value = { success: true, message: '审批定义编码已保存' }
|
||||
ElMessage.success('审批定义编码已保存')
|
||||
} catch (error) {
|
||||
const message = errorText(error)
|
||||
saveHint.value = { success: false, message }
|
||||
ElMessage.error(`保存失败:${message}`)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const syncApprovalDefinition = async () => {
|
||||
if (!canApprovalSync.value || approvalSyncing.value || saving.value) return
|
||||
if (!approvalCode.value.trim()) {
|
||||
ElMessage.warning('请先填写并保存审批定义编码')
|
||||
return
|
||||
}
|
||||
approvalSyncing.value = true
|
||||
approvalSyncStatus.value = null
|
||||
try {
|
||||
const result = await adminApi.syncFeishuApprovalDefinition()
|
||||
const message = result?.message
|
||||
|| (result?.eventSubscribed === false
|
||||
? '已验证审批定义;事件订阅已存在'
|
||||
: '已验证审批定义并完成事件订阅')
|
||||
approvalSyncStatus.value = { success: true, message }
|
||||
ElMessage.success(message)
|
||||
} catch (error) {
|
||||
const message = approvalSyncErrorText(error)
|
||||
approvalSyncStatus.value = { success: false, message }
|
||||
ElMessage.error(message)
|
||||
} finally {
|
||||
approvalSyncing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => route.query.tab, () => resolveTabFromRoute())
|
||||
watch(activeTab, key => {
|
||||
if (key === 'feishu' && canViewFeishu.value && !feishuLoaded.value && !loading.value) {
|
||||
void loadConfig()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await userStore.loadPermissions()
|
||||
resolveTabFromRoute()
|
||||
if (activeTab.value === 'feishu' && canViewFeishu.value) 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-page { display: flex; min-height: 0; flex: 1 1 auto; flex-direction: column; }
|
||||
.integration-tabs { margin-bottom: 14px; }
|
||||
.integration-page > [role="tabpanel"] { min-width: 0; }
|
||||
#config-panel-scheduled-tasks { display: flex; min-height: 0; flex: 1 1 auto; flex-direction: column; }
|
||||
.integration-note { margin-top: 0; margin-bottom: 14px; }
|
||||
.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-body { display: flex; flex: 1; flex-direction: column; min-width: 0; padding: 0 22px; }
|
||||
.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-tool { display: flex; align-items: center; justify-content: space-between; gap: 14px; padding: 13px 0 16px; border-top: 1px solid var(--line); }
|
||||
.integration-tool > div { min-width: 0; }
|
||||
.integration-tool strong, .integration-tool small, .sync-status { display: block; overflow-wrap: anywhere; }
|
||||
.integration-tool strong { font-size: 12px; }
|
||||
.integration-tool small { margin-top: 2px; color: var(--muted); font-size: 11px; }
|
||||
.sync-status { margin-top: 5px; font-size: 11px; }
|
||||
.field-hint { margin-top: 3px; color: var(--text); font-size: 12px; line-height: 1.55; overflow-wrap: anywhere; }
|
||||
.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; } }
|
||||
@media (max-width: 760px) {
|
||||
.integration-actions { justify-content: flex-end; }
|
||||
.test-result { width: 100%; margin-right: 0; }
|
||||
.integration-tool { align-items: stretch; flex-direction: column; }
|
||||
.integration-tool .btn { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,16 @@
|
||||
<template>
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">FINANCE · KINGDEE</span>
|
||||
<h1>金蝶账号绑定</h1>
|
||||
<p>财务角色须绑定个人金蝶云星空账号后,方可变更金蝶财务单据。系统同步仍使用配置文件中的系统账号。</p>
|
||||
</div>
|
||||
</div>
|
||||
<KingdeeAccountBindingPanel />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import KingdeeAccountBindingPanel from '@/components/KingdeeAccountBindingPanel.vue'
|
||||
</script>
|
||||
+99
-214
@@ -12,62 +12,55 @@
|
||||
</span>
|
||||
</div>
|
||||
<div class="product-name">
|
||||
员工报销工作台
|
||||
<span>财务与报销管理</span>
|
||||
<strong>费用与付款</strong>
|
||||
<span>SPEND OPERATIONS</span>
|
||||
</div>
|
||||
<nav class="main-nav" aria-label="主导航">
|
||||
<div class="nav-group" v-if="canAccess('dashboard')">
|
||||
<span>工作台</span>
|
||||
<div class="nav-group" v-if="canAccess('page.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> 工作台
|
||||
<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>
|
||||
<div class="nav-group" v-if="canAnyPage(['page.applications', 'page.application-create', 'page.application-edit', 'page.source-documents'])">
|
||||
<span>申请与报销</span>
|
||||
<router-link v-if="canAccess('page.applications')" 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">
|
||||
<router-link v-if="canAccess('page.application-create')" to="/applications/new" @click="sidebarOpen = false"><b aria-hidden="true"><Plus /></b> 发起申请</router-link>
|
||||
<router-link v-if="canAccess('page.source-documents')" 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>
|
||||
</div>
|
||||
|
||||
<div class="nav-group" v-if="canAnyPage(['page.finance-receipt', 'page.payments'])">
|
||||
<span>财务处理</span>
|
||||
<router-link v-if="canAccess('page.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('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 v-if="canAccess('page.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>
|
||||
</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">
|
||||
<div class="nav-group admin-nav" v-if="canAnyPage(['page.expense-types', 'page.payees', 'page.roles', 'page.groups', 'page.integration-config', 'page.kingdee-account-binding', 'page.feishu-directory', 'page.scheduled-tasks', 'page.operation-log'])">
|
||||
<span>管理中心</span>
|
||||
<router-link v-if="canAnyPage(['page.groups', 'page.roles', 'page.feishu-directory'])" 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('page.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">
|
||||
<router-link v-if="canAccess('page.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>
|
||||
<router-link v-if="canAnyPage(['page.integration-config', 'page.kingdee-account-binding', 'page.scheduled-tasks'])" :to="configNavTo" @click="sidebarOpen = false" :class="{ active: route.path.startsWith('/integration-config') || route.path.startsWith('/scheduled-tasks') }" :aria-current="route.path.startsWith('/integration-config') || route.path.startsWith('/scheduled-tasks') ? 'page' : undefined">
|
||||
<b aria-hidden="true"><Connection /></b> 配置管理
|
||||
</router-link>
|
||||
<router-link v-if="canAccess('page.operation-log')" 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>
|
||||
</nav>
|
||||
<div class="sidebar-foot">
|
||||
@@ -84,13 +77,13 @@
|
||||
<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>
|
||||
<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>
|
||||
<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" />
|
||||
@@ -103,7 +96,7 @@
|
||||
</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>
|
||||
<div v-if="showDataSyncBanner" 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>
|
||||
@@ -111,17 +104,18 @@
|
||||
|
||||
<dialog
|
||||
ref="notificationDialog"
|
||||
class="notification-dialog"
|
||||
v-dialog-drag
|
||||
class="app-dialog 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">
|
||||
<section class="app-dialog__panel notification-dialog-panel" aria-describedby="notification-dialog-description">
|
||||
<header class="notification-modal-head" data-dialog-drag-handle title="拖动通知面板">
|
||||
<div>
|
||||
<span class="eyebrow">通知中心</span>
|
||||
<span class="eyebrow">NOTIFICATION CENTER</span>
|
||||
<h2 id="notification-dialog-title">通知</h2>
|
||||
<p id="notification-dialog-description">
|
||||
{{ notificationItems.length ? `共 ${notificationItems.length} 条待关注事项` : '暂无待关注事项' }}
|
||||
@@ -163,7 +157,7 @@
|
||||
<span>新的报销进度和付款状态会显示在这里。</span>
|
||||
</div>
|
||||
<footer class="notification-modal-actions">
|
||||
<button class="btn small" type="button" @click="closeNotifications">关闭</button>
|
||||
<button class="btn" type="button" @click="closeNotifications">关闭</button>
|
||||
</footer>
|
||||
</section>
|
||||
</dialog>
|
||||
@@ -171,10 +165,10 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, nextTick, onBeforeUnmount, onMounted, watch } from 'vue'
|
||||
import { ref, computed, nextTick, onMounted, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useUserStore } from '@/store/user'
|
||||
import { authApi } from '@/api/auth'
|
||||
import { authApi, type UserProfile } from '@/api/auth'
|
||||
import { useWorkbenchStore } from '@/store/workbench'
|
||||
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
@@ -198,16 +192,8 @@ 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 () => {
|
||||
// 刷新时从后端获取最新的用户信息(包括角色变更)
|
||||
@@ -237,76 +223,62 @@ onMounted(async () => {
|
||||
// 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()
|
||||
void loadWorkbenchIfAllowed()
|
||||
})
|
||||
|
||||
const userType = computed(() => userStore.userInfo?.userType || '')
|
||||
const userName = computed(() => userStore.userInfo?.realName || '用户')
|
||||
const userInitial = computed(() => userName.value.charAt(0) || '用')
|
||||
|
||||
const userTypeLabel = computed(() => {
|
||||
const resolveUserTypeLabel = (profile: UserProfile | null) => {
|
||||
const labels: Record<string, string> = {
|
||||
'SUPER_ADMIN': '超级管理员',
|
||||
'ADMIN': '系统管理员',
|
||||
'FINANCE': '财务人员',
|
||||
'EMPLOYEE': '员工',
|
||||
SUPER_ADMIN: '超级管理员',
|
||||
ADMIN: '系统管理员',
|
||||
FINANCE: '财务人员',
|
||||
EMPLOYEE: '员工',
|
||||
}
|
||||
return labels[userType.value] || userType.value || '普通用户'
|
||||
})
|
||||
const hasEffectiveRoleData = typeof profile?.isSuperAdmin === 'boolean' || Array.isArray(profile?.roleCodes)
|
||||
if (hasEffectiveRoleData) {
|
||||
const roleCodes = (profile?.roleCodes || []).map(code => String(code).trim().toUpperCase())
|
||||
if (profile?.isSuperAdmin === true || roleCodes.includes('SUPER_ADMIN')) return labels.SUPER_ADMIN
|
||||
const effectiveRole = ['ADMIN', 'FINANCE', 'EMPLOYEE'].find(code => roleCodes.includes(code))
|
||||
return effectiveRole ? labels[effectiveRole] : '普通用户'
|
||||
}
|
||||
const fallbackType = String(profile?.userType || '').trim().toUpperCase()
|
||||
return labels[fallbackType] || profile?.userType || '普通用户'
|
||||
}
|
||||
const userTypeLabel = computed(() => resolveUserTypeLabel(userStore.userInfo))
|
||||
|
||||
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'],
|
||||
// Navigation is derived exclusively from page.* permissions. Missing and
|
||||
// failed permission state is hidden by the store's fail-closed accessors.
|
||||
const canAccess = (code: string) => userStore.canRead(code)
|
||||
const canAnyPage = (codes: string[]) => userStore.canAny(codes)
|
||||
/** Finance-only users land on the Kingdee binding tab; admins open Feishu by default. */
|
||||
const configNavTo = computed(() => {
|
||||
if (canAccess('page.integration-config')) return '/integration-config'
|
||||
if (canAccess('page.kingdee-account-binding')) {
|
||||
return { path: '/integration-config', query: { tab: 'kingdee' } }
|
||||
}
|
||||
return { path: '/integration-config', query: { tab: 'scheduled-tasks' } }
|
||||
})
|
||||
const snapshotPermissionByRoute: Record<string, string> = {
|
||||
Dashboard: 'page.dashboard',
|
||||
Applications: 'page.applications',
|
||||
ApplicationNew: 'page.application-create',
|
||||
ApplicationDetail: 'page.applications',
|
||||
ApplicationEdit: 'page.application-edit',
|
||||
}
|
||||
|
||||
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 currentSnapshotPermission = computed(() => snapshotPermissionByRoute[String(route.name || '')] || '')
|
||||
const showDataSyncBanner = computed(() => Boolean(currentSnapshotPermission.value) && canAccess(currentSnapshotPermission.value))
|
||||
const loadWorkbenchIfAllowed = async () => {
|
||||
if (!showDataSyncBanner.value || workbench.reimbursements.length || workbench.loading) return
|
||||
await workbench.load()
|
||||
}
|
||||
watch(() => route.name, () => { void loadWorkbenchIfAllowed() })
|
||||
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)
|
||||
@@ -347,7 +319,7 @@ const money = (value: unknown) => {
|
||||
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 financeRoute = (item: ReimApplicationDetail) => canAccess('page.finance-receipt') ? '/finance-receipt' : applicationRoute(item)
|
||||
|
||||
const buildNotifications = (count: number) => {
|
||||
const rows = workbench.reimbursements
|
||||
@@ -376,7 +348,7 @@ const buildNotifications = (count: number) => {
|
||||
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),
|
||||
time: notificationTime(item), icon: 'Wallet', tone: 'success', route: canAccess('page.payments') ? '/payments' : applicationRoute(item),
|
||||
}))
|
||||
|
||||
// Only render notifications that can be traced back to a real business row.
|
||||
@@ -388,51 +360,6 @@ const buildNotifications = (count: number) => {
|
||||
}))
|
||||
}
|
||||
|
||||
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
|
||||
@@ -455,10 +382,8 @@ 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) => {
|
||||
@@ -466,16 +391,6 @@ const openNotification = (item: NotificationItem) => {
|
||||
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()
|
||||
@@ -494,41 +409,10 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
|
||||
.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;
|
||||
width: min(450px, calc(100vw - 24px));
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
|
||||
@@ -555,9 +439,8 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
|
||||
.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-modal-body { max-height: min(480px, calc(100vh - 190px)); padding: 10px 12px; overflow-y: auto; background: #f6f8fa; }
|
||||
.notification-list { display: grid; gap: 7px; list-style: none; }
|
||||
|
||||
.notification-item {
|
||||
display: grid;
|
||||
@@ -565,16 +448,17 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
|
||||
grid-template-columns: 34px minmax(0, 1fr) auto;
|
||||
align-items: start;
|
||||
gap: 11px;
|
||||
padding: 14px 18px;
|
||||
border: 0;
|
||||
border-bottom: 1px solid var(--line);
|
||||
min-height: 76px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
color: var(--text);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.notification-item.actionable { cursor: pointer; }
|
||||
.notification-item.actionable:hover { background: #f7faff; }
|
||||
.notification-item.actionable:hover { border-color: #b8cee4; background: #f7faff; }
|
||||
.notification-item:focus-visible { position: relative; z-index: 1; outline: 3px solid #72adff; outline-offset: -3px; }
|
||||
|
||||
.notification-item-icon {
|
||||
@@ -610,12 +494,13 @@ watch(() => route.query.denied, value => { if (value) ElMessage.warning(`无权
|
||||
.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); }
|
||||
.notification-modal-actions { display: flex; justify-content: flex-end; padding: 13px 21px; border-top: 1px solid var(--line); background: var(--surface-raised); }
|
||||
|
||||
@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-body { padding: 8px; }
|
||||
.notification-item { grid-template-columns: 34px minmax(0, 1fr); padding: 11px; }
|
||||
.notification-item-link { grid-column: 2; padding-top: 0; }
|
||||
.notification-modal-actions { padding: 12px 17px; }
|
||||
}
|
||||
|
||||
|
||||
+26
-42
@@ -5,56 +5,54 @@
|
||||
<span class="brand-mark" aria-hidden="true"><i></i><i></i></span>
|
||||
<span>
|
||||
<strong>零差云控</strong>
|
||||
<small>ZEROERR · 财务管理平台</small>
|
||||
<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>
|
||||
<span class="eyebrow login-eyebrow">企业登录</span>
|
||||
<h1 id="loginTitle">统一费用付款平台</h1>
|
||||
<p id="loginIntro">使用飞书账号登录,连接付款申请、审批、收单与付款办理。</p>
|
||||
</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>
|
||||
<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>
|
||||
<span class="login-spinner" aria-hidden="true"></span>
|
||||
<span>
|
||||
<strong>正在验证身份…</strong>
|
||||
<small v-if="loadingMessage">{{ loadingMessage }}</small>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-else>
|
||||
<div v-else class="login-action">
|
||||
<div v-if="loginError" class="inline-alert danger" role="alert">
|
||||
<b aria-hidden="true">!</b>
|
||||
<span>{{ loginError }}</span>
|
||||
</div>
|
||||
<button
|
||||
class="btn"
|
||||
class="btn primary login-submit"
|
||||
type="button"
|
||||
:disabled="feishuLoading"
|
||||
:aria-busy="feishuLoading"
|
||||
@click="handleFeishuLogin"
|
||||
>
|
||||
{{ feishuLoading ? '正在前往飞书…' : '飞书授权登录' }}
|
||||
<span v-if="feishuLoading" class="login-button-spinner" aria-hidden="true"></span>
|
||||
<img v-else src="@/assets/feishu-logo.png" alt="">
|
||||
{{ feishuLoading ? '正在前往飞书…' : '使用飞书登录' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="login-card-foot">
|
||||
登录信息由飞书授权提供,本平台不单独维护登录密码
|
||||
身份授权由飞书提供,本平台不存储飞书密码。通讯录同步用于员工资料与业务管理,不作为登录条件。
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<footer class="login-foot">企业财务工作台 · 飞书统一身份认证</footer>
|
||||
<footer class="login-foot">零差云控 · ZEROERR · 统一费用付款平台</footer>
|
||||
</div>
|
||||
</main>
|
||||
</template>
|
||||
@@ -104,7 +102,11 @@ onMounted(async () => {
|
||||
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 (token || code || error || state) {
|
||||
// Replace the current history entry before making any network request. Do
|
||||
// not retain OAuth credentials in the address bar, referrer, or history.
|
||||
window.history.replaceState({}, document.title, window.location.pathname)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
const attempt = sessionStorage.getItem('feishuOAuthAttempt')
|
||||
@@ -114,27 +116,9 @@ onMounted(async () => {
|
||||
}
|
||||
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 || '登录验证失败,请重新授权'
|
||||
}
|
||||
// Provider errors may echo sensitive callback data; show a fixed message.
|
||||
loginError.value = '飞书授权未完成,请重新登录'
|
||||
ElMessage.error(loginError.value)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+142
-15
@@ -1,32 +1,159 @@
|
||||
<template>
|
||||
<div class="page-content">
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">OPERATION LOGS</span>
|
||||
<h1>操作日志</h1>
|
||||
<p>系统操作记录,按时间倒序排列。</p>
|
||||
<p>记录变更类接口访问(不含查看),按时间倒序排列。</p>
|
||||
</div>
|
||||
<div class="head-actions">
|
||||
<button class="btn" type="button" :disabled="!loaded" @click="load">刷新</button>
|
||||
</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 class="card filter-card">
|
||||
<div class="log-filters">
|
||||
<label class="field">
|
||||
<span>分类</span>
|
||||
<select v-model="category" class="select" @change="load">
|
||||
<option value="">全部</option>
|
||||
<option v-for="item in categoryOptions" :key="item" :value="item">{{ item }}</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="field">
|
||||
<span>操作人</span>
|
||||
<input v-model.trim="operator" type="search" placeholder="姓名" autocomplete="off" @keyup.enter="load">
|
||||
</label>
|
||||
<button class="btn primary" type="button" @click="load">查询</button>
|
||||
</div>
|
||||
<div class="empty-state" v-else-if="loaded"><strong>暂无操作日志</strong></div>
|
||||
</div>
|
||||
|
||||
<div class="card fill-list-card primary-list-card">
|
||||
<div class="card-head">
|
||||
<div>
|
||||
<h2>接口访问记录</h2>
|
||||
<p>包含方法、路径、状态码与耗时。</p>
|
||||
</div>
|
||||
<span>{{ items.length }} 条</span>
|
||||
</div>
|
||||
|
||||
<div v-if="loaded && !error && items.length" class="table-wrap" tabindex="0" role="region" aria-label="操作日志列表">
|
||||
<table class="data-table responsive-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>时间</th>
|
||||
<th>操作人</th>
|
||||
<th>分类</th>
|
||||
<th>接口</th>
|
||||
<th>状态</th>
|
||||
<th>耗时</th>
|
||||
<th>详情</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in paginatedItems" :key="item.id">
|
||||
<td data-label="时间"><small>{{ item.time || '—' }}</small></td>
|
||||
<td data-label="操作人"><strong>{{ item.operator || '匿名' }}</strong></td>
|
||||
<td data-label="分类"><span class="tag neutral">{{ item.category || '接口访问' }}</span></td>
|
||||
<td data-label="接口">
|
||||
<strong class="log-method" :class="methodTone(item.method)">{{ item.method || methodFromAction(item.action) }}</strong>
|
||||
<small>{{ item.path || pathFromAction(item.action) }}</small>
|
||||
</td>
|
||||
<td data-label="状态"><span class="tag" :class="statusTone(item.statusCode)">{{ item.statusCode ?? '—' }}</span></td>
|
||||
<td data-label="耗时"><span class="mono">{{ item.durationMs != null ? `${item.durationMs} ms` : '—' }}</span></td>
|
||||
<td data-label="详情"><small class="log-detail">{{ item.detail || '—' }}</small></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div v-else-if="error" class="empty-state" role="alert"><strong>操作日志加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></div>
|
||||
<div class="empty-state" v-else-if="loaded"><strong>暂无操作日志</strong><span>访问任意接口后会自动出现在这里。</span></div>
|
||||
<div v-else class="load-wrap" role="status"><span class="loader" aria-hidden="true"></span><span>正在加载操作日志…</span></div>
|
||||
<AppListPagination v-if="loaded && !error && items.length" v-model:page="page" v-model:page-size="pageSize" :total="items.length" aria-label="操作日志分页" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import request from '@/api/request'
|
||||
const items = ref<any[]>([])
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
|
||||
type LogItem = {
|
||||
id: number | string
|
||||
operator?: string
|
||||
action?: string
|
||||
detail?: string
|
||||
category?: string
|
||||
method?: string
|
||||
path?: string
|
||||
statusCode?: number
|
||||
durationMs?: number
|
||||
time?: string
|
||||
}
|
||||
|
||||
const items = ref<LogItem[]>([])
|
||||
const loaded = ref(false)
|
||||
onMounted(async () => { try { items.value = await request.get('/logs') || [] } catch {} finally { loaded.value = true } })
|
||||
const error = ref('')
|
||||
const category = ref('')
|
||||
const operator = ref('')
|
||||
const categoryOptions = ['接口访问', '认证登录', '报销申请', '付款操作', '收单操作', '飞书通讯录', '飞书集成', '配置管理', '人员权限', '主数据', '自动任务', '系统日志']
|
||||
const { page, pageSize, paginatedItems } = useListPagination(items)
|
||||
|
||||
const methodFromAction = (action?: string) => String(action || '').split(/\s+/)[0] || '—'
|
||||
const pathFromAction = (action?: string) => {
|
||||
const parts = String(action || '').split(/\s+/)
|
||||
return parts.length > 1 ? parts.slice(1).join(' ') : '—'
|
||||
}
|
||||
const methodTone = (method?: string) => {
|
||||
const value = String(method || '').toUpperCase()
|
||||
if (value === 'GET') return 'is-get'
|
||||
if (value === 'POST') return 'is-post'
|
||||
if (value === 'PUT' || value === 'PATCH') return 'is-put'
|
||||
if (value === 'DELETE') return 'is-delete'
|
||||
return ''
|
||||
}
|
||||
const statusTone = (code?: number) => {
|
||||
if (code == null) return 'neutral'
|
||||
if (code >= 400) return 'danger'
|
||||
if (code >= 200 && code < 300) return 'success'
|
||||
return 'neutral'
|
||||
}
|
||||
|
||||
const load = async () => {
|
||||
loaded.value = false
|
||||
error.value = ''
|
||||
try {
|
||||
const params: Record<string, string | number> = { limit: 200 }
|
||||
if (category.value) params.category = category.value
|
||||
if (operator.value) params.operator = operator.value
|
||||
items.value = (await request.get('/logs', { params })) || []
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。'
|
||||
} finally {
|
||||
loaded.value = true
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.filter-card { margin-bottom: 16px; padding: 16px 22px; }
|
||||
.log-filters { display: flex; flex-wrap: wrap; align-items: end; gap: 16px; }
|
||||
.log-filters .field { min-width: 180px; flex: 1 1 180px; gap: 6px; }
|
||||
.log-filters .btn { flex: 0 0 auto; }
|
||||
.log-method { display: inline-block; min-width: 3.2em; margin-right: 6px; font: 700 11px var(--mono); }
|
||||
.log-method.is-get { color: var(--blue); }
|
||||
.log-method.is-post { color: var(--success); }
|
||||
.log-method.is-put { color: #b7791f; }
|
||||
.log-method.is-delete { color: var(--danger); }
|
||||
.mono { font: 600 12px var(--mono); }
|
||||
.log-detail { display: block; max-width: 420px; color: var(--muted); overflow-wrap: anywhere; }
|
||||
@media (max-width: 720px) {
|
||||
.log-filters { flex-direction: column; align-items: stretch; }
|
||||
.log-filters .btn { width: 100%; }
|
||||
.log-detail { max-width: none; }
|
||||
}
|
||||
</style>
|
||||
+17
-10
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="page-content">
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">PAYEES</span>
|
||||
@@ -7,28 +7,35 @@
|
||||
<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">
|
||||
<div class="card fill-list-card primary-list-card">
|
||||
<div class="table-wrap" v-if="loaded && !error && items.length > 0" tabindex="0" role="region" aria-label="付款对象列表"><table class="data-table responsive-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 v-for="item in paginatedItems" :key="item.id">
|
||||
<td data-label="账户名称"><strong>{{ item.name }}</strong></td>
|
||||
<td data-label="银行"><small>{{ item.bankName }}</small></td>
|
||||
<td data-label="账号"><small>{{ item.bankAccountMask || '已脱敏' }}</small></td>
|
||||
<td data-label="默认"><span class="tag" :class="item.isDefault?'success':'draft'">{{ item.isDefault?'默认':'否' }}</span></td>
|
||||
<td data-label="状态"><span class="tag" :class="item.status==='ACTIVE'?'success':'draft'">{{ item.status }}</span></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<div v-else-if="error" class="empty-state" role="alert"><strong>付款对象加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></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>
|
||||
<AppListPagination v-if="loaded && !error && items.length" v-model:page="page" v-model:page-size="pageSize" :total="items.length" aria-label="付款对象列表分页" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted } from 'vue'
|
||||
import request from '@/api/request'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
const items = ref<any[]>([])
|
||||
const loaded = ref(false)
|
||||
onMounted(async () => { try { items.value = await request.get('/metadata/payees') || [] } catch {} finally { loaded.value = true } })
|
||||
const error = ref('')
|
||||
const { page, pageSize, paginatedItems } = useListPagination(items)
|
||||
const load = async () => { loaded.value = false; error.value = ''; try { items.value = await request.get('/metadata/payees') || [] } catch (e) { error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。' } finally { loaded.value = true } }
|
||||
onMounted(load)
|
||||
</script>
|
||||
+52
-15
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="page-content">
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">PAYMENT QUEUE</span>
|
||||
@@ -36,7 +36,7 @@
|
||||
<div><span>已付款</span><strong>{{ completed.length }}</strong><small>全额完成</small></div>
|
||||
</div>
|
||||
|
||||
<div class="card fill-list-card">
|
||||
<div class="card fill-list-card primary-list-card">
|
||||
<div class="card-head">
|
||||
<div><h2>付款登记队列</h2><p>登记结果后,付款状态自动派生并保留付款事实。</p></div>
|
||||
<span class="tag info">财务处理</span>
|
||||
@@ -60,7 +60,7 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in filtered" :key="item.id">
|
||||
<tr v-for="item in paginatedItems" :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>
|
||||
@@ -70,14 +70,15 @@
|
||||
<td data-label="付款状态"><span class="tag" :class="tone(item.paymentStatus)">{{ item.paymentStatus }}</span></td>
|
||||
<td data-label="操作">
|
||||
<button
|
||||
v-if="store.balance(item) > 0"
|
||||
v-if="store.balance(item) > 0 && canRegister"
|
||||
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>
|
||||
<span v-else-if="store.balance(item) <= 0" class="muted-copy">已完成</span>
|
||||
<span v-else class="muted-copy">无操作权限</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -91,35 +92,39 @@
|
||||
<strong>没有符合条件的付款记录</strong>
|
||||
<span>请调整搜索关键词后重试。</span>
|
||||
</div>
|
||||
<AppListPagination v-if="filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="付款登记队列分页" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<dialog
|
||||
ref="dialog"
|
||||
class="payment-dialog"
|
||||
v-dialog-drag
|
||||
class="app-dialog payment-dialog"
|
||||
aria-modal="true"
|
||||
aria-labelledby="payment-dialog-title"
|
||||
aria-describedby="payment-dialog-description"
|
||||
@close="handleDialogClose"
|
||||
@click.self="closePayment"
|
||||
@cancel="handlePaymentCancel"
|
||||
@click.self="handlePaymentBackdrop"
|
||||
>
|
||||
<form v-if="selected" class="payment-form" @submit.prevent="submitPayment">
|
||||
<div class="modal-head">
|
||||
<div class="modal-head" data-dialog-drag-handle>
|
||||
<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>
|
||||
<button class="modal-close" type="button" aria-label="关闭付款登记窗口" :disabled="saving" @click="closePayment">×</button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<div class="modal-body payment-dialog-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="form-grid payment-fields">
|
||||
<div class="field">
|
||||
<label for="pay-amount">本次付款金额 <em>*</em></label>
|
||||
<input
|
||||
@@ -159,9 +164,14 @@
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import type { ReimApplicationDetail } from '@/api/reimbursement'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
import { useWorkbenchStore } from '@/store/workbench'
|
||||
import { useUserStore } from '@/store/user'
|
||||
|
||||
const store = useWorkbenchStore()
|
||||
const userStore = useUserStore()
|
||||
const canRegister = computed(() => userStore.canEdit('finance.payment.register'))
|
||||
const query = ref('')
|
||||
const hasLoaded = ref(false)
|
||||
const selected = ref<ReimApplicationDetail | null>(null)
|
||||
@@ -181,6 +191,7 @@ 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 { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [query] })
|
||||
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)
|
||||
@@ -196,7 +207,7 @@ const refreshQueue = async () => {
|
||||
}
|
||||
|
||||
const openPayment = async (item: ReimApplicationDetail) => {
|
||||
if (saving.value) return
|
||||
if (!canRegister.value || saving.value) return
|
||||
trigger = document.activeElement instanceof HTMLElement ? document.activeElement : null
|
||||
selected.value = item
|
||||
amount.value = Number(store.balance(item).toFixed(2))
|
||||
@@ -217,14 +228,17 @@ const restoreDialogFocus = () => {
|
||||
}
|
||||
|
||||
const closePayment = () => {
|
||||
if (saving.value) return
|
||||
if (dialog.value?.open) dialog.value.close()
|
||||
restoreDialogFocus()
|
||||
}
|
||||
|
||||
const handleDialogClose = () => restoreDialogFocus()
|
||||
const handlePaymentCancel = (event: Event) => { event.preventDefault();if(!saving.value)closePayment() }
|
||||
const handlePaymentBackdrop = (event: MouseEvent) => { if(saving.value){event.preventDefault();return}closePayment() }
|
||||
|
||||
const submitPayment = async () => {
|
||||
if (!selected.value || saving.value) return
|
||||
if (!canRegister.value || !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) {
|
||||
@@ -234,16 +248,39 @@ const submitPayment = async () => {
|
||||
|
||||
saving.value = true
|
||||
formError.value = ''
|
||||
let succeeded = false
|
||||
try {
|
||||
await store.pay(selected.value.id, Number(enteredAmount.toFixed(2)), remark.value.trim(), idempotencyKey.value)
|
||||
closePayment()
|
||||
ElMessage.success('付款记录已登记')
|
||||
succeeded = true
|
||||
} catch (error) {
|
||||
formError.value = error instanceof Error ? error.message : '付款失败,请检查后重试'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
if (succeeded) {
|
||||
closePayment()
|
||||
ElMessage.success('付款记录已登记')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => { void refreshQueue() })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.payment-dialog-body { background: #fff; }
|
||||
.payment-summary { overflow: hidden; border-color: #d7e0e8; border-radius: 6px; }
|
||||
.payment-summary > div { padding: 12px 14px; background: var(--surface-raised); }
|
||||
.payment-summary > div:last-child { background: var(--blue-soft); }
|
||||
.payment-summary strong { color: var(--navy); font-size: 15px; }
|
||||
.payment-summary > div:last-child strong { color: var(--blue-dark); }
|
||||
.payment-fields { grid-template-columns: 1fr; gap: 14px; padding: 15px 0 0; }
|
||||
.payment-fields .field:first-child { max-width: 310px; }
|
||||
.payment-fields textarea { min-height: 78px; }
|
||||
.amount-error { margin: 12px 0 0; padding: 9px 11px; border-left: 3px solid var(--danger); background: var(--danger-soft); }
|
||||
@media (max-width: 560px) {
|
||||
.payment-summary { grid-template-columns: 1fr; }
|
||||
.payment-fields .field:first-child { max-width: none; }
|
||||
.payment-dialog .modal-actions { flex-direction: column-reverse; }
|
||||
.payment-dialog .modal-actions .btn { width: 100%; min-height: 44px; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,604 @@
|
||||
<template>
|
||||
<div class="scheduled-page page-content route-list-page" :class="{ 'scheduled-embedded': embedded }" :aria-busy="initialLoading || refreshing">
|
||||
<section class="card task-card" aria-labelledby="scheduled-task-title">
|
||||
<div class="card-head task-head">
|
||||
<div>
|
||||
<span class="eyebrow">SCHEDULED TASKS</span>
|
||||
<h2 id="scheduled-task-title">自动任务</h2>
|
||||
<p>查看固定系统任务的计划与运行状态。页面时间均按本地时间显示。</p>
|
||||
</div>
|
||||
<button class="btn small" type="button" :disabled="initialLoading || refreshing" @click="refreshAll">
|
||||
{{ refreshing ? '刷新中…' : '刷新' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="initialLoading" class="load-wrap page-state" role="status" aria-live="polite">
|
||||
<span class="loader" aria-hidden="true"></span><span>正在加载自动任务…</span>
|
||||
</div>
|
||||
<div v-else-if="listError && !tasks.length" class="empty-state page-state" role="alert">
|
||||
<strong>自动任务加载失败</strong><span>{{ listError }}</span>
|
||||
<button class="btn small" type="button" @click="loadTasks">重试</button>
|
||||
</div>
|
||||
<div v-else-if="!tasks.length" class="empty-state page-state">
|
||||
<strong>暂无自动任务</strong><span>系统尚未提供可管理的固定任务。</span>
|
||||
</div>
|
||||
<div v-else class="task-layout">
|
||||
<div v-if="listError" class="inline-alert danger task-list-warning" role="alert">{{ listError }}</div>
|
||||
<nav class="task-selector" aria-label="自动任务列表">
|
||||
<button
|
||||
v-for="item in tasks"
|
||||
:key="item.code"
|
||||
type="button"
|
||||
class="task-option"
|
||||
:class="{ active: item.code === selectedCode }"
|
||||
:aria-current="item.code === selectedCode ? 'true' : undefined"
|
||||
@click="selectTask(item.code)"
|
||||
>
|
||||
<span class="task-option-title"><strong>{{ item.name }}</strong><i class="status-dot-small" :class="taskTone(item)"></i></span>
|
||||
<small>{{ item.enabled ? `每 ${item.intervalHours} 小时` : '计划已停用' }} · {{ item.status === 'RUNNING' ? '运行中' : '空闲' }}</small>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<div class="task-detail">
|
||||
<div v-if="detailError && !task" class="empty-state detail-state" role="alert">
|
||||
<strong>任务详情加载失败</strong><span>{{ detailError }}</span>
|
||||
<button class="btn small" type="button" @click="refreshSelected()">重试</button>
|
||||
</div>
|
||||
<template v-else-if="task">
|
||||
<div class="detail-title-row">
|
||||
<div>
|
||||
<h3>{{ task.name }}</h3>
|
||||
<p class="muted-copy">{{ task.enabled ? '自动执行已启用' : '自动执行已停用' }} · {{ intervalLabel(task.intervalHours) }} · 时区 {{ task.timeZone || '—' }}</p>
|
||||
</div>
|
||||
<div class="detail-actions">
|
||||
<button v-if="canUpdate" class="btn" type="button" :disabled="refreshing" @click="openScheduleDialog">编辑计划</button>
|
||||
<button v-if="canExecute" class="btn primary" type="button" :disabled="executeDisabled" :aria-busy="executing || executeUncertain" @click="confirmExecute">
|
||||
{{ executeButtonLabel }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="detailError" class="inline-alert danger" role="alert">
|
||||
<span>{{ detailError }}</span><button class="btn small" type="button" @click="refreshSelected()">重新加载</button>
|
||||
</div>
|
||||
<p v-if="executeNotice" class="inline-note" role="status">{{ executeNotice }}</p>
|
||||
|
||||
<dl class="task-summary" aria-label="任务状态摘要">
|
||||
<div><dt>计划状态</dt><dd><span class="state-badge" :class="task.enabled ? 'success' : 'neutral'">{{ task.enabled ? '已启用' : '已停用' }}</span></dd></div>
|
||||
<div><dt>执行间隔</dt><dd>{{ intervalLabel(task.intervalHours) }}</dd></div>
|
||||
<div><dt>下次执行 <span>本地时间</span></dt><dd>{{ task.enabled ? formatLocalDateTime(task.nextDueAt, '待计算') : '—' }}</dd></div>
|
||||
<div><dt>当前状态</dt><dd><span class="state-badge" :class="isActive ? 'running' : 'neutral'">{{ isActive ? '运行中' : '空闲' }}</span></dd></div>
|
||||
<div><dt>最近运行</dt><dd>{{ latestRun ? `${stateLabels[latestRun.state]} · ${formatLocalDateTime(latestRun.queuedAt)}` : '暂无' }}</dd></div>
|
||||
<div><dt>最近成功 <span>本地时间</span></dt><dd>{{ formatLocalDateTime(lastSuccess?.finishedAt, '暂无') }}</dd></div>
|
||||
</dl>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="task" class="card history-card primary-list-card" aria-labelledby="run-history-title">
|
||||
<div class="card-head history-head">
|
||||
<div><h2 id="run-history-title">运行记录</h2><p>按入队时间从新到旧显示;错误内容已作安全处理。</p></div>
|
||||
<span class="muted-copy" aria-live="polite">{{ pollingLabel }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="historyLoading" class="load-wrap history-state" role="status" aria-live="polite">
|
||||
<span class="loader" aria-hidden="true"></span><span>正在加载运行记录…</span>
|
||||
</div>
|
||||
<div v-else-if="historyError" class="empty-state history-state" role="alert">
|
||||
<strong>运行记录加载失败</strong><span>{{ historyError }}</span>
|
||||
<button class="btn small" type="button" @click="loadHistory">重试</button>
|
||||
</div>
|
||||
<div v-else-if="!runs.length" class="empty-state history-state">
|
||||
<strong>暂无运行记录</strong><span>任务执行后,结果会显示在这里。</span>
|
||||
</div>
|
||||
<div v-else class="table-wrap history-table-wrap" tabindex="0" role="region" aria-label="自动任务运行记录">
|
||||
<table class="data-table history-table">
|
||||
<thead><tr><th>状态</th><th>触发方式</th><th>入队时间</th><th>执行时间</th><th>结果统计</th><th>结果</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="run in runs" :key="run.runId">
|
||||
<td data-label="状态"><span class="state-badge" :class="runTone(run.state)">{{ stateLabels[run.state] }}</span><small v-if="run.attempts > 1">第 {{ run.attempts }} 次尝试</small></td>
|
||||
<td data-label="触发方式">{{ triggerLabels[run.trigger] }}</td>
|
||||
<td data-label="入队时间"><time :datetime="run.queuedAt">{{ formatLocalDateTime(run.queuedAt) }}</time></td>
|
||||
<td data-label="执行时间"><span>{{ formatLocalDateTime(run.startedAt, '尚未开始') }}</span><small>{{ run.finishedAt ? `完成于 ${formatLocalDateTime(run.finishedAt)}` : '尚未结束' }}</small></td>
|
||||
<td data-label="结果统计"><span class="counts-summary">{{ countsSummary(run) }}</span></td>
|
||||
<td data-label="结果">
|
||||
<span>{{ run.complete ? (run.applied ? '已完成并生效' : '已完成,保留当前目录') : '尚未完成' }}</span>
|
||||
<details v-if="run.errorCode || run.errorMessage" class="error-detail">
|
||||
<summary>查看错误</summary><p>{{ safeError(run) }}</p>
|
||||
</details>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<AppListPagination
|
||||
v-if="!historyLoading && !historyError && historyTotal"
|
||||
v-model:page="historyPage"
|
||||
v-model:page-size="historyPageSize"
|
||||
:total="historyTotal"
|
||||
:disabled="historyLoading"
|
||||
:page-sizes="[10, 20, 50]"
|
||||
aria-label="运行记录分页"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<p class="sr-status" aria-live="polite" aria-atomic="true">{{ liveMessage }}</p>
|
||||
|
||||
<dialog ref="scheduleDialog" v-dialog-drag class="app-dialog schedule-dialog" aria-labelledby="schedule-dialog-title" aria-modal="true" @cancel="handleScheduleCancel" @click="handleScheduleBackdrop">
|
||||
<section class="app-dialog__panel">
|
||||
<header class="modal-head" data-dialog-drag-handle>
|
||||
<div><span class="eyebrow">SCHEDULE CONFIGURATION</span><h2 id="schedule-dialog-title">编辑自动计划</h2><p>{{ task?.name }}</p></div>
|
||||
<button class="modal-close" type="button" aria-label="关闭计划配置窗口" :disabled="scheduleSaving" @click="closeScheduleDialog"></button>
|
||||
</header>
|
||||
<div class="modal-body schedule-form">
|
||||
<div v-if="scheduleError" class="inline-alert danger" role="alert">{{ scheduleError }}</div>
|
||||
<label class="switch-row">
|
||||
<span><strong>启用自动执行</strong><small>停用后不会按计划发起新运行,手动执行不受影响。</small></span>
|
||||
<el-switch v-model="draftEnabled" :disabled="scheduleSaving" aria-label="启用自动执行" />
|
||||
</label>
|
||||
<fieldset :disabled="scheduleSaving">
|
||||
<legend>执行间隔</legend>
|
||||
<div class="interval-grid">
|
||||
<label v-for="hours in intervalOptions" :key="hours" :class="{ selected: draftInterval === hours }">
|
||||
<input v-model="draftInterval" type="radio" name="interval" :value="hours"><span>每 {{ hours }} 小时</span>
|
||||
</label>
|
||||
</div>
|
||||
</fieldset>
|
||||
<p class="form-hint">保存使用当前版本校验;如其他管理员已修改,将加载最新版本并保留本次选择。</p>
|
||||
</div>
|
||||
<footer class="modal-actions">
|
||||
<button class="btn" type="button" :disabled="scheduleSaving" @click="closeScheduleDialog">取消</button>
|
||||
<button class="btn primary" type="button" :disabled="scheduleSaving" :aria-busy="scheduleSaving" @click="saveSchedule">{{ scheduleSaving ? '保存中…' : '保存计划' }}</button>
|
||||
</footer>
|
||||
</section>
|
||||
</dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useUserStore } from '@/store/user'
|
||||
import {
|
||||
scheduledTasksApi,
|
||||
type ScheduledIntervalHours,
|
||||
type ScheduledTask,
|
||||
type ScheduledTaskRun,
|
||||
type ScheduledRunState,
|
||||
} from '@/api/scheduledTasks'
|
||||
|
||||
const DEFAULT_TASK_CODE = 'FEISHU_DIRECTORY_SYNC'
|
||||
withDefaults(defineProps<{ embedded?: boolean }>(), { embedded: false })
|
||||
const intervalOptions: ScheduledIntervalHours[] = [1, 2, 3, 6, 12, 24]
|
||||
const stateLabels = { QUEUED: '排队中', RUNNING: '运行中', SUCCEEDED: '成功', FAILED: '失败' } as const
|
||||
const triggerLabels = { MANUAL: '手动', STARTUP: '启动时', SCHEDULED: '自动计划' } as const
|
||||
const userStore = useUserStore()
|
||||
const canUpdate = computed(() => userStore.canEdit('system.scheduled-task.config.update'))
|
||||
const canExecute = computed(() => userStore.canEdit('system.scheduled-task.execute'))
|
||||
|
||||
const tasks = ref<ScheduledTask[]>([])
|
||||
const selectedCode = ref('')
|
||||
const task = ref<ScheduledTask | null>(null)
|
||||
const runs = ref<ScheduledTaskRun[]>([])
|
||||
const latestRuns = ref<ScheduledTaskRun[]>([])
|
||||
const historyPage = ref(1)
|
||||
const historyPageSize = ref(20)
|
||||
const historyTotal = ref(0)
|
||||
const initialLoading = ref(true)
|
||||
const refreshing = ref(false)
|
||||
const historyLoading = ref(false)
|
||||
const listError = ref('')
|
||||
const detailError = ref('')
|
||||
const historyError = ref('')
|
||||
const liveMessage = ref('')
|
||||
const executing = ref(false)
|
||||
const executeUncertain = ref(false)
|
||||
const executeNotice = ref('')
|
||||
const scheduleDialog = ref<HTMLDialogElement | null>(null)
|
||||
const scheduleSaving = ref(false)
|
||||
const scheduleError = ref('')
|
||||
const draftEnabled = ref(false)
|
||||
const draftInterval = ref<ScheduledIntervalHours>(24)
|
||||
const draftVersion = ref(0)
|
||||
let disposed = false
|
||||
let readController: AbortController | null = null
|
||||
let writeController: AbortController | null = null
|
||||
let pollTimer: ReturnType<typeof setTimeout> | undefined
|
||||
let activeSince = 0
|
||||
let executeSubmittedAt = 0
|
||||
let executeObservedActive = false
|
||||
let executeIdleConfirmations = 0
|
||||
let requestGeneration = 0
|
||||
|
||||
const orderedLatestRuns = computed(() => [...latestRuns.value].sort((a, b) => dateValue(b.queuedAt) - dateValue(a.queuedAt)))
|
||||
const latestRun = computed(() => orderedLatestRuns.value[0] || null)
|
||||
const lastSuccess = computed(() => orderedLatestRuns.value.find(item => item.state === 'SUCCEEDED') || null)
|
||||
const hasActiveRun = computed(() => orderedLatestRuns.value.some(item => item.state === 'QUEUED' || item.state === 'RUNNING'))
|
||||
const isActive = computed(() => task.value?.status === 'RUNNING' || hasActiveRun.value)
|
||||
const executeDisabled = computed(() => !canExecute.value || executing.value || executeUncertain.value || refreshing.value || isActive.value)
|
||||
const executeButtonLabel = computed(() => executing.value ? '提交中…' : executeUncertain.value ? '正在确认结果…' : isActive.value ? '任务运行中' : '立即运行')
|
||||
const pollingLabel = computed(() => document.visibilityState === 'hidden' ? '页面不可见,已暂停更新' : isActive.value || executeUncertain.value ? '运行期间自动更新' : '每 30 秒自动更新')
|
||||
|
||||
const dateValue = (value: unknown) => {
|
||||
const result = new Date(typeof value === 'string' || typeof value === 'number' ? value : '').getTime()
|
||||
return Number.isFinite(result) ? result : 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 intervalLabel = (hours: number) => `每 ${hours} 小时`
|
||||
const taskTone = (item: ScheduledTask) => item.status === 'RUNNING' ? 'running' : item.enabled ? 'success' : 'neutral'
|
||||
const runTone = (state: ScheduledRunState) => ({ QUEUED: 'queued', RUNNING: 'running', SUCCEEDED: 'success', FAILED: 'danger' }[state])
|
||||
const countsSummary = (run: ScheduledTaskRun) => {
|
||||
const count = run.counts || ({} as ScheduledTaskRun['counts'])
|
||||
return `部门 ${Number(count.departments) || 0} · 扫描 ${Number(count.usersSeen) || 0} · 符合 ${Number(count.eligible) || 0} · 排除 ${Number(count.excluded) || 0} · 新增 ${Number(count.created) || 0} · 更新 ${Number(count.updated) || 0} · 不符合 ${Number(count.ineligible) || 0} · 范围外 ${Number(count.outOfScope) || 0}`
|
||||
}
|
||||
const safeError = (run: ScheduledTaskRun) => {
|
||||
const raw = [run.errorCode, run.errorMessage].filter(Boolean).join(':').slice(0, 500)
|
||||
return (raw || '运行失败,暂无更多信息。')
|
||||
.replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi, '[已隐藏邮箱]')
|
||||
.replace(/(?:\+?86[- ]?)?1\d{10}\b/g, '[已隐藏号码]')
|
||||
.replace(/\b(?:token|secret|authorization|open[_-]?id|user[_-]?id)\s*[:=]\s*\S+/gi, '$1=[已隐藏]')
|
||||
}
|
||||
|
||||
const messageOf = (error: unknown, fallback: string) => error instanceof Error && error.message ? error.message : fallback
|
||||
const isConflict = (error: unknown) => Number((error as { response?: { status?: number } } | null)?.response?.status) === 409
|
||||
const normalizeRuns = (items: ScheduledTaskRun[] | undefined) => Array.isArray(items)
|
||||
? [...items].sort((a, b) => dateValue(b.queuedAt) - dateValue(a.queuedAt))
|
||||
: []
|
||||
|
||||
function applyTask(next: ScheduledTask) {
|
||||
task.value = next
|
||||
const index = tasks.value.findIndex(item => item.code === next.code)
|
||||
if (index >= 0) tasks.value[index] = next
|
||||
else tasks.value.push(next)
|
||||
}
|
||||
|
||||
function reconcileExecuteLock(active: boolean) {
|
||||
if (!executeUncertain.value) return
|
||||
if (active) {
|
||||
executeObservedActive = true
|
||||
executeIdleConfirmations = 0
|
||||
return
|
||||
}
|
||||
if (executeObservedActive) {
|
||||
executeUncertain.value = false
|
||||
executeNotice.value = '本次运行已结束,状态已从服务器更新。'
|
||||
return
|
||||
}
|
||||
if (Date.now() - executeSubmittedAt < 2_000) return
|
||||
executeIdleConfirmations += 1
|
||||
if (executeIdleConfirmations >= 2) {
|
||||
executeUncertain.value = false
|
||||
executeNotice.value = '服务器未发现进行中的运行,可以重新发起。'
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleNextPoll() {
|
||||
clearTimeout(pollTimer)
|
||||
if (disposed || document.visibilityState === 'hidden' || !selectedCode.value) return
|
||||
const active = isActive.value || executeUncertain.value
|
||||
if (active && !activeSince) activeSince = Date.now()
|
||||
if (!active) activeSince = 0
|
||||
const delay = active ? (Date.now() - activeSince < 30_000 ? 2_000 : 5_000) : 30_000
|
||||
pollTimer = setTimeout(() => void refreshSelected(true), delay)
|
||||
}
|
||||
|
||||
async function loadTasks() {
|
||||
if (disposed) return
|
||||
readController?.abort()
|
||||
const controller = new AbortController()
|
||||
readController = controller
|
||||
const generation = ++requestGeneration
|
||||
initialLoading.value = true
|
||||
listError.value = ''
|
||||
try {
|
||||
const result = await scheduledTasksApi.list(controller.signal)
|
||||
if (disposed || generation !== requestGeneration) return
|
||||
tasks.value = Array.isArray(result) ? result : []
|
||||
const preferred = tasks.value.find(item => item.code === DEFAULT_TASK_CODE) || tasks.value[0]
|
||||
selectedCode.value = preferred?.code || ''
|
||||
if (preferred) await refreshSelected(false, generation)
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted && !disposed) listError.value = messageOf(error, '请求失败,请稍后重试。')
|
||||
} finally {
|
||||
if (generation === requestGeneration) initialLoading.value = false
|
||||
scheduleNextPoll()
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshSelected(background = false, inheritedGeneration?: number) {
|
||||
if (disposed || !selectedCode.value || document.visibilityState === 'hidden') return
|
||||
const code = selectedCode.value
|
||||
readController?.abort()
|
||||
const controller = new AbortController()
|
||||
readController = controller
|
||||
const generation = inheritedGeneration ?? ++requestGeneration
|
||||
if (!background) refreshing.value = true
|
||||
if (!runs.value.length) historyLoading.value = true
|
||||
detailError.value = ''
|
||||
historyError.value = ''
|
||||
try {
|
||||
const pageRequest = scheduledTasksApi.runs(code, historyPage.value - 1, historyPageSize.value, controller.signal)
|
||||
const latestRequest = historyPage.value === 1 && historyPageSize.value === 50
|
||||
? pageRequest
|
||||
: scheduledTasksApi.runs(code, 0, 50, controller.signal)
|
||||
const [detailResult, pageResult, latestResult] = await Promise.allSettled([
|
||||
scheduledTasksApi.detail(code, controller.signal), pageRequest, latestRequest,
|
||||
])
|
||||
if (disposed || generation !== requestGeneration || code !== selectedCode.value) return
|
||||
if (detailResult.status === 'fulfilled') applyTask(detailResult.value)
|
||||
else detailError.value = messageOf(detailResult.reason, '任务详情请求失败,请稍后重试。')
|
||||
if (pageResult.status === 'fulfilled') {
|
||||
runs.value = normalizeRuns(pageResult.value.items)
|
||||
historyTotal.value = Math.max(0, Number(pageResult.value.total) || 0)
|
||||
} else historyError.value = messageOf(pageResult.reason, '运行记录请求失败,请稍后重试。')
|
||||
if (latestResult.status === 'fulfilled') latestRuns.value = normalizeRuns(latestResult.value.items)
|
||||
else if (pageResult.status === 'fulfilled' && historyPage.value === 1) latestRuns.value = normalizeRuns(pageResult.value.items)
|
||||
const confirmedActive = detailResult.status === 'fulfilled' && detailResult.value.status === 'RUNNING'
|
||||
|| latestResult.status === 'fulfilled' && latestRuns.value.some(item => item.state === 'QUEUED' || item.state === 'RUNNING')
|
||||
if (detailResult.status === 'fulfilled' || latestResult.status === 'fulfilled') reconcileExecuteLock(confirmedActive)
|
||||
if (detailResult.status === 'fulfilled' || pageResult.status === 'fulfilled') {
|
||||
liveMessage.value = `已更新${detailResult.status === 'fulfilled' ? detailResult.value.name : '自动任务'}的状态和运行记录。`
|
||||
}
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted && !disposed) {
|
||||
const message = messageOf(error, '请求失败,请稍后重试。')
|
||||
detailError.value = message
|
||||
historyError.value = message
|
||||
}
|
||||
} finally {
|
||||
if (generation === requestGeneration) {
|
||||
refreshing.value = false
|
||||
historyLoading.value = false
|
||||
scheduleNextPoll()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function loadHistory() {
|
||||
await refreshSelected(false)
|
||||
}
|
||||
|
||||
async function refreshAll() {
|
||||
if (initialLoading.value || refreshing.value) return
|
||||
await loadTasks()
|
||||
}
|
||||
|
||||
function selectTask(code: string) {
|
||||
if (code === selectedCode.value) return
|
||||
selectedCode.value = code
|
||||
task.value = tasks.value.find(item => item.code === code) || null
|
||||
runs.value = []
|
||||
latestRuns.value = []
|
||||
historyPage.value = 1
|
||||
historyTotal.value = 0
|
||||
executeUncertain.value = false
|
||||
executeNotice.value = ''
|
||||
void refreshSelected()
|
||||
}
|
||||
|
||||
function openScheduleDialog() {
|
||||
if (!task.value || !canUpdate.value || scheduleSaving.value) return
|
||||
draftEnabled.value = task.value.enabled
|
||||
draftInterval.value = task.value.intervalHours
|
||||
draftVersion.value = task.value.version
|
||||
scheduleError.value = ''
|
||||
scheduleDialog.value?.showModal()
|
||||
}
|
||||
|
||||
function closeScheduleDialog() {
|
||||
if (!scheduleSaving.value) scheduleDialog.value?.close()
|
||||
}
|
||||
|
||||
function handleScheduleCancel(event: Event) {
|
||||
if (scheduleSaving.value) event.preventDefault()
|
||||
}
|
||||
|
||||
function handleScheduleBackdrop(event: MouseEvent) {
|
||||
if (event.target !== event.currentTarget) return
|
||||
if (scheduleSaving.value) event.preventDefault()
|
||||
else closeScheduleDialog()
|
||||
}
|
||||
|
||||
async function saveSchedule() {
|
||||
if (!task.value || !canUpdate.value || scheduleSaving.value) return
|
||||
const code = task.value.code
|
||||
const intendedEnabled = draftEnabled.value
|
||||
const intendedInterval = draftInterval.value
|
||||
scheduleSaving.value = true
|
||||
scheduleError.value = ''
|
||||
writeController?.abort()
|
||||
const controller = new AbortController()
|
||||
writeController = controller
|
||||
try {
|
||||
const updated = await scheduledTasksApi.updateSchedule(code, { enabled: intendedEnabled, intervalHours: intendedInterval, version: draftVersion.value }, controller.signal)
|
||||
if (disposed) return
|
||||
applyTask(updated)
|
||||
scheduleDialog.value?.close()
|
||||
ElMessage.success('自动计划已保存')
|
||||
liveMessage.value = '自动计划已保存。'
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || disposed) return
|
||||
if (isConflict(error)) {
|
||||
try {
|
||||
const latest = await scheduledTasksApi.detail(code, controller.signal)
|
||||
if (disposed) return
|
||||
applyTask(latest)
|
||||
draftVersion.value = latest.version
|
||||
draftEnabled.value = intendedEnabled
|
||||
draftInterval.value = intendedInterval
|
||||
scheduleError.value = '计划已被其他管理员更新。已加载最新版本并保留你的选择,请确认后再次保存。'
|
||||
} catch (reloadError) {
|
||||
scheduleError.value = `计划版本冲突,且最新配置加载失败:${messageOf(reloadError, '请稍后重试。')}`
|
||||
}
|
||||
} else scheduleError.value = messageOf(error, '计划保存失败,请稍后重试。')
|
||||
} finally {
|
||||
scheduleSaving.value = false
|
||||
scheduleNextPoll()
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmExecute() {
|
||||
if (executeDisabled.value || !task.value) return
|
||||
executing.value = true
|
||||
try {
|
||||
await ElMessageBox.confirm(`确定立即运行“${task.value.name}”吗?`, '确认运行', { confirmButtonText: '立即运行', cancelButtonText: '取消', type: 'warning' })
|
||||
} catch {
|
||||
executing.value = false
|
||||
return
|
||||
}
|
||||
if (!task.value || executeUncertain.value || isActive.value) {
|
||||
executing.value = false
|
||||
return
|
||||
}
|
||||
const code = task.value.code
|
||||
executeUncertain.value = true
|
||||
executeSubmittedAt = Date.now()
|
||||
executeObservedActive = false
|
||||
executeIdleConfirmations = 0
|
||||
executeNotice.value = '运行请求已提交,正在向服务器确认结果,请勿重复操作。'
|
||||
writeController?.abort()
|
||||
const controller = new AbortController()
|
||||
writeController = controller
|
||||
try {
|
||||
const accepted = await scheduledTasksApi.execute(code, controller.signal)
|
||||
if (disposed) return
|
||||
latestRuns.value = normalizeRuns([accepted, ...latestRuns.value.filter(item => item.runId !== accepted.runId)])
|
||||
executeObservedActive = accepted.state === 'QUEUED' || accepted.state === 'RUNNING'
|
||||
if (!executeObservedActive) executeUncertain.value = false
|
||||
executeNotice.value = executeObservedActive ? '任务已受理,运行期间将自动更新。' : '运行已返回最终结果。'
|
||||
} catch (error) {
|
||||
if (!disposed && !controller.signal.aborted) executeNotice.value = '提交结果未确认(可能已被服务器受理),正在从服务器核对,请勿重复操作。'
|
||||
} finally {
|
||||
executing.value = false
|
||||
await refreshSelected(true)
|
||||
}
|
||||
}
|
||||
|
||||
function handleVisibilityChange() {
|
||||
clearTimeout(pollTimer)
|
||||
if (document.visibilityState === 'hidden') {
|
||||
readController?.abort()
|
||||
return
|
||||
}
|
||||
void refreshSelected(true)
|
||||
}
|
||||
|
||||
watch(historyPage, () => { if (!initialLoading.value) void loadHistory() })
|
||||
watch(historyPageSize, () => {
|
||||
if (historyPage.value !== 1) historyPage.value = 1
|
||||
else if (!initialLoading.value) void loadHistory()
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('visibilitychange', handleVisibilityChange)
|
||||
void loadTasks()
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
requestGeneration += 1
|
||||
clearTimeout(pollTimer)
|
||||
readController?.abort()
|
||||
writeController?.abort()
|
||||
document.removeEventListener('visibilitychange', handleVisibilityChange)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.scheduled-page { min-width: 0; }
|
||||
.scheduled-page.scheduled-embedded { height: 100%; min-height: 0; flex: 1 1 0; overflow: hidden; }
|
||||
.task-card, .history-card { min-width: 0; }
|
||||
.scheduled-embedded .task-card { flex: 0 0 auto; }
|
||||
.scheduled-embedded .history-card { min-height: 0; flex: 1 1 0; overflow: hidden; }
|
||||
.scheduled-embedded .history-card > .history-table-wrap { min-height: 0; max-height: none; flex: 1 1 auto; overflow: auto; }
|
||||
.task-head, .history-head, .detail-title-row { display: flex; align-items: flex-start; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
|
||||
.task-head > div, .history-head > div, .detail-title-row > div:first-child { min-width: 0; flex: 1 1 280px; }
|
||||
.task-head p, .detail-title-row p, .history-head p { overflow-wrap: anywhere; }
|
||||
.page-state { min-height: 180px; padding: 30px 18px; }
|
||||
.page-state .btn, .detail-state .btn, .history-state .btn { margin-top: 12px; }
|
||||
.task-layout { display: grid; grid-template-columns: minmax(210px, .34fr) minmax(0, 1fr); gap: 18px; padding: 0 22px 22px; }
|
||||
.task-list-warning { grid-column: 1 / -1; }
|
||||
.task-selector { display: grid; align-content: start; gap: 7px; }
|
||||
.task-option { width: 100%; padding: 12px; border: 1px solid var(--line); border-radius: var(--radius); background: #fff; color: var(--body); text-align: left; }
|
||||
.task-option:hover, .task-option.active { border-color: #a8c4df; background: var(--blue-soft); }
|
||||
.task-option-title { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.task-option strong { color: var(--text); font-size: 12px; overflow-wrap: anywhere; }
|
||||
.task-option small { display: block; margin-top: 4px; color: var(--muted); font-size: 10px; }
|
||||
.status-dot-small { width: 8px; height: 8px; flex: none; border-radius: 50%; background: var(--quiet); }
|
||||
.status-dot-small.success { background: var(--success); }
|
||||
.status-dot-small.running { background: var(--blue); box-shadow: 0 0 0 3px var(--blue-soft); }
|
||||
.task-detail { min-width: 0; padding: 16px; border: 1px solid var(--line); border-radius: var(--radius); background: var(--surface-raised); }
|
||||
.detail-state { min-height: 160px; }
|
||||
.detail-title-row h3 { font-size: 16px; }
|
||||
.detail-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||
.inline-note { margin: 12px 0 0; padding: 9px 11px; border-left: 3px solid var(--blue); background: var(--blue-soft); color: var(--body); font-size: 11px; }
|
||||
.task-summary { display: grid; grid-template-columns: repeat(3, minmax(145px, 1fr)); gap: 1px; margin-top: 16px; overflow: hidden; border: 1px solid var(--line); border-radius: 6px; background: var(--line); }
|
||||
.task-summary > div { min-width: 0; padding: 11px 12px; background: #fff; }
|
||||
.task-summary dt { color: var(--muted); font-size: 10px; }
|
||||
.task-summary dt span { color: var(--quiet); font-weight: 400; }
|
||||
.task-summary dd { margin-top: 3px; overflow-wrap: anywhere; color: var(--body); font-size: 12px; }
|
||||
.state-badge { display: inline-flex; align-items: center; min-height: 22px; padding: 2px 8px; border-radius: 99px; background: #eef1f4; color: var(--muted); font-size: 10px; font-weight: 700; white-space: nowrap; }
|
||||
.state-badge.success { background: var(--success-soft); color: var(--success); }
|
||||
.state-badge.danger { background: var(--danger-soft); color: var(--danger); }
|
||||
.state-badge.running, .state-badge.queued { background: var(--blue-soft); color: var(--blue-dark); }
|
||||
.history-card { display: flex; margin-top: 16px; flex-direction: column; }
|
||||
.history-state { min-height: 180px; padding: 30px 18px; }
|
||||
.history-table-wrap { margin: 0 18px; }
|
||||
.history-table { min-width: 920px; }
|
||||
.history-table td { vertical-align: top; }
|
||||
.history-table td > small, .history-table td > span:not(.state-badge) { display: block; }
|
||||
.history-table td > small { margin-top: 3px; color: var(--quiet); font-size: 10px; }
|
||||
.counts-summary { max-width: 300px; color: var(--body); line-height: 1.65; }
|
||||
.error-detail { margin-top: 5px; max-width: 260px; color: var(--danger); }
|
||||
.error-detail summary { cursor: pointer; font-size: 10px; }
|
||||
.error-detail p { margin-top: 4px; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
.schedule-dialog { width: min(560px, calc(100vw - 24px)); }
|
||||
.modal-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; padding: 19px var(--dialog-header-x); border-bottom: 1px solid var(--line); background: var(--surface-raised); }
|
||||
.modal-head h2 { margin-top: 3px; font-size: 19px; }
|
||||
.modal-head p { margin-top: 2px; color: var(--muted); font-size: 11px; }
|
||||
.schedule-form { display: grid; gap: 18px; padding: 20px var(--dialog-body-x); }
|
||||
.switch-row { display: flex; align-items: center; justify-content: space-between; gap: 18px; }
|
||||
.switch-row > span { min-width: 0; }
|
||||
.switch-row strong, .switch-row small { display: block; }
|
||||
.switch-row strong { font-size: 13px; }
|
||||
.switch-row small, .form-hint { margin-top: 3px; color: var(--muted); font-size: 11px; }
|
||||
.schedule-form fieldset { border: 0; }
|
||||
.schedule-form legend { margin-bottom: 8px; color: var(--body); font-size: 12px; font-weight: 700; }
|
||||
.interval-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
|
||||
.interval-grid label { position: relative; display: grid; min-height: 40px; place-items: center; border: 1px solid var(--line); border-radius: 6px; background: #fff; color: var(--body); cursor: pointer; }
|
||||
.interval-grid label.selected { border-color: var(--blue); background: var(--blue-soft); color: var(--blue-dark); font-weight: 700; }
|
||||
.interval-grid input { position: absolute; opacity: 0; pointer-events: none; }
|
||||
.interval-grid label:focus-within { outline: 3px solid #7eb4f2; outline-offset: 2px; }
|
||||
.sr-status { 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: 800px) {
|
||||
.task-layout { grid-template-columns: minmax(0, 1fr); }
|
||||
.task-selector { grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); }
|
||||
.task-summary { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 680px) {
|
||||
.task-layout { padding-right: 12px; padding-left: 12px; }
|
||||
.detail-actions { width: 100%; }
|
||||
.detail-actions .btn { flex: 1; }
|
||||
.task-summary { grid-template-columns: minmax(0, 1fr); }
|
||||
.history-table-wrap { margin: 0 12px; overflow: visible; }
|
||||
.history-table { min-width: 0; }
|
||||
.history-table thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0, 0, 0, 0); }
|
||||
.history-table, .history-table tbody, .history-table tr, .history-table td { display: block; width: 100%; }
|
||||
.history-table tr { margin-bottom: 10px; padding: 7px 12px; border: 1px solid var(--line); border-radius: var(--radius); background: #fff; }
|
||||
.history-table td { display: grid; grid-template-columns: 82px minmax(0, 1fr); gap: 9px; padding: 7px 0; border: 0; border-bottom: 1px solid var(--line); }
|
||||
.history-table td:last-child { border-bottom: 0; }
|
||||
.history-table td::before { content: attr(data-label); color: var(--muted); font-size: 10px; font-weight: 700; }
|
||||
.history-table td > * { grid-column: 2; }
|
||||
.history-table td::before { grid-column: 1; grid-row: 1 / span 3; }
|
||||
.counts-summary, .error-detail { max-width: none; }
|
||||
.interval-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
}
|
||||
</style>
|
||||
+17
-10
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="page-content">
|
||||
<div class="page-content route-list-page">
|
||||
<div class="page-head">
|
||||
<div>
|
||||
<span class="eyebrow">SOURCE DOCUMENTS</span>
|
||||
@@ -7,39 +7,46 @@
|
||||
<p>来自金蝶 ERP 的源单据,只读展示。</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card fill-list-card">
|
||||
<div class="card fill-list-card primary-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">
|
||||
<div class="table-wrap" v-if="loaded && !error && filtered.length > 0" tabindex="0" role="region" aria-label="业务单据列表"><table class="data-table responsive-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 v-for="item in paginatedItems" :key="item.id">
|
||||
<td data-label="单据编号"><strong>{{ item.sourceDocNo }}</strong></td>
|
||||
<td data-label="类型"><span class="tag">{{ item.sourceDocType }}</span></td>
|
||||
<td data-label="金额" class="amount">{{ fmt(item.amount) }}</td>
|
||||
<td data-label="日期"><small>{{ item.sourceDate }}</small></td>
|
||||
<td data-label="来源"><small>{{ item.sourceSystem }}</small></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
<div v-else-if="error" class="empty-state" role="alert"><strong>业务单据加载失败</strong><span>{{ error }}</span><button class="btn small" type="button" @click="load">重试</button></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>
|
||||
<AppListPagination v-if="loaded && !error && filtered.length" v-model:page="page" v-model:page-size="pageSize" :total="filtered.length" aria-label="业务单据列表分页" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from 'vue'
|
||||
import request from '@/api/request'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
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 error = ref('')
|
||||
const load = async () => { loaded.value = false; error.value = ''; try { items.value = await request.get('/sources') || [] } catch (e) { error.value = e instanceof Error ? e.message : '请求失败,请稍后重试。' } finally { loaded.value = true } }
|
||||
onMounted(load)
|
||||
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 { page, pageSize, paginatedItems } = useListPagination(filtered, { resetSources: [search] })
|
||||
const fmt = (v: number) => `¥ ${(v||0).toLocaleString('zh-CN',{minimumFractionDigits:2})}`
|
||||
</script>
|
||||
+331
-51
@@ -1,73 +1,353 @@
|
||||
<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>
|
||||
<div class="admin-page page-content route-list-page">
|
||||
<div class="page-head"><div><span class="eyebrow">SYSTEM MANAGEMENT</span><h1>人员与角色</h1><p>{{ pageDescription }}</p></div><div class="head-actions"><button v-if="activeTab==='roles' && canEdit('system.role.create')" class="btn primary" type="button" @click="openRoleForm()">新建角色</button><button v-if="activeTab==='groups' && canRead('page.groups') && canEdit('system.group.create')" class="btn primary" type="button" @click="openGroupForm()">新建用户组</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" role="tablist" aria-label="系统管理页面" @keydown="moveTab">
|
||||
<button v-for="tab in availableTabs" :id="`admin-tab-${tab.key}`" :key="tab.key" class="tab" :class="{active:activeTab===tab.key}" type="button" role="tab" :aria-selected="activeTab===tab.key" :tabindex="activeTab===tab.key?0:-1" @click="switchTab(tab.key)">{{ tab.label }}</button>
|
||||
</nav>
|
||||
<div v-else-if="!permissionsFailed" class="card empty-state" role="alert"><strong>无可访问管理页面</strong><span>请联系管理员配置用户组、角色或飞书通讯录页面权限。</span></div>
|
||||
|
||||
<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>
|
||||
<dialog ref="memberDialog" v-dialog-drag class="app-dialog admin-dialog member-dialog" aria-labelledby="member-dialog-title" @cancel="handleMemberDialogCancel"><form @submit.prevent="saveGroupMembers"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">GROUP MEMBERS</span><h2 id="member-dialog-title">绑定用户 · {{ memberGroup ? groupDisplayName(memberGroup) : '' }}</h2><p>维护用户组成员归属。</p></div><button class="modal-close" type="button" aria-label="关闭成员绑定窗口" :disabled="memberSaving" @click="closeMemberDialog">×</button></div><div class="modal-body binding-dialog-body">
|
||||
<div v-if="memberGroup?.status!=='ACTIVE'" class="inline-alert warning" role="status"><b>!</b><span>停用后成员仍占用该组归属,但本组角色不会生效。</span></div><p v-if="isDefaultGroup(memberGroup)" class="binding-note default-group-note"><strong>普通用户组</strong>:组织内所有飞书用户,无需绑定。该组固定置顶且只读。</p><p v-else-if="isSuperAdminGroup(memberGroup)" class="binding-note default-group-note"><strong>默认超级管理员组</strong>:可按现有权限维护成员;后台会确保至少保留一名超级管理员。</p><div v-if="blockedCandidateWarning" class="inline-alert warning blocked-candidate-warning" role="alert" aria-live="assertive"><b>!</b><span>{{ blockedCandidateWarning }}</span></div>
|
||||
<LoadState :loading="memberBindingLoading" :error="memberBindingError" label="成员绑定" @retry="reloadMemberDialog" /><template v-if="!memberBindingLoading&&!memberBindingError"><div v-if="!canViewMemberCandidates" class="member-list-restricted" role="note"><strong>{{ currentMemberIds.length }} 名成员</strong><span>需要成员管理或用户查看权限才能查看名单</span></div><template v-else><div v-if="snapshotAlert" class="inline-alert warning snapshot-alert" role="alert"><b>!</b><span>{{ snapshotAlert }}</span></div><label class="filter-search"><span class="sr-only">{{ candidateSearchLabel }}</span><input v-model="candidateKeyword" type="search" :placeholder="candidateSearchPlaceholder" autocomplete="off" :aria-label="candidateSearchLabel" :aria-controls="memberGroup ? `group-candidates-${memberGroup.id}` : undefined"></label><div class="candidate-state" aria-live="polite"><span v-if="candidateLoading" role="status">正在搜索候选人员…</span><span v-else-if="candidateError" class="candidate-error" role="alert">候选人员加载失败:{{ candidateError }} <button class="table-action" type="button" @click="loadCandidates(candidateKeyword)">重试</button></span><span v-else-if="candidateKeyword.trim()">找到 {{ candidateMatches.length }} 个匹配结果</span></div><div v-if="candidateTruncated&&!candidateLoading&&!candidateError" class="inline-alert warning truncation-notice" role="status"><span>结果较多,仅显示前 {{ candidateLimit }} 条,请缩小搜索范围。</span></div><div :id="memberGroup ? `group-candidates-${memberGroup.id}` : undefined" class="candidate-list" :aria-busy="candidateLoading"><div v-for="person in displayedCandidates" :key="person.id" class="candidate-row" :class="{disabled:memberCandidateDisabled(person)}"><label class="candidate-main"><input v-model="selectedMemberIds" type="checkbox" :value="person.id" :disabled="groupMembersDynamic||!groupMembersEditable||!canEdit('system.group.member.bind')||memberCandidateDisabled(person)"><span><strong>{{ memberDisplayName(person) }}</strong><small>{{ person.employeeNo||'无工号' }} · {{ departmentText(person) }}</small><small v-if="person.assignedGroupId!==null && person.assignedGroupId!==memberGroup?.id" class="assignment-note">不可选择,已属于:{{ person.assignedGroupName||'其他用户组' }}</small><small v-else-if="selectedMemberIds.includes(person.id) && !currentMembers.some(item=>item.id===person.id) && !candidateMatches.some(item=>item.id===person.id)" class="assignment-note selected-note">已选草稿(保留显示)</small></span></label><button v-if="memberCandidateDisabled(person)&&selectedMemberIds.includes(person.id)&&canEdit('system.group.member.bind')" class="table-action draft-remove" type="button" :aria-label="`从成员草稿移除 ${memberDisplayName(person)}`" @click="removeMemberDraft(person.id)">移出草稿</button></div><div v-if="showFreshEmpty" class="empty-state compact-empty" role="status"><span>{{ candidateKeyword.trim()?'没有匹配的飞书用户。':'当前没有可添加的飞书用户。' }}</span></div></div></template></template></div><div class="modal-actions"><button class="btn" type="button" :disabled="memberSaving" @click="closeMemberDialog">取消</button><button v-if="!isDefaultGroup(memberGroup)&&!groupMembersDynamic&&groupMembersEditable&&canEdit('system.group.member.bind')" class="btn primary" type="submit" :disabled="memberSaving||memberBindingLoading||!!memberBindingError||hasBlockedMemberDraft">{{ memberSaving?'保存中…':'保存成员' }}</button></div></form></dialog>
|
||||
|
||||
<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>
|
||||
<dialog ref="groupRoleDialog" v-dialog-drag class="app-dialog admin-dialog group-role-dialog" aria-labelledby="group-role-dialog-title" @cancel="handleGroupRoleDialogCancel"><form @submit.prevent="saveGroupRoles"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">GROUP ROLES</span><h2 id="group-role-dialog-title">绑定角色 · {{ roleGroup ? groupDisplayName(roleGroup) : '' }}</h2><p>为当前用户组选择统一生效的角色。</p></div><button class="modal-close" type="button" aria-label="关闭角色绑定窗口" :disabled="groupRoleSaving" @click="closeGroupRoleDialog">×</button></div><div class="modal-body binding-dialog-body"><p v-if="isDefaultGroup(roleGroup)" class="binding-note default-group-note"><strong>普通用户组</strong>:系统默认组固定角色,只读且不可修改。</p><div v-if="isDefaultGroup(roleGroup)" class="fixed-role"><span class="tag info">EMPLOYEE</span><div><strong>普通用户</strong><small>系统默认组固定角色,只读且不可修改。</small></div></div><LoadState :loading="roleBindingLoading" :error="groupRoleCandidateError" label="角色绑定" @retry="loadGroupRoleBinding" /><template v-if="!isDefaultGroup(roleGroup)&&!roleBindingLoading&&!groupRoleCandidateError"><p class="binding-note">可多选启用中的角色;已绑定后停用的角色仅可移除,移除后不可重新选择。</p><div v-if="!roles.length" class="empty-state compact-empty"><strong>暂无角色候选</strong><span>当前没有可绑定角色。</span></div><div class="role-options group-role-options"><label v-for="role in roles" :key="role.id" class="check-option" :class="{disabled:role.status!=='ACTIVE'&&!selectedGroupRoleIds.includes(role.id)}"><input v-model="selectedGroupRoleIds" type="checkbox" :value="role.id" :disabled="!canEdit('system.group.role.bind')||(role.status!=='ACTIVE'&&!selectedGroupRoleIds.includes(role.id))"><span><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}<template v-if="role.description"> · {{ role.description }}</template><template v-if="role.status!=='ACTIVE'"> · {{ selectedGroupRoleIds.includes(role.id)?'已停用,仅可移除':'已停用,不可绑定' }}</template></small></span></label></div></template></div><div class="modal-actions"><button class="btn" type="button" :disabled="groupRoleSaving" @click="closeGroupRoleDialog">取消</button><button v-if="!isDefaultGroup(roleGroup)&&canEdit('system.group.role.bind')" class="btn primary" type="submit" :disabled="groupRoleSaving||roleBindingLoading||!!groupRoleCandidateError">{{ groupRoleSaving?'保存中…':'保存角色' }}</button></div></form></dialog>
|
||||
|
||||
<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 v-if="activeTab==='groups' && canReadWorkspace" class="management-workspace route-list-region" role="tabpanel" aria-labelledby="admin-tab-groups">
|
||||
<div class="card admin-card primary-list-card"><div class="card-head"><div><h2>用户组</h2><p>分别维护成员归属与角色绑定。</p></div><span>{{ groups.length }} 个</span></div><LoadState :loading="groupsLoading" :error="groupsError" label="用户组" @retry="loadGroups" /><div v-if="!groupsLoading&&!groupsError&&groups.length" class="table-wrap" tabindex="0" role="region" aria-label="用户组列表"><table class="data-table responsive-table"><thead><tr><th>用户组</th><th>成员 / 角色</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="group in paginatedGroups" :key="group.id"><td data-label="用户组"><div class="group-name-line"><strong>{{ groupDisplayName(group) }}</strong><span v-if="isDefaultGroup(group)" class="tag info">普通用户组 · 无需绑定</span><span v-if="isSuperAdminGroup(group)" class="tag info">默认超级管理员组</span><span v-if="group.membershipMode==='DYNAMIC'" class="tag neutral">动态成员</span></div><small>{{ group.groupCode }}<template v-if="isDefaultGroup(group)"> · 组织内所有飞书用户</template></small></td><td data-label="成员 / 角色"><span :class="{'unresolved-count':group.memberCount===null}">{{ memberCountText(group.memberCount) }}</span> / {{ group.roleCount }}</td><td data-label="状态"><span class="tag" :class="group.status==='ACTIVE'?'success':'danger'">{{ group.status==='ACTIVE'?'启用':'停用' }}</span></td><td data-label="操作" class="actions-cell"><button class="table-action" type="button" aria-haspopup="dialog" :aria-label="`为${groupDisplayName(group)}绑定用户`" @click="openMemberDialog(group)">绑定用户</button><button class="table-action" type="button" aria-haspopup="dialog" :aria-label="`为${groupDisplayName(group)}绑定角色`" @click="openGroupRoleDialog(group)">绑定角色</button><button v-if="!isDefaultGroup(group) && canEdit('system.group.edit')" class="table-action" type="button" @click="openGroupForm(group)">编辑</button><button v-if="!isDefaultGroup(group) && canEdit('system.group.delete')" class="table-action danger-action" type="button" @click="deleteGroup(group)">删除</button></td></tr></tbody></table></div><div v-else-if="!groupsLoading&&!groupsError" class="empty-state"><strong>暂无用户组</strong></div><AppListPagination v-if="!groupsLoading&&!groupsError&&groups.length" v-model:page="groupPage" v-model:page-size="groupPageSize" :total="groups.length" aria-label="用户组列表分页" /></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>
|
||||
<section v-if="activeTab==='roles' && canRead('page.roles')" class="card admin-card primary-list-card" role="tabpanel" aria-labelledby="admin-tab-roles">
|
||||
<div class="card-head"><div><h2>角色列表</h2><p>角色资料与权限配置分别受控。</p></div><span>{{ roles.length }} 个</span></div><LoadState :loading="rolesLoading" :error="rolesError" label="角色" @retry="loadRoles" />
|
||||
<div v-if="!rolesLoading && !rolesError && roles.length" class="table-wrap"><table class="data-table responsive-table"><thead><tr><th>角色</th><th>说明</th><th>状态</th><th>权限</th><th>操作</th></tr></thead><tbody><tr v-for="role in paginatedRoles" :key="role.id"><td data-label="角色"><strong>{{ role.roleName }}</strong><small>{{ role.roleCode }}</small></td><td data-label="说明">{{ role.description||'-' }}</td><td data-label="状态"><span class="tag" :class="role.status==='ACTIVE'?'success':'danger'">{{ role.status==='ACTIVE'?'启用':'停用' }}</span></td><td data-label="权限">{{ role.permissionCount??0 }}</td><td data-label="操作" class="actions-cell"><button v-if="canEdit('system.role.edit') || canEdit('system.role.permission.configure')" class="table-action" type="button" @click="openRoleForm(role)">编辑 / 配权</button><button v-if="!role.builtIn && canEdit('system.role.delete')" class="table-action danger-action" type="button" @click="deleteRole(role)">删除</button></td></tr></tbody></table></div><div v-else-if="!rolesLoading&&!rolesError" class="empty-state"><strong>暂无角色</strong></div><AppListPagination v-if="!rolesLoading&&!rolesError&&roles.length" v-model:page="rolePage" v-model:page-size="rolePageSize" :total="roles.length" aria-label="角色列表分页" />
|
||||
</section>
|
||||
|
||||
<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>
|
||||
<section v-if="activeTab==='directory' && canRead('page.feishu-directory')" class="directory-tab-panel route-list-region" role="tabpanel" aria-labelledby="admin-tab-directory">
|
||||
<FeishuDirectory embedded />
|
||||
</section>
|
||||
|
||||
<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>
|
||||
<dialog ref="roleDialog" v-dialog-drag class="app-dialog admin-dialog wide-dialog" aria-labelledby="role-title" @cancel="handleRoleDialogCancel"><form @submit.prevent="saveRole"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">ROLE CONFIGURATION</span><h2 id="role-title">{{ editingRole?'编辑角色':'新建角色' }}</h2><p>维护角色身份与细粒度授权。权限保存后立即生效,加载异常时不会以空权限覆盖。</p></div><button class="modal-close" type="button" aria-label="关闭角色配置窗口" :disabled="roleSaving" @click="closeRoleDialog">×</button></div><div class="modal-body role-dialog-body"><section class="role-basic-section" aria-labelledby="role-basic-title"><div class="dialog-section-head"><div><span class="section-index">01</span><h3 id="role-basic-title">基础信息</h3></div><p>用于识别角色及说明适用范围</p></div><div class="form-grid role-basic-grid"><div class="field"><label for="role-code">角色编码 <em>*</em></label><input id="role-code" v-model.trim="roleForm.roleCode" required :disabled="roleSaving||!!editingRole||!canEdit(editingRole?'system.role.edit':'system.role.create')"></div><div class="field"><label for="role-name">角色名称 <em>*</em></label><input id="role-name" v-model.trim="roleForm.roleName" required :disabled="roleSaving||!canEdit(editingRole?'system.role.edit':'system.role.create')"></div><div class="field full"><label for="role-description">角色说明</label><textarea id="role-description" v-model.trim="roleForm.description" rows="2" :disabled="roleSaving||!canEdit(editingRole?'system.role.edit':'system.role.create')"></textarea></div></div></section><section class="role-permission-section" aria-labelledby="role-permission-section-title"><div class="dialog-section-head permission-section-head"><div><span class="section-index">02</span><h3 id="role-permission-section-title">权限范围</h3></div><p>菜单、操作与字段权限分别配置</p></div><div v-if="rolePermissionLoading" class="load-wrap modal-state" role="status"><span class="loader"></span><span>正在加载权限目录与角色权限…</span></div><div v-else-if="rolePermissionError" class="inline-alert danger permission-alert" role="alert"><span>{{ rolePermissionError }}</span><button class="btn small" type="button" @click="loadRolePermissionData">重试</button></div><RolePermissionEditor v-else-if="canEdit('system.role.permission.configure')" v-model="permissionDraft" :catalog="roleCatalog" /></section></div><div class="modal-actions"><button class="btn" type="button" :disabled="roleSaving" @click="closeRoleDialog">取消</button><button class="btn primary" type="submit" :disabled="roleSaving||rolePermissionLoading||!!rolePermissionError||!canSaveRole">{{ roleSaving?'保存中…':'保存角色' }}</button></div></form></dialog>
|
||||
|
||||
<dialog ref="groupDialog" v-dialog-drag class="app-dialog admin-dialog" aria-labelledby="group-title" @cancel="handleGroupDialogCancel"><form @submit.prevent="saveGroup"><div class="modal-head" data-dialog-drag-handle><div><span class="eyebrow">USER GROUP</span><h2 id="group-title">{{ editingGroup?'编辑用户组':'新建用户组' }}</h2><p>维护用户组基础资料,成员与角色绑定可在保存后单独配置。</p></div><button class="modal-close" type="button" aria-label="关闭用户组窗口" :disabled="groupSaving" @click="closeGroupDialog">×</button></div><div class="modal-body"><div class="form-grid group-form-grid"><div class="field"><label for="group-code">组编码 <em>*</em></label><input id="group-code" v-model.trim="groupForm.groupCode" required :disabled="groupSaving||!!editingGroup"></div><div class="field"><label for="group-name">名称 <em>*</em></label><input id="group-name" v-model.trim="groupForm.groupName" required :disabled="groupSaving"></div><div class="field"><label for="group-status">状态</label><select id="group-status" v-model="groupForm.status" class="select" :disabled="groupSaving||isDefaultGroup(editingGroup)"><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" :disabled="groupSaving"></textarea></div><div v-if="isDefaultGroup(editingGroup)" class="inline-alert warning full" role="status"><span>系统默认组的编码和状态不可修改。</span></div><div v-else-if="editingGroup&&groupForm.status==='INACTIVE'" class="inline-alert warning full" role="status"><span>停用后成员仍占用该组归属,但本组角色不会生效。</span></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">{{ groupSaving?'保存中…':'保存用户组' }}</button></div></form></dialog>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, defineComponent, h, nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
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 { adminApi, type DirectoryIdentity, type GroupCandidate, type GroupMemberCandidates, type PermissionAccess, type PermissionItem, type Role, type UserGroup } from '@/api/admin'
|
||||
import { hasUnsavedRoleDraft, hydrateRolePermissions, serializeRolePermissions, validatePermissionCatalog } from '@/composables/permissionEditor'
|
||||
import { candidateDisabled, directoryIdentityKey, directoryIdentityPayload, isDefaultGroup, isSuperAdminGroup, localMemberKey, memberCountText, sortUserGroups } from '@/composables/userGroupPolicy'
|
||||
import RolePermissionEditor from '@/components/admin/permissions/RolePermissionEditor.vue'
|
||||
import FeishuDirectory from '@/views/FeishuDirectory.vue'
|
||||
import AppListPagination from '@/components/common/AppListPagination.vue'
|
||||
import { useListPagination } from '@/composables/useListPagination'
|
||||
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)}`) } }
|
||||
type Tab='groups'|'roles'|'directory'
|
||||
const LoadState=defineComponent({props:{loading:Boolean,error:String,label:String},emits:['retry'],setup(p,{emit}){return()=>p.loading?h('div',{class:'load-wrap',role:'status'},`正在加载${p.label}…`):p.error?h('div',{class:'empty-state',role:'alert'},[h('strong',`${p.label}加载失败`),h('span',p.error),h('button',{class:'btn small',onClick:()=>emit('retry')},'重试')]):null}})
|
||||
const userStore=useUserStore(); const canRead=userStore.canRead; const canEdit=userStore.canEdit
|
||||
const route=useRoute(); const router=useRouter()
|
||||
const canReadWorkspace=computed(()=>canRead('page.groups'))
|
||||
const tabs:{key:Tab;label:string;permissions:string[]}[]=[{key:'groups',label:'用户组管理',permissions:['page.groups']},{key:'roles',label:'角色管理',permissions:['page.roles']},{key:'directory',label:'飞书通讯录',permissions:['page.feishu-directory']}]
|
||||
const availableTabs=computed(()=>tabs.filter(tab=>tab.permissions.some(canRead))); const activeTab=ref<Tab>('groups'); const permissionsFailed=computed(()=>Boolean(userStore.permissionsError))
|
||||
const pageDescription=computed(()=>activeTab.value==='directory'?'查看已同步的飞书组织架构与员工资料,并维护通讯录同步状态。':activeTab.value==='roles'?'维护角色资料与细粒度权限配置。':'通过用户组管理成员归属,并为用户组统一绑定角色权限。')
|
||||
const roles=ref<Role[]>([]),groups=ref<UserGroup[]>([]); const rolesLoading=ref(false),groupsLoading=ref(false),rolesLoaded=ref(false); const rolesError=ref(''),groupsError=ref('')
|
||||
const {page:groupPage,pageSize:groupPageSize,paginatedItems:paginatedGroups}=useListPagination(groups)
|
||||
const {page:rolePage,pageSize:rolePageSize,paginatedItems:paginatedRoles}=useListPagination(roles)
|
||||
const canLoadRoleCandidates=computed(()=>canRead('page.roles')||canEdit('system.group.role.bind')||canRead('page.groups'))
|
||||
const canViewMemberCandidates=computed(()=>canEdit('system.group.member.bind')||canRead('page.users'))
|
||||
const candidateSearchPlaceholder=computed(()=>canEdit('system.group.member.bind')?'搜索已同步飞书通讯录:姓名、User ID、Open ID、手机号、工号或部门':'搜索已同步飞书通讯录:姓名、工号或部门')
|
||||
const candidateSearchLabel=computed(()=>canEdit('system.group.member.bind')?'搜索已同步的飞书通讯录,可按姓名、User ID、Open ID、手机号、工号或部门查询':'搜索已同步的飞书通讯录,可按姓名、工号或部门查询')
|
||||
let roleLoadPromise:Promise<boolean>|null=null
|
||||
const errorText=(error:unknown)=>{const responseMessage=(error as {response?:{data?:{message?:unknown}}})?.response?.data?.message;return typeof responseMessage==='string'&&responseMessage?responseMessage:error instanceof Error&&error.message?error.message:'请求失败,请稍后重试。'}
|
||||
const loadRoles=async()=>{if(!canLoadRoleCandidates.value)return false;if(roleLoadPromise)return roleLoadPromise;rolesLoading.value=true;rolesError.value='';const current=(async()=>{try{roles.value=await adminApi.listRoles()||[];rolesLoaded.value=true;return true}catch(e){rolesLoaded.value=false;rolesError.value=errorText(e);ElMessage.error(`角色候选加载失败:${rolesError.value}`);return false}finally{rolesLoading.value=false}})();roleLoadPromise=current;try{return await current}finally{if(roleLoadPromise===current)roleLoadPromise=null}}; const loadGroups=async()=>{await loadList(groups,groupsLoading,groupsError,adminApi.listGroups,'用户组');if(!groupsError.value)groups.value=sortUserGroups(groups.value)}
|
||||
async function loadList<T>(target:{value:T[]},loading:{value:boolean},error:{value:string},loader:()=>Promise<T[]>,label:string){loading.value=true;error.value='';try{target.value=await loader()||[]}catch(e){error.value=errorText(e);ElMessage.error(`${label}加载失败:${error.value}`)}finally{loading.value=false}}
|
||||
const syncTabQuery=(tab:Tab)=>{if(String(route.query.tab||'')===tab)return;void router.replace({query:{...route.query,tab}})}
|
||||
const activateTab=(tab:Tab)=>{activeTab.value=tab;if(tab==='groups'&&!groups.value.length)void loadGroups();if(tab==='roles'&&!rolesLoaded.value)void loadRoles()}
|
||||
const switchTab=(tab:Tab)=>{if(!availableTabs.value.some(item=>item.key===tab))return;activateTab(tab);syncTabQuery(tab)}
|
||||
const moveTab=(event:KeyboardEvent)=>{if(!['ArrowLeft','ArrowRight','Home','End'].includes(event.key))return;event.preventDefault();const current=availableTabs.value.findIndex(t=>t.key===activeTab.value);const next=event.key==='Home'?0:event.key==='End'?availableTabs.value.length-1:(current+(event.key==='ArrowRight'?1:-1)+availableTabs.value.length)%availableTabs.value.length;switchTab(availableTabs.value[next].key);nextTick(()=>document.getElementById(`admin-tab-${activeTab.value}`)?.focus())}
|
||||
const resolveTab=(candidate:unknown):Tab|null=>{const key=String(candidate||'').trim() as Tab;return availableTabs.value.some(item=>item.key===key)?key:null}
|
||||
const loadInitial=async()=>{const tab=resolveTab(route.query.tab)||availableTabs.value[0]?.key;if(!tab)return;activeTab.value=tab;syncTabQuery(tab);if(tab==='groups')await loadGroups();else if(tab==='roles')await loadRoles()}
|
||||
const retryPermissions=async()=>{try{await userStore.loadPermissions(true);await loadInitial()}catch(e){ElMessage.error(errorText(e))}}
|
||||
watch(()=>route.query.tab,tab=>{const next=resolveTab(tab);if(next&&next!==activeTab.value)activateTab(next)})
|
||||
onMounted(async()=>{try{await userStore.loadPermissions();await loadInitial()}catch(e){ElMessage.error(errorText(e))}})
|
||||
|
||||
const groupDisplayName=(group:UserGroup)=>isDefaultGroup(group)?'普通用户组':isSuperAdminGroup(group)?'超级管理员组':group.groupName
|
||||
type MemberCandidateOption=Omit<GroupCandidate,'id'>&{id:string;localUserId:number|null}
|
||||
const memberDisplayName=(person:MemberCandidateOption)=>person.localUserId===userStore.userInfo?.id?'我(我的账号)':person.realName
|
||||
const show=async(dialog:HTMLDialogElement|null)=>{await nextTick();if(dialog&&!dialog.open)dialog.showModal()}; const closeDialog=(dialog:HTMLDialogElement|null)=>dialog?.close()
|
||||
|
||||
const roleDialog=ref<HTMLDialogElement|null>(null),editingRole=ref<Role|null>(null),roleSaving=ref(false),rolePermissionLoading=ref(false),rolePermissionError=ref(''),roleCatalog=ref<PermissionItem[]>([]),permissionDraft=ref<Record<string,PermissionAccess>>({})
|
||||
const roleForm=reactive({roleCode:'',roleName:'',description:'',status:'ACTIVE' as string}); const canSaveRole=computed(()=>canEdit(editingRole.value?'system.role.edit':'system.role.create')||(Boolean(editingRole.value)&&canEdit('system.role.permission.configure')))
|
||||
const roleFormBaseline=ref(''), permissionBaseline=ref(''), roleDiscardPending=ref(false)
|
||||
const roleHasUnsavedChanges=computed(()=>hasUnsavedRoleDraft(roleForm,permissionDraft.value,roleFormBaseline.value,permissionBaseline.value))
|
||||
const snapshotRoleBaseline=()=>{roleFormBaseline.value=JSON.stringify(roleForm);permissionBaseline.value=JSON.stringify(permissionDraft.value)}
|
||||
let rolePermissionGeneration=0
|
||||
const currentRoleId=()=>editingRole.value?.id??null
|
||||
const openRoleForm=async(role?:Role)=>{if(roleSaving.value)return;rolePermissionGeneration++;editingRole.value=role||null;Object.assign(roleForm,{roleCode:role?.roleCode||'',roleName:role?.roleName||'',description:role?.description||'',status:role?.status||'ACTIVE'});permissionDraft.value={};rolePermissionError.value='';snapshotRoleBaseline();await show(roleDialog.value);await loadRolePermissionData()}
|
||||
const loadRolePermissionData=async()=>{const generation=++rolePermissionGeneration;const targetRoleId=currentRoleId();rolePermissionLoading.value=true;rolePermissionError.value='';try{const [catalog,current]=await Promise.all([adminApi.listPermissions(),targetRoleId!==null?adminApi.getRolePermissions(targetRoleId):Promise.resolve({permissionCodes:[],fieldPermissions:{},permissionAccess:{}})]);if(generation!==rolePermissionGeneration||currentRoleId()!==targetRoleId)return;if(!Array.isArray(catalog))throw new Error('权限目录响应无效');const catalogError=validatePermissionCatalog(catalog);if(catalogError)throw new Error(catalogError);const next=hydrateRolePermissions(current);catalog.forEach(item=>{if(!(item.code in next))next[item.code]='HIDDEN'});roleCatalog.value=catalog;permissionDraft.value=next;snapshotRoleBaseline()}catch(e){if(generation!==rolePermissionGeneration||currentRoleId()!==targetRoleId)return;rolePermissionError.value=errorText(e);ElMessage.error(`权限配置加载失败:${rolePermissionError.value}`)}finally{if(generation===rolePermissionGeneration&¤tRoleId()===targetRoleId)rolePermissionLoading.value=false}}
|
||||
const finishCloseRoleDialog=()=>{rolePermissionGeneration++;rolePermissionLoading.value=false;rolePermissionError.value='';closeDialog(roleDialog.value);editingRole.value=null;permissionDraft.value={};roleCatalog.value=[];roleFormBaseline.value='';permissionBaseline.value=''}
|
||||
const closeRoleDialog=async()=>{if(roleSaving.value||roleDiscardPending.value)return;if(roleHasUnsavedChanges.value){roleDiscardPending.value=true;try{await ElMessageBox.confirm('角色资料或权限草稿尚未保存,确定放弃本次修改吗?','确认放弃修改',{type:'warning',confirmButtonText:'放弃修改',cancelButtonText:'继续编辑'});finishCloseRoleDialog()}catch{}finally{roleDiscardPending.value=false}}else finishCloseRoleDialog()}
|
||||
const handleRoleDialogCancel=(event:Event)=>{event.preventDefault();void closeRoleDialog()}
|
||||
const saveRole=async()=>{
|
||||
if(roleSaving.value||!canSaveRole.value||rolePermissionLoading.value||rolePermissionError.value||validatePermissionCatalog(roleCatalog.value)||!roleForm.roleCode||!roleForm.roleName)return
|
||||
const targetRole=editingRole.value
|
||||
const targetGeneration=rolePermissionGeneration
|
||||
const formSnapshot={...roleForm}
|
||||
const permissionSnapshot=serializeRolePermissions({...permissionDraft.value},[...roleCatalog.value])
|
||||
const mayEditRole=canEdit(targetRole?'system.role.edit':'system.role.create')
|
||||
const mayConfigurePermissions=canEdit('system.role.permission.configure')
|
||||
roleSaving.value=true
|
||||
let completedRoleId:number|null=null
|
||||
try{
|
||||
let saved=targetRole
|
||||
if(mayEditRole){saved=targetRole?await adminApi.updateRole(targetRole.id,formSnapshot):await adminApi.createRole(formSnapshot);if(saved){Object.assign(roleForm,{roleCode:saved.roleCode,roleName:saved.roleName,description:saved.description||'',status:saved.status});roleFormBaseline.value=JSON.stringify(roleForm)}}
|
||||
if(!saved?.id)throw new Error('角色保存响应无效')
|
||||
if(!targetRole)editingRole.value=saved
|
||||
if(mayConfigurePermissions){
|
||||
try{await adminApi.updateRolePermissions(saved.id,{...permissionSnapshot,expectedPermissionAccess:JSON.parse(permissionBaseline.value||'{}')})}catch(e){await loadRoles();ElMessage.error(targetRole?`权限保存失败:${errorText(e)}`:`角色已创建,但权限保存失败:${errorText(e)}。权限草稿已保留,请重试。`);return}
|
||||
}
|
||||
await loadRoles()
|
||||
ElMessage.success(mayConfigurePermissions?(mayEditRole?'角色和权限已保存':'角色权限已保存'):(targetRole?'角色资料已保存':'角色已创建'))
|
||||
snapshotRoleBaseline()
|
||||
completedRoleId=saved.id
|
||||
}catch(e){
|
||||
ElMessage.error(`角色资料保存失败:${errorText(e)}`)
|
||||
}finally{
|
||||
roleSaving.value=false
|
||||
if(completedRoleId!==null&&targetGeneration===rolePermissionGeneration&¤tRoleId()===completedRoleId)closeRoleDialog()
|
||||
}
|
||||
}
|
||||
const deleteRole=async(role:Role)=>{if(!canEdit('system.role.delete'))return;try{await ElMessageBox.confirm(`确定删除角色“${role.roleName}”吗?`,'确认删除',{type:'warning'});await adminApi.deleteRole(role.id);roles.value=roles.value.filter(r=>r.id!==role.id)}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(errorText(e))}}
|
||||
|
||||
const groupDialog=ref<HTMLDialogElement|null>(null),editingGroup=ref<UserGroup|null>(null),groupSaving=ref(false),groupForm=reactive({groupCode:'',groupName:'',description:'',status:'ACTIVE' as string})
|
||||
const closeGroupDialog=()=>{if(groupSaving.value)return;closeDialog(groupDialog.value)}
|
||||
const handleGroupDialogCancel=(event:Event)=>{event.preventDefault();if(!groupSaving.value)closeGroupDialog()}
|
||||
const openGroupForm=async(group?:UserGroup)=>{if(groupSaving.value||isDefaultGroup(group))return;const code=group?'system.group.edit':'system.group.create';if(!canEdit(code))return;editingGroup.value=group||null;Object.assign(groupForm,{groupCode:group?.groupCode||'',groupName:group?.groupName||'',description:group?.description||'',status:group?.status||'ACTIVE'});await show(groupDialog.value)}
|
||||
const saveGroup=async()=>{const targetGroup=editingGroup.value;const code=targetGroup?'system.group.edit':'system.group.create';if(groupSaving.value||isDefaultGroup(targetGroup)||!canEdit(code))return;if(targetGroup&&targetGroup.status==='ACTIVE'&&groupForm.status==='INACTIVE'){try{await ElMessageBox.confirm('停用后成员仍占用该组归属,但本组角色不会生效。确定继续吗?','确认停用用户组',{type:'warning'})}catch(e){if(e==='cancel'||e==='close')return;throw e}}const payload={...groupForm};groupSaving.value=true;let savedSuccessfully=false;try{const saved=targetGroup?await adminApi.updateGroup(targetGroup.id,payload):await adminApi.createGroup(payload);if(targetGroup)Object.assign(targetGroup,saved);else groups.value=sortUserGroups([...groups.value,saved]);await loadGroups();savedSuccessfully=true;ElMessage.success('用户组已保存')}catch(e){ElMessage.error(errorText(e))}finally{groupSaving.value=false;if(savedSuccessfully)closeGroupDialog()}}
|
||||
const memberDialog=ref<HTMLDialogElement|null>(null),groupRoleDialog=ref<HTMLDialogElement|null>(null)
|
||||
const memberGroup=ref<UserGroup|null>(null),roleGroup=ref<UserGroup|null>(null)
|
||||
const memberBindingLoading=ref(false),memberBindingError=ref(''),candidateLoading=ref(false),candidateError=ref(''),candidateKeyword=ref('')
|
||||
const currentMembers=ref<MemberCandidateOption[]>([]),candidateMatches=ref<MemberCandidateOption[]>([]),candidateHistory=ref<MemberCandidateOption[]>([])
|
||||
const selectedMemberIds=ref<string[]>([]),currentMemberIds=ref<string[]>([]),memberBaselineIds=ref<number[]>([])
|
||||
const validDirectoryKeys=ref(new Set<string>())
|
||||
const activeDirectoryRevision=ref<string|null>(null)
|
||||
const directoryRevisionObserved=ref(false)
|
||||
const groupMembersDynamic=ref(false),groupMembersEditable=ref(false),membershipSnapshotState=ref<string>('UNAVAILABLE')
|
||||
const memberAdditionsAllowed=ref(false)
|
||||
const candidateLimit=ref(0),candidateTruncated=ref(false),blockedMatchesPresent=ref(false),memberSaving=ref(false)
|
||||
const roleBindingLoading=ref(false),roleBindingError=ref(''),selectedGroupRoleIds=ref<number[]>([]),roleBaselineIds=ref<number[]>([]),groupRoleSaving=ref(false)
|
||||
let memberGeneration=0,roleBindingGeneration=0,candidateSearchGeneration=0
|
||||
let candidateSearchTimer:ReturnType<typeof setTimeout>|undefined
|
||||
let candidateWatchSuppressed=false
|
||||
type DialogControl=HTMLButtonElement|HTMLInputElement|HTMLSelectElement|HTMLTextAreaElement
|
||||
const memberDisabledState=new WeakMap<DialogControl,boolean>(),roleDisabledState=new WeakMap<DialogControl,boolean>()
|
||||
const lockDialogControls=(dialog:HTMLDialogElement|null,locked:boolean,previous:WeakMap<DialogControl,boolean>)=>{const form=dialog?.querySelector('form');if(!form)return;form.toggleAttribute('inert',locked);form.classList.toggle('binding-save-locked',locked);form.setAttribute('aria-busy',String(locked));form.querySelectorAll<DialogControl>('button,input,select,textarea').forEach(control=>{if(locked){if(!previous.has(control))previous.set(control,control.disabled);control.disabled=true}else if(previous.has(control)){control.disabled=previous.get(control)??false;previous.delete(control)}})}
|
||||
watch(memberSaving,locked=>void nextTick(()=>lockDialogControls(memberDialog.value,locked,memberDisabledState)),{flush:'sync'})
|
||||
watch(groupRoleSaving,locked=>void nextTick(()=>lockDialogControls(groupRoleDialog.value,locked,roleDisabledState)),{flush:'sync'})
|
||||
const sameIds=(left:number[],right:number[])=>left.length===right.length&&[...left].sort((a,b)=>a-b).every((id,index)=>id===[...right].sort((a,b)=>a-b)[index])
|
||||
const sameKeys=(left:string[],right:string[])=>left.length===right.length&&[...left].sort().every((key,index)=>key===[...right].sort()[index])
|
||||
const baselineMemberKeys=computed(()=>memberBaselineIds.value.map(localMemberKey))
|
||||
const memberBindingDirty=computed(()=>!sameKeys(selectedMemberIds.value,baselineMemberKeys.value))
|
||||
const roleBindingDirty=computed(()=>!sameIds(selectedGroupRoleIds.value,roleBaselineIds.value))
|
||||
const displayedCandidates=computed(()=>{const byKey=new Map<string,MemberCandidateOption>();currentMembers.value.forEach(person=>byKey.set(person.id,person));candidateHistory.value.filter(person=>selectedMemberIds.value.includes(person.id)).forEach(person=>{if(!byKey.has(person.id))byKey.set(person.id,person)});candidateMatches.value.forEach(person=>{if(!byKey.has(person.id))byKey.set(person.id,person)});return [...byKey.values()]})
|
||||
const snapshotAlert=computed(()=>{
|
||||
if(memberAdditionsAllowed.value){
|
||||
if(membershipSnapshotState.value==='STALE')return '服务返回旧版 STALE 状态;当前目录仍可用于添加用户,建议同步更新资料。'
|
||||
if(membershipSnapshotState.value==='CONTEXT_CHANGED')return '飞书组织上下文已变化,仅作为诊断提示;当前目录仍可用于添加用户。'
|
||||
return ''
|
||||
}
|
||||
return ({NEVER_SYNCED:'通讯录尚未同步,请先同步飞书通讯录后再添加用户;仍可移除现有成员。',STALE:'服务返回旧版 STALE 状态且未确认当前目录可用,暂不可添加用户;仍可移除现有成员。',CONTEXT_CHANGED:'飞书组织上下文已变化且未确认当前目录可用,暂不可添加用户;仍可移除现有成员。',UNAVAILABLE:'当前目录不可用,请检查集成配置或稍后重试;仍可移除现有成员。'}[membershipSnapshotState.value]||'')
|
||||
})
|
||||
const blockedCandidateWarning=computed(()=>!candidateKeyword.value.trim()||candidateLoading.value||candidateError.value||candidateMatches.value.length>0||!blockedMatchesPresent.value?'':'飞书目录中有匹配人员未在结果中返回,请确认成员绑定权限和当前目录状态后重试。')
|
||||
const showFreshEmpty=computed(()=>memberAdditionsAllowed.value&&!candidateLoading.value&&!candidateError.value&&candidateMatches.value.length===0&&!blockedMatchesPresent.value)
|
||||
const memberCandidateDisabled=(person:MemberCandidateOption)=>currentMemberIds.value.includes(person.id)?false:!memberAdditionsAllowed.value||!person.directoryIdentity||!validDirectoryKeys.value.has(person.id)||Boolean(memberGroup.value&&candidateDisabled({...person,id:person.localUserId},memberGroup.value.id))
|
||||
const hasBlockedMemberDraft=computed(()=>selectedMemberIds.value.some(key=>!currentMemberIds.value.includes(key)&&(!candidateHistory.value.find(person=>person.id===key)||memberCandidateDisabled(candidateHistory.value.find(person=>person.id===key)!))))
|
||||
const departmentText=(person:MemberCandidateOption)=>person.departmentNames?.length?person.departmentNames.join('、'):person.departmentName||'未分配部门'
|
||||
const groupRoleCandidateError=computed(()=>isDefaultGroup(roleGroup.value)?'':roleBindingError.value||rolesError.value||(!roleBindingLoading.value&&selectedGroupRoleIds.value.length>0&&roles.value.length===0?'当前用户组已有角色,但角色候选为空,禁止保存以避免清空现有绑定。':''))
|
||||
const confirmDiscard=async(kind:'成员'|'角色',dirty:boolean)=>{if(!dirty)return true;try{await ElMessageBox.confirm(`${kind}绑定尚未保存,确定放弃这些更改吗?`,'放弃未保存更改',{type:'warning'});return true}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(errorText(e));return false}}
|
||||
const candidateOption=(person:GroupCandidate,currentIds:ReadonlySet<number>):MemberCandidateOption=>{const id=person.id!==null&¤tIds.has(person.id)?localMemberKey(person.id):person.directoryIdentity?directoryIdentityKey(person.directoryIdentity):person.id!==null?`readonly-local:${person.id}`:`readonly-directory:${JSON.stringify([person.realName,person.employeeNo??'',person.departmentNames??[]])}`;return {...person,id,localUserId:person.id}}
|
||||
const rememberCandidates=(people:MemberCandidateOption[])=>{const history=new Map(candidateHistory.value.map(person=>[person.id,person]));people.forEach(person=>history.set(person.id,person));candidateHistory.value=[...history.values()]}
|
||||
const additionsAllowedFor=(result:GroupMemberCandidates)=>typeof result.additionsAllowed==='boolean'?result.additionsAllowed:result.availabilityState!==undefined&&result.availabilityState!==null?result.availabilityState==='AVAILABLE':result.snapshotState==='FRESH'
|
||||
const revisionFor=(result:GroupMemberCandidates,people:MemberCandidateOption[])=>{
|
||||
if(result.currentRevision!==undefined)return typeof result.currentRevision==='string'&&result.currentRevision.trim()?result.currentRevision.trim():null
|
||||
const revisions=new Set(people.flatMap(person=>person.directoryIdentity?[person.directoryIdentity.generationId]:[]))
|
||||
return revisions.size===1?[...revisions][0]:null
|
||||
}
|
||||
const loadGroupMemberBinding=async(preserveDraft=false)=>{const target=memberGroup.value;if(!target)return;const generation=memberGeneration;const draft=[...selectedMemberIds.value];memberBindingLoading.value=true;memberBindingError.value='';try{const members=await adminApi.getGroupMembers(target.id);if(generation!==memberGeneration||memberGroup.value?.id!==target.id)return;if(!members||!Array.isArray(members.userIds))throw new Error('成员绑定响应无效');currentMemberIds.value=members.userIds.map(localMemberKey);memberBaselineIds.value=[...members.userIds];selectedMemberIds.value=preserveDraft?draft.filter(key=>key.startsWith('directory:')||currentMemberIds.value.includes(key)):[...currentMemberIds.value];groupMembersDynamic.value=members.dynamic;groupMembersEditable.value=members.editable}catch(e){if(generation===memberGeneration&&memberGroup.value?.id===target.id)memberBindingError.value=errorText(e)}finally{if(generation===memberGeneration&&memberGroup.value?.id===target.id)memberBindingLoading.value=false}}
|
||||
const loadCandidates=async(query=candidateKeyword.value)=>{
|
||||
const target=memberGroup.value
|
||||
if(!target||!canViewMemberCandidates.value)return
|
||||
const dialogGeneration=memberGeneration
|
||||
const searchGeneration=++candidateSearchGeneration
|
||||
candidateLoading.value=true
|
||||
candidateError.value=''
|
||||
blockedMatchesPresent.value=false
|
||||
try{
|
||||
const result=await adminApi.searchGroupMemberCandidates(target.id,query.trim())
|
||||
if(dialogGeneration!==memberGeneration||searchGeneration!==candidateSearchGeneration||memberGroup.value?.id!==target.id)return
|
||||
if(!result||!Array.isArray(result.currentMembers)||!Array.isArray(result.matches))throw new Error('候选人员响应无效')
|
||||
const currentIds=new Set(result.currentMembers.flatMap(person=>person.id===null?[]:[person.id]))
|
||||
currentMembers.value=result.currentMembers.map(person=>candidateOption(person,currentIds))
|
||||
candidateMatches.value=result.matches.map(person=>candidateOption(person,currentIds))
|
||||
blockedMatchesPresent.value=Boolean(result.blockedMatchesPresent)
|
||||
membershipSnapshotState.value=result.snapshotState
|
||||
memberAdditionsAllowed.value=additionsAllowedFor(result)
|
||||
candidateLimit.value=result.limit
|
||||
candidateTruncated.value=result.truncated
|
||||
const received=[...currentMembers.value,...candidateMatches.value]
|
||||
const responseRevision=revisionFor(result,received)
|
||||
const revisionObserved=result.currentRevision!==undefined||responseRevision!==null
|
||||
if(revisionObserved&&directoryRevisionObserved.value&&responseRevision!==activeDirectoryRevision.value)validDirectoryKeys.value=new Set()
|
||||
activeDirectoryRevision.value=responseRevision
|
||||
directoryRevisionObserved.value=revisionObserved
|
||||
if(memberAdditionsAllowed.value)received.forEach(person=>{if(person.directoryIdentity)validDirectoryKeys.value.add(person.id)})
|
||||
rememberCandidates(received)
|
||||
}catch(e){
|
||||
if(dialogGeneration===memberGeneration&&searchGeneration===candidateSearchGeneration&&memberGroup.value?.id===target.id)candidateError.value=errorText(e)
|
||||
}finally{
|
||||
if(dialogGeneration===memberGeneration&&searchGeneration===candidateSearchGeneration&&memberGroup.value?.id===target.id)candidateLoading.value=false
|
||||
}
|
||||
}
|
||||
const reloadMemberDialog=async()=>{await Promise.all([loadGroupMemberBinding(true),loadCandidates(candidateKeyword.value)])}
|
||||
const resetMemberDialog=()=>{memberGeneration++;candidateSearchGeneration++;if(candidateSearchTimer)clearTimeout(candidateSearchTimer);candidateSearchTimer=undefined;memberGroup.value=null;memberBindingLoading.value=false;memberBindingError.value='';candidateLoading.value=false;candidateError.value='';candidateWatchSuppressed=true;candidateKeyword.value='';candidateWatchSuppressed=false;currentMembers.value=[];candidateMatches.value=[];candidateHistory.value=[];selectedMemberIds.value=[];currentMemberIds.value=[];memberBaselineIds.value=[];validDirectoryKeys.value=new Set();activeDirectoryRevision.value=null;directoryRevisionObserved.value=false;memberAdditionsAllowed.value=false;candidateTruncated.value=false;candidateLimit.value=0;blockedMatchesPresent.value=false;membershipSnapshotState.value='UNAVAILABLE'}
|
||||
const openMemberDialog=async(group:UserGroup)=>{if(memberSaving.value)return;memberGeneration++;candidateSearchGeneration++;memberGroup.value=group;candidateWatchSuppressed=true;candidateKeyword.value='';candidateWatchSuppressed=false;groupMembersDynamic.value=group.membershipMode==='DYNAMIC';groupMembersEditable.value=false;currentMembers.value=[];candidateMatches.value=[];candidateHistory.value=[];selectedMemberIds.value=[];currentMemberIds.value=[];memberBaselineIds.value=[];validDirectoryKeys.value=new Set();activeDirectoryRevision.value=null;directoryRevisionObserved.value=false;memberAdditionsAllowed.value=false;blockedMatchesPresent.value=false;await show(memberDialog.value);await Promise.all([loadGroupMemberBinding(),loadCandidates('')])}
|
||||
const closeMemberDialog=async()=>{if(memberSaving.value||!await confirmDiscard('成员',memberBindingDirty.value))return;closeDialog(memberDialog.value);resetMemberDialog()}
|
||||
const handleMemberDialogCancel=(event:Event)=>{event.preventDefault();if(!memberSaving.value)void closeMemberDialog()}
|
||||
const loadGroupRoleBinding=async(preserveDraft=false)=>{const target=roleGroup.value;if(!target||isDefaultGroup(target)){roleBindingLoading.value=false;roleBindingError.value='';selectedGroupRoleIds.value=[];roleBaselineIds.value=[];return}const generation=roleBindingGeneration;const draft=[...selectedGroupRoleIds.value];roleBindingLoading.value=true;roleBindingError.value='';try{const [assigned,ready]=await Promise.all([adminApi.getGroupRoles(target.id),rolesLoaded.value?Promise.resolve(true):loadRoles()]);if(generation!==roleBindingGeneration||roleGroup.value?.id!==target.id)return;if(!assigned||!Array.isArray(assigned.roleIds))throw new Error('角色绑定响应无效');selectedGroupRoleIds.value=preserveDraft?draft:[...assigned.roleIds];roleBaselineIds.value=[...assigned.roleIds];if(!ready)roleBindingError.value=rolesError.value||'角色候选加载失败'}catch(e){if(generation===roleBindingGeneration&&roleGroup.value?.id===target.id)roleBindingError.value=errorText(e)}finally{if(generation===roleBindingGeneration&&roleGroup.value?.id===target.id)roleBindingLoading.value=false}}
|
||||
const openGroupRoleDialog=async(group:UserGroup)=>{if(groupRoleSaving.value)return;roleBindingGeneration++;roleGroup.value=group;selectedGroupRoleIds.value=[];roleBaselineIds.value=[];await show(groupRoleDialog.value);await loadGroupRoleBinding()}
|
||||
const closeGroupRoleDialog=async()=>{if(groupRoleSaving.value||!await confirmDiscard('角色',roleBindingDirty.value))return;roleBindingGeneration++;closeDialog(groupRoleDialog.value);roleGroup.value=null;selectedGroupRoleIds.value=[];roleBaselineIds.value=[];roleBindingError.value='';roleBindingLoading.value=false}
|
||||
const handleGroupRoleDialogCancel=(event:Event)=>{event.preventDefault();if(!groupRoleSaving.value)void closeGroupRoleDialog()}
|
||||
watch(candidateKeyword,()=>{if(candidateWatchSuppressed||memberSaving.value||!memberGroup.value||!canViewMemberCandidates.value)return;candidateSearchGeneration++;candidateError.value='';blockedMatchesPresent.value=false;if(candidateSearchTimer)clearTimeout(candidateSearchTimer);candidateSearchTimer=setTimeout(()=>void loadCandidates(candidateKeyword.value),300)},{flush:'sync'})
|
||||
onBeforeUnmount(()=>{memberGeneration++;roleBindingGeneration++;candidateSearchGeneration++;if(candidateSearchTimer)clearTimeout(candidateSearchTimer)})
|
||||
const isConflict=(error:unknown)=>(error as {response?:{status?:number}})?.response?.status===409
|
||||
const removeMemberDraft=(selectionKey:string)=>{if(memberSaving.value)return;selectedMemberIds.value=selectedMemberIds.value.filter(key=>key!==selectionKey)}
|
||||
const refreshMembersAfterConflict=async(targetId:number,targetGeneration:number)=>{
|
||||
const identities=selectedMemberIds.value.flatMap(key=>{const identity=candidateHistory.value.find(person=>person.id===key)?.directoryIdentity;return identity?[identity]:[]})
|
||||
validDirectoryKeys.value=new Set()
|
||||
activeDirectoryRevision.value=null
|
||||
directoryRevisionObserved.value=false
|
||||
await Promise.all([loadGroupMemberBinding(true),loadCandidates(candidateKeyword.value)])
|
||||
if(memberGroup.value?.id!==targetId||memberGeneration!==targetGeneration)return
|
||||
const revision=activeDirectoryRevision.value
|
||||
const checks=await Promise.allSettled(identities.map(identity=>adminApi.searchGroupMemberCandidates(targetId,identity.openId)))
|
||||
if(memberGroup.value?.id!==targetId||memberGeneration!==targetGeneration)return
|
||||
const validated=new Set(validDirectoryKeys.value)
|
||||
const refreshed:MemberCandidateOption[]=[]
|
||||
checks.forEach((check,index)=>{
|
||||
if(check.status!=='fulfilled'||!additionsAllowedFor(check.value))return
|
||||
const people=[...check.value.currentMembers,...check.value.matches]
|
||||
const currentIds=new Set(check.value.currentMembers.flatMap(person=>person.id===null?[]:[person.id]))
|
||||
const options=people.map(person=>candidateOption(person,currentIds))
|
||||
const checkedRevision=revisionFor(check.value,options)
|
||||
if(revision&&checkedRevision!==revision)return
|
||||
const expectedKey=directoryIdentityKey(identities[index])
|
||||
options.forEach(person=>{if(person.id===expectedKey){validated.add(person.id);refreshed.push(person)}})
|
||||
})
|
||||
validDirectoryKeys.value=validated
|
||||
rememberCandidates(refreshed)
|
||||
selectedMemberIds.value=selectedMemberIds.value.filter(key=>currentMemberIds.value.includes(key)||validated.has(key))
|
||||
}
|
||||
const saveGroupMembers=async()=>{if(memberSaving.value)return;const target=memberGroup.value;if(!target||isDefaultGroup(target)||groupMembersDynamic.value||!groupMembersEditable.value||!canEdit('system.group.member.bind')||memberBindingLoading.value||memberBindingError.value||hasBlockedMemberDraft.value)return;const targetGroup=target,targetId=target.id,targetGeneration=memberGeneration;const selectedKeysSnapshot=[...selectedMemberIds.value],expectedUserIdsSnapshot=[...memberBaselineIds.value];const userIdsSnapshot=expectedUserIdsSnapshot.filter(id=>selectedKeysSnapshot.includes(localMemberKey(id)));const directoryIdentitiesSnapshot=selectedKeysSnapshot.flatMap(key=>{if(currentMemberIds.value.includes(key))return [];const identity=candidateHistory.value.find(person=>person.id===key)?.directoryIdentity;return identity?[directoryIdentityPayload(identity)]:[]}) as DirectoryIdentity[];memberSaving.value=true;try{const result=await adminApi.updateGroupMembers(targetId,{userIds:userIdsSnapshot,directoryIdentities:directoryIdentitiesSnapshot,expectedUserIds:expectedUserIdsSnapshot});if(!result||!Array.isArray(result.userIds))throw new Error('成员绑定响应无效');targetGroup.memberCount=result.userIds.length;if(memberGroup.value?.id===targetId&&memberGeneration===targetGeneration){memberBaselineIds.value=[...result.userIds];currentMemberIds.value=result.userIds.map(localMemberKey);selectedMemberIds.value=[...currentMemberIds.value];validDirectoryKeys.value=new Set();await loadCandidates(candidateKeyword.value)}ElMessage.success('成员绑定已保存')}catch(e){ElMessage.error(errorText(e));if(isConflict(e)&&memberGroup.value?.id===targetId&&memberGeneration===targetGeneration)await refreshMembersAfterConflict(targetId,targetGeneration)}finally{memberSaving.value=false}}
|
||||
const saveGroupRoles=async()=>{if(groupRoleSaving.value)return;const target=roleGroup.value;if(!target||isDefaultGroup(target)||!canEdit('system.group.role.bind')||roleBindingLoading.value||groupRoleCandidateError.value)return;const targetGroup=target,targetId=target.id,targetGeneration=roleBindingGeneration;const roleIdsSnapshot=[...selectedGroupRoleIds.value],expectedRoleIdsSnapshot=[...roleBaselineIds.value];groupRoleSaving.value=true;try{await adminApi.updateGroupRoles(targetId,{roleIds:roleIdsSnapshot,expectedRoleIds:expectedRoleIdsSnapshot});targetGroup.roleCount=roleIdsSnapshot.length;if(roleGroup.value?.id===targetId&&roleBindingGeneration===targetGeneration)roleBaselineIds.value=[...roleIdsSnapshot];ElMessage.success('角色绑定已保存')}catch(e){ElMessage.error(errorText(e));if(isConflict(e)&&roleGroup.value?.id===targetId&&roleBindingGeneration===targetGeneration)await loadGroupRoleBinding(true)}finally{groupRoleSaving.value=false}}
|
||||
const deleteGroup=async(group:UserGroup)=>{if(memberSaving.value||groupRoleSaving.value||isDefaultGroup(group)||!canEdit('system.group.delete'))return;try{await ElMessageBox.confirm(`确定删除用户组“${group.groupName}”吗?`,'确认删除',{type:'warning'});await adminApi.deleteGroup(group.id);groups.value=groups.value.filter(g=>g.id!==group.id)}catch(e){if(e!=='cancel'&&e!=='close')ElMessage.error(errorText(e))}}
|
||||
</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); }
|
||||
.directory-tab-panel {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
flex: 1 1 0;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.directory-tab-panel :deep(.directory-page) {
|
||||
height: 100%;
|
||||
flex: 1 1 auto;
|
||||
max-height: 100%;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
.admin-card { min-width: 0; }
|
||||
.management-workspace { display: grid; min-width: 0; flex: 1 1 auto; gap: 16px; }
|
||||
.actions-cell { min-width: 210px; }
|
||||
.danger-action { color: var(--danger); }
|
||||
.member-dialog { width: min(760px, calc(100vw - 24px)); max-width: calc(100vw - 24px); }
|
||||
.group-role-dialog { width: min(620px, calc(100vw - 24px)); max-width: calc(100vw - 24px); }
|
||||
.binding-dialog-body { max-height: calc(100dvh - 164px); overflow: auto; }
|
||||
.snapshot-alert, .truncation-notice { margin-bottom: 10px; }
|
||||
.blocked-candidate-warning { margin-bottom: 10px; }
|
||||
.binding-section { padding: 14px; }
|
||||
.binding-section + .binding-section { border-top: 1px solid var(--line); }
|
||||
.candidate-list { max-height: 330px; overflow: auto; }
|
||||
.candidate-state { min-height: 28px; padding: 6px 2px; color: var(--muted); font-size: 11px; }
|
||||
.candidate-error { color: var(--danger); }
|
||||
.candidate-row, .check-option { display: flex; align-items: center; gap: 10px; padding: 10px; }
|
||||
.candidate-row { border-bottom: 1px solid var(--line); }
|
||||
.candidate-row.disabled { background: #f6f8fa; color: var(--muted); cursor: not-allowed; }
|
||||
.candidate-main { display: flex; min-width: 0; flex: 1; align-items: center; gap: 10px; }
|
||||
.candidate-row span, .candidate-row small, .check-option span, .check-option small, .check-option strong { display: block; min-width: 0; }
|
||||
.candidate-row input, .check-option input { width: 16px; height: 16px; flex: none; accent-color: var(--blue); }
|
||||
.binding-actions { display: flex; justify-content: flex-end; padding-top: 10px; }
|
||||
.draft-remove { flex: none; }
|
||||
.member-list-restricted { display: grid; gap: 4px; padding: 14px; border: 1px dashed var(--line); border-radius: 6px; background: #f8fafc; }
|
||||
.member-list-restricted strong { color: var(--navy); font-size: 12px; }
|
||||
.member-list-restricted span { color: var(--muted); font-size: 11px; }
|
||||
.group-name-line { display: flex; min-width: 0; align-items: center; flex-wrap: wrap; gap: 6px; }
|
||||
.group-name-line .tag { margin: 0; }
|
||||
.unresolved-count, .assignment-note { color: var(--warning) !important; font-weight: 700; }
|
||||
.selected-note { color: var(--blue) !important; }
|
||||
.binding-note { margin: 0 0 10px; color: var(--muted); font-size: 11px; line-height: 1.6; }
|
||||
.default-group-note { padding: 9px 10px; border-left: 3px solid var(--blue); background: var(--blue-soft); }
|
||||
.group-warning { margin: 12px 14px 0; }
|
||||
.fixed-role { display: flex; align-items: center; gap: 12px; padding: 12px; border: 1px solid #b8cee4; border-radius: 6px; background: var(--blue-soft); }
|
||||
.fixed-role strong, .fixed-role small { display: block; }
|
||||
.fixed-role small { margin-top: 3px; color: var(--muted); font-size: 10px; }
|
||||
.group-role-options { grid-template-columns: 1fr; }
|
||||
.wide-dialog { width: min(1180px, calc(100vw - 24px)); max-width: calc(100vw - 24px); }
|
||||
.wide-dialog .modal-body { max-height: calc(100dvh - 164px); overflow: auto; }
|
||||
.role-option-body { padding: 16px; }
|
||||
.role-options { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 9px; }
|
||||
.check-option { min-width: 0; min-height: 62px; align-items: flex-start; border: 1px solid var(--line); border-radius: 6px; background: #fff; cursor: pointer; transition: border-color .15s ease, background-color .15s ease; }
|
||||
.check-option:hover { border-color: #b8cee4; background: #f8fbff; }
|
||||
.check-option:has(input:checked) { border-color: #9bbde2; background: var(--blue-soft); }
|
||||
.check-option.disabled { border-color: var(--line); background: #f6f8fa; cursor: not-allowed; }
|
||||
.check-option.disabled strong, .check-option.disabled small { color: var(--muted); }
|
||||
.check-option strong { color: var(--text); font-size: 12px; }
|
||||
.check-option small { margin-top: 2px; color: var(--muted); font-size: 10px; overflow-wrap: anywhere; }
|
||||
.modal-state { min-height: 180px; }
|
||||
.role-dialog-body { padding: 18px; background: #f6f8fa; }
|
||||
.role-basic-section, .role-permission-section { overflow: hidden; border: 1px solid var(--line); border-radius: 7px; background: #fff; }
|
||||
.role-permission-section { margin-top: 14px; }
|
||||
.dialog-section-head { display: flex; min-width: 0; align-items: center; justify-content: space-between; gap: 14px; padding: 12px 16px; border-bottom: 1px solid var(--line); background: var(--surface-raised); }
|
||||
.dialog-section-head > div { display: flex; min-width: 0; align-items: center; gap: 9px; }
|
||||
.dialog-section-head h3 { color: var(--navy); font-size: 13px; }
|
||||
.dialog-section-head p { color: var(--muted); font-size: 11px; text-align: right; }
|
||||
.section-index { color: var(--blue); font: 700 10px var(--mono); letter-spacing: .04em; }
|
||||
.role-basic-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 13px 16px; padding: 16px; }
|
||||
.role-basic-grid textarea { min-height: 66px; }
|
||||
.permission-alert { margin: 16px; }
|
||||
.group-form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 0; }
|
||||
@media (max-width: 900px) {
|
||||
.member-dialog, .group-role-dialog { width: calc(100vw - 18px); max-width: calc(100vw - 18px); }
|
||||
.wide-dialog { width: calc(100vw - 18px); max-width: calc(100vw - 18px); }
|
||||
}
|
||||
@media (max-width: 560px) {
|
||||
.candidate-ids { flex-basis: 100%; padding-left: 26px; text-align: left; }
|
||||
.binding-dialog-body { padding: 11px; }
|
||||
.candidate-row { align-items: flex-start; flex-wrap: wrap; padding: 10px 4px; }
|
||||
.candidate-main { align-items: flex-start; }
|
||||
.draft-remove { margin-left: 26px; }
|
||||
.actions-cell { min-width: 0; }
|
||||
.actions-cell .table-action { min-height: 36px; }
|
||||
.role-options, .role-basic-grid, .group-form-grid { grid-template-columns: 1fr; }
|
||||
.role-dialog-body { padding: 10px; }
|
||||
.dialog-section-head { align-items: flex-start; flex-direction: column; gap: 3px; padding: 11px 13px; }
|
||||
.dialog-section-head p { padding-left: 28px; text-align: left; }
|
||||
.role-basic-grid { padding: 13px; }
|
||||
.modal-actions { flex-direction: column-reverse; }
|
||||
.modal-actions .btn { width: 100%; min-height: 44px; }
|
||||
}
|
||||
</style>
|
||||