# Complete Task Integration System

## 🎯 Overview

This document covers the complete task integration system that connects your CRM with Microsoft Outlook and To-Do. The system provides three powerful ways to create and manage tasks:

1. **📧 Email-to-Task** - Send emails to create tasks automatically
2. **🔄 Microsoft To-Do Sync** - Bidirectional sync with Microsoft To-Do
3. **📱 Outlook Add-in** - Direct task creation from Outlook interface

## 🚀 Features

### ✅ Email-to-Task System
- **IMAP Processing**: Automatically monitors `task@firmly.webiton.pt`
- **Smart Parsing**: Extracts priorities, due dates, matter references
- **Auto-Assignment**: Assigns tasks based on email sender
- **Confirmations**: Sends email confirmations back to users

### ✅ Microsoft To-Do Sync
- **Bidirectional Sync**: Tasks sync both ways
- **Real-time**: New CRM tasks appear immediately in Microsoft To-Do
- **Scheduled**: Full sync every 15 minutes
- **Conflict Resolution**: Smart handling of updates from both sides

### ✅ Outlook Add-in
- **Direct Creation**: Create tasks directly from Outlook interface
- **Email Context**: Auto-populate from current email
- **Rich Forms**: Full task creation with all metadata
- **Instant Sync**: Tasks appear in both CRM and Microsoft To-Do

## 📧 Email-to-Task Usage

### Basic Task Creation
```
To: task@firmly.webiton.pt
Subject: Review client contract
Body: Need to review the Johnson contract by Friday
```

### Advanced Task with Metadata
```
To: task@firmly.webiton.pt
Subject: [HIGH] Court documents - Due: 2025-08-10
Body:
Priority: high
Matter: 123
Hours: 4
Assign: lawyer@ccsllegal.com

Prepare all court documents for the Johnson case.
```

### Email Format Options
- **Priority**: `[HIGH]`, `[URGENT]`, `[LOW]`, `Priority: high`
- **Due Date**: `Due: 2025-08-10`, `Deadline: 2025-08-10`
- **Matter**: `Matter: 123`, `#matter123`
- **Assignment**: `Assign: user@domain.com`
- **Hours**: `Hours: 4`

## 🔄 Microsoft To-Do Sync

### How It Works
1. **CRM → Microsoft**: Tasks created in CRM appear in Microsoft To-Do
2. **Microsoft → CRM**: Tasks created in Microsoft To-Do appear in CRM
3. **Updates**: Changes in either system sync to the other
4. **Completion**: Mark complete in either system updates both

### Sync Schedule
- **Real-time**: New CRM tasks sync immediately
- **Scheduled**: Full bidirectional sync every 15 minutes
- **Manual**: Use sync dashboard or commands

### Sync Dashboard
Access the sync interface:
```php
<livewire:microsoft-task-sync />
```

## 📱 Outlook Add-in

### Installation
1. **Deploy**: Add-in is deployed to `https://firmly.webiton.pt/outlook-addon/`
2. **Manifest**: Upload `manifest.xml` to Office Admin Center
3. **Sideload**: For testing, sideload the manifest in Outlook

### Usage
1. **Open Email** in Outlook
2. **Click Add-in** button in ribbon
3. **Extract Email** data
4. **Create Task** with rich form
5. **Submit** - Task appears in CRM and Microsoft To-Do

### Features
- **Auto-populate** from email content
- **Full metadata** entry (priority, due date, hours, etc.)
- **Matter linking** and user assignment
- **Instant sync** to Microsoft To-Do

## ⚙️ Setup & Configuration

### 1. Email Configuration
Update `.env`:
```env
TASK_EMAIL_HOST=firmly.webiton.pt
TASK_EMAIL_PORT=993
TASK_EMAIL_ENCRYPTION=ssl
TASK_EMAIL_USERNAME=task@firmly.webiton.pt
TASK_EMAIL_PASSWORD=Webpower5565
```

### 2. Azure AD Permissions
Add to your Azure AD app:
- `Tasks.ReadWrite` (for Microsoft To-Do sync)
- `User.Read` (for user identification)
- `openid` (for authentication)

### 3. Database Migrations
```bash
php artisan migrate
```

### 4. Scheduler Setup
Add to crontab:
```bash
* * * * * cd /path/to/your/app && php artisan schedule:run >> /dev/null 2>&1
```

## 🔧 Management Commands

### Email Processing
```bash
# Test email processing
php artisan email:process-tasks --dry-run

# Process emails manually
php artisan email:process-tasks

# Check email logs
tail -f storage/logs/email-tasks.log
```

### Microsoft To-Do Sync
```bash
# Test sync
php artisan microsoft:sync-tasks --dry-run

# Sync specific user
php artisan microsoft:sync-tasks --user=1

# One-way sync
php artisan microsoft:sync-tasks --direction=crm-to-ms

# Check sync logs
tail -f storage/logs/microsoft-sync.log
```

## 🔍 API Endpoints

### Outlook Add-in APIs
```bash
# Create task from add-in
POST /api/outlook/tasks/create
Content-Type: application/json

{
  "title": "Task title",
  "description": "Task description",
  "priority": "high",
  "dueDate": "2025-08-10",
  "estimatedHours": 4,
  "matterId": "123",
  "assignedTo": "user@domain.com",
  "emailSubject": "Original email subject",
  "emailFrom": "sender@domain.com",
  "emailBody": "Email content..."
}

# Get user tasks
GET /api/outlook/tasks/user?email=user@domain.com
```

## 🎯 User Workflows

### Workflow 1: Email-to-Task
1. **Receive Email** requiring action
2. **Forward to** `task@firmly.webiton.pt` with metadata
3. **Task Created** automatically in CRM
4. **Syncs to** Microsoft To-Do
5. **Confirmation** email sent back

### Workflow 2: Outlook Add-in
1. **Open Email** in Outlook
2. **Click "Firmly CRM"** add-in
3. **Extract Email** data
4. **Fill Task Form** with details
5. **Submit** - Task created everywhere

### Workflow 3: Microsoft To-Do Direct
1. **Create Task** in Microsoft To-Do app
2. **Automatic Sync** to CRM (within 15 minutes)
3. **View/Edit** in CRM interface
4. **Updates Sync** back to Microsoft To-Do

## 🔐 Security & Permissions

### Email Security
- **User Authentication**: Only registered users can create tasks
- **IMAP SSL**: Secure email connection
- **App Passwords**: Use dedicated email passwords

### API Security
- **CORS**: Configured for Outlook add-in domain
- **Validation**: Input validation on all endpoints
- **Logging**: Comprehensive audit trail

### Microsoft Integration
- **OAuth 2.0**: Secure token-based authentication
- **Scoped Permissions**: Only necessary permissions requested
- **Token Storage**: Encrypted storage of access tokens

## 📊 Monitoring & Logs

### Log Files
- `storage/logs/laravel.log` - General application logs
- `storage/logs/email-tasks.log` - Email processing logs
- `storage/logs/microsoft-sync.log` - Microsoft sync logs

### Key Log Events
- Email processing success/failure
- Microsoft API calls and responses
- Task creation and updates
- Sync statistics and errors

### Monitoring Commands
```bash
# Monitor email processing
tail -f storage/logs/laravel.log | grep -i "email.*task"

# Monitor Microsoft sync
tail -f storage/logs/laravel.log | grep -i "microsoft.*sync"

# Monitor API calls
tail -f storage/logs/laravel.log | grep -i "outlook.*api"
```

## 🛠️ Troubleshooting

### Common Issues

#### Email-to-Task
- **"Connection failed"**: Check IMAP settings and credentials
- **"User not found"**: Sender email must be registered in CRM
- **No tasks created**: Verify email sent to correct address

#### Microsoft To-Do Sync
- **"No access token"**: User needs to authenticate with Microsoft
- **"403 Forbidden"**: Check Azure AD permissions
- **Tasks not syncing**: Verify `Tasks.ReadWrite` permission granted

#### Outlook Add-in
- **Add-in not loading**: Check manifest URLs and deployment
- **API errors**: Verify CORS and endpoint availability
- **Task creation fails**: Check user authentication and validation

### Debug Steps

1. **Check Configuration**
   ```bash
   php artisan email:process-tasks --dry-run
   php artisan microsoft:sync-tasks --dry-run
   ```

2. **Test Connections**
   ```bash
   php artisan tinker
   >>> $service = new \App\Services\EmailToTaskService();
   >>> $service->processTaskEmails();
   ```

3. **Verify Permissions**
   - Check Azure AD app permissions
   - Verify user has Microsoft connection
   - Test API endpoints manually

## 🚀 Deployment Checklist

### Production Setup
- [ ] Email account `task@firmly.webiton.pt` configured
- [ ] IMAP credentials added to `.env`
- [ ] Azure AD app has `Tasks.ReadWrite` permission
- [ ] Database migrations run
- [ ] Scheduler configured and running
- [ ] Outlook add-in deployed to `/public/outlook-addon/`
- [ ] API endpoints accessible
- [ ] CORS configured for add-in

### Testing
- [ ] Send test email to `task@firmly.webiton.pt`
- [ ] Authenticate user with Microsoft OAuth
- [ ] Test Microsoft To-Do sync
- [ ] Sideload and test Outlook add-in
- [ ] Verify logs for errors

## 📈 Future Enhancements

### Planned Features
1. **Calendar Integration**: Sync tasks as calendar events
2. **Contacts Integration**: Link tasks to contact records
3. **Advanced Parsing**: AI-powered email content extraction
4. **Bulk Operations**: Handle multiple tasks from single email
5. **Mobile App**: Native mobile task creation
6. **Teams Integration**: Task creation from Microsoft Teams

### Outlook Add-in Enhancements
1. **Authentication**: Direct OAuth login in add-in
2. **Task Templates**: Predefined task types
3. **Attachment Handling**: Include email attachments
4. **Calendar Integration**: Create calendar events
5. **Quick Actions**: One-click task creation

## 📞 Support

### Resources
- **Email Integration**: `docs/EMAIL_TO_TASK_INTEGRATION.md`
- **Microsoft OAuth**: `docs/MICROSOFT_OAUTH_SETUP.md`
- **API Documentation**: `/api/outlook/` endpoints
- **Logs**: `storage/logs/` directory

### Common Commands
```bash
# Full system test
php artisan email:process-tasks --dry-run
php artisan microsoft:sync-tasks --dry-run

# Force sync
php artisan microsoft:sync-tasks

# Check system status
php artisan tinker
>>> User::whereNotNull('microsoft_access_token')->count()
>>> Task::where('created_from_email', true)->count()
```

---

## 🎉 Summary

You now have a complete task integration system that provides:

1. **📧 Email-to-Task**: Users email `task@firmly.webiton.pt` to create tasks
2. **🔄 Microsoft To-Do Sync**: Bidirectional sync keeps everything in sync
3. **📱 Outlook Add-in**: Direct task creation from Outlook interface

**All three methods work together seamlessly:**
- Email creates task → Syncs to Microsoft To-Do
- Add-in creates task → Syncs to Microsoft To-Do  
- Microsoft To-Do task → Syncs to CRM
- Any updates sync bidirectionally

The system is production-ready and provides comprehensive task management integration with Microsoft ecosystem!






