npm package: @rxbenefits/admin
Description: Administrative functionality for RxBenefits platform including user management, roles, and permissions
Author: RxBenefits
Latest version: 1.0.0

# @rxbenefits/admin

**Administrative functionality for the RxBenefits platform including user management, roles, permissions, and feature flags.**

[![npm version](https://img.shields.io/npm/v/@rxbenefits/admin.svg)](https://www.npmjs.com/package/@rxbenefits/admin)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue)](https://www.typescriptlang.org/)
[![React](https://img.shields.io/badge/React-18.0-blue)](https://reactjs.org/)

## 📋 Table of Contents

- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
- [Components](#components)
- [Hooks](#hooks)
- [API](#api)
- [Development](#development)
- [Contributing](#contributing)
- [License](#license)

## 🎯 Overview

The `@rxbenefits/admin` package provides a comprehensive suite of administrative tools for the RxBenefits platform. It includes user management, role-based access control, feature flags administration, and user import/export functionality.

### Key Capabilities

- **User Management**: Create, edit, view, and manage users across the platform
- **Role-Based Access Control**: Comprehensive roles and permissions system
- **User Import**: Import users from DataNet or other external systems
- **Feature Flags**: Admin interface for managing feature flags
- **Multi-Tenant Support**: Organization-based user management
- **User Types**: Support for Internal, Broker, and Client user types

## ✨ Features

### User Management
- Create new users (Internal, Broker, Client types)
- Edit existing user details
- View comprehensive user information
- Import users from external systems
- Manage user activation/deactivation
- Assign roles and permissions
- Manage organizational access

### Role Management
- View and manage user roles
- Assign roles to users
- Role-based permission system
- Custom role configurations

### Feature Flags Administration
- View all feature flags
- Enable/disable feature flags
- Real-time feature flag management
- Developer-only access control

### Organization Management
- Assign users to organizations
- Manage benefit group access
- Multi-organization support
- Organization-level permissions

## 📦 Installation

```bash
# Using yarn
yarn add @rxbenefits/admin

# Using npm
npm install @rxbenefits/admin
```

### Peer Dependencies

This package requires the following peer dependencies:

```json
{
  "react": "^18.0.0",
  "react-dom": "^18.0.0"
}
```

### Additional Dependencies

The package also depends on other RxBenefits packages:

```bash
yarn add @rxbenefits/api @rxbenefits/components @rxbenefits/constants \
         @rxbenefits/contexts @rxbenefits/forms @rxbenefits/hooks \
         @rxbenefits/types @rxbenefits/ui @rxbenefits/utils
```

## 🚀 Usage

### Basic Usage

```typescript
import { AdminModule } from '@rxbenefits/admin';
import { ModuleConfig } from '@rxbenefits/contexts';

function App() {
  return (
    <ModuleConfig basePath="/admin">
      <AdminModule basePath="/admin" />
    </ModuleConfig>
  );
}
```

### User Management

```typescript
import { AdminCreateUser, AdminUsers, AdminUserDetail } from '@rxbenefits/admin';
import { Route, Routes } from 'react-router-dom';

function UserManagement() {
  return (
    <Routes>
      <Route path="/users" element={<AdminUsers />} />
      <Route path="/users/create" element={<AdminCreateUser />} />
      <Route path="/users/:id" element={<AdminUserDetail />} />
    </Routes>
  );
}
```

### Role Management

```typescript
import { AdminRoles } from '@rxbenefits/admin';

function RoleManagement() {
  return <AdminRoles />;
}
```

### Feature Flags Administration

```typescript
import { AdminFeatureFlags } from '@rxbenefits/admin';

function FeatureFlagsAdmin() {
  return <AdminFeatureFlags />;
}
```

### User Import

```typescript
import { ImportUser } from '@rxbenefits/admin';

function UserImport() {
  return <ImportUser />;
}
```

## 📚 Components

### AdminModule

Main module component that provides routing for all admin features.

**Props:**
- `basePath: string` - Base path for admin routes

**Example:**
```typescript
<AdminModule basePath="/admin" />
```

### AdminUsers

User list component with search, filtering, and pagination.

**Features:**
- Display paginated list of users
- Search by name, email, organization
- Filter by user type, status, role
- Quick actions (view, edit, deactivate)

**Example:**
```typescript
<AdminUsers />
```

### AdminCreateUser

User creation form with validation and role assignment.

**Features:**
- User type selection (Internal, Broker, Client)
- User details form
- Organization selection
- Role and permission assignment
- Benefit group management
- User activation toggle

**Example:**
```typescript
<AdminCreateUser />
```

### AdminUserDetail

User detail view and edit form.

**Features:**
- View/edit user information
- Update roles and permissions
- Manage organizational access
- Update user status
- View user activity

**Example:**
```typescript
<AdminUserDetail />
```

### AdminRoles

Role management interface.

**Features:**
- View all available roles
- Role descriptions and permissions
- Role assignment interface

**Example:**
```typescript
<AdminRoles />
```

### AdminFeatureFlags

Feature flags administration interface.

**Features:**
- View all feature flags
- Enable/disable flags
- Real-time updates
- Developer-only access

**Example:**
```typescript
<AdminFeatureFlags />
```

### ImportUser

User import from external systems (DataNet).

**Features:**
- Email-based user lookup
- Preview user data
- Import user to Optimize platform
- Error handling and validation

**Example:**
```typescript
<ImportUser />
```

## 🎣 Hooks

### useCurrentUser

Hook to get current user information and permissions.

**Returns:**
- `currentUser` - Current user object
- `currentUserAccess` - Current user access permissions
- `currentUserOrganizations` - Current user's organizations
- `isCurrentUserRxBAdmin` - Whether current user is RxB admin
- `isCurrentUserLoading` - Loading state
- `userData` - Extended user data
- `isUserDataLoading` - User data loading state

**Example:**
```typescript
import { useCurrentUser } from '@rxbenefits/admin';

function MyComponent() {
  const { currentUser, isCurrentUserRxBAdmin } = useCurrentUser();
  
  if (isCurrentUserRxBAdmin) {
    return <div>Admin features</div>;
  }
  
  return <div>Regular features</div>;
}
```

### useEditUser

Hook for editing user information.

**Parameters:**
- `userId: number` - User ID to edit

**Returns:**
- `userData` - User data
- `isLoading` - Loading state
- `updateUser` - Function to update user
- `isUpdating` - Update in progress state

**Example:**
```typescript
import { useEditUser } from '@rxbenefits/admin';

function EditUserComponent({ userId }) {
  const { userData, updateUser, isUpdating } = useEditUser(userId);
  
  const handleUpdate = (data) => {
    updateUser(data, {
      onSuccess: () => console.log('User updated'),
      onError: (error) => console.error('Update failed', error)
    });
  };
  
  return <div>Edit user form</div>;
}
```

### useSelectedSet

Hook for managing selected items (roles, organizations, etc.).

**Returns:**
- `[selected, setSelected, handleUpdates]` - Array of selected items, setter, and update handler

**Example:**
```typescript
import { useSelectedSet } from '@rxbenefits/admin';

function RoleSelection() {
  const [selectedRoles, setSelectedRoles, handleRoleUpdates] = useSelectedSet<number>([]);
  
  const handleRoleChange = (roleId: number, checked: boolean) => {
    handleRoleUpdates(roleId, checked);
  };
  
  return <div>Role selection UI</div>;
}
```

## 🛠️ Development

### Setup

```bash
# Clone the repository
git clone https://github.com/rxbenefits/admin.git
cd admin

# Install dependencies
yarn install

# Run tests
yarn test

# Build the package
yarn build
```

### Scripts

- `yarn build` - Build the package for production
- `yarn test` - Run the test suite
- `yarn test:watch` - Run tests in watch mode
- `yarn test:coverage` - Generate test coverage report
- `yarn lint` - Lint the codebase
- `yarn lint:fix` - Fix linting issues
- `yarn typecheck` - Run TypeScript type checking
- `yarn clean` - Clean build artifacts

### Testing

```bash
# Run all tests
yarn test

# Run tests in watch mode
yarn test:watch

# Generate coverage report
yarn test:coverage
```

### Building

```bash
# Build for production
yarn build

# Clean and rebuild
yarn clean && yarn build
```

## 📝 API Reference

### Types

```typescript
import {
  UserType,
  AuthUser,
  CreateAuthUserRequest,
  UpdateAuthUserRequest,
  AuthCreateUserOrgs,
  SelectedBenefitGroups
} from '@rxbenefits/admin';
```

### Constants

```typescript
import {
  MANAGE_USER_PERMISSIONS,
  ORGANIZATION_PERMISSIONS
} from '@rxbenefits/admin';
```

### Utilities

```typescript
import {
  filterTransferOptions,
  scrollToError,
  RoleGroupMappings
} from '@rxbenefits/admin';
```

## 🔒 Security

### Authentication

All admin features require authentication via Auth0. Users must be logged in to access any admin functionality.

### Authorization

Admin features use role-based access control (RBAC):

- **View Users**: Requires `MANAGE_USER_PERMISSIONS.VIEW` and `ORGANIZATION_PERMISSIONS.AUTH_VIEW`
- **Create Users**: Requires `MANAGE_USER_PERMISSIONS.ADD` and `ORGANIZATION_PERMISSIONS.AUTH_VIEW`
- **Edit Users**: Requires `MANAGE_USER_PERMISSIONS.EDIT` and `ORGANIZATION_PERMISSIONS.AUTH_VIEW`
- **Import Users**: Requires `MANAGE_USER_PERMISSIONS.IMPORTDNUSER`
- **View Roles**: Requires specific role permissions
- **Feature Flags**: Requires developer permissions

### Data Protection

- All user data is encrypted in transit and at rest
- HIPAA compliance for protected health information
- Audit logging for all administrative actions
- Multi-factor authentication support

## 🤝 Contributing

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

### Development Process

1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for your changes
5. Run tests and linting (`yarn test && yarn lint`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request

### Code Style

- Follow the existing code style
- Use TypeScript for all new code
- Write tests for new features
- Update documentation as needed
- Use meaningful commit messages

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🔗 Related Packages

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

## 📞 Support

For support, please contact:
- Email: support@rxbenefits.com
- Issues: [GitHub Issues](https://github.com/rxbenefits/admin/issues)

## 📊 Changelog

See [CHANGELOG.md](CHANGELOG.md) for a list of changes.

---

Made with ❤️ by RxBenefits