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 = { DRAFT: '草稿', SUBMITTED: '已提交', PENDING: '审批中', APPROVING: '审批中', APPROVED: '审批通过', REJECTED: '退回', RETURNED: '退回', CANCELLED: '已取消', RECEIPT_PENDING: '待收单', RECEIVED: '已收单', UNRECEIVED: '未触发', UNPAID: '未付款', PARTIAL: '部分付款', PAID: '已付款', OCCUPIED: '已占用', EXECUTED: '已转执行', ACTIVE: '有效', INACTIVE: '停用' } const toneMap: Record = { 草稿: '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(null) const reimbursements = ref([]) const payments = ref([]) const source = ref('connecting') const loading = ref(false) const error = ref('') const financeQueueError = ref('') const notifications = ref(0) const fallbackPaymentKeys = new Map() let loadPromise: Promise | 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(() => 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 = (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 (operation: () => Promise, 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 } })