File size: 2,290 Bytes
2fe81ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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 {
  /**
   * Get aggregated chat history across agents for the current user
   */
  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;

      // Build query with filters
      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();

      // Attach minimal agent info
      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' });
    }
  }
}