netanalyzer/services/avService.js
Joseph McQueen b3c37bd7df feat: st command suite, Webex phone + Atlas AV integrations, dockerized remote agent
Rebrand NetAnalyzer -> StoreHealthAnalyzer and consolidate the store
reporting surface into a single `st [number]` command with focused
sub-modes.

Commands
- st [number]                - general info (SIW + brands + Meraki net link)
- st [number] network        - switches, APs, store server
- st [number] pos            - registers, payment terminals, customer display
- st [number] ios            - MDM-tracked iOS hardware
- st [number] phone          - wired 78xx + DECT basestations/handsets with
                               registration state, extensions and main DID
- st [number] av             - Atlas AMPs + MDM-tracked Apple TVs, video
                               walls, music players, LED displays
- Removed `analyze` in favor of the unified `st` surface

Integrations
- integrations/webex: Service App OAuth with rotating refresh tokens,
  seed + cleanup scripts, tokens/ storage (git-ignored)
- integrations/atlas: Xyte client + cached device discovery keyed on
  zero-padded 6-digit store numbers, cold-cache failure -> unavailable
  banner instead of a misleading empty result
- services/webexPhone, services/webexService, services/avService: shape
  raw upstream data into the report layer's contract
- utils/merakiMatcher: FQDN hostname extraction so payment terminals
  match Meraki descriptions; case-insensitive lookup
- utils/chunkReport: split long markdown replies at 7000-char boundaries

Reliability / ops
- server.js: awaited framework.stop() + 8s hard-kill timer so nodemon /
  Docker restarts don't leak WDM device registrations ("excessive device
  registrations")
- nodemon.json: SIGINT so the graceful path always runs
- scripts/cleanupWebexDevices.js: one-shot WDM cleanup utility
- Group-space routing: hears() regexes tolerate the leading @BotName
  prefix Webex prepends to mentions
- Replaced HTML-unsafe <number> placeholders with [number] in all help
  strings

Remote agent containerization
- docker/remote-agent/: multi-stage node:22-alpine image, non-root user,
  tini for signal handling, minimal deps (ws/axios/dotenv)
- docker/remote-agent/package.sh: docker buildx build defaulting to
  linux/amd64 (with override), saves image + assembles deploy/ + writes
  SHA256 + zips for offline transfer
- docker/remote-agent/deploy/: runtime docker-compose.yml, install.sh
  with platform sanity check, remote-host README
- .dockerignore + .gitignore updates for build artifacts and dist bundles
- npm run agent:package convenience script

Cleanup
- Dropped storeHealth.js / HealthReport.js and their tests/mocks in favor
  of the shared storeDetail pipeline
- Store model handles null SIW records gracefully; toSummary always
  ends with a newline so the Meraki link sits on its own line

Tests
- 144 tests across 14 suites passing; new coverage for atlasClient,
  atlasDevices, avService, avCategory classification, webexPhone,
  webexServiceAppAuth, storeDetail integration, siw, chunkReport and
  the updated meraki matcher

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-06 09:54:41 -04:00

110 lines
3.5 KiB
JavaScript

/**
* AV (Atlas) device-discovery service.
*
* Thin shim over integrations/atlas: pulls the Atlas devices belonging to a
* store and shapes each into a renderer-friendly object the storeDetail AV
* report consumes. Mirrors the contract of services/webexPhone.js — on any
* unrecoverable failure (missing ATLAS_AUTH_KEY, transport error) it returns
* `{ devices: [], unavailable: true, reason }` rather than throwing, so the
* bot can render a banner alongside whatever other AV data (MDM Apple TVs
* etc.) is still available.
*
* Atlas field names vary subtly across device types; `shapeAtlasDevice`
* picks defensively from the locations the collabFinder reference touched
* (`state.IpAddress`, `state.MacAddress`, `connection_status`, `status`,
* etc.). The renderer treats `online === null` as "unknown" so an unfamiliar
* payload degrades gracefully.
*/
const { getAtlasDevicesForStore } = require('../integrations/atlas/atlasDevices');
const logger = require('../utils/logger');
const ONLINE_KEYWORDS = new Set(['online', 'connected', 'active', 'up']);
const OFFLINE_KEYWORDS = new Set(['offline', 'disconnected', 'inactive', 'down']);
function deriveOnline(dev) {
// Try the most specific fields first; fall back to top-level `status`.
const candidates = [
dev?.connection_status,
dev?.state?.connection_status,
dev?.state?.status,
dev?.status,
];
for (const c of candidates) {
if (typeof c === 'boolean') return c;
if (typeof c !== 'string') continue;
const lower = c.trim().toLowerCase();
if (!lower) continue;
if (ONLINE_KEYWORDS.has(lower)) return true;
if (OFFLINE_KEYWORDS.has(lower)) return false;
}
return null;
}
function pickFirst(...values) {
for (const v of values) {
if (v !== undefined && v !== null && v !== '') return v;
}
return null;
}
function shapeAtlasDevice(dev) {
const state = dev?.state || {};
const model = pickFirst(
typeof dev?.model === 'string' ? dev.model : null,
dev?.model?.name,
dev?.model_name,
dev?.product
);
const firmware = pickFirst(dev?.firmware?.version, dev?.firmware_version, state?.firmware);
return {
id: dev?.id || null,
name: dev?.name || dev?.displayName || 'Unknown AV Device',
model,
firmware,
mac: pickFirst(dev?.mac, state?.MacAddress, state?.macAddress, dev?.mac_address),
ip: pickFirst(state?.IpAddress, state?.ipAddress, dev?.ip, dev?.ip_address),
online: deriveOnline(dev),
lastSeen: pickFirst(
dev?.last_connection,
dev?.last_seen,
state?.lastSeen,
state?.last_seen,
dev?.updated_at
),
};
}
/**
* Collect AV devices for the given store. Always resolves with the
* unavailable banner contract — never throws — so the storeDetail layer can
* compose this alongside MDM and Meraki output without try/catch noise.
*/
async function collectAvStatus(storeNumber) {
logger.debug('collectAvStatus start', { storeNumber });
let result;
try {
result = await getAtlasDevicesForStore(storeNumber);
} catch (err) {
logger.error('Atlas lookup threw unexpectedly', { storeNumber, error: err.message });
return { devices: [], unavailable: true, reason: err.message };
}
if (result.unavailable) {
return { devices: [], unavailable: true, reason: result.reason };
}
const devices = (result.devices || []).map(shapeAtlasDevice);
logger.info('collectAvStatus done', { storeNumber, count: devices.length });
return { devices };
}
module.exports = {
collectAvStatus,
// Exposed for tests
shapeAtlasDevice,
deriveOnline,
};