83 lines
2.3 KiB
JavaScript
83 lines
2.3 KiB
JavaScript
'use strict'
|
|
|
|
/**
|
|
* nwTeamsController.js — Proxy de sectors/teams do WA-Inbox
|
|
*
|
|
* GET /api/admin/nw-teams
|
|
* Retorna a árvore de setores + equipes cadastrados no WA-Inbox,
|
|
* usando a integration_key do par já configurado em plugin_configs.
|
|
*
|
|
* PATCH /api/admin/accounts/:id
|
|
* Estende o updateAccount para aceitar nw_team_id e nw_sector_id.
|
|
* (implementado diretamente em equipeController.js)
|
|
*/
|
|
|
|
const { queryOne, execute } = require('../database/postgres')
|
|
|
|
// Cache em memória: evita hammering no WA-Inbox a cada request
|
|
let _cache = null
|
|
let _cacheAt = 0
|
|
const CACHE_TTL_MS = 60_000
|
|
|
|
async function getNwConfig(tenantId) {
|
|
const rows = await require('../database/postgres').query(
|
|
`SELECT key, value FROM plugin_configs WHERE plugin_id = 'newwhats'`
|
|
)
|
|
const cfg = {}
|
|
for (const r of rows) cfg[r.key] = r.value
|
|
return cfg
|
|
}
|
|
|
|
async function listNwTeams(req, res) {
|
|
try {
|
|
const now = Date.now()
|
|
if (_cache && now - _cacheAt < CACHE_TTL_MS) {
|
|
return res.json(_cache)
|
|
}
|
|
|
|
const cfg = await getNwConfig()
|
|
if (!cfg.newwhats_url || !cfg.integration_key) {
|
|
return res.json([])
|
|
}
|
|
|
|
const baseUrl = cfg.newwhats_url.replace(/\/$/, '')
|
|
const headers = { 'x-nw-key': cfg.integration_key, 'Content-Type': 'application/json' }
|
|
|
|
// Busca setores
|
|
const sectorsResp = await fetch(`${baseUrl}/api/sectors`, { headers })
|
|
if (!sectorsResp.ok) {
|
|
console.warn('[nwTeams] falha ao buscar sectors:', sectorsResp.status)
|
|
return res.json([])
|
|
}
|
|
const sectors = await sectorsResp.json()
|
|
|
|
// Busca teams de cada setor em paralelo
|
|
const tree = await Promise.all(
|
|
sectors.map(async (sector) => {
|
|
try {
|
|
const teamsResp = await fetch(`${baseUrl}/api/sectors/${sector.id}/teams`, { headers })
|
|
const teams = teamsResp.ok ? await teamsResp.json() : []
|
|
return { ...sector, teams }
|
|
} catch {
|
|
return { ...sector, teams: [] }
|
|
}
|
|
})
|
|
)
|
|
|
|
_cache = tree
|
|
_cacheAt = now
|
|
res.json(tree)
|
|
} catch (e) {
|
|
console.error('[nwTeams] listNwTeams:', e)
|
|
res.status(500).json({ error: 'Erro ao buscar teams do WA-Inbox' })
|
|
}
|
|
}
|
|
|
|
// Invalida o cache (chamado quando um sector/team é criado/editado no WA-Inbox)
|
|
function invalidateCache() {
|
|
_cache = null
|
|
_cacheAt = 0
|
|
}
|
|
|
|
module.exports = { listNwTeams, invalidateCache }
|