|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import { getErrorMessage } from '@sim/utils/errors' |
| 3 | +import { type NextRequest, NextResponse } from 'next/server' |
| 4 | +import { zohoDeskAgentsSelectorContract } from '@/lib/api/contracts/selectors' |
| 5 | +import { parseRequest } from '@/lib/api/server' |
| 6 | +import { secureFetchWithValidation } from '@/lib/core/security/input-validation.server' |
| 7 | +import { generateRequestId } from '@/lib/core/utils/request' |
| 8 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 9 | +import { resolveZohoDeskSelectorCredential } from '@/app/api/tools/zoho_desk/selector-credential' |
| 10 | +import { assertZohoUrl } from '@/tools/zoho_desk/host-allowlist' |
| 11 | +import { buildZohoDeskHeaders, getZohoDeskErrorMessage } from '@/tools/zoho_desk/utils' |
| 12 | + |
| 13 | +export const dynamic = 'force-dynamic' |
| 14 | + |
| 15 | +const logger = createLogger('ZohoDeskAgentsAPI') |
| 16 | + |
| 17 | +/** |
| 18 | + * `GET /api/v1/agents` is index-paginated exactly like `/departments`: `from` is |
| 19 | + * a 0-based offset and `limit` caps at 200 (default 10). A short page means the |
| 20 | + * list is exhausted. The page cap bounds the drain so a provider that keeps |
| 21 | + * returning full pages cannot loop forever. |
| 22 | + */ |
| 23 | +const AGENT_PAGE_SIZE = 200 |
| 24 | +const MAX_AGENT_PAGES = 20 |
| 25 | + |
| 26 | +/** |
| 27 | + * Only active agents can own a ticket, so a disabled or deleted agent in the |
| 28 | + * picker would only produce an assignment the API rejects. |
| 29 | + */ |
| 30 | +const AGENT_STATUS = 'ACTIVE' |
| 31 | + |
| 32 | +interface ZohoAgent { |
| 33 | + id?: string | number |
| 34 | + name?: string |
| 35 | + firstName?: string |
| 36 | + lastName?: string |
| 37 | + emailId?: string |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Zoho returns `name` for most agents but leaves it (and `firstName`) empty on |
| 42 | + * some rows, so fall back through the name parts and finally the email before |
| 43 | + * showing a bare numeric id the user cannot recognize. |
| 44 | + */ |
| 45 | +function getAgentLabel(agent: ZohoAgent): string { |
| 46 | + if (agent.name?.trim()) return agent.name.trim() |
| 47 | + const fullName = [agent.firstName, agent.lastName] |
| 48 | + .map((part) => part?.trim()) |
| 49 | + .filter(Boolean) |
| 50 | + .join(' ') |
| 51 | + if (fullName) return fullName |
| 52 | + return agent.emailId?.trim() || String(agent.id) |
| 53 | +} |
| 54 | + |
| 55 | +/** Backs the `zoho_desk.agents` selector. */ |
| 56 | +export const POST = withRouteHandler(async (request: NextRequest) => { |
| 57 | + const requestId = generateRequestId() |
| 58 | + |
| 59 | + const parsed = await parseRequest(zohoDeskAgentsSelectorContract, request, {}) |
| 60 | + if (!parsed.success) return parsed.response |
| 61 | + const { credential, workflowId, orgId } = parsed.data.body |
| 62 | + |
| 63 | + const resolved = await resolveZohoDeskSelectorCredential(request, { |
| 64 | + credentialId: credential, |
| 65 | + workflowId, |
| 66 | + requestId, |
| 67 | + }) |
| 68 | + if (!resolved.ok) return resolved.response |
| 69 | + const { accessToken, apiBase } = resolved.credential |
| 70 | + |
| 71 | + const headers = buildZohoDeskHeaders({ accessToken, orgId }) |
| 72 | + const agents: Array<{ id: string; name: string }> = [] |
| 73 | + |
| 74 | + try { |
| 75 | + for (let page = 0; page < MAX_AGENT_PAGES; page++) { |
| 76 | + let agentsUrl: URL |
| 77 | + try { |
| 78 | + agentsUrl = assertZohoUrl(`${apiBase}/agents`) |
| 79 | + } catch { |
| 80 | + return NextResponse.json( |
| 81 | + { error: 'Credential resolved to a non-Zoho host' }, |
| 82 | + { status: 400 } |
| 83 | + ) |
| 84 | + } |
| 85 | + agentsUrl.searchParams.set('from', String(page * AGENT_PAGE_SIZE)) |
| 86 | + agentsUrl.searchParams.set('limit', String(AGENT_PAGE_SIZE)) |
| 87 | + agentsUrl.searchParams.set('status', AGENT_STATUS) |
| 88 | + |
| 89 | + // Same rationale as the organizations/departments/attachment routes: pin |
| 90 | + // the resolved IP, block private/reserved hops, and drop the token if a |
| 91 | + // Zoho-side redirect leaves the original origin. |
| 92 | + const response = await secureFetchWithValidation(agentsUrl.toString(), { |
| 93 | + method: 'GET', |
| 94 | + headers, |
| 95 | + timeout: 15_000, |
| 96 | + stripAuthOnRedirect: true, |
| 97 | + }) |
| 98 | + |
| 99 | + const body: { data?: unknown } = await response |
| 100 | + .json() |
| 101 | + .then((json) => (json && typeof json === 'object' ? (json as { data?: unknown }) : {})) |
| 102 | + .catch(() => ({})) |
| 103 | + |
| 104 | + // Zoho answers 204 with no body once the offset runs past the last agent, |
| 105 | + // which is a successful end-of-list, not an error. |
| 106 | + if (response.status === 204) break |
| 107 | + |
| 108 | + if (!response.ok) { |
| 109 | + const message = getZohoDeskErrorMessage( |
| 110 | + body, |
| 111 | + `Failed to list agents (HTTP ${response.status})` |
| 112 | + ) |
| 113 | + logger.warn('Failed to list Zoho Desk agents', { status: response.status, message }) |
| 114 | + return NextResponse.json( |
| 115 | + { error: message }, |
| 116 | + { status: response.status >= 400 && response.status < 500 ? response.status : 502 } |
| 117 | + ) |
| 118 | + } |
| 119 | + |
| 120 | + const pageItems = Array.isArray(body.data) ? (body.data as ZohoAgent[]) : [] |
| 121 | + for (const agent of pageItems) { |
| 122 | + if (agent.id === undefined || agent.id === null) continue |
| 123 | + agents.push({ id: String(agent.id), name: getAgentLabel(agent) }) |
| 124 | + } |
| 125 | + |
| 126 | + if (pageItems.length < AGENT_PAGE_SIZE) break |
| 127 | + if (page === MAX_AGENT_PAGES - 1) { |
| 128 | + logger.warn('Zoho Desk agents listing hit the page cap; list may be incomplete', { |
| 129 | + pages: MAX_AGENT_PAGES, |
| 130 | + }) |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + return NextResponse.json({ agents }) |
| 135 | + } catch (error) { |
| 136 | + const message = getErrorMessage(error, 'Failed to list agents') |
| 137 | + logger.error('Error listing Zoho Desk agents', { error: message }) |
| 138 | + return NextResponse.json({ error: message }, { status: 502 }) |
| 139 | + } |
| 140 | +}) |
0 commit comments