import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { AgentPresence } from '../entities/agent-presence.entity.js'; export type PresenceStatus = 'idle' | 'on_call' | 'busy' | 'exhausted' | 'offline' | 'unknown'; @Injectable() export class AgentPresenceService { constructor( @InjectRepository(AgentPresence) private readonly repo: Repository, ) {} /** * Get a user's current presence. Returns 'unknown' if no row. * Used by `RealtimeGateway` per-recipient when xType === 'announce'. */ async getStatus(userId: string): Promise { if (!userId) return 'unknown'; const row = await this.repo.findOne({ where: { userId } }); return row?.status ?? 'unknown'; } /** Bulk variant for delivery-time lookups across many recipients in one trip. */ async getStatusMap(userIds: string[]): Promise> { const out = new Map(); for (const id of userIds) out.set(id, 'unknown'); if (userIds.length === 0) return out; const rows = await this.repo .createQueryBuilder('p') .where('p.userId IN (:...ids)', { ids: userIds }) .getMany(); for (const r of rows) out.set(r.userId, r.status); return out; } /** * Upsert a user's presence. Source is a free-text tag for debugging * (e.g. "hf-plugin", "manual", "test"). PUT /agents/:id/presence * calls this; the plugin pushes only on diff so writes are sparse. */ async setStatus(userId: string, status: PresenceStatus, source: string): Promise { const existing = await this.repo.findOne({ where: { userId } }); if (existing) { existing.status = status; existing.source = source; return this.repo.save(existing); } const row = this.repo.create({ userId, status, source }); return this.repo.save(row); } }