# CRM Application Feature Documentation

This document provides a comprehensive overview of all features in the CRM application, including their migration status, model implementation, and controller availability.

## Summary

- **Total Features with Migrations**: 39
- **✅ Complete Features (Migration + Model + Controller)**: 22
- **⚠️ Incomplete Features (Migration + Model, Missing Controller)**: 17
- **❌ Missing Features (Migration Only, No Model/Controller)**: 0

---

# ✅ COMPLETED FEATURES

*These features have full implementation with migration, model, and controller.*


### 1. Accounts
- **Migration**: `0001_01_01_000000_create_accounts_table.php`
- **Model**: `app/Models/Account.php`
- **Controller**: `app/Http/Controllers/AccountController.php`
- **Description**: Company account management with basic information and settings

### 2. Shifts
- **Migration**: `0001_01_01_000002_create_shifts_table.php`
- **Model**: `app/Models/Shift.php`
- **Controller**: `app/Http/Controllers/ShiftController.php`
- **Description**: Work shift management with time tracking settings

### 3. Users
- **Migration**: `0001_01_01_000003_create_users_table.php`
- **Model**: `app/Models/User.php`
- **Controller**: `app/Http/Controllers/UserController.php`
- **Description**: User management system

### 4. Companies
- **Migration**: `2026_03_12_040447_create_companies_table.php`
- **Model**: `app/Models/Company.php`
- **Controller**: `app/Http/Controllers/CompanyController.php`
- **Description**: Company information management

### 5. Leads
- **Migration**: `2026_03_12_055100_create_leads_table.php`
- **Model**: `app/Models/Lead.php`
- **Controller**: `app/Http/Controllers/LeadController.php`
- **Description**: Lead management and tracking system

### 6. Lead Notes
- **Migration**: `2026_03_12_071534_create_lead_notes_table.php`
- **Model**: `app/Models/LeadNote.php`
- **Controller**: Integrated with LeadController
- **Description**: Notes and comments for leads

### 7. Lead Follow-ups
- **Migration**: `2026_03_12_095817_create_lead_follow_up_table.php`
- **Model**: `app/Models/LeadFollowup.php`
- **Controller**: Integrated with LeadController
- **Description**: Follow-up scheduling for leads

### 8. Meetings
- **Migration**: `2026_03_12_125411_create_meetings_table.php`
- **Model**: `app/Models/Meeting.php`
- **Controller**: `app/Http/Controllers/MeetingController.php`
- **Description**: Meeting scheduling and management

### 9. Meeting Schedules
- **Migration**: `2026_03_12_132012_create_meeting_schedules_table.php`
- **Model**: `app/Models/MeetingSchedule.php`
- **Controller**: Integrated with MeetingController
- **Description**: Meeting time slot management

### 10. Products
- **Migration**: `2026_03_12_132344_create_products_table.php`
- **Model**: `app/Models/Product.php`
- **Controller**: `app/Http/Controllers/ProductController.php`
- **Description**: Product catalog management

### 11. Meeting Products
- **Migration**: `2026_03_12_132711_create_meeting_products_table.php`
- **Model**: `app/Models/MeetingProduct.php`
- **Controller**: Integrated with MeetingController
- **Description**: Products associated with meetings

### 12. Visits
- **Migration**: `2026_03_12_133320_create_visits_table.php`
- **Model**: `app/Models/Visit.php`
- **Controller**: `app/Http/Controllers/VisitController.php`
- **Description**: Customer visit management

### 13. Quotations
- **Migration**: `2026_03_14_053015_create_quotations_table.php`
- **Model**: `app/Models/Quotation.php`
- **Controller**: `app/Http/Controllers/QuotationController.php`
- **Description**: Quotation management system

### 14. Quotation Details
- **Migration**: `2026_03_14_054546_create_quotation_details_table.php`
- **Model**: `app/Models/QuotationDetails.php`
- **Controller**: Integrated with QuotationController
- **Description**: Line items for quotations

### 15. Quotation Templates
- **Migration**: `2026_03_14_055423_create_quotation_templates_table.php`
- **Model**: `app/Models/QuotationTemplate.php`
- **Controller**: Integrated with QuotationController
- **Description**: Reusable quotation templates

### 16. Quotation Terms
- **Migration**: `2026_03_14_060027_create_quotation_terms_table.php`
- **Model**: `app/Models/QuotationTerms.php`
- **Controller**: Integrated with QuotationController
- **Description**: Terms and conditions for quotations

### 17. Tags
- **Migration**: `2026_03_14_062046_create_tags_table.php`
- **Model**: `app/Models/Tag.php`
- **Controller**: `app/Http/Controllers/TagController.php`
- **Description**: Tagging system for categorization

### 18. Projects
- **Migration**: `2026_03_14_062955_create_projects_table.php`
- **Model**: `app/Models/Project.php`
- **Controller**: `app/Http/Controllers/ProjectController.php`
- **Description**: Project management system

### 19. Project Assignees
- **Migration**: `2026_03_14_063953_create_project_assignees_table.php`
- **Model**: `app/Models/ProjectAssignee.php`
- **Controller**: Integrated with ProjectController
- **Description**: Team member assignments to projects

### 20. Project Tickets
- **Migration**: `2026_03_14_065127_create_project_tickets_table.php`
- **Model**: `app/Models/ProjectTicket.php`
- **Controller**: Integrated with ProjectController
- **Description**: Issue tracking within projects

### 21. Tasks
- **Migration**: `2026_03_14_071045_create_tasks_table.php`
- **Model**: `app/Models/Task.php`
- **Controller**: `app/Http/Controllers/TaskController.php`
- **Description**: Task management system

### 22. Holidays
- **Migration**: `2026_04_23_064825_create_holidays_table.php`
- **Model**: `app/Models/Holiday.php`
- **Controller**: `app/Http/Controllers/HolidayController.php`
- **Description**: Holiday management system

---

# ⚠️ INCOMPLETE FEATURES

*These features have migrations and models but are missing dedicated controllers. Some may be integrated into parent controllers.*

### 1. User Profiles
- **Migration**: `2026_03_10_071801_create_user_profiles.php`
- **Model**: `app/Models/UserProfile.php`
- **Controller**: Missing (likely integrated with UserController)
- **Description**: Extended user profile information

### 2. User Documents
- **Migration**: `2026_03_10_104321_create_user_documents.php`
- **Model**: `app/Models/UserDocument.php`
- **Controller**: Missing (likely integrated with UserController)
- **Description**: Document management for users

### 3. Demos
- **Migration**: `2026_03_12_133527_create_demos_table.php`
- **Model**: Missing (should be `app/Models/Demo.php`)
- **Controller**: Missing
- **Description**: Product demonstration management

### 4. Demo Assignees
- **Migration**: `2026_03_14_052205_create_demo_assignees_table.php`
- **Model**: Missing (should be `app/Models/DemoAssignee.php`)
- **Controller**: Missing
- **Description**: Staff assignments for demos

### 5. Demo Products
- **Migration**: `2026_03_14_052352_create_demo_products_table.php`
- **Model**: Missing (should be `app/Models/DemoProduct.php`)
- **Controller**: Missing
- **Description**: Products featured in demos

### 6. Demo Schedules
- **Migration**: `2026_03_14_052707_create_demo_schedules_table.php`
- **Model**: Missing (should be `app/Models/DemoSchedule.php`)
- **Controller**: Missing
- **Description**: Demo scheduling system

### 7. Project Tags
- **Migration**: `2026_03_14_065709_create_project_tags_table.php`
- **Model**: `app/Models/ProjectTag.php`
- **Controller**: Missing (likely integrated with ProjectController)
- **Description**: Tag association for projects

### 8. Project Media Files
- **Migration**: `2026_03_14_070423_create_project_media_files_table.php`
- **Model**: `app/Models/ProjectMediaFile.php`
- **Controller**: Missing (likely integrated with ProjectController)
- **Description**: Media files for projects

### 9. Project Chats
- **Migration**: `2026_03_14_070727_create_project_chats_table.php`
- **Model**: `app/Models/ProjectChat.php`
- **Controller**: Missing (likely integrated with ProjectController)
- **Description**: Chat system for projects

### 10. Project Chat Files
- **Migration**: `2026_03_14_070834_create_project_chat_files_table.php`
- **Model**: `app/Models/ProjectChatFile.php`
- **Controller**: Missing (likely integrated with ProjectController)
- **Description**: File attachments for project chats

### 11. Task Logs
- **Migration**: `2026_03_14_071453_create_task_logs_table.php`
- **Model**: `app/Models/TaskLog.php`
- **Controller**: Missing (likely integrated with TaskController)
- **Description**: Activity logs for tasks

### 12. Task Queries
- **Migration**: `2026_03_14_071658_create_task_queries_table.php`
- **Model**: `app/Models/TaskQuery.php`
- **Controller**: Missing (likely integrated with TaskController)
- **Description**: Query management for tasks

### 13. Task Tags
- **Migration**: `2026_03_14_071852_create_task_tags_table.php`
- **Model**: `app/Models/TaskTag.php`
- **Controller**: Missing (likely integrated with TaskController)
- **Description**: Tag association for tasks

### 14. User Addresses
- **Migration**: `2026_04_23_064623_create_user_addresses_table.php`
- **Model**: `app/Models/UserAddress.php`
- **Controller**: Missing (likely integrated with UserController)
- **Description**: Address management for users

### 15. User Working Days
- **Migration**: `2026_04_23_064714_create_user_working_days_table.php`
- **Model**: `app/Models/UserWorkingDay.php`
- **Controller**: Missing (likely integrated with UserController)
- **Description**: Working day preferences for users

### 16. Attendances
- **Migration**: `2026_04_23_064845_create_attendances_table.php`
- **Model**: `app/Models/Attendance.php`
- **Controller**: `app/Http/Controllers/AttendanceController.php`
- **Description**: Attendance tracking system

### 17. Leave Applications
- **Migration**: `2026_04_23_064925_create_leave_applications_table.php`
- **Model**: `app/Models/LeaveApplication.php`
- **Controller**: Missing
- **Description**: Leave request management

---

## Additional Models (No Dedicated Migrations)

These models exist but may not have dedicated migration files or are related to other systems:

### 1. Attendance
- **Model**: `app/Models/Attendance.php`
- **Controller**: `app/Http/Controllers/AttendanceController.php`
- **Migration**: Exists
- **Status**: Complete

### 2. Leave Approval
- **Model**: `app/Models/LeaveApproval.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Leave approval workflow

### 3. Leave Entitlement
- **Model**: `app/Models/LeaveEntitlement.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Leave balance management

### 4. Leave Type
- **Model**: `app/Models/LeaveType.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Leave category management

### 5. Lead Sale
- **Model**: `app/Models/LeadSale.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Sales conversion tracking

### 6. Lead Service
- **Model**: `app/Models/LeadService.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Service offerings for leads

### 7. Meeting Companion
- **Model**: `app/Models/MeetingCompanion.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Additional meeting participants

### 8. Meeting User
- **Model**: `app/Models/MeetingUser.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Meeting participant management

### 9. Notification Integration
- **Model**: `app/Models/NotificationIntegration.php`
- **Controller**: `app/Http/Controllers/NotificationIntegrationController.php`
- **Migration**: Missing
- **Description**: External notification system integration

### 10. Sale Target
- **Model**: `app/Models/saleTarget.php`
- **Controller**: Missing
- **Migration**: Missing
- **Description**: Sales target management

### 11. User Asset
- **Model**: `app/Models/userAsset.php`
- **Controller**: `app/Http/Controllers/userAssetsController.php`
- **Migration**: Missing
- **Description**: User asset management

---

## Recommendations

### High Priority - Missing Core Features

1. **Demo Management System**
   - Create `Demo.php` model
   - Create `DemoController.php`
   - Create related models: `DemoAssignee.php`, `DemoProduct.php`, `DemoSchedule.php`

2. **Leave Management System**
   - Create migrations for leave types, entitlements, and approvals
   - Create `LeaveController.php`
   - Integrate with existing `LeaveApplication.php` model

### Medium Priority - Enhanced Functionality

1. **User Management Enhancements**
   - Create dedicated controllers for user profiles, documents, addresses, and working days
   - Consider integrating into existing UserController or creating separate controllers

2. **Project Management Enhancements**
   - Create dedicated controllers for project media, chats, and ticket management
   - Consider real-time features for project chats

### Low Priority - Additional Features

1. **Sales Management**
   - Create migrations and controllers for lead sales and services
   - Create sales target management system

2. **Notification System**
   - Create migration for notification integrations
   - Enhance notification capabilities

---

## Architecture Notes

1. **Multi-tenant Structure**: The application uses a multi-tenant architecture with landlord and tenant migrations
2. **Soft Deletes**: Most tables implement soft deletes for data integrity
3. **Foreign Key Constraints**: Proper relationships are maintained with cascade deletes
4. **Indexing**: Important fields are indexed for performance
5. **Status Management**: Most entities use status flags for workflow management

---

# 📱 Push Notifications

The application supports Firebase Cloud Messaging (FCM) for push notifications using the secure FCM HTTP v1 API with OAuth2 authentication.

## Setup

### 1. Download Firebase Service Account JSON

1. Go to [Firebase Console](https://console.firebase.google.com/)
2. Select your project: `agent-chat-22847`
3. Go to Project Settings → Service Accounts
4. Click "Generate new private key"
5. Save the JSON file securely

### 2. Store Service Account JSON

Save the downloaded JSON file to:
```
storage/app/private/firebase-service-account.json
```

Or set the path in `.env`:
```env
FCM_SERVICE_ACCOUNT_PATH=/path/to/your/firebase-service-account.json
FCM_PROJECT_ID=agent-chat-22847
```

**Security Note**: Never commit the service account JSON to version control. Add it to `.gitignore`.

### 3. Service Components

- **Service**: `app/Services/PushNotificationService.php`
- **Trait**: `app/Traits/SendsPushNotifications.php`
- **Config**: `config/services.php` (FCM section)

### 4. Device Token Registration

Users must register their device tokens via API:

```http
POST /user/device_token/update
Content-Type: application/json

{
    "device_token": "fcm_device_token_from_mobile_app"
}
```

The token is stored in the `fcm_token` field of the `users` table.

## Usage

### Using the Trait in Controllers

```php
use App\Traits\SendsPushNotifications;

class ProjectController extends Controller
{
    use SendsPushNotifications;

    public function create_task(Request $request)
    {
        // ... create task logic ...

        // Notify assignee
        $this->notifyTaskAssigned($assignee, $task, $project);

        // Notify all project team members
        $this->notifyProjectTeam($project, 'New Task', "Task {$task->name} was created");

        return $this->success('Task created', $task);
    }
}
```

### Using the Service Directly

```php
use App\Services\PushNotificationService;

class SomeController extends Controller
{
    public function sendNotification(PushNotificationService $service)
    {
        // To a single user
        $service->sendToUser($user, 'Title', 'Body', ['key' => 'value']);

        // To multiple users
        $service->sendToUsers([$user1, $user2], 'Title', 'Body');

        // To a topic
        $service->sendToTopic('all_users', 'Announcement', 'Message');

        // To specific tokens
        $service->sendToTokens(['token1', 'token2'], 'Title', 'Body');
    }
}
```

### Available Helper Methods (Trait)

| Method | Description |
|--------|-------------|
| `notifyUser($user, $title, $body, $data)` | Send to a single user |
| `notifyUsers($users, $title, $body, $data)` | Send to multiple users |
| `notifyProjectTeam($project, $title, $body, $data)` | Send to all project members |
| `notifyTaskAssigned($assignee, $task, $project)` | Task assignment notification |
| `notifyMeeting($user, $meeting, $action)` | Meeting status notification |
| `notifyLeaveAction($user, $leave, $action)` | Leave status notification |
| `notifySupervisors($user, $title, $body, $data)` | Notify user's supervisors |

## Testing

Use the Artisan command to test push notifications:

```bash
# Send test notification to user ID 1
php artisan push:test 1

# With custom title and body
php artisan push:test 1 --title="Hello" --body="Test message"
```

## Notification Payload Structure

```json
{
    "notification": {
        "title": "Notification Title",
        "body": "Notification body text",
        "sound": "default",
        "badge": 1
    },
    "data": {
        "type": "task_assigned",
        "task_id": 123,
        "project_id": 456
    }
}
```

## Mobile App Integration

### Android (Firebase)

1. Add Firebase SDK to your Android app
2. Get FCM token: `FirebaseMessaging.getInstance().getToken()`
3. Send token to backend via `/user/device_token/update`
4. Handle incoming messages with `FirebaseMessagingService`

### iOS (APNs via FCM)

1. Configure APNs certificate in Firebase Console
2. Add Firebase SDK to your iOS app
3. Get FCM token after requesting notification permissions
4. Send token to backend via `/user/device_token/update`

### React Native (Expo)

```javascript
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';

async function registerForPushNotificationsAsync() {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;

    if (existingStatus !== 'granted') {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
    }

    if (finalStatus !== 'granted') {
        return;
    }

    const token = (await Notifications.getExpoPushTokenAsync()).data;

    // Send to your backend
    await fetch('/api/user/device_token/update', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ device_token: token })
    });
}
```

## Troubleshooting

| Issue | Solution |
|-------|----------|
| Notifications not received | Check FCM_SERVER_KEY in .env |
| Invalid token errors | Ensure user has updated device token |
| iOS not receiving | Check APNs certificate in Firebase Console |
| Android not receiving | Check Firebase app configuration |

---

*This documentation was generated on April 27, 2026. Please update as new features are added.*
