# @impact/chatbot v2.0.0

Standalone chatbot library - TypeScript conversion of smartBot with enhanced features.

## Overview

This library is a **TypeScript conversion** of `src/core/commonComponents/smartBot` with additional enhancements for widget rendering, streaming, and special character handling.

**Key Features:**
- TypeScript support with full type declarations
- Widget data accumulation for tables, graphs, and combined content
- Special character decoding (`ia_char` placeholders)
- Streaming/SSE support with abort handling
- Step-by-step progress indicators

---

## Quick Start

### Prerequisites

- Node.js 16+ 
- npm 8+
- Host application with Redux store configured

### Installation

```bash
# Navigate to the chatbot-v2 directory
cd frontend/chatbot-v2

# Install dependencies
npm install --legacy-peer-deps

# Build the library
npm run build

# Create distributable package
npm pack
```

This creates `impact-chatbot-2.0.0.tgz` in the project root.

### Install in Host Application

```bash
# From host app directory (e.g., mtp-mfe-inventorysmart/frontend)
npm install ../../chatbot-v2/impact-chatbot-2.0.0.tgz --legacy-peer-deps
```

---

## Build Guide

### Development Build

```bash
# Install dependencies (use legacy-peer-deps for compatibility)
npm install --legacy-peer-deps

# Build library (creates dist/ folder)
npm run build

# Type check only (no emit)
npm run typecheck

# Create tarball for distribution
npm pack
```

### Build Output Structure

```
dist/
├── index.cjs.js          # CommonJS bundle (~5.4MB)
├── index.esm.js          # ESM bundle (~5.3MB)
├── index.cjs.css         # Styles (~8KB)
├── index.esm.css         # Styles (~8KB)
├── index.cjs.js.map      # Source map
├── index.esm.js.map      # Source map
├── *.d.ts                # Type declarations
├── chatbot/              # SVG assets
├── components/           # Component type declarations
├── hooks/                # Hook type declarations
└── services/             # Service type declarations
```

### Rebuild After Changes

```bash
# Quick rebuild and reinstall in host app
npm run build && npm pack

# Then in host app directory:
npm install ../../chatbot-v2/impact-chatbot-2.0.0.tgz --legacy-peer-deps
```

---

## Installation in Host Application

### Step 1: Install the Package

```bash
# From local tarball (recommended)
npm install ./path/to/impact-chatbot-2.0.0.tgz --legacy-peer-deps

# Or link locally during development
cd chatbot-v2 && npm link
cd ../host-app && npm link @impact/chatbot
```

### Step 2: Configure Module Aliases

The library requires the host application to provide certain modules. Add these aliases to your bundler config:

**Webpack (craco.config.js or webpack.config.js):**
```javascript
const path = require('path');

module.exports = {
  webpack: {
    alias: {
      'core': path.resolve(__dirname, 'src/core'),
      'coreAssets': path.resolve(__dirname, 'src/assets'),
      'config': path.resolve(__dirname, 'src/config'),
    }
  }
};
```

**Vite (vite.config.js):**
```javascript
import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
  resolve: {
    alias: {
      'core': path.resolve(__dirname, 'src/core'),
      'coreAssets': path.resolve(__dirname, 'src/assets'),
      'config': path.resolve(__dirname, 'src/config'),
    }
  }
});
```

### Step 3: Import Styles

```javascript
// In your app's entry point (e.g., index.js or App.js)
import '@impact/chatbot/dist/index.esm.css';
```

### Step 4: Configure Redux Store

Ensure your Redux store has the required reducers:

```javascript
// store.js
import { combineReducers } from 'redux';
import smartBotReducer from 'core/reducers/smartBotReducer';
import filterReducer from 'core/reducers/filterReducer';

const rootReducer = combineReducers({
  smartBotReducer,
  filterReducer,
  // ... other reducers
});
```

---

## Usage

### Basic Usage

```tsx
import SmartBot from '@impact/chatbot';

function App() {
  const [showModal, setShowModal] = useState(false);
  const [minimizedMode, setMinimizedMode] = useState(false);

  return (
    <SmartBot
      userName="John Doe"
      showModal={showModal}
      setShowModal={setShowModal}
      minimizedMode={minimizedMode}
      setMinimizedMode={setMinimizedMode}
      invokeBot={true}
      dateFormat="MM/DD/YYYY"
    />
  );
}
```

### Props Reference

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `userName` | string | Yes | Display name for user messages |
| `showModal` | boolean | Yes | Controls chatbot visibility |
| `setShowModal` | function | Yes | Callback to toggle visibility |
| `minimizedMode` | boolean | Yes | Whether chatbot is minimized |
| `setMinimizedMode` | function | Yes | Callback to toggle minimize |
| `invokeBot` | boolean | No | Auto-invoke bot on mount |
| `dateFormat` | string | No | Date format for messages |
| `baseUrl` | string | No | API base URL override |

---

## External Dependencies

The host application must provide these modules via aliases:

### Required Modules

| Alias | Path | Description |
|-------|------|-------------|
| `core` | `src/core` | Redux actions, utilities, styles |
| `coreAssets` | `src/assets` | SVG icons and images |
| `config` | `src/config` | API configuration |

### Key Dependencies from Host

```
core/
├── actions/
│   ├── smartBotActions.js
│   └── tenantConfigActions.js
├── reducers/
│   └── smartBotReducer.js
├── Utils/
│   ├── axios.js
│   └── functions/utils.js (replaceSpecialCharacter)
├── commonComponents/
│   ├── dateRangePicker/
│   └── AgGrid/
└── styles/
    └── colours.js

config/
└── api.js (COMBINED_CROSS_DIMENSIONAL_API)
```

See [DEPENDENCIES.md](./DEPENDENCIES.md) for the complete list.

---

## Troubleshooting

### Common Issues

**1. Module not found errors**
```
Module not found: Can't resolve 'core/...'
```
Solution: Ensure module aliases are configured in your bundler.

**2. Peer dependency warnings**
```
npm WARN peer dependencies
```
Solution: Use `--legacy-peer-deps` flag during installation.

**3. Redux state errors**
```
Cannot read property 'smartBotReducer' of undefined
```
Solution: Ensure `smartBotReducer` is added to your Redux store.

**4. Styles not loading**
```
Chatbot appears unstyled
```
Solution: Import the CSS file in your app entry point.

### Debug Mode

To enable debug logging (development only):
```javascript
localStorage.setItem('CHATBOT_DEBUG', 'true');
```

---

## Changelog

### v2.0.0 (Current)

**Features:**
- TypeScript conversion with full type declarations
- Widget data accumulation for streaming responses
- Special character decoding (`replaceSpecialCharacter`)
- Step update logic with position preservation
- Streaming abort handling (`wasStreamingAborted`)

**Bug Fixes:**
- Fixed table widget not rendering from `widget_data`
- Fixed step order during streaming
- Fixed submit button appearing after abort
- Removed debug console.log statements

---

## Source

Converted from: `frontend/src/core/commonComponents/smartBot`

## Migration from Original smartBot

This library is a drop-in replacement for the original smartBot component:

1. Install the package
2. Configure module aliases
3. Import from `@impact/chatbot` instead of `core/commonComponents/smartBot`
4. Import the CSS file

All props, behavior, and functionality remain compatible with the original.
