GuDingZiChan/backend/src/controllers/syncController.ts

275 lines
7.6 KiB
TypeScript

import type { Request, Response } from 'express'
import prisma from '../utils/prisma'
import { errorResponse, successResponse } from '../utils/response'
import { getHrSyncConfigStatus, previewHrSync, runHrSync } from '../services/hrSyncService'
const SYNC_CHANGE_PROCESSING_STATUSES = ['pending', 'processed', 'ignored'] as const
type SyncChangeProcessingStatus = (typeof SYNC_CHANGE_PROCESSING_STATUSES)[number]
const resolveSyncErrorCode = (message: string) => {
if (message.includes('SQL Server 同步配置不完整')) {
return 400
}
return 500
}
const parseJsonText = (value: string | null) => {
if (!value) return null
try {
return JSON.parse(value)
} catch {
return null
}
}
const toRecord = (value: unknown) =>
value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, number>) : {}
const normalizeProcessingStatus = (value: unknown): SyncChangeProcessingStatus | null => {
if (typeof value !== 'string') return null
const normalized = value.trim().toLowerCase()
return SYNC_CHANGE_PROCESSING_STATUSES.includes(normalized as SyncChangeProcessingStatus)
? (normalized as SyncChangeProcessingStatus)
: null
}
const normalizeProcessingNotes = (value: unknown) => {
if (typeof value !== 'string') return null
const normalized = value.trim()
return normalized ? normalized : null
}
const serializeSyncJob = (job: any) => {
const payload = parseJsonText(job.result_payload)
return {
id: job.id,
sync_type: job.sync_type,
trigger_mode: job.trigger_mode,
status: job.status,
operator: job.operator,
summary: job.summary,
created_at: job.created_at,
changes_count:
typeof payload?.changes_count === 'number' ? payload.changes_count : job._count?.changes || 0,
counts: toRecord(payload?.counts),
error_message: typeof payload?.error_message === 'string' ? payload.error_message : null
}
}
const resolveProcessedByName = (change: any) => {
if (!change.processedBy) return null
return change.processedBy.name || change.processedBy.username || null
}
const serializeSyncChange = (change: any) => ({
id: change.id,
entity_type: change.entity_type,
entity_key: change.entity_key,
entity_name: change.entity_name,
change_type: change.change_type,
title: change.title,
detail: change.detail,
before_snapshot: parseJsonText(change.before_snapshot),
after_snapshot: parseJsonText(change.after_snapshot),
processing_status: change.processing_status,
processing_notes: change.processing_notes,
processed_by: change.processed_by,
processed_by_name: resolveProcessedByName(change),
processed_at: change.processed_at,
created_at: change.created_at
})
export const getHrSyncStatusController = async (_req: Request, res: Response) => {
try {
const result = getHrSyncConfigStatus()
successResponse(res, result, '获取成功')
} catch (error: any) {
errorResponse(res, error.message || '获取同步状态失败', 500)
}
}
export const previewHrSyncController = async (_req: Request, res: Response) => {
try {
const result = await previewHrSync()
successResponse(res, result, '预览成功')
} catch (error: any) {
const message = error.message || '预览同步数据失败'
errorResponse(res, message, resolveSyncErrorCode(message))
}
}
export const runHrSyncController = async (_req: Request, res: Response) => {
try {
const operator = res.locals.user?.username || res.locals.user?.name || 'system-sync'
const result = await runHrSync(operator)
successResponse(res, result, '同步成功')
} catch (error: any) {
const message = error.message || '执行同步失败'
errorResponse(res, message, resolveSyncErrorCode(message))
}
}
export const getHrSyncJobListController = async (req: Request, res: Response) => {
try {
const page = Math.max(1, Number(req.query.page) || 1)
const pageSize = Math.min(50, Math.max(1, Number(req.query.pageSize) || 10))
const skip = (page - 1) * pageSize
const where = {
sync_type: 'hr'
}
const [list, total] = await Promise.all([
prisma.syncJob.findMany({
where,
skip,
take: pageSize,
orderBy: { created_at: 'desc' },
include: {
_count: {
select: {
changes: true
}
}
}
}),
prisma.syncJob.count({ where })
])
successResponse(
res,
{
list: list.map(serializeSyncJob),
total,
page,
pageSize
},
'获取成功'
)
} catch (error: any) {
errorResponse(res, error.message || '获取同步历史失败', 500)
}
}
export const getHrSyncJobDetailController = async (req: Request, res: Response) => {
try {
const id = Number(req.params.id)
if (!Number.isInteger(id) || id <= 0) {
return errorResponse(res, '同步任务不存在', 404)
}
const job = await prisma.syncJob.findFirst({
where: {
id,
sync_type: 'hr'
},
include: {
_count: {
select: {
changes: true
}
},
changes: {
include: {
processedBy: {
select: {
id: true,
username: true,
name: true
}
}
},
orderBy: { created_at: 'desc' }
}
}
})
if (!job) {
return errorResponse(res, '同步任务不存在', 404)
}
successResponse(
res,
{
...serializeSyncJob(job),
changes: job.changes.map(serializeSyncChange)
},
'获取成功'
)
} catch (error: any) {
errorResponse(res, error.message || '获取同步任务详情失败', 500)
}
}
export const updateHrSyncChangeProcessingController = async (req: Request, res: Response) => {
try {
const id = Number(req.params.id)
if (!Number.isInteger(id) || id <= 0) {
return errorResponse(res, '同步变更不存在', 404)
}
const processingStatus = normalizeProcessingStatus(req.body?.processing_status)
if (!processingStatus) {
return errorResponse(res, '处理状态无效', 400)
}
const currentUserId = Number(res.locals.user?.id)
if (processingStatus !== 'pending' && (!Number.isInteger(currentUserId) || currentUserId <= 0)) {
return errorResponse(res, '未获取到当前处理人信息', 401)
}
const existingChange = await prisma.syncChange.findFirst({
where: {
id,
syncJob: {
sync_type: 'hr'
}
},
select: {
id: true
}
})
if (!existingChange) {
return errorResponse(res, '同步变更不存在', 404)
}
const now = new Date()
const updateData =
processingStatus === 'pending'
? {
processing_status: processingStatus,
processing_notes: normalizeProcessingNotes(req.body?.processing_notes),
processed_by: null,
processed_at: null
}
: {
processing_status: processingStatus,
processing_notes: normalizeProcessingNotes(req.body?.processing_notes),
processed_by: currentUserId,
processed_at: now
}
const updatedChange = await prisma.syncChange.update({
where: {
id
},
data: updateData,
include: {
processedBy: {
select: {
id: true,
username: true,
name: true
}
}
}
})
successResponse(res, serializeSyncChange(updatedChange), '更新成功')
} catch (error: any) {
errorResponse(res, error.message || '更新同步变更处理状态失败', 500)
}
}