npm package: @rxbenefits/data-management
Description: Eligibility import schema management and data transformation utilities for RxBenefits applications
Author: RxBenefits
Latest version: 1.0.0

# @rxbenefits/data-management

> Eligibility import schema management and data transformation utilities for RxBenefits applications

[![npm version](https://img.shields.io/npm/v/@rxbenefits/data-management.svg)](https://www.npmjs.com/package/@rxbenefits/data-management)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

## Overview

The `@rxbenefits/data-management` library provides a comprehensive solution for managing eligibility import schemas and data transformations within RxBenefits applications. It offers a multi-step wizard interface for creating and editing import schemas, visual field mapping with the DataMapper component, and a transformation management system for testing and deploying data transformations.

### Key Features

- **📋 Eligibility Import Schema Management**: Create, edit, view, and manage complex import schemas
- **🗺️ Visual Field Mapping**: Intuitive DataMapper integration for field-to-field mapping
- **⚙️ Data Transformations**: Create, test, and manage data transformation expressions
- **🔐 Permission-Based Access Control**: Role-based access for different operations
- **📊 Multi-Step Workflow**: Stepper-based UI for guided schema creation
- **📝 File Definition Management**: Define file structures, headers, trailers, and field mappings
- **🔍 Schema Usage Tracking**: View which configurations use specific schemas
- **✨ Advanced Options**: Configurable import options for different use cases

## Installation

```bash
npm install @rxbenefits/data-management
```

Or using Yarn:

```bash
yarn add @rxbenefits/data-management
```

### Peer Dependencies

This package has several peer dependencies that must be installed:

```bash
npm install @rxbenefits/api @rxbenefits/components @rxbenefits/constants @rxbenefits/hooks @rxbenefits/icons @rxbenefits/types @rxbenefits/ui @rxbenefits/utils react react-dom react-router-dom
```

## Usage

### Basic Setup

The `DataManagementModule` is the main entry point for the data management functionality. It provides routing for all data management features.

```tsx
import { DataManagementModule } from '@rxbenefits/data-management';
import { Routes, Route } from 'react-router-dom';

function App() {
  return (
    <Routes>
      <Route
        path="/data-management/*"
        element={<DataManagementModule basePath="/data-management" />}
      />
    </Routes>
  );
}
```

### Component Structure

The library is organized into several key areas:

#### 1. Eligibility Imports Management

Provides a table view for searching and managing eligibility import schemas.

```tsx
import { EligibilityImports } from '@rxbenefits/data-management';

// Used internally by DataManagementModule
// Requires DATA_MANAGEMENT_PERMISSIONS.ELIGIBILITY_IMPORTS_VIEW permission
```

**Features**:

- Search schemas by name, importer type, organization, status
- Filter schemas by "My Schemas" or "All Schemas"
- View schema usage tracking
- Edit schemas (with appropriate permissions)
- Link to create new schemas

#### 2. Import Schema Creation Wizard

Multi-step wizard for creating or editing import schemas.

**Steps**:

1. **File Definition**: Define the import file type and basic configuration
2. **Field Definitions**: Specify field structure, headers, trailers, and field mappings
3. **Mapping** (DataMapper files only): Visual field-to-field mapping with transformations
4. **Advanced Options**: Configure additional import options
5. **Description**: Add description and comments to the schema

```tsx
import { CreateImportSchema } from '@rxbenefits/data-management';

// Used internally by DataManagementModule
// Access controlled by permissions:
// - CREATE: DATA_MANAGEMENT_PERMISSIONS.ELIGIBILITY_IMPORTS_CREATE
// - EDIT: DATA_MANAGEMENT_PERMISSIONS.ELIGIBILITY_IMPORTS_EDIT_ALL or EDIT_MINE
// - VIEW: DATA_MANAGEMENT_PERMISSIONS.ELIGIBILITY_IMPORTS_VIEW
```

#### 3. Data Transformations Management

Interface for creating and managing data transformation expressions.

```tsx
import { AdminTransformations } from '@rxbenefits/data-management';

// Used internally by DataManagementModule
// Requires DATA_MANAGEMENT_PERMISSIONS.TRANSFORMATIONS permission
```

**Features**:

- Create new transformations
- Edit existing transformations (if not used in templates)
- Clone transformations
- Test transformations with sample input
- Search/filter transformations
- View which templates use each transformation

## Permissions

This library uses the RxBenefits permission system. The following permissions are required:

| Permission                      | Description                      |
| ------------------------------- | -------------------------------- |
| `ELIGIBILITY_IMPORTS_VIEW`      | View eligibility import schemas  |
| `ELIGIBILITY_IMPORTS_CREATE`    | Create new import schemas        |
| `ELIGIBILITY_IMPORTS_EDIT_ALL`  | Edit any import schema           |
| `ELIGIBILITY_IMPORTS_EDIT_MINE` | Edit own import schemas only     |
| `TRANSFORMATIONS`               | Access transformation management |

These permissions are defined in `@rxbenefits/hooks` as `DATA_MANAGEMENT_PERMISSIONS`.

```tsx
import { DATA_MANAGEMENT_PERMISSIONS, useCheckAnyPermissions } from '@rxbenefits/hooks';

const hasViewAccess = useCheckAnyPermissions(DATA_MANAGEMENT_PERMISSIONS.ELIGIBILITY_IMPORTS_VIEW);
```

## API Integration

The library integrates with several RxBenefits API modules:

### Eligibility Import API

```tsx
import { EligibilityImportAPI } from '@rxbenefits/api';

// Get all schemas
const schemas = await EligibilityImportAPI.eligibilityImport.getAllEligibilityImportSchemas(params);

// Get schema details
const schema = await EligibilityImportAPI.eligibilityImport.getEligibilityImportSchemaByNo(eisNo);

// Create/update schema
await EligibilityImportAPI.eligibilityImport.createEligibilityImportSchema(data);
await EligibilityImportAPI.eligibilityImport.updateEligibilityImportSchema(eisNo, data);
```

### Templates API

```tsx
import { Templates } from '@rxbenefits/api';

// Get template data
const template = await Templates.getTemplateById(id);

// Create/update template
await Templates.createTemplate(data);
await Templates.updateTemplate(id, data);
```

### Transformations API

```tsx
import { Transformations } from '@rxbenefits/api';

// Get all transformations
const transformations = await Transformations.getAll();

// Create/update transformation
await Transformations.create(data);
await Transformations.update(id, data);

// Test transformation
const result = await Transformations.test({ expression, input });
```

## Components

### DataManagementModule

Main module component that provides routing for all data management features.

**Props**:

```tsx
interface ModuleDefinition {
  basePath: string; // Base path for routing (e.g., "/data-management")
}
```

**Routes**:

- `/transformations` - Transformation management interface
- `/eligibility-imports` - Schema list and search
- `/import-schema` - Create new schema
- `/import-schema/:eisNo` - View schema details
- `/import-schema/:eisNo/edit` - Edit existing schema

### EligibilityImports

Table view for managing eligibility import schemas.

**Features**:

- Paginated table with server-side search
- Filters for name, importer type, organization, status
- "My Schemas" vs "All Schemas" toggle
- Schema usage tracking drawer
- Edit links with permission checks

### CreateImportSchema

Multi-step wizard for schema creation and editing.

**Features**:

- File type selection (Legacy, DataMapper)
- Field definition table with headers/trailers
- Visual DataMapper for field mapping (DataMapper files only)
- Advanced options configuration
- Description and comments
- View-only mode for schema details
- Edit mode for updating schemas
- Clone functionality

### AdminTransformations

Transformation management interface.

**Features**:

- List all transformations with search
- Create new transformations
- Edit transformations (if not used in templates)
- Clone existing transformations
- Test transformations with sample input
- View template usage

## Advanced Usage

### Custom Routing

You can integrate the module into your custom routing structure:

```tsx
import {
  EligibilityImports,
  CreateImportSchema,
  AdminTransformations,
} from '@rxbenefits/data-management';
import { ImportsSchemaContextProvider } from '@rxbenefits/data-management';

function DataManagementRoutes() {
  return (
    <Routes>
      <Route path="/transformations" element={<AdminTransformations />} />
      <Route path="/eligibility-imports" element={<EligibilityImports />} />
      <Route
        path="/import-schema"
        element={
          <ImportsSchemaContextProvider>
            <CreateImportSchema />
          </ImportsSchemaContextProvider>
        }
      />
      <Route
        path="/import-schema/:eisNo"
        element={
          <ImportsSchemaContextProvider>
            <CreateImportSchema />
          </ImportsSchemaContextProvider>
        }
      />
      <Route
        path="/import-schema/:eisNo/edit"
        element={
          <ImportsSchemaContextProvider>
            <CreateImportSchema />
          </ImportsSchemaContextProvider>
        }
      />
    </Routes>
  );
}
```

### Schema Context

The `ImportsSchemaContextProvider` provides shared state for the schema creation wizard:

```tsx
import { useImportSchemaContext } from '@rxbenefits/data-management';

function CustomComponent() {
  const {
    form, // Ant Design form instance
    importSchema, // Current schema data
    dmTemplate, // DataMapper template data
    isViewOnly, // View-only mode flag
    isEdit, // Edit mode flag
    isClone, // Clone mode flag
    refetchSchema, // Refetch schema data
    // ... other context values
  } = useImportSchemaContext();

  // Use context values
}
```

## TypeScript Support

This library is written in TypeScript and provides full type definitions.

```tsx
import type {
  EligibilityImportSchemaResponse,
  EligibilityImportSchemaLimitedFieldResponse,
  EISCommentCreateUpdateRequest,
  FileDetailResponse,
  ModuleDefinition,
} from '@rxbenefits/types';

import type { Templates, Transformations } from '@rxbenefits/api';
```

## React Router v6

This library requires React Router v6. All routing components use the v6 API:

```tsx
// Uses Routes, Route, Navigate
import { Routes, Route, Navigate } from 'react-router-dom';

// Uses useNavigate, useParams, useLocation
import { useNavigate, useParams, useLocation } from 'react-router-dom';
```

### Migration from v5

If migrating from React Router v5:

| v5                                | v6                                  |
| --------------------------------- | ----------------------------------- |
| `<Switch>`                        | `<Routes>`                          |
| `<Route component={Component} />` | `<Route element={<Component />} />` |
| `useHistory()`                    | `useNavigate()`                     |
| `history.push(path)`              | `navigate(path)`                    |
| `<Redirect to="/path" />`         | `<Navigate to="/path" replace />`   |

## Security Considerations

### Input Validation

Always validate import data before processing:

```tsx
// File validation
const validateFile = (file: File) => {
  if (file.size > MAX_FILE_SIZE) {
    throw new Error('File too large');
  }
  // Additional validation
};

// Schema validation
const validateSchema = (schema: unknown) => {
  // Use Zod or similar for validation
};
```

### Permission Checks

Always check permissions before allowing operations:

```tsx
import { useCheckAnyPermissions, DATA_MANAGEMENT_PERMISSIONS } from '@rxbenefits/hooks';

const canEdit = useCheckAnyPermissions([
  DATA_MANAGEMENT_PERMISSIONS.ELIGIBILITY_IMPORTS_EDIT_ALL,
  DATA_MANAGEMENT_PERMISSIONS.ELIGIBILITY_IMPORTS_EDIT_MINE,
]);

if (!canEdit) {
  return <AccessDenied />;
}
```

### Transformation Security

Transformation expressions should be validated and sanitized:

```tsx
// Limit transformation execution time
const testTransformation = async (expression: string, input: string) => {
  const timeout = setTimeout(() => {
    throw new Error('Transformation timeout');
  }, 5000);

  try {
    const result = await Transformations.test({ expression, input });
    return result;
  } finally {
    clearTimeout(timeout);
  }
};
```

### HIPAA Compliance

This library may process Protected Health Information (PHI):

- Enable audit logging for all operations
- Implement appropriate access controls
- Encrypt data in transit and at rest
- Follow your organization's HIPAA compliance procedures

## Testing

```bash
# Run tests
npm test

# Run tests in watch mode
npm run test:watch

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

### Example Test

```tsx
import { render, screen } from '@testing-library/react';
import { DataManagementModule } from '@rxbenefits/data-management';
import { BrowserRouter } from 'react-router-dom';

test('renders data management module', () => {
  render(
    <BrowserRouter>
      <DataManagementModule basePath="/data-management" />
    </BrowserRouter>
  );

  // Add assertions
});
```

## Building

```bash
# Build the library
npm run build

# Build in watch mode
npm run build:watch
```

## Contributing

Please read our [Contributing Guide](CONTRIBUTING.md) and [Code of Conduct](CODE_OF_CONDUCT.md) before contributing.

### Development Setup

1. Clone the repository
2. Install dependencies: `npm install`
3. Run tests: `npm test`
4. Build: `npm run build`

## Breaking Changes from Monorepo

### 1. Import Paths

**Before (Monorepo)**:

```tsx
import { DataManagementModule } from '@optimize/data-management';
```

**After (Independent Package)**:

```tsx
import { DataManagementModule } from '@rxbenefits/data-management';
```

### 2. React Router v6 Required

This package requires React Router v6. Consuming applications must upgrade from v5 to v6.

### 3. Directory Name Fixed

Internal directory name `EligbilityImports` (typo) was corrected to `EligibilityImports`. No consumer impact as exports are unchanged.

### 4. Peer Dependencies

All dependencies are now peer dependencies. Consuming applications must install them explicitly.

## License

MIT © RxBenefits

## Support

For issues or questions:

- GitHub Issues: https://github.com/rxbenefits/data-management/issues
- Email: support@rxbenefits.com

## Related Packages

- [@rxbenefits/api](https://www.npmjs.com/package/@rxbenefits/api) - API clients
- [@rxbenefits/components](https://www.npmjs.com/package/@rxbenefits/components) - Shared components
- [@rxbenefits/ui](https://www.npmjs.com/package/@rxbenefits/ui) - UI component library
- [@rxbenefits/hooks](https://www.npmjs.com/package/@rxbenefits/hooks) - React hooks
- [@rxbenefits/types](https://www.npmjs.com/package/@rxbenefits/types) - TypeScript types