初始化
This commit is contained in:
commit
3a4e81a070
43 files changed
+10871
No files matched your search
@@ -0,0 +1,12 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
|
||||
export const useAppStore = defineStore('app', () => {
|
||||
const sidebarCollapsed = ref(false)
|
||||
const loading = ref(false)
|
||||
const notifications = ref(3)
|
||||
|
||||
const toggleSidebar = () => { sidebarCollapsed.value = !sidebarCollapsed.value }
|
||||
|
||||
return { sidebarCollapsed, loading, notifications, toggleSidebar }
|
||||
})
|
||||
@@ -0,0 +1,251 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref, computed } from 'vue'
|
||||
import { authApi, type UserProfile } from '@/api/auth'
|
||||
import request from '@/api/request'
|
||||
import {
|
||||
AUTH_DAY_KEY,
|
||||
DEMO_SESSION_TOKEN,
|
||||
TOKEN_KEY,
|
||||
USER_INFO_KEY,
|
||||
clearStoredSession,
|
||||
getBusinessDay,
|
||||
saveAuthDay,
|
||||
} from '@/utils/dailyAuth'
|
||||
|
||||
const readStoredUser = (): UserProfile | null => {
|
||||
try {
|
||||
const value = localStorage.getItem(USER_INFO_KEY)
|
||||
return value ? JSON.parse(value) as UserProfile : null
|
||||
} catch {
|
||||
localStorage.removeItem(USER_INFO_KEY)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const FEISHU_OAUTH_ATTEMPT_KEY = 'feishuOAuthAttempt'
|
||||
|
||||
const randomAttemptId = () => {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
|
||||
return `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
}
|
||||
|
||||
export const useUserStore = defineStore('user', () => {
|
||||
const token = ref(localStorage.getItem(TOKEN_KEY) || '')
|
||||
const userInfo = ref<UserProfile | null>(readStoredUser())
|
||||
const permissionCodes = ref<string[]>([])
|
||||
const fieldPermissions = ref<Record<string, 'HIDDEN' | 'READ' | 'EDIT'>>({})
|
||||
const permissionsLoaded = ref(false)
|
||||
const permissionsError = ref('')
|
||||
let permissionRequest: Promise<void> | null = null
|
||||
let sessionVersion = 0
|
||||
|
||||
const isLoggedIn = computed(() => !!token.value)
|
||||
const isFinance = computed(() => ['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(userInfo.value?.userType || ''))
|
||||
|
||||
const isValidUser = (user: unknown): user is UserProfile => {
|
||||
if (!user || typeof user !== 'object') return false
|
||||
const candidate = user as Partial<UserProfile>
|
||||
return Boolean(candidate.id && candidate.realName && candidate.userType)
|
||||
}
|
||||
|
||||
// Keep the marker behind the verified identity. This is the only operation
|
||||
// that turns a token/user pair into an authenticated session for today.
|
||||
const completeLogin = (jwt: string, user: UserProfile) => {
|
||||
if (!jwt || !isValidUser(user)) throw new Error('登录响应缺少有效身份信息')
|
||||
sessionVersion += 1
|
||||
token.value = jwt
|
||||
userInfo.value = user
|
||||
localStorage.setItem(TOKEN_KEY, jwt)
|
||||
localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))
|
||||
saveAuthDay()
|
||||
}
|
||||
|
||||
const beginFeishuLogin = () => {
|
||||
const attempt = randomAttemptId()
|
||||
sessionStorage.setItem(FEISHU_OAUTH_ATTEMPT_KEY, attempt)
|
||||
localStorage.setItem(FEISHU_OAUTH_ATTEMPT_KEY, attempt)
|
||||
return attempt
|
||||
}
|
||||
|
||||
const isCurrentFeishuLogin = (attempt: string | null | undefined) => {
|
||||
return Boolean(attempt)
|
||||
&& sessionStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt
|
||||
&& localStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt
|
||||
}
|
||||
|
||||
const clearFeishuLogin = (attempt: string | null | undefined) => {
|
||||
if (sessionStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt) {
|
||||
sessionStorage.removeItem(FEISHU_OAUTH_ATTEMPT_KEY)
|
||||
}
|
||||
if (localStorage.getItem(FEISHU_OAUTH_ATTEMPT_KEY) === attempt) {
|
||||
localStorage.removeItem(FEISHU_OAUTH_ATTEMPT_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
const feishuLogin = async (code: string, state?: string, attempt?: string) => {
|
||||
if (!isCurrentFeishuLogin(attempt)) throw new Error('登录状态已更新,请重新登录')
|
||||
const requestVersion = sessionVersion
|
||||
const res = await authApi.feishuLogin(code, state)
|
||||
if (requestVersion !== sessionVersion || !isCurrentFeishuLogin(attempt)) {
|
||||
throw new Error('登录状态已更新,请重新登录')
|
||||
}
|
||||
completeLogin(res.token, res.user)
|
||||
clearFeishuLogin(attempt)
|
||||
}
|
||||
|
||||
const setToken = async (jwt: string) => {
|
||||
if (!jwt) throw new Error('登录响应缺少有效令牌')
|
||||
sessionVersion += 1
|
||||
token.value = jwt
|
||||
userInfo.value = null
|
||||
localStorage.setItem(TOKEN_KEY, jwt)
|
||||
localStorage.removeItem(USER_INFO_KEY)
|
||||
await fetchUserInfo()
|
||||
// fetchUserInfo validates the callback token and user before this marker
|
||||
// is saved. A failed request clears the whole local session.
|
||||
saveAuthDay()
|
||||
}
|
||||
|
||||
const refreshToken = async () => {
|
||||
const requestVersion = sessionVersion
|
||||
const requestToken = token.value
|
||||
if (!requestToken) throw new Error('未登录')
|
||||
const response = await authApi.refreshToken()
|
||||
if (requestVersion !== sessionVersion || token.value !== requestToken || localStorage.getItem(TOKEN_KEY) !== requestToken) {
|
||||
throw new Error('登录状态已更新,请重新登录')
|
||||
}
|
||||
completeLogin(response.token, response.user)
|
||||
return response
|
||||
}
|
||||
|
||||
const fetchUserInfo = async () => {
|
||||
const requestVersion = sessionVersion
|
||||
const requestToken = token.value || localStorage.getItem(TOKEN_KEY) || ''
|
||||
if (!requestToken) {
|
||||
logout()
|
||||
throw new Error('未登录')
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await authApi.getUserInfo()
|
||||
if (requestVersion !== sessionVersion || token.value !== requestToken || localStorage.getItem(TOKEN_KEY) !== requestToken) {
|
||||
throw new Error('登录状态已更新,请重新加载页面')
|
||||
}
|
||||
if (!isValidUser(user)) throw new Error('用户信息无效')
|
||||
userInfo.value = user
|
||||
localStorage.setItem(USER_INFO_KEY, JSON.stringify(user))
|
||||
return user
|
||||
} catch (error) {
|
||||
// Do not let a late response from an old session clear a newer login.
|
||||
if (requestVersion === sessionVersion && token.value === requestToken && localStorage.getItem(TOKEN_KEY) === requestToken) logout()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate local session age and synchronize Pinia with storage. A missing
|
||||
* marker is invalid for real JWT sessions; the demo fallback is allowed one
|
||||
* migration when it already has a complete locally-verified user object.
|
||||
*/
|
||||
const ensureDailyAuth = (): boolean => {
|
||||
const storedToken = localStorage.getItem(TOKEN_KEY) || ''
|
||||
const storedDay = localStorage.getItem(AUTH_DAY_KEY)
|
||||
const storedUser = readStoredUser()
|
||||
|
||||
if (!storedToken) {
|
||||
const hadState = Boolean(token.value || userInfo.value || storedUser || storedDay)
|
||||
token.value = ''
|
||||
userInfo.value = null
|
||||
if (hadState) {
|
||||
sessionVersion += 1
|
||||
clearStoredSession()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// workbench.loginFallback is an existing development entry point and
|
||||
// writes its complete token/user pair synchronously. Give that pair a
|
||||
// marker on first use, while still rejecting any explicitly stale marker.
|
||||
if (!storedDay && storedToken === DEMO_SESSION_TOKEN && isValidUser(storedUser)) {
|
||||
token.value = storedToken
|
||||
userInfo.value = storedUser
|
||||
saveAuthDay()
|
||||
return true
|
||||
}
|
||||
|
||||
if (storedDay !== getBusinessDay()) {
|
||||
sessionVersion += 1
|
||||
clearStoredSession()
|
||||
token.value = ''
|
||||
userInfo.value = null
|
||||
return false
|
||||
}
|
||||
|
||||
token.value = storedToken
|
||||
userInfo.value = storedUser
|
||||
return true
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
sessionVersion += 1
|
||||
token.value = ''
|
||||
userInfo.value = null
|
||||
permissionCodes.value = []
|
||||
fieldPermissions.value = {}
|
||||
permissionsLoaded.value = false
|
||||
permissionsError.value = ''
|
||||
clearStoredSession()
|
||||
}
|
||||
|
||||
const loadPermissions = async (force = false) => {
|
||||
if (!force && permissionsLoaded.value && !permissionsError.value) return
|
||||
if (permissionRequest && !force) return permissionRequest
|
||||
permissionRequest = (async () => {
|
||||
permissionsError.value = ''
|
||||
try {
|
||||
const result = await request.get<{
|
||||
roleCodes?: string[]
|
||||
permissionCodes?: string[]
|
||||
fieldPermissions?: Record<string, 'HIDDEN' | 'READ' | 'EDIT'>
|
||||
}>('/roles/current-permissions')
|
||||
permissionCodes.value = Array.isArray(result?.permissionCodes) ? result.permissionCodes : []
|
||||
fieldPermissions.value = result?.fieldPermissions || {}
|
||||
permissionsLoaded.value = true
|
||||
} catch (error) {
|
||||
permissionCodes.value = []
|
||||
fieldPermissions.value = {}
|
||||
permissionsLoaded.value = false
|
||||
permissionsError.value = error instanceof Error ? error.message : '权限加载失败'
|
||||
throw error
|
||||
} finally {
|
||||
permissionRequest = null
|
||||
}
|
||||
})()
|
||||
return permissionRequest
|
||||
}
|
||||
|
||||
const hasPermission = (code: string) => permissionsLoaded.value && !permissionsError.value && permissionCodes.value.includes(code)
|
||||
|
||||
return {
|
||||
token,
|
||||
userInfo,
|
||||
isLoggedIn,
|
||||
isFinance,
|
||||
feishuLogin,
|
||||
beginFeishuLogin,
|
||||
isCurrentFeishuLogin,
|
||||
clearFeishuLogin,
|
||||
completeLogin,
|
||||
setToken,
|
||||
refreshToken,
|
||||
fetchUserInfo,
|
||||
ensureDailyAuth,
|
||||
permissionCodes,
|
||||
fieldPermissions,
|
||||
permissionsLoaded,
|
||||
permissionsError,
|
||||
loadPermissions,
|
||||
hasPermission,
|
||||
logout,
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,158 @@
|
||||
import { computed, ref } from 'vue'
|
||||
import { defineStore } from 'pinia'
|
||||
import { accountsPayableApi, cashierApi, reimbursementApi, type CreateApplicationRequest, type PaymentRecord, type ReimApplicationDetail, type ReimApplicationSummary } from '@/api/reimbursement'
|
||||
import { cloneFallback, createFallbackDetail, fallbackLogin, type FallbackUser } from '@/api/fallback'
|
||||
|
||||
export type DataSource = 'connecting' | 'api' | 'fallback' | 'error'
|
||||
export type StatusTone = 'info' | 'pending' | 'success' | 'danger' | 'draft' | 'neutral'
|
||||
const labels: Record<string, string> = { DRAFT: '草稿', SUBMITTED: '已提交', PENDING: '审批中', APPROVING: '审批中', APPROVED: '审批通过', REJECTED: '退回', RETURNED: '退回', CANCELLED: '已取消', RECEIPT_PENDING: '待收单', RECEIVED: '已收单', UNRECEIVED: '未触发', UNPAID: '未付款', PARTIAL: '部分付款', PAID: '已付款', OCCUPIED: '已占用', EXECUTED: '已转执行', ACTIVE: '有效', INACTIVE: '停用' }
|
||||
const toneMap: Record<string, StatusTone> = { 草稿: 'draft', 已提交: 'info', 审批中: 'pending', 审批通过: 'success', 退回: 'danger', 未触发: 'neutral', 待收单: 'pending', 已收单: 'success', 未付款: 'neutral', 部分付款: 'info', 已付款: 'success', 已占用: 'info', 已转执行: 'success', 有效: 'success' }
|
||||
const text = (value: unknown, fallback = '') => String(value ?? fallback)
|
||||
const number = (value: unknown) => Number(value || 0)
|
||||
const status = (value: unknown, fallback: string) => labels[text(value)] || text(value, fallback)
|
||||
const budgetStatus = (value: unknown) => ({ PENDING: '待处理', OCCUPIED: '已占用', EXECUTED: '已转执行' }[text(value)] || status(value, '已占用'))
|
||||
|
||||
export const useWorkbenchStore = defineStore('workbench', () => {
|
||||
const user = ref<FallbackUser | null>(null)
|
||||
const reimbursements = ref<ReimApplicationDetail[]>([])
|
||||
const payments = ref<PaymentRecord[]>([])
|
||||
const source = ref<DataSource>('connecting')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const financeQueueError = ref('')
|
||||
const notifications = ref(0)
|
||||
const fallbackPaymentKeys = new Map<string, PaymentRecord>()
|
||||
let loadPromise: Promise<void> | null = null
|
||||
let sessionVersion = 0
|
||||
const queueVersions: Record<'receipt' | 'payment', number> = { receipt: 0, payment: 0 }
|
||||
|
||||
const normalizePayment = (raw: any): PaymentRecord => ({ id: raw.id ?? raw.paymentNo ?? `payment-${Date.now()}`, paymentNo: text(raw.paymentNo, raw.reference || raw.id), applicationId: raw.applicationId ?? raw.reimbursementId, paymentAmount: number(raw.paymentAmount ?? raw.amount), totalAmount: number(raw.totalAmount), paidAmount: number(raw.paidAmount ?? raw.amount), remainingAmount: number(raw.remainingAmount), paymentMethod: text(raw.paymentMethod, raw.method || '银行转账'), referenceNo: text(raw.referenceNo, raw.reference), paymentStatus: status(raw.paymentStatus, '有效'), operatorName: text(raw.operatorName, raw.operator || '—'), paymentTime: text(raw.paymentTime, raw.time), remark: text(raw.remark, raw.referenceNo || raw.reference) })
|
||||
const maskAccount = (value: unknown) => {
|
||||
const account = text(value)
|
||||
if (!account || account.includes('*')) return account
|
||||
const digits = account.replace(/\s+/g, '')
|
||||
return digits.length > 4 ? `**** ${digits.slice(-4)}` : '已脱敏'
|
||||
}
|
||||
const normalize = (raw: any): ReimApplicationDetail => {
|
||||
const paymentsForItem = payments.value.filter(payment => String(payment.applicationId) === String(raw.id))
|
||||
const amount = number(raw.totalAmount ?? raw.amount)
|
||||
// “退回” belongs to approvalStatus. Keep the application fact as submitted.
|
||||
const application = text(raw.applicationStatus) === '草稿' || text(raw.applicationStatus) === 'DRAFT' || text(raw.status) === 'DRAFT'
|
||||
? '草稿'
|
||||
: '已提交'
|
||||
const approvalRaw = text(raw.approvalStatus ?? raw.applicationStatus)
|
||||
const approval = application === '草稿' && !['退回', 'REJECTED', 'RETURNED', 'CANCELLED', '已取消'].includes(approvalRaw)
|
||||
? '未触发'
|
||||
: status(approvalRaw, '未触发')
|
||||
const receiptRaw = text(raw.receiptStatus)
|
||||
const receipt = approval === '审批通过' && (!receiptRaw || ['UNRECEIVED', '未触发'].includes(receiptRaw))
|
||||
? '待收单'
|
||||
: status(raw.receiptStatus, '未触发')
|
||||
return {
|
||||
...raw, id: raw.id, applicationNo: text(raw.applicationNo, raw.id), title: text(raw.title, '未命名报销'), applicantName: text(raw.applicantName, raw.owner || raw.payeeName), applicantEmployeeNo: text(raw.applicantEmployeeNo), departmentName: text(raw.departmentName, raw.department), expenseTypeId: number(raw.expenseTypeId || 1), expenseTypeName: text(raw.expenseTypeName, raw.expenseType || '员工报销'), category: text(raw.category), totalAmount: amount, applicationStatus: application, approvalStatus: approval, currentApprovalNode: text(raw.currentApprovalNode, raw.approvalNode || '—'), receiptStatus: receipt, paymentStatus: status(raw.paymentStatus, '未付款'), budgetStatus: budgetStatus(raw.budgetStatus), sourceDocNo: text(raw.sourceDocNo), sourceStatus: text(raw.sourceStatus, '未关联'), payeeName: text(raw.payeeName, raw.payee), payeeBankId: number(raw.payeeBankId), bankName: text(raw.bankName), bankAccountMask: maskAccount(raw.bankAccountMask), returnReason: text(raw.returnReason), submitTime: text(raw.submitTime, raw.date), createdAt: text(raw.createdAt, raw.date), updatedAt: text(raw.updatedAt, raw.lastUpdated), paidAmountSnapshot: raw.paidAmount == null ? undefined : number(raw.paidAmount), remainingAmountSnapshot: raw.remainingAmount == null ? undefined : number(raw.remainingAmount), expenseItems: Array.isArray(raw.expenseItems) ? raw.expenseItems : [], invoices: Array.isArray(raw.invoices) ? raw.invoices : [], attachments: Array.isArray(raw.attachments) ? raw.attachments : [], approvalRecords: Array.isArray(raw.approvalRecords) ? raw.approvalRecords : [], payments: paymentsForItem,
|
||||
}
|
||||
}
|
||||
const refreshPaymentStatuses = () => reimbursements.value.forEach(item => { const linked = payments.value.filter(payment => String(payment.applicationId) === String(item.id)); if (linked.length || source.value === 'fallback' || item.paidAmountSnapshot !== undefined) { const paid = paidAmount(item); item.paymentStatus = paid <= 0 ? '未付款' : paid >= item.totalAmount ? '已付款' : '部分付款'; item.payments = linked } })
|
||||
const paidAmount = (item: ReimApplicationDetail) => { const linked = payments.value.filter(payment => String(payment.applicationId) === String(item.id) && payment.paymentStatus !== '无效'); if (linked.length) return linked.reduce((sum, payment) => sum + number(payment.paymentAmount || payment.paidAmount), 0); return item.paidAmountSnapshot ?? 0 }
|
||||
const balance = (item: ReimApplicationDetail) => Math.max(0, number(item.totalAmount) - paidAmount(item))
|
||||
const summaries = computed<ReimApplicationSummary[]>(() => reimbursements.value.map(item => ({ ...item } as ReimApplicationSummary)))
|
||||
|
||||
const setSnapshot = (payload: any, nextSource: DataSource) => { payments.value = (payload?.payments || []).map(normalizePayment); const rows: ReimApplicationDetail[] = (payload?.reimbursements || payload?.content || []).map(normalize); user.value = nextSource === 'fallback' ? (user.value || payload?.user) : (payload?.user || user.value); reimbursements.value = nextSource === 'fallback' && user.value?.userType === 'EMPLOYEE' ? rows.filter((item: ReimApplicationDetail) => item.applicantName === user.value?.realName) : rows; notifications.value = number(payload?.notifications); source.value = nextSource; refreshPaymentStatuses() }
|
||||
const load = async () => {
|
||||
if (loadPromise) return loadPromise
|
||||
const requestVersion = sessionVersion
|
||||
const currentPromise: Promise<void> = (async () => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const payload = await reimbursementApi.getWorkbench()
|
||||
if (!payload || (!Array.isArray(payload.reimbursements) && !Array.isArray(payload.content))) throw new Error('工作台数据格式不兼容')
|
||||
if (requestVersion !== sessionVersion) return
|
||||
setSnapshot(payload, 'api')
|
||||
} catch {
|
||||
if (requestVersion !== sessionVersion) return
|
||||
const canFallback = import.meta.env.DEV && typeof window !== 'undefined' && ['localhost', '127.0.0.1'].includes(window.location.hostname)
|
||||
if (canFallback) {
|
||||
setSnapshot(cloneFallback(), 'fallback')
|
||||
error.value = '数据服务暂不可用,当前显示本地可用数据;新增和付款操作仅保留在当前会话。'
|
||||
} else {
|
||||
reimbursements.value = []
|
||||
payments.value = []
|
||||
source.value = 'error'
|
||||
error.value = '无法连接财务服务,请联系管理员;为避免展示过期数据,业务记录已隐藏。'
|
||||
}
|
||||
} finally {
|
||||
if (requestVersion === sessionVersion) loading.value = false
|
||||
}
|
||||
})()
|
||||
loadPromise = currentPromise
|
||||
try {
|
||||
await currentPromise
|
||||
} finally {
|
||||
if (loadPromise === currentPromise) loadPromise = null
|
||||
}
|
||||
}
|
||||
const loadList = async () => { if (reimbursements.value.length) return; await load() }
|
||||
const loadDetail = async (id: string | number) => {
|
||||
const requestVersion = sessionVersion
|
||||
await loadList()
|
||||
if (requestVersion !== sessionVersion) return null
|
||||
if (source.value !== 'api') return getById(id)
|
||||
try {
|
||||
const detail = await reimbursementApi.getDetail(id)
|
||||
if (requestVersion !== sessionVersion) return null
|
||||
const normalized = normalize(detail)
|
||||
reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item)
|
||||
const detailPayments = (detail.payments || []).map((payment: any) => normalizePayment({ ...payment, applicationId: id }))
|
||||
payments.value = payments.value.filter(payment => String(payment.applicationId) !== String(id)).concat(detailPayments)
|
||||
refreshPaymentStatuses()
|
||||
return normalized
|
||||
} catch {
|
||||
return getById(id)
|
||||
}
|
||||
}
|
||||
const loadFinanceQueue = async (kind: 'receipt' | 'payment') => {
|
||||
const requestVersion = sessionVersion
|
||||
const queueVersion = ++queueVersions[kind]
|
||||
await loadList()
|
||||
if (requestVersion !== sessionVersion || source.value !== 'api') return
|
||||
try {
|
||||
const allRows: any[] = []
|
||||
let page = 0
|
||||
let total = Number.POSITIVE_INFINITY
|
||||
do {
|
||||
const payload = kind === 'receipt'
|
||||
? await accountsPayableApi.getTasks({ status: 'APPROVED', page, size: 100 })
|
||||
: await cashierApi.getTasks({ status: 'PENDING', page, size: 100 })
|
||||
if (requestVersion !== sessionVersion || queueVersion !== queueVersions[kind]) return
|
||||
const rows = payload?.content || payload?.tasks || payload?.records || (Array.isArray(payload) ? payload : [])
|
||||
allRows.push(...rows)
|
||||
total = Number(payload?.totalElements ?? payload?.total ?? allRows.length)
|
||||
page += 1
|
||||
if (!rows.length || rows.length < 100 || page >= 1000) break
|
||||
} while (allRows.length < total)
|
||||
if (requestVersion !== sessionVersion || queueVersion !== queueVersions[kind]) return
|
||||
const normalized: ReimApplicationDetail[] = allRows.map((row: any) => normalize(row))
|
||||
const byId = new Map(reimbursements.value.map(item => [String(item.id), item]))
|
||||
normalized.forEach((item: ReimApplicationDetail) => byId.set(String(item.id), item))
|
||||
reimbursements.value = [...byId.values()]
|
||||
refreshPaymentStatuses()
|
||||
financeQueueError.value = ''
|
||||
} catch {
|
||||
if (requestVersion === sessionVersion && queueVersion === queueVersions[kind]) financeQueueError.value = kind === 'receipt' ? '无法读取财务收单队列,请重试。' : '无法读取待付款队列,请重试。'
|
||||
}
|
||||
}
|
||||
const getById = (id: string | number) => reimbursements.value.find(item => String(item.id) === String(id)) || null
|
||||
const saveMutation = async <T>(operation: () => Promise<T>, fallbackOperation: () => T) => { if (source.value === 'fallback') return fallbackOperation(); return operation() }
|
||||
const save = async (payload: CreateApplicationRequest, id?: string | number) => {
|
||||
const requestVersion = sessionVersion
|
||||
const local = () => { const existing = id ? getById(id) : null; if (existing && (existing.applicantName !== user.value?.realName || !['草稿', '退回', '已取消'].includes(existing.approvalStatus === '退回' ? '退回' : existing.approvalStatus === '已取消' ? '已取消' : existing.applicationStatus))) throw new Error('只能修改本人草稿、退回或已取消的报销'); const result = existing ? normalize({ ...existing, ...payload, expenseItems: payload.items }) : createFallbackDetail(payload, `BX${new Date().toISOString().slice(0, 10).replace(/-/g, '')}${String(Date.now()).slice(-4)}`, user.value || fallbackLogin().user); if (existing) reimbursements.value = reimbursements.value.map(item => item.id === existing.id ? result : item); else reimbursements.value.unshift(result); return result }
|
||||
const result = await saveMutation(() => id ? reimbursementApi.update(id, payload) : reimbursementApi.create(payload), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback') { const normalized = normalize(result); if (id) reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item); else reimbursements.value.unshift(normalized); return normalized } return result
|
||||
}
|
||||
const submit = async (id: string | number) => { const requestVersion = sessionVersion; const local = () => { const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.applicantName !== user.value?.realName) throw new Error('只能提交本人报销'); if (item.applicationStatus !== '草稿' && item.approvalStatus !== '退回' && item.approvalStatus !== '已取消') throw new Error('只能提交草稿、退回或已取消报销'); item.applicationStatus = '已提交'; item.approvalStatus = '审批中'; item.currentApprovalNode = '部门负责人审批'; return item }; const result = await saveMutation(() => reimbursementApi.submit(id), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback' && result) { const normalized = normalize(result); reimbursements.value = reimbursements.value.map(item => String(item.id) === String(id) ? normalized : item); return normalized } return result }
|
||||
const receive = async (id: string | number) => { const requestVersion = sessionVersion; const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.approvalStatus !== '审批通过') throw new Error('仅审批通过的报销可以收单'); if (source.value === 'fallback') { if (!['FINANCE', 'ADMIN', 'SUPER_ADMIN'].includes(user.value?.userType || '')) throw new Error('仅财务人员可以确认收单'); item.receiptStatus = '已收单'; item.updatedAt = new Date().toISOString(); return item } const result = await reimbursementApi.receive(id); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); const normalized = normalize(result); reimbursements.value = reimbursements.value.map(row => String(row.id) === String(id) ? normalized : row); return normalized }
|
||||
const pay = async (id: string | number, amount: number, remark: string, idempotencyKey: string) => { const requestVersion = sessionVersion; const item = getById(id); if (!item) throw new Error('报销单不存在'); if (item.receiptStatus !== '已收单') throw new Error('申请尚未完成财务收单,无法付款'); if (!(amount > 0) || amount > balance(item) + 0.005) throw new Error(`付款金额须大于 0 且不超过未付余额 ¥ ${balance(item).toFixed(2)}`); const local = () => { const previous = fallbackPaymentKeys.get(idempotencyKey); if (previous) return previous; const record: PaymentRecord = { id: `PAY-${Date.now()}`, paymentNo: `PAY-${new Date().toISOString().slice(0, 10).replace(/-/g, '')}-${String(Date.now()).slice(-4)}`, applicationId: id, paymentAmount: amount, totalAmount: item.totalAmount, paidAmount: amount, remainingAmount: balance(item) - amount, paymentMethod: '银行转账', paymentStatus: '有效', operatorName: user.value?.realName || '财务人员', paymentTime: new Date().toISOString().slice(0, 16).replace('T', ' '), remark: remark || idempotencyKey }; fallbackPaymentKeys.set(idempotencyKey, record); payments.value.unshift(record); refreshPaymentStatuses(); return record }; const result = await saveMutation(() => (amount < balance(item) ? cashierApi.partialPayment(id, amount, remark, idempotencyKey) : cashierApi.executePayment(id, amount, remark, idempotencyKey)), local); if (requestVersion !== sessionVersion) throw new Error('登录状态已更新,请重新加载页面'); if (source.value !== 'fallback') { const record = normalizePayment({ ...(result || {}), applicationId: id, paymentStatus: result?.paymentStatus || result?.status || '有效', totalAmount: item.totalAmount }); payments.value.unshift(record); refreshPaymentStatuses() } return result }
|
||||
const reset = () => { sessionVersion += 1; queueVersions.receipt += 1; queueVersions.payment += 1; loadPromise = null; user.value = null; reimbursements.value = []; payments.value = []; source.value = 'connecting'; loading.value = false; error.value = ''; financeQueueError.value = ''; notifications.value = 0; fallbackPaymentKeys.clear() }
|
||||
const loginFallback = (employeeNo?: string) => { reset(); const result = fallbackLogin(employeeNo); user.value = result.user; localStorage.setItem('token', result.token); localStorage.setItem('userInfo', JSON.stringify(result.user)); return result }
|
||||
return { user, reimbursements, payments, source, loading, error, financeQueueError, notifications, summaries, balance, paidAmount, load, loadList, loadDetail, loadFinanceQueue, getById, save, submit, receive, pay, loginFallback, reset, refreshPaymentStatuses }
|
||||
})
|
||||