Backend Documentation

Architecture

The backend is organized around a small number of runtime responsibilities: authenticate actors, resolve the right bot context, execute domain logic, persist state, and coordinate realtime or webhook responses.

HTTP Runtime

  • `app.js` boots Express, sessions, cookies, CORS, Passport, and route mounts.
  • Most request flow is conventional: route -> controller -> model or service -> JSON response.
  • Global error and 404 handlers live at the app boundary rather than being repeated inside route modules.

Persistence

  • MongoDB stores users, bots, features, chat handlers, sessions, API keys, payments, and deduplicated webhook events.
  • The data model is centered on `createdBy` ownership so each authenticated user controls their own assistant resources.

Core Runtime Flows

The most important application behavior is easier to understand as product flows than as folder structure.

Owner Dashboard Flow

  • Owner registers and verifies the account.
  • Owner creates bots, features, chat handlers, and billing state through protected `/api/*` routes.
  • The backend enforces plan limits before creating additional bots or consuming more messages.

Public Conversation Flow

  • A public chat request hits `POST /api/chat-handlers/:id/chat`.
  • The backend resumes or creates a chat session, checks subscription limits, and decides between AI continuation and agent handoff.
  • If AI continues, the reply is generated with OpenAI and persisted into the chat session.

Webhook Conversation Flow

  • Meta webhook POST routes acknowledge immediately.
  • The backend deduplicates the message, finds the bound bot, reconstructs context, and sends the reply through the provider API.
  • This flow can branch into commerce tools, receipt validation, or human handoff.

Realtime Support Flow

  • Socket.IO is initialized at server startup and is used for live chat coordination.
  • Agent assignment and user notification can occur through socket broadcasts when a handoff is accepted or completed.