79 lines
5.3 KiB
TypeScript

/** @jest-environment node */
import { NextRequest } from 'next/server'
import { getServerSession } from 'next-auth'
import { prisma } from '@/lib/prisma'
import { getPerformanceSalaryDetails } from '@/lib/performance-salary-details'
import { GET } from './route'
import { SalaryError } from '@/lib/personnel-salary'
jest.mock('next-auth', () => ({ getServerSession: jest.fn() }))
jest.mock('@/lib/auth', () => ({ authOptions: {} }))
jest.mock('@/lib/prisma', () => ({ prisma: { user: { findUnique: jest.fn() } } }))
jest.mock('@/lib/performance-salary-details', () => ({ getPerformanceSalaryDetails: jest.fn() }))
const session = getServerSession as jest.Mock, user = prisma.user.findUnique as jest.Mock, details = getPerformanceSalaryDetails as jest.Mock
const request = () => new NextRequest('http://localhost/api/organization/performance-salary/details?month=2026-10')
beforeEach(() => { jest.resetAllMocks(); session.mockResolvedValue({ user: { id: 'old-admin', isSuperAdmin: true } }); user.mockResolvedValue({ id: 'old-admin', isSuperAdmin: false, isActive: true, status: 'active', archivedAt: null }) })
test('旧超管会话被数据库当前状态拒绝,拒绝响应也不缓存', async () => {
const response = await GET(request())
expect(response.status).toBe(403)
expect(response.headers.get('cache-control')).toContain('no-store')
expect(response.headers.get('vary')).toContain('Cookie')
expect(details).not.toHaveBeenCalled()
})
test('未登录及停用账号无法访问', async () => {
session.mockResolvedValue(null); expect((await GET(request())).status).toBe(401)
session.mockResolvedValue({ user: { id: 'admin' } }); user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: false }); expect((await GET(request())).status).toBe(403)
})
test.each(['c156778c-307d-42aa-89d3-f785aeb3ef86', '463c5a60-c8a8-45dd-b4cd-4a31a6b1b84f', 'c041d8d8-93db-41f1-984d-5f76f114da48', '2b1ccc12-844c-4eff-8006-58607157efc1', 'admin'])('指定只读账号或超管允许查询:%s', async id => {
session.mockResolvedValue({ user: { id } }); user.mockResolvedValue({ id, isSuperAdmin: id === 'admin', isActive: true, status: 'active', archivedAt: null })
details.mockResolvedValue({ displayMonth: '2026-10', sourceMonth: '2026-10', marketSourceMonth: '2026-09', isFallback: false, roles: {} })
const response = await GET(request())
expect(response.status).toBe(200); expect(response.headers.get('cache-control')).toContain('private, no-store')
expect(details).toHaveBeenCalledWith(id, '2026-10')
expect(await response.json()).toMatchObject({ displayMonth: '2026-10', sourceMonth: '2026-10', marketSourceMonth: '2026-09', isFallback: false })
})
test('内部查询异常不泄露工资和SQL', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
details.mockRejectedValue(new Error('SELECT salary secret payroll'))
const response = await GET(request())
expect(response.status).toBe(500); expect(JSON.stringify(await response.json())).not.toContain('secret')
})
test('历史快照未补齐时返回可重试503且不缓存或返回部分积分', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
details.mockRejectedValue(new SalaryError('流程积分正在同步,请稍后重新加载。', 503, 'WORKFLOW_POINTS_SYNCING'))
const response = await GET(request())
expect(response.status).toBe(503)
expect(response.headers.get('cache-control')).toContain('no-store')
expect(await response.json()).toEqual({ error: '流程积分正在同步,请稍后重新加载。', code: 'WORKFLOW_POINTS_SYNCING' })
})
test('流式接口先发送基础快照,中途分项更新,最后完成;响应禁止缓存和代理缓冲', async () => {
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
let finish!: () => void
details.mockImplementation(async (_id, _month, { onProgress }) => {
onProgress({ scope: { phase: 'base' } })
await new Promise<void>(resolve => { finish = resolve })
onProgress({ scope: { phase: 'partial' } })
return { scope: { phase: 'full' } }
})
const streamRequest = new NextRequest(`${request().url}&role=management`, { headers: { Accept: 'application/x-ndjson' } })
const response = await GET(streamRequest)
expect(response.headers.get('content-type')).toContain('application/x-ndjson')
expect(response.headers.get('cache-control')).toContain('private, no-store')
expect(response.headers.get('x-accel-buffering')).toBe('no')
const reader = response.body!.getReader()
const nextPhase = async () => JSON.parse(new TextDecoder().decode((await reader.read()).value)).data.scope.phase
expect(await nextPhase()).toBe('base')
finish()
expect(await nextPhase()).toBe('partial')
expect(await nextPhase()).toBe('full')
expect((await reader.read()).done).toBe(true)
})
test('非法岗位和无权限不会打开薪资响应流', async () => {
const streamRequest = new NextRequest(`${request().url}&role=invalid`, { headers: { Accept: 'application/x-ndjson' } })
expect((await GET(streamRequest)).status).toBe(403)
user.mockResolvedValue({ id: 'admin', isSuperAdmin: true, isActive: true, status: 'active', archivedAt: null })
expect((await GET(streamRequest)).status).toBe(400)
expect(details).not.toHaveBeenCalled()
})