linuxfront-v2-logistics/xai.php

Overview

This file implements a lightweight web chat widget named Howie! for customer support. It leverages PHP session data to identify the user and initializes a JavaScript-driven chat interface. Messages flow via both RESTful API calls and a WebSocket connection to a backend at trynew.techlogistics.com .

HTML Structure

The widget markup lives entirely within a <div id="chatContainer">, initially hidden. Key elements include:

Element ID Role Emoji
chatContainer Main chat panel 📂
chatMessages Scrollable message display area 💬
typingIndicator Shows “Typing…” or processing dots ⏳
messageInput Multiline text input for user messages ✏️
fileButton/fileInput Trigger & select file attachments 📎
sendButton Send text message ➤
needsAssistanceButton Request human agent assistance 🆘
chatIcon Floating button to toggle chat panel 💬
<div id="chatContainer">
  <h2>Howie!</h2>
  <div id="chatTraining"></div>
  <div id="chatMessages"></div>
  <div id="typingIndicator"></div>
  <div id="chatInput">
    <textarea id="messageInput" placeholder="Type a message..."></textarea>
    <button id="fileButton" title="Attach a file">📎</button>
    <input id="fileInput" type="file">
    <button id="sendButton">Send</button>
  </div>
  <button id="needsAssistanceButton">Request Human Assistance</button>
</div>
<div id="chatIcon">💬</div>

All of the above is dynamically shown/hidden via JavaScript .

Styling

The embedded CSS provides a clean, responsive look:

  • Colors & Typography
    • Light background (#f4f4f4)
    • White chat panel with subtle box-shadow
    • Sans-serif font (Arial)
  • Layouts
    • max-width: 600px central panel
    • Flex containers for input controls
    • Scrollable message area limited to 400px height
  • State Styles
    • .user messages: blue background, right-aligned
    • .bot and .agent: neutral backgrounds
    • .system: italic, gray text
#chatMessages div.user { background-color: #e3f2fd; text-align: right; }
#chatMessages div.bot { background-color: #f5f5f5; }
#chatMessages div.system { font-style: italic; color: #555; }

JavaScript Architecture

All functionality is implemented in a single <script> block. Major components:

1. Initialization

  • Session Data is read from PHP $_SESSION into chatSetup and stored in localStorage for persistence .
  • On DOMContentLoaded, it calls:
    • connectWebSocket()
    • initializeChat()

2. WebSocket Integration

function connectWebSocket() { … }
ws = new WebSocket(`wss://trynew.techlogistics.com:2053?userId=${userId}&newChat=true`);
  • Reconnects on error/close after 5 seconds
  • Listens for:
    • message events → calls displayMessage()
    • typing → toggles indicator text
    • processing → shows animated dots

3. Message Rendering

function displayMessage({ sender, message, originalName, messageId, training }) { … }
  • Detects file messages prefixed with "File: "
  • Uses getFileIcon(ext) to match file extensions to icons
  • Appends a <div> with classes user|bot|agent|system

4. Sending Messages

async function sendMessage(message, sender='user', needsAssistance=false, originalName=null) { … }
  • POST to /api/chat with JSON:
    {
      "message": "...",
      "userId": "...",
      "chatId": "...",
      "sender": "user",
      "needsAssistance": false,
      "originalName": null,
      "page_url": "…",
      "training": "Intro",
      "customer_email": "...",
      "customer_id": "...",
      "location_code": "..."
    }
    

5. File Uploads

async function uploadFile(file) { … }
  • Uploads via FormData to /api/upload
  • On success, sends a File: /path message to chat

6. Fetching Historical Messages

async function fetchMessages() { … }
  • GET /api/messages?chatId=…
  • Clears and repopulates #chatMessages in chronological order

7. Debounced Typing Indicator

function debounce(func, wait) { … }
const sendTyping = debounce(() => {
  ws.send(JSON.stringify({ type: 'typing', chatId, isTyping: messageInput.value.length>0 }));
}, 500);

Interaction Flow

sequenceDiagram
  participant U as User
  participant F as Frontend
  participant API as Chat API
  participant WS as WebSocket
  U->>F: Click chat icon
  F->>API: GET /api/chats?userId
  API-->>F: [ chat sessions ]
  alt no chat exists
    F->>API: POST /api/chat (New chat)
  end
  F->>WS: CONNECT wss://…?userId=…
  U->>F: Type message + Send
  F->>API: POST /api/chat
  API-->>F: { chatId }
  WS-->>F: { type: "message", message: "…", sender: "bot" }
  F->>F: displayMessage()

API Endpoints

Each endpoint uses https://trynew.techlogistics.com:2053 as baseUrl.

{
  "title": "Send Chat Message",
  "description": "Submit a new chat message",
  "method": "POST",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/chat",
  "headers": [
    { "key": "Content-Type", "value": "application/json", "required": true }
  ],
  "bodyType": "json",
  "requestBody": "{\n  \"message\": \"Hello\",\n  \"userId\": \"user123\",\n  \"chatId\": \"chat456\",\n  \"sender\": \"user\",\n  \"needsAssistance\": false,\n  \"originalName\": null,\n  \"page_url\": \"https://example.com\",\n  \"training\": \"Intro\",\n  \"customer_email\": \"[email protected]\",\n  \"customer_id\": \"cust789\",\n  \"location_code\": \"LOC1\"\n}",
  "responses": {
    "200": {
      "description": "Chat message enqueued",
      "body": "{ \"chatId\": \"chat456\", \"status\": \"success\" }"
    },
    "400": {
      "description": "Invalid request",
      "body": "{ \"error\": \"Missing message\" }"
    }
  }
}
{
  "title": "Upload File",
  "description": "Attach a file to a chat session",
  "method": "POST",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/upload",
  "headers": [
    { "key": "Content-Type", "value": "multipart/form-data", "required": true }
  ],
  "bodyType": "form",
  "formData": [
    { "key": "file", "value": "Binary file data", "required": true }
  ],
  "responses": {
    "200": {
      "description": "File uploaded",
      "body": "{ \"filePath\": \"/uploads/doc.pdf\", \"originalName\": \"doc.pdf\" }"
    },
    "400": {
      "description": "Unsupported file",
      "body": "{ \"error\": \"Unsupported file type\" }"
    }
  }
}
{
  "title": "Get Chat Messages",
  "description": "Retrieve all messages in a chat session",
  "method": "GET",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/messages",
  "queryParams": [
    { "key": "chatId", "value": "Chat session ID", "required": true }
  ],
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "Array of messages",
      "body": "[\n  {\"id\":\"msg1\",\"sender\":\"user\",\"message\":\"Hi\",\"created_at\":\"2025-09-19T12:00:00Z\"},\n  {\"id\":\"msg2\",\"sender\":\"bot\",\"message\":\"Hello!\"}\n]"
    },
    "404": {
      "description": "Chat not found",
      "body": "{ \"error\": \"Chat session not found\" }"
    }
  }
}
{
  "title": "Get User Chats",
  "description": "List all chat sessions for a user",
  "method": "GET",
  "baseUrl": "https://trynew.techlogistics.com:2053",
  "endpoint": "/api/chats",
  "queryParams": [
    { "key": "userId", "value": "User identifier", "required": true }
  ],
  "bodyType": "none",
  "responses": {
    "200": {
      "description": "Array of chat sessions",
      "body": "[\n  {\"id\":\"chat1\",\"user_id\":\"user123\",\"created_at\":\"2025-09-19T11:00:00Z\"}\n]"
    }
  }
}

Key Functions at a Glance

Function Purpose
getFileIcon(ext) Returns icon URL for file extension
connectWebSocket() Opens/reconnects to chat WebSocket server
displayMessage() Renders incoming/outgoing messages in the UI
sendMessage() Posts a message to the chat API
uploadFile() Uploads attachments then sends file link as message
fetchMessages() Loads historical messages for an existing chat
initializeChat() Ensures a chat session exists or creates a new one
debounce() Utility to limit rapid typing event emissions

Usage

  1. Include this PHP file in any page where sessions hold user_id, Customer_email, Customer_ID, and company_code.
  2. The floating chat icon appears; click to toggle the chat panel.
  3. Users can send text, attach files, or request human assistance.

Note: Ensure your backend at trynew.techlogistics.com:2053 supports the documented API routes and WebSocket protocol.