# Salesforce CRM Module

## Overview
This module provides a complete Salesforce CRM integration for the Centralized Reporting System, including dashboard visualizations, data management, and comprehensive analytics.

## Structure

```
salesforce/
├── components/
│   └── SalesforceDataCards.tsx      # Card components for each data type
├── screens/
│   ├── SalesforceCrmDashboardScreen.tsx  # Dashboard with KPIs and charts
│   └── SalesforceDataScreen.tsx          # Tabbed data view with all CRM data
├── services/
│   └── salesforceCrmAPI.ts          # API service for Salesforce data
├── store/
│   ├── salesforceCrmSlice.ts        # Redux slice with state management
│   └── selectors.ts                 # Redux selectors
├── types/
│   └── SalesforceCrmTypes.ts        # TypeScript type definitions
└── index.ts                         # Module exports
```

## API Endpoints

The module integrates with the following Salesforce CRM endpoints:

- **Events**: `/api/v1/n8n/salesforce/crm/events`
- **Leads**: `/api/v1/n8n/salesforce/crm/leads`
- **Tasks**: `/api/v1/n8n/salesforce/crm/tasks`
- **Accounts**: `/api/v1/n8n/salesforce/crm/accounts`
- **Opportunities**: `/api/v1/n8n/salesforce/crm/opportunities`

## Features

### Dashboard Screen (`SalesforceCrmDashboardScreen`)
- **Hero Stats**: Large cards showing Leads and Opportunities totals
- **Pipeline Overview**: Total pipeline value, average deal size, and open deals
- **Module Counts**: Compact grid showing Events, Tasks, and Accounts counts
- **Lead Status Distribution**: Pie chart showing New, Working, and Qualified leads
- **Task Status**: Stacked bar chart showing Open, Completed, and High Priority tasks
- **Key Metrics**: Upcoming Events and Won Deals summary
- **Pull-to-refresh** functionality
- **Real-time data updates**

### Data Screen (`SalesforceDataScreen`)
- **Tabbed Interface**: Switch between Events, Leads, Tasks, Accounts, and Opportunities
- **Data Cards**: Rich card display for each data type with relevant information
- **Infinite Scrolling**: Load more data as you scroll
- **Count Badges**: Show total count for each tab
- **Pull-to-refresh** functionality
- **Error handling and loading states**

### Data Types

#### Event
- Subject, Location, Description
- Start/End DateTime
- All Day Event indicator
- Created date

#### Lead
- Name (First + Last)
- Company, Email, Phone
- Status (New, Working, Nurturing, Qualified, Unqualified)
- Title, Lead Source
- Created date

#### Task
- Subject, Description
- Status (Open, In Progress, Completed, Waiting, Deferred)
- Priority (High, Normal, Low)
- Activity Date
- Created/Modified dates

#### Account
- Name, Industry, Type
- Phone, Website
- Billing Address (City, State, Country)
- Annual Revenue
- Created date

#### Opportunity
- Name, Stage, Type
- Amount, Probability
- Close Date, Forecast Category
- Created/Modified dates

## Redux State Management

### State Structure
```typescript
{
  events: SalesforceEvent[];
  leads: SalesforceLead[];
  tasks: SalesforceTask[];
  accounts: SalesforceAccount[];
  opportunities: SalesforceOpportunity[];
  loading: { /* loading states for each type */ };
  errors: { /* error states for each type */ };
  pagination: { /* pagination info for each type */ };
  counts: { /* total counts from API */ };
  lastUpdated: { /* last updated timestamps */ };
}
```

### Actions
- `fetchAllSalesforceCrmData()` - Fetch all data types in parallel
- `fetchSalesforceEvents()` - Fetch events with pagination
- `fetchSalesforceLeads()` - Fetch leads with pagination
- `fetchSalesforceTasks()` - Fetch tasks with pagination
- `fetchSalesforceAccounts()` - Fetch accounts with pagination
- `fetchSalesforceOpportunities()` - Fetch opportunities with pagination
- `fetchSalesforceCrmCounts()` - Fetch total counts for all types
- `resetEventsPagination()` - Reset events pagination
- `resetLeadsPagination()` - Reset leads pagination
- `resetTasksPagination()` - Reset tasks pagination
- `resetAccountsPagination()` - Reset accounts pagination
- `resetOpportunitiesPagination()` - Reset opportunities pagination
- `clearData()` - Clear all data
- `clearErrors()` - Clear all errors

### Selectors
- `selectSalesforceEvents` - Get events array
- `selectSalesforceLeads` - Get leads array
- `selectSalesforceTasks` - Get tasks array
- `selectSalesforceAccounts` - Get accounts array
- `selectSalesforceOpportunities` - Get opportunities array
- `selectSalesforceCrmLoading` - Get loading states
- `selectSalesforceCrmErrors` - Get error states
- `selectSalesforceCrmCounts` - Get total counts
- `selectDashboardData` - Get computed dashboard data with summary
- `selectIsAnyLoading` - Check if any data is loading
- `selectHasAnyError` - Check if any errors exist

## Navigation

The module is integrated into the CRM navigator:

```typescript
<Stack.Screen 
  name="SalesforceDashboard" 
  component={SalesforceCrmDashboardScreen} 
  options={{headerShown:false}} 
/>
<Stack.Screen 
  name="SalesforceData" 
  component={SalesforceDataScreen} 
  options={{headerShown:false}} 
/>
```

## Usage

### Navigate to Salesforce Dashboard
```typescript
navigation.navigate('SalesforceDashboard');
```

### Navigate to Salesforce Data Screen
```typescript
navigation.navigate('SalesforceData');
```

### Fetch Salesforce Data
```typescript
import { useDispatch } from 'react-redux';
import { fetchAllSalesforceCrmData } from '@/modules/crm/salesforce';

const dispatch = useDispatch();

// Fetch all data
await dispatch(fetchAllSalesforceCrmData()).unwrap();

// Fetch specific data type with pagination
await dispatch(fetchSalesforceLeads({ page: 1, limit: 20 })).unwrap();
```

### Access Salesforce Data
```typescript
import { useSelector } from 'react-redux';
import { selectSalesforceLeads, selectDashboardData } from '@/modules/crm/salesforce';

// Get leads
const leads = useSelector(selectSalesforceLeads);

// Get dashboard data with computed summaries
const dashboardData = useSelector(selectDashboardData);
```

## API Response Format

All endpoints return responses in the following format:

```json
{
  "status": "success",
  "message": "Salesforce crm {resource} data fetched successfully",
  "data": {
    "success": true,
    "data": [ /* array of records */ ],
    "count": 56,
    "metadata": {
      "totalSize": 56,
      "done": true,
      "nextRecordsUrl": null
    }
  },
  "timestamp": "2025-10-09T06:40:31.428Z"
}
```

## Styling

The module follows the application's design system:
- Uses theme colors from `useTheme()` hook
- Consistent spacing and typography
- Responsive layouts
- Material Community Icons
- Smooth animations and transitions

## Data Persistence

The Salesforce CRM state is persisted using Redux Persist:
- State is saved to AsyncStorage
- Survives app restarts
- Automatically rehydrated on app launch

## Error Handling

- All API calls wrapped in try-catch blocks
- Error states stored in Redux
- User-friendly error messages via Toast notifications
- Retry functionality on error screens
- Loading states for all async operations

## Performance Optimizations

- **Parallel Data Fetching**: All data types fetched simultaneously
- **Infinite Scrolling**: Load data in chunks to reduce initial load time
- **Memoized Selectors**: Prevent unnecessary re-renders
- **Redux Persist**: Cache data locally to reduce API calls
- **Pull-to-refresh**: Manual refresh when needed
- **Optimized Re-renders**: Use React.memo where appropriate

## Future Enhancements

- Advanced filtering options
- Search functionality
- Sort options for each data type
- Export data to CSV/Excel
- Detailed view screens for each record
- Create/Edit/Delete operations
- Real-time sync with Salesforce
- Offline mode support
- Analytics and reporting
- Custom dashboard widgets

## Related Modules

- **Zoho CRM** (`src/modules/crm/zoho/`) - Similar structure for Zoho integration
- **CRM Navigator** (`src/modules/crm/navigation/CrmNavigator.tsx`) - Navigation configuration
- **Root Store** (`src/store/store.ts`) - Redux store configuration

