npm package: @rxbenefits/agent
Description: Agent desktop functionality for RxBenefits applications including member search, member summary, and issue management
Author: RxBenefits
Latest version: 1.0.0

# @rxbenefits/agent

> Agent desktop functionality for RxBenefits applications

[![NPM Version](https://img.shields.io/npm/v/@rxbenefits/agent.svg)](https://www.npmjs.com/package/@rxbenefits/agent)
[![License](https://img.shields.io/npm/l/@rxbenefits/agent.svg)](https://github.com/rxbenefits/agent/blob/main/LICENSE)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.7-blue.svg)](https://www.typescriptlang.org/)

## Overview

The **Agent Library** provides comprehensive call center and customer service functionality for RxBenefits pharmacy benefits management applications. This library includes components for member search, member summary views, issue management, incoming call handling, and agent desktop workflows.

## Table of Contents

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Modules](#core-modules)
- [Components](#components)
- [Hooks](#hooks)
- [API Reference](#api-reference)
- [Examples](#examples)
- [Architecture](#architecture)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

## Features

### 🔍 Member Search & Verification

- **Advanced Search**: Search members by multiple criteria (name, DOB, member ID, etc.)
- **AI-Powered Verification**: GenAI-based member identity verification
- **Real-time Results**: Instant search with advanced filtering
- **Search History**: Track and revisit recent searches

### 👥 Member Summary

- **Comprehensive Profile**: View complete member information
- **Organization Details**: Organization-level data and relationships
- **Plan Eligibility**: Active coverage and plan details
- **Communication Preferences**: Manage member contact preferences
- **Temporary ID Cards**: Generate and manage temp cards

### 📋 Issue Management

- **Create Issues**: Track member problems and requests
- **AI Summary**: GenAI-generated issue summaries
- **Issue History**: View and manage all member issues
- **File Attachments**: Support for document uploads
- **Status Tracking**: Monitor issue resolution progress

### 📞 Incoming Call Handling

- **Call Events**: Real-time call assignment notifications
- **Caller Verification**: Verify caller identity
- **Call Routing**: Automatic member lookup and routing
- **AI Insights**: GenAI-powered repeat caller detection

### 📊 Agent Resources

- **Group Information**: Organization contacts, materials, programs
- **PBC Information**: Pharmacy Benefits Coordinator details
- **Plan Changes**: Track plan modifications
- **Plan Notes**: Important organization-level notes

### 📜 Member History

- **Claims History**: View member claims with PBM links
- **Prior Authorizations**: PA history and status
- **Recent Notes**: Latest agent interactions
- **Authorization Details**: Detailed PA information
- **PA Instructions**: Email/fax PA instructions to providers

## Installation

```bash
npm install @rxbenefits/agent
```

### Peer Dependencies

This library requires the following peer dependencies:

```bash
npm install react@^18.3.1 react-dom@^18.3.1 react-router-dom@^6.0.0 antd@^4.18.0 styled-components@^5.3.0
```

### Dependencies

The agent library depends on other RxBenefits packages:

```bash
npm install @rxbenefits/api @rxbenefits/components @rxbenefits/constants @rxbenefits/contexts @rxbenefits/forms @rxbenefits/hooks @rxbenefits/types @rxbenefits/ui @rxbenefits/utils
```

## Quick Start

### Basic Setup

```tsx
import { AgentModule } from '@rxbenefits/agent';
import { BrowserRouter } from 'react-router-dom';

function App() {
  return (
    <BrowserRouter>
      <AgentModule />
    </BrowserRouter>
  );
}
```

### Member Search

```tsx
import { MemberSearch } from '@rxbenefits/agent';

function SearchPage() {
  return (
    <MemberSearch
      onMemberSelect={(member) => {
        console.log('Selected member:', member);
      }}
    />
  );
}
```

### Member Summary

```tsx
import { MemberSummary } from '@rxbenefits/agent';

function SummaryPage() {
  const memberId = '12345';

  return <MemberSummary memberId={memberId} employeeData={employeeData} />;
}
```

### Issue Management

```tsx
import { MemberIssuesForm } from '@rxbenefits/agent';

function IssuesPage() {
  return (
    <MemberIssuesForm
      memberId="12345"
      onSubmit={(issue) => {
        console.log('Issue created:', issue);
      }}
    />
  );
}
```

## Core Modules

### AgentModule

Main routing module for agent desktop functionality.

```tsx
import { AgentModule } from '@rxbenefits/agent';

<AgentModule />;
```

**Features:**

- Routing configuration for all agent features
- Lazy-loaded components for performance
- Integrated with React Router v6

### AgentDesktop

Primary agent workspace with tabbed interface.

```tsx
import { AgentDesktopMain } from '@rxbenefits/agent';

<AgentDesktopMain />;
```

**Features:**

- Tabbed interface for multiple member sessions
- Pending notes management
- Member not found handling
- Session persistence

### AgentEventsProvider

Manages real-time agent events via AWS AppSync.

```tsx
import { AgentEventsProvider } from '@rxbenefits/agent';

<AgentEventsProvider>{/* Your agent components */}</AgentEventsProvider>;
```

**Features:**

- Subscribes to call assignment events
- Manages WebSocket connections
- Event normalization and handling
- Automatic reconnection

## Components

### Layout Components

#### DataRow

Displays data in a labeled row format.

```tsx
import { DataRow } from '@rxbenefits/agent';

<DataRow label="Member ID" value="ABC123" />;
```

#### DetailLayout

Standardized layout for detail views.

```tsx
import { DetailLayout } from '@rxbenefits/agent';

<DetailLayout header={<h1>Member Details</h1>} content={<div>Content here</div>} />;
```

### Search Components

#### MemberSearchForm

Search form with advanced filtering.

```tsx
import { MemberSearchForm } from '@rxbenefits/agent';

<MemberSearchForm onSearch={(criteria) => performSearch(criteria)} />;
```

**Search Criteria:**

- First Name / Last Name
- Date of Birth
- Member ID / SSN
- Phone Number
- Organization

#### MemberSearchWarningModal

Displays validation warnings during search.

```tsx
import { MemberSearchWarningModal } from '@rxbenefits/agent';

<MemberSearchWarningModal
  visible={showWarning}
  message="Please provide more search criteria"
  onClose={() => setShowWarning(false)}
/>;
```

### Issue Components

#### MemberIssuesForm

Create and manage member issues.

```tsx
import { MemberIssuesForm } from '@rxbenefits/agent';

<MemberIssuesForm memberId="12345" employeeData={employee} onSubmit={handleIssueCreation} />;
```

**Issue Types:**

- Benefit Questions
- Claim Issues
- Prior Authorization
- ID Card Requests
- General Inquiries

#### IssueDrawer

Side drawer for viewing issue details.

```tsx
import { IssueDrawer } from '@rxbenefits/agent';

<IssueDrawer issueId="issue-123" visible={drawerVisible} onClose={() => setDrawerVisible(false)} />;
```

#### AISummaryField

GenAI-powered issue summary generation.

```tsx
import { AISummaryField } from '@rxbenefits/agent';

<AISummaryField issueData={currentIssue} onSummaryGenerated={(summary) => console.log(summary)} />;
```

### Summary Components

#### MemberProfile

Displays comprehensive member profile.

```tsx
import { MemberProfile } from '@rxbenefits/agent';

<MemberProfile employee={employeeData} dependent={dependentData} />;
```

**Profile Information:**

- Personal details (name, DOB, gender)
- Contact information
- Member status and eligibility
- Coverage information
- Age and relationship

#### OrganizationProfile

Shows organization-level information.

```tsx
import { OrganizationProfile } from '@rxbenefits/agent';

<OrganizationProfile organization={orgData} />;
```

**Organization Information:**

- Organization name and ID
- Status and effective dates
- Group structure
- Broker information

#### CommunicationPreference

Manage member communication preferences.

```tsx
import { CommunicationPreference } from '@rxbenefits/agent';

<CommunicationPreference memberId="12345" onUpdate={(prefs) => console.log('Updated:', prefs)} />;
```

**Preference Options:**

- Contact methods (email, phone, mail)
- Language preferences
- Confidentiality settings
- Additional contact options

#### PlanEligibility

Displays member plan eligibility and coverage.

```tsx
import { PlanEligibility } from '@rxbenefits/agent';

<PlanEligibility coverage={coverageData} planProvision={planData} />;
```

#### TempIdCard

Generate and manage temporary ID cards.

```tsx
import { TempIdCard } from '@rxbenefits/agent';

<TempIdCard employee={employeeData} onCardGenerated={(card) => console.log('Card:', card)} />;
```

#### AOR (Authorization Representative)

View and manage authorized representatives.

```tsx
import { AOR } from '@rxbenefits/agent';

<AOR memberId="12345" onUpdate={() => refetchData()} />;
```

### Incoming Call Components

#### IncomingCallPopup

Displays incoming call notifications.

```tsx
import { IncomingCallPopup } from '@rxbenefits/agent';

<IncomingCallPopup
  callData={incomingCall}
  onAccept={(call) => handleCallAccept(call)}
  onDismiss={() => dismissCall()}
/>;
```

**Features:**

- Real-time call notifications
- Caller information display
- Auto-search for matching members
- GenAI member verification

### Panel Components

#### AgentResourcesPanel

Comprehensive agent resources and tools.

```tsx
import { AgentResourcesPanel } from '@rxbenefits/agent';

<AgentResourcesPanel organizationNo="ORG123" />;
```

**Sections:**

- Group Information (contacts, materials, programs)
- PBC Information (coordinators and contacts)
- Plan Changes
- Plan Notes

#### MemberHistoryPanel

Complete member interaction history.

```tsx
import { MemberHistoryPanel } from '@rxbenefits/agent';

<MemberHistoryPanel memberId="12345" employeeData={employee} />;
```

**History Types:**

- Claims History
- Prior Authorization History
- Recent Notes
- Issue History

## Hooks

### useAgent

Core hook for agent functionality.

```tsx
import { useAgent } from '@rxbenefits/agent';

function AgentComponent() {
  const { agentId, isAgentActive, currentCall } = useAgent();

  return <div>Agent ID: {agentId}</div>;
}
```

### useAgentRoutes

Hook for agent routing configuration.

```tsx
import { useAgentRoutes } from '@rxbenefits/agent';

function RouterComponent() {
  const routes = useAgentRoutes();

  return <Routes>{routes}</Routes>;
}
```

### useMember

Hook for member data and operations.

```tsx
import { useMember } from '@rxbenefits/agent';

function MemberComponent({ memberId }: { memberId: string }) {
  const { member, isLoading, error, refetch } = useMember(memberId);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return <div>{member.name}</div>;
}
```

### useEventTracking

Hook for tracking agent events.

```tsx
import { useEventTracking } from '@rxbenefits/agent';

function TrackedComponent() {
  const { trackEvent } = useEventTracking();

  const handleAction = () => {
    trackEvent('member_search', { criteria: 'name' });
  };

  return <button onClick={handleAction}>Search</button>;
}
```

### useRequestNewCard

Hook for requesting new member ID cards.

```tsx
import { useRequestNewCard } from '@rxbenefits/agent';

function CardRequestComponent({ memberId }: { memberId: string }) {
  const { requestCard, isRequesting, error } = useRequestNewCard(memberId);

  return (
    <button onClick={requestCard} disabled={isRequesting}>
      Request New Card
    </button>
  );
}
```

### useAISummary

Hook for GenAI summary generation.

```tsx
import { useAISummary } from '@rxbenefits/agent';

function SummaryComponent({ issueId }: { issueId: string }) {
  const { summary, generateSummary, isGenerating } = useAISummary(issueId);

  return (
    <div>
      <button onClick={generateSummary}>Generate Summary</button>
      {summary && <p>{summary}</p>}
    </div>
  );
}
```

## API Reference

### Types

#### Employee

```typescript
interface Employee {
  employeeNo: number;
  firstName: string;
  lastName: string;
  dateOfBirth: string;
  gender: string;
  ssn?: string;
  status: string;
  effectiveDate: string;
  terminationDate?: string;
  // ... additional fields
}
```

#### Dependent

```typescript
interface Dependent {
  dependentNo: number;
  employeeNo: number;
  firstName: string;
  lastName: string;
  dateOfBirth: string;
  gender: string;
  relationship: string;
  status: string;
  // ... additional fields
}
```

#### MemberIssue

```typescript
interface CreateIssueRequest {
  employeeNo: number;
  organizationNo: number;
  issueType: string;
  description: string;
  priority: 'low' | 'medium' | 'high';
  attachments?: File[];
  // ... additional fields
}
```

### Utilities

#### appSyncClient

AppSync client configuration for real-time events.

```typescript
import { appSyncClient } from '@rxbenefits/agent';

const client = appSyncClient(auth);
```

#### getBrowserRequirement

Check browser compatibility.

```typescript
import { getBrowserRequirement } from '@rxbenefits/agent';

const isCompatible = getBrowserRequirement();
```

#### partnerPbms

PBM (Pharmacy Benefit Manager) partner utilities.

```typescript
import { partnerPbms } from '@rxbenefits/agent';

const pbmList = partnerPbms.getAllPBMs();
```

## Examples

### Complete Agent Desktop Setup

```tsx
import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import { AgentModule, AgentEventsProvider, EditingWarningContext } from '@rxbenefits/agent';

function AgentApp() {
  return (
    <BrowserRouter>
      <AgentEventsProvider>
        <EditingWarningContext>
          <AgentModule />
        </EditingWarningContext>
      </AgentEventsProvider>
    </BrowserRouter>
  );
}

export default AgentApp;
```

### Member Search with Results

```tsx
import React, { useState } from 'react';
import { MemberSearch, MemberSummary } from '@rxbenefits/agent';

function SearchAndView() {
  const [selectedMember, setSelectedMember] = useState(null);

  return (
    <div>
      <MemberSearch onMemberSelect={(member) => setSelectedMember(member)} />
      {selectedMember && (
        <MemberSummary memberId={selectedMember.id} employeeData={selectedMember} />
      )}
    </div>
  );
}
```

### Issue Creation with AI Summary

```tsx
import React from 'react';
import { MemberIssuesForm, AISummaryField } from '@rxbenefits/agent';

function CreateIssue({ memberId, employeeData }) {
  const handleSubmit = async (issueData) => {
    console.log('Creating issue:', issueData);
    // Submit to API
  };

  return (
    <MemberIssuesForm
      memberId={memberId}
      employeeData={employeeData}
      onSubmit={handleSubmit}
      renderSummaryField={(props) => <AISummaryField {...props} />}
    />
  );
}
```

### Incoming Call Handler

```tsx
import React, { useEffect } from 'react';
import { useAgent, IncomingCallPopup } from '@rxbenefits/agent';
import { AgentEventsProvider } from '@rxbenefits/agent';

function CallHandler() {
  const { currentCall, acceptCall, dismissCall } = useAgent();

  return (
    <AgentEventsProvider>
      {currentCall && (
        <IncomingCallPopup callData={currentCall} onAccept={acceptCall} onDismiss={dismissCall} />
      )}
    </AgentEventsProvider>
  );
}
```

## Architecture

### Module Structure

```
@rxbenefits/agent/
├── AgentModule.tsx          # Main routing module
├── AgentDesktop/            # Agent workspace
│   ├── AgentDesktopMain.tsx
│   └── Components/
├── AgentEvents/             # Real-time events
│   ├── AgentEventsProvider.tsx
│   └── normalizeCallAssignedEvent.ts
├── MemberSearch/            # Member search
│   ├── MemberSearch.tsx
│   └── Components/
├── MemberSummary/           # Member details
│   ├── MemberSummary.tsx
│   ├── OrganizationSummary.tsx
│   └── Components/
├── MemberIssues/            # Issue management
│   ├── MemberIssuesForm.tsx
│   └── Components/
├── IncomingCall/            # Call handling
│   ├── IncomingCallPopup.tsx
│   └── searchQueryBuilder.ts
├── Components/              # Shared components
├── Hooks/                   # Custom hooks
├── Contexts/                # React contexts
└── Utils/                   # Utilities
```

### Data Flow

1. **Agent Events**: Real-time call events via AWS AppSync subscriptions
2. **Member Search**: Query members via API, display results
3. **Member Summary**: Load complete member profile on selection
4. **Issue Creation**: Submit issues with GenAI summaries
5. **History**: Fetch and display member interaction history

### State Management

- **React Context**: EditingWarningContext for unsaved changes
- **React Query**: API data fetching and caching
- **Zustand**: Local state management (optional)
- **AgentEventsProvider**: WebSocket event management

## Testing

### Running Tests

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage
```

### Test Structure

```typescript
import { render, screen, fireEvent } from '@testing-library/react';
import { MemberSearch } from '@rxbenefits/agent';

describe('MemberSearch', () => {
  it('should render search form', () => {
    render(<MemberSearch onMemberSelect={jest.fn()} />);
    expect(screen.getByRole('form')).toBeInTheDocument();
  });

  it('should handle search submission', () => {
    const onSearch = jest.fn();
    render(<MemberSearch onMemberSelect={onSearch} />);

    // Fill form and submit
    fireEvent.change(screen.getByLabelText('First Name'), {
      target: { value: 'John' },
    });
    fireEvent.submit(screen.getByRole('form'));

    expect(onSearch).toHaveBeenCalled();
  });
});
```

### Test Coverage

Current test coverage:

- Components: Tests for AgentEventsProvider, IncomingCallPopup
- Utilities: Tests for event normalization, search query builder
- Target: 70%+ coverage for all modules

## Performance

### Bundle Size

- Minified: ~450 KB
- Gzipped: ~120 KB

### Optimization Tips

1. **Lazy Loading**: Use React.lazy() for route-based code splitting
2. **Memoization**: Use React.memo() for expensive components
3. **Virtual Scrolling**: For large lists in search results
4. **Debouncing**: Debounce search inputs to reduce API calls

### Performance Metrics

- Initial render: < 200ms
- Search response: < 500ms (network dependent)
- Member summary load: < 300ms

## Browser Support

- Chrome 90+
- Firefox 88+
- Safari 14+
- Edge 90+

## Accessibility

- WCAG 2.1 AA compliant
- Keyboard navigation support
- Screen reader compatible
- Proper ARIA labels

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

```bash
# Clone repository
git clone https://github.com/rxbenefits/agent.git

# Install dependencies
cd agent
npm install

# Run tests
npm test

# Build library
npm run build
```

### Code Style

- TypeScript with strict mode
- ESLint + Prettier for formatting
- Follow existing code patterns
- Write tests for new features

## License

MIT © RxBenefits

## Support

- Documentation: [https://docs.rxbenefits.com](https://docs.rxbenefits.com)
- Issues: [https://github.com/rxbenefits/agent/issues](https://github.com/rxbenefits/agent/issues)
- Email: support@rxbenefits.com

## Changelog

See [CHANGELOG.md](CHANGELOG.md) for version history and release notes.

## Related Packages

- [@rxbenefits/api](https://www.npmjs.com/package/@rxbenefits/api) - API clients and services
- [@rxbenefits/components](https://www.npmjs.com/package/@rxbenefits/components) - Shared React components
- [@rxbenefits/ui](https://www.npmjs.com/package/@rxbenefits/ui) - UI component library
- [@rxbenefits/hooks](https://www.npmjs.com/package/@rxbenefits/hooks) - Custom React hooks
- [@rxbenefits/types](https://www.npmjs.com/package/@rxbenefits/types) - TypeScript type definitions
- [@rxbenefits/utils](https://www.npmjs.com/package/@rxbenefits/utils) - Utility functions
- [@rxbenefits/forms](https://www.npmjs.com/package/@rxbenefits/forms) - Form schemas and validation
- [@rxbenefits/contexts](https://www.npmjs.com/package/@rxbenefits/contexts) - React contexts
- [@rxbenefits/constants](https://www.npmjs.com/package/@rxbenefits/constants) - Application constants