# Service Report Guide

## Overview

The service report system provides detailed analysis of service performance and revenue within specified sessions. It shows which services are generating the most revenue, their transaction counts, and performance metrics.

## Features

### 1. **Service Performance Analysis**
- Individual service revenue and transaction counts
- Service status tracking (active/inactive)
- Average unit prices and quantities sold
- Discount analysis per service

### 2. **Top Performing Services**
- Ranking of services by revenue
- Transaction count analysis
- Average transaction value per service

### 3. **Revenue Analytics**
- Total service revenue vs overall sales
- Service revenue percentage of total sales
- Payment method breakdown for service transactions

### 4. **Session-Based Reporting**
- Filter by specific sessions
- Date range analysis
- Cashier/operator attribution

## Backend Implementation

### ServiceReportService

**File**: `app/Services/ServiceReportService.php`

The service handles all business logic for service report generation:

```php
class ServiceReportService
{
    public function generateReportData(array $sessionIds): array
    public function getPerformanceMetrics(array $sessionIds): array
}
```

#### Key Methods

1. **`generateReportData()`** - Main method that generates comprehensive report data
2. **`getServicesData()`** - Retrieves service performance data from both invoices and sales
3. **`getServicePerformanceData()`** - Gets top performing services and hourly utilization
4. **`calculateSummary()`** - Calculates summary metrics and percentages

### Data Sources

The service report combines data from multiple sources:

1. **Invoices Table** - Service-related items with quantities and prices
2. **Sales Table** - Direct service transactions (service_id field)
3. **Services Table** - Service definitions and status
4. **Payment Methods** - Payment breakdown for service transactions

### Data Processing

```php
// Get services from invoices
$servicesFromInvoices = DB::table('invoices')
    ->join('services', 'invoices.service_id', '=', 'services.id')
    ->join('sales', 'invoices.id', '=', DB::raw('(SELECT invoice_id FROM sale_invoice WHERE sale_id = sales.id LIMIT 1)'))
    ->selectRaw('...')
    ->whereIn('sales.session_id', $sessionIds)
    ->whereNotNull('invoices.service_id')
    ->groupBy('services.id', 'services.name', 'services.status')
    ->get();

// Get services from sales table
$servicesFromSales = DB::table('sales')
    ->join('users as service_users', 'sales.service_id', '=', 'service_users.id')
    ->selectRaw('...')
    ->whereIn('sales.session_id', $sessionIds)
    ->whereNotNull('sales.service_id')
    ->groupBy('service_users.id', 'service_users.name')
    ->get();
```

## API Endpoints

### Generate Service Report

```http
POST /api/v1/sessions/service-report
Content-Type: application/json
Authorization: Bearer {token}

{
  "sessions": [1, 2, 3],
  "download": true
}
```

#### Response Types

**Stream Response (download: true)**
```http
HTTP/1.1 200 OK
Content-Type: application/pdf
Content-Disposition: attachment; filename="service_report_SALAMANDA_2025-01-17_123456_3sessions_5services.pdf"
Cache-Control: no-cache, must-revalidate

[PDF Binary Data]
```

**JSON Response (download: false)**
```json
{
  "status": "success",
  "url": "http://localhost/storage/tmp/service_report_2025-01-17_123456.pdf",
  "data": {
    "total_sales": 1500000,
    "total_service_revenue": 450000,
    "total_discount": 50000,
    "total_payments": 1450000,
    "services_count": 5,
    "sessions_count": 3,
    "transactions_count": 125,
    "service_transactions_count": 45,
    "performance": {
      "execution_time_ms": 245.67,
      "memory_usage_mb": 12.5,
      "data_points": {
        "sessions": 3,
        "transactions": 125,
        "services": 5,
        "service_transactions": 45
      }
    }
  }
}
```

## Frontend Implementation

### Service Report Service

**File**: `frontend-examples/sessionReportService.js`

```javascript
// Download service report
const result = await sessionReportService.downloadServiceReport([1, 2, 3])

// Generate service report preview
const preview = await sessionReportService.generateServicePreview([1, 2, 3])
```

### Vue.js Component

**File**: `frontend-examples/ServiceReportDownload.vue`

Features:
- Session selection interface
- Report type selection (Session vs Service)
- Download mode selection
- Progress indicators
- Error handling

## PDF Template

**File**: `resources/views/reports/service_report.blade.php`

### Sections

1. **Header** - Company letterhead and report title
2. **Summary** - Key metrics in grid layout
3. **Services Performance** - Detailed service table
4. **Top Performing Services** - Ranked service list
5. **Payment Methods** - Payment breakdown
6. **Footer** - Generation details

### Styling

- Professional blue color scheme (#007cbf)
- Responsive grid layouts
- Clean table designs
- Status indicators (active/inactive)
- Amount formatting with currency symbols

## Usage Examples

### 1. Simple Service Report Download

```javascript
import sessionReportService from './sessionReportService.js'

// Download service report for specific sessions
const sessionIds = [1, 2, 3]
const result = await sessionReportService.downloadServiceReport(sessionIds)
console.log('Downloaded:', result.filename)
```

### 2. Generate Service Report Preview

```javascript
// Generate preview and get URL
const preview = await sessionReportService.generateServicePreview(sessionIds)
console.log('Preview URL:', preview.url)

// Download from preview URL
await sessionReportService.downloadFromUrl(preview.url)
```

### 3. Vue.js Component Usage

```javascript
import ServiceReportDownload from './ServiceReportDownload.vue'

export default {
  components: {
    ServiceReportDownload
  }
}
```

### 4. React Hook Usage

```javascript
import { useServiceReport } from './usage-example.js'

function ServiceReportComponent() {
  const { isLoading, error, downloadServiceReport } = useServiceReport()
  
  const handleDownload = async () => {
    await downloadServiceReport([1, 2, 3])
  }
  
  return (
    <button onClick={handleDownload} disabled={isLoading}>
      {isLoading ? 'Generating...' : 'Download Service Report'}
    </button>
  )
}
```

## Data Structure

### Report Data Format

```php
[
    'sessions' => Collection, // Session objects
    'dateRange' => [
        'start' => '2025-01-17 09:00:00',
        'end' => '2025-01-17 17:00:00'
    ],
    'cashierNames' => 'John Doe, Jane Smith',
    'servicesData' => [
        [
            'service_id' => 1,
            'service_name' => 'Consultation',
            'service_status' => 'active',
            'total_transactions' => 25,
            'total_quantity' => 25.0,
            'total_amount' => 125000.00,
            'total_discount' => 5000.00,
            'avg_unit_price' => 5000.00
        ]
    ],
    'salesData' => [
        'total_sales' => 1500000.00,
        'total_discount' => 50000.00,
        'total_paid' => 1450000.00,
        'total_transactions' => 125,
        'avg_transaction_value' => 12000.00
    ],
    'paymentMethods' => [
        'methods' => [
            'Cash' => ['amount' => 800000.00, 'transaction_count' => 60],
            'Card' => ['amount' => 650000.00, 'transaction_count' => 65]
        ],
        'total' => 1450000.00,
        'total_transactions' => 125
    ],
    'servicePerformance' => [
        'top_services' => [
            [
                'service_name' => 'Consultation',
                'transaction_count' => 25,
                'total_revenue' => 125000.00,
                'avg_transaction_value' => 5000.00
            ]
        ],
        'hourly_utilization' => [
            [
                'hour' => 9,
                'transaction_count' => 5,
                'total_revenue' => 25000.00
            ]
        ],
        'total_services' => 5,
        'total_service_revenue' => 450000.00
    ],
    'summary' => [
        'total_sales' => 1500000.00,
        'total_service_revenue' => 450000.00,
        'total_transactions' => 125,
        'total_service_transactions' => 45,
        'unique_services_count' => 5,
        'avg_service_transaction_value' => 10000.00,
        'service_revenue_percentage' => 30.0,
        'sessions_count' => 3
    ]
]
```

## Performance Considerations

### 1. **Query Optimization**
- Uses database-level aggregations (SUM, COUNT, AVG)
- Joins optimized for performance
- Indexes on session_id, service_id fields

### 2. **Memory Management**
- Streaming PDF generation
- Efficient data processing
- Minimal memory footprint

### 3. **Caching**
- Session data cached during processing
- Payment method data aggregated once
- Service performance calculated efficiently

## Error Handling

### Common Error Scenarios

1. **No Services Found**
   ```
   Error: No services found for the provided sessions
   ```

2. **Invalid Session IDs**
   ```
   Error: Some sessions do not exist: 999
   ```

3. **Database Errors**
   ```
   Error: Database error occurred while generating service report
   ```

### Error Recovery

- Automatic retry for transient errors
- Detailed error logging
- User-friendly error messages
- Graceful degradation

## Testing

### Unit Tests

```php
// Test service report generation
public function testServiceReportGeneration()
{
    $service = new ServiceReportService();
    $reportData = $service->generateReportData([1, 2, 3]);
    
    $this->assertArrayHasKey('servicesData', $reportData);
    $this->assertArrayHasKey('summary', $reportData);
    $this->assertGreaterThan(0, $reportData['summary']['unique_services_count']);
}
```

### Integration Tests

```php
// Test API endpoint
public function testServiceReportEndpoint()
{
    $response = $this->post('/api/v1/sessions/service-report', [
        'sessions' => [1, 2, 3],
        'download' => false
    ]);
    
    $response->assertStatus(200);
    $response->assertJsonStructure([
        'status',
        'url',
        'data' => [
            'total_sales',
            'total_service_revenue',
            'services_count'
        ]
    ]);
}
```

## Security Features

### 1. **Authentication**
- JWT token required for all endpoints
- User session validation
- Role-based access control

### 2. **Input Validation**
- Session ID validation
- Data sanitization
- SQL injection prevention

### 3. **Data Access Control**
- Users can only access their own sessions
- Department-based filtering
- Audit logging for downloads

## Monitoring and Analytics

### 1. **Performance Metrics**
- Execution time tracking
- Memory usage monitoring
- Query performance analysis

### 2. **Usage Analytics**
- Report generation frequency
- Popular session combinations
- Service performance trends

### 3. **Error Tracking**
- Failed report generations
- Database query errors
- User error patterns

## Best Practices

### 1. **Data Accuracy**
- Validate session IDs before processing
- Cross-reference service data
- Handle missing or invalid data gracefully

### 2. **Performance**
- Use database indexes effectively
- Optimize query patterns
- Implement caching where appropriate

### 3. **User Experience**
- Provide clear error messages
- Show progress indicators
- Offer multiple download options

### 4. **Maintenance**
- Regular performance monitoring
- Database query optimization
- Template updates and improvements

## Conclusion

The service report system provides comprehensive analysis of service performance within sessions, enabling better business insights and decision-making. The implementation is production-ready with robust error handling, performance optimization, and user-friendly interfaces.

Key benefits:
1. **Detailed Service Analysis** - Complete breakdown of service performance
2. **Revenue Insights** - Service contribution to overall sales
3. **Performance Tracking** - Top performing services identification
4. **Flexible Reporting** - Session-based filtering and analysis
5. **Professional Output** - High-quality PDF reports with company branding 