netanalyzer/bot/handlers.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

177 lines
6.4 KiB
JavaScript

const { getStoreDetail } = require('../integrations/storeDetail');
const { parseStoreNumber } = require('../utils/validate');
const { isAgentConnected } = require('../services/websocket');
const { STORE_MODES } = require('../constants');
const { chunkReport } = require('../utils/chunkReport');
const logger = require('../utils/logger');
const REMOTE_AGENT_WARNING =
'⚠️ **Remote agent is not connected.** SIW data (store info, registers, ' +
'printers, payment terminals) will be unavailable. Meraki and MDM sections ' +
'will still appear. Start `remoteAgent.js` on the internal host to restore ' +
'full data.';
/**
* Map of `st` subcommand keyword → mode. Order matters only for documentation.
* `iphone` is an alias for `ios` (carried over from the old `store` command).
*/
const MODE_KEYWORDS = Object.freeze({
network: STORE_MODES.NETWORK,
pos: STORE_MODES.POS,
ios: STORE_MODES.IOS,
iphone: STORE_MODES.IOS,
phone: STORE_MODES.PHONE,
av: STORE_MODES.AV,
});
const MODE_LABELS = Object.freeze({
[STORE_MODES.INFO]: 'Info',
[STORE_MODES.NETWORK]: 'Network',
[STORE_MODES.POS]: 'POS',
[STORE_MODES.IOS]: 'iOS',
[STORE_MODES.PHONE]: 'Phone',
[STORE_MODES.AV]: 'AV',
});
/**
* Get the user-facing command text from a webex-node-bot-framework trigger,
* with the leading "@BotName " stripped in group spaces. The framework
* exposes this via `trigger.command + trigger.prompt` after a regex match;
* we fall back to the raw message text when those aren't populated (e.g.
* direct callers in tests).
*/
function getCommandText(trigger) {
const command = trigger?.command ?? '';
const prompt = trigger?.prompt ?? '';
if (command || prompt) return `${command}${prompt}`;
return trigger?.message?.text || '';
}
/**
* Parse a `st <number> [subcommand]` message. Returns the store number and
* the chosen mode. If no number is found, mode is null.
*/
function parseStoreCommand(text) {
const storeNumber = parseStoreNumber(text);
if (!storeNumber) return { storeNumber: null, mode: null };
const lower = ` ${text.toLowerCase()} `;
let mode = STORE_MODES.INFO;
for (const [keyword, value] of Object.entries(MODE_KEYWORDS)) {
// Match keyword as a whole word so "phone" doesn't trip on "phones".
if (new RegExp(`\\b${keyword}\\b`).test(lower)) {
mode = value;
break;
}
}
return { storeNumber, mode };
}
function usageMessage() {
return [
'**Usage:** `st [number] [subcommand]`',
'',
'**Example:** `st 305`',
'',
'**Subcommands:**',
'- `st 305` — store info (location, brand, status, environment)',
'- `st 305 network` — switches, APs, store server(s)',
'- `st 305 pos` — POS devices (registers, mobile registers, customer displays, printers, payment terminals)',
'- `st 305 ios` — iOS devices (iPhones)',
'- `st 305 phone` — wired (78xx) + DECT bases & handsets via Webex',
'- `st 305 av` — A/V hardware (Atlas AMPs + MDM-tracked Apple TVs, video walls, music, LED)',
'',
'Type `help` for the full reference.',
].join('\n');
}
async function handleStoreCommand(bot, trigger) {
const { storeNumber, mode } = parseStoreCommand(getCommandText(trigger));
if (!storeNumber) {
return bot.say('markdown', usageMessage());
}
const modeLabel = MODE_LABELS[mode] || mode;
bot.say('markdown', `🔍 Analyzing Store **${storeNumber}** (${modeLabel})...`);
// SIW depends on the remote agent. INFO and POS both need SIW data; warn up
// front if the agent is down. NETWORK / IOS / PHONE / AV don't use SIW so
// they're unaffected.
const modesThatNeedSiw = new Set([STORE_MODES.INFO, STORE_MODES.POS]);
if (modesThatNeedSiw.has(mode) && !isAgentConnected()) {
logger.warn('st command running without remote agent', { storeNumber, mode });
await bot.say('markdown', REMOTE_AGENT_WARNING);
}
try {
const report = await getStoreDetail(storeNumber, mode);
const chunks = chunkReport(report);
if (chunks.length === 0) {
await bot.say('markdown', '_No data to display for this view._');
return;
}
for (let i = 0; i < chunks.length; i++) {
await bot.say('markdown', chunks[i]);
// Small gap between multi-chunk replies so Webex keeps them in order
// visually. Single-chunk replies (the common case) have no delay.
if (i < chunks.length - 1) await new Promise(r => setTimeout(r, 300));
}
} catch (err) {
logger.error('Store analysis error', { storeNumber, mode, error: err.message });
bot.say('markdown', `❌ Error analyzing store **${storeNumber}**:\n${err.message}`);
}
}
async function handleHelpCommand(bot, trigger) {
const text = getCommandText(trigger).toLowerCase().trim();
let response;
if (/\bst\b|store/.test(text) && text !== 'help') {
response = [
'**`st` — Store Commands**',
'',
'- `st [number]` — store info (location, brand, status, environment)',
'- `st [number] network` — switches, APs, store server(s)',
'- `st [number] pos` — POS devices (registers, mobile registers, customer displays, printers, payment terminals)',
'- `st [number] ios` — iOS devices (mainly iPhones; alias: `iphone`)',
'- `st [number] phone` — wired (78xx) and DECT bases + handsets via Webex Service App',
'- `st [number] av` — A/V hardware: Atlas AMPs + MDM-tracked Apple TVs, video walls, music, LED displays',
'',
'**Tip:** type `st` without a number for a quick usage example.',
].join('\n');
} else {
response = [
'**StoreHealthAnalyzer — Help**',
'',
'**Store Commands**',
'- `st [number]` — store info (location, brand, status, environment)',
'- `st [number] network` — switches, APs, store server(s)',
'- `st [number] pos` — POS devices (registers, mobile registers, customer displays, printers, payment terminals)',
'- `st [number] ios` — iOS devices (mainly iPhones)',
'- `st [number] phone` — wired (78xx) + DECT bases & handsets via Webex',
'- `st [number] av` — A/V hardware (Atlas AMPs + MDM Apple TVs / VW / MSC / LED)',
'',
'**Tips**',
'- Works in both group spaces and 1:1 chats.',
'- Type `st` without a number for usage examples.',
'- Use `help st` for command-specific help.',
'- Try `st 782` to get started.',
].join('\n');
}
bot.say('markdown', response);
}
module.exports = {
handleStoreCommand,
handleHelpCommand,
parseStoreCommand,
getCommandText,
MODE_LABELS,
};