| import { Request, Response } from 'express'; |
| import { AppDataSource } from '../config/database'; |
| import { ChatMessage } from '../entities/ChatMessage'; |
| import { Agent } from '../entities/Agent'; |
|
|
| const messageRepository = AppDataSource.getRepository(ChatMessage); |
| const agentRepository = AppDataSource.getRepository(Agent); |
|
|
| export class UserController { |
| |
| |
| |
| async getMyHistory(req: Request, res: Response) { |
| try { |
| const userId = (req as any).user.id; |
| const { limit = 50, offset = 0, agentId, role, from, to, search } = req.query as any; |
|
|
| |
| let qb = messageRepository |
| .createQueryBuilder('m') |
| .where('m.userId = :userId', { userId }) |
| .orderBy('m.createdAt', 'DESC') |
| .limit(Number(limit)) |
| .offset(Number(offset)); |
|
|
| if (agentId) { |
| qb = qb.andWhere('m.agentId = :agentId', { agentId }); |
| } |
| if (role) { |
| qb = qb.andWhere('m.role = :role', { role }); |
| } |
| if (from) { |
| qb = qb.andWhere('m.createdAt >= :from', { from }); |
| } |
| if (to) { |
| qb = qb.andWhere('m.createdAt <= :to', { to }); |
| } |
| if (search) { |
| qb = qb.andWhere('m.content ILIKE :search', { search: `%${search}%` }); |
| } |
|
|
| const messages = await qb.getMany(); |
|
|
| |
| const agentIds = Array.from(new Set(messages.map((m) => m.agentId))); |
| const agents = agentIds.length ? await agentRepository.findByIds(agentIds) : []; |
| const agentMap = new Map(agents.map((a) => [a.id, { id: a.id, name: a.name, avatar: a.avatar, category: a.category }])); |
|
|
| res.json({ |
| messages: messages.map((m) => ({ |
| id: m.id, |
| agentId: m.agentId, |
| agent: agentMap.get(m.agentId) || null, |
| role: m.role, |
| content: m.content, |
| metadata: m.metadata, |
| createdAt: m.createdAt, |
| })), |
| pagination: { |
| limit: Number(limit), |
| offset: Number(offset), |
| count: messages.length, |
| }, |
| }); |
| } catch (error) { |
| console.error('Get user history error:', error); |
| res.status(500).json({ error: 'Failed to get history' }); |
| } |
| } |
| } |
|
|