# Promotion Module Integration Testing Guide

## Overview

This document describes the comprehensive integration testing suite for the promotion module, ensuring that all components work correctly together in the admin panel, sales/return/exchange cycle, and backend integration.

## Test Structure

### 1. Core Integration Tests (`PromotionIntegrationTest.php`)

**Purpose**: Tests the fundamental promotion functionality and API endpoints.

**Test Cases**:

-   ✅ Admin can create promotions with conditions and actions
-   ✅ Admin can create vouchers for promotions
-   ✅ Promotion service applies conditions correctly
-   ✅ Promotion service validates voucher codes
-   ✅ Promotion reports API returns correct data
-   ✅ Vouchers API CRUD operations work correctly
-   ✅ Promotion integration with POS system
-   ✅ Promotion validation prevents invalid data
-   ✅ Promotion permissions are enforced

### 2. Sales Cycle Integration Tests (`PromotionSalesCycleIntegrationTest.php`)

**Purpose**: Tests promotion functionality within the sales/return/exchange transaction cycle.

**Test Cases**:

-   ✅ Promotion applies correctly during sale transactions
-   ✅ Voucher codes work during sale transactions
-   ✅ Promotion handles return transactions correctly
-   ✅ Promotion handles exchange transactions correctly
-   ✅ Promotion usage tracking works correctly
-   ✅ Promotion branch scope works correctly
-   ✅ Promotion stackable logic works correctly

### 3. Frontend Integration Tests (`PromotionFrontendIntegrationTest.php`)

**Purpose**: Tests the admin panel frontend integration with backend APIs.

**Test Cases**:

-   ✅ Admin promotion list API returns correct structure
-   ✅ Admin can create promotion via API
-   ✅ Admin can update promotion via API
-   ✅ Admin can delete promotion via API
-   ✅ Voucher management API works correctly
-   ✅ Promotion reports API returns expected data
-   ✅ Promotion reports API supports filtering
-   ✅ Voucher stats API works correctly
-   ✅ Voucher bulk operations work correctly
-   ✅ API returns proper error responses

## Running the Tests

### Prerequisites

1. **Laravel Environment**: Ensure you're in the Laravel project root directory
2. **Dependencies**: Run `composer install` to ensure all dependencies are installed
3. **Database**: Tests use SQLite in-memory database for speed

### Quick Test Run

```bash
# Run the comprehensive test suite
./scripts/test-promotion-integration.sh
```

### Individual Test Categories

```bash
# Run core integration tests only
php artisan test tests/Feature/PromotionIntegration/PromotionIntegrationTest.php

# Run sales cycle tests only
php artisan test tests/Feature/PromotionIntegration/PromotionSalesCycleIntegrationTest.php

# Run frontend integration tests only
php artisan test tests/Feature/PromotionIntegration/PromotionFrontendIntegrationTest.php

# Run all promotion tests
php artisan test tests/Feature/PromotionIntegration/
```

### With Coverage Report

```bash
# Run tests with coverage report
php artisan test tests/Feature/PromotionIntegration/ --coverage

# Run with specific PHPUnit configuration
php artisan test --configuration=phpunit-promotion.xml
```

## Test Data Setup

### Database Seeding

The tests automatically seed the following data:

1. **Condition Types**:

    - `product_quantity` - Product Quantity
    - `category_quantity` - Category Quantity
    - `cart_total` - Cart Total
    - `customer_group` - Customer Group
    - `first_order` - First Order
    - `order_frequency` - Order Frequency
    - `day_of_week` - Day of Week

2. **Action Types**:

    - `add_free_item` - Add Free Item
    - `percentage_discount` - Percentage Discount
    - `fixed_discount` - Fixed Amount Discount
    - `free_shipping` - Free Shipping
    - `bonus_points` - Bonus Points
    - `gift_card` - Gift Card

3. **Test Entities**:
    - Test users (admin and regular users)
    - Test locations
    - Test products and categories
    - Sample promotions and vouchers

## API Endpoints Tested

### Admin Promotion Management

-   `GET /api/admin/promotions` - List promotions
-   `POST /api/admin/promotions` - Create promotion
-   `GET /api/admin/promotions/{id}` - Get promotion details
-   `PUT /api/admin/promotions/{id}` - Update promotion
-   `DELETE /api/admin/promotions/{id}` - Delete promotion

### Voucher Management

-   `GET /api/admin/promotions/vouchers` - List vouchers
-   `POST /api/admin/promotions/vouchers` - Create voucher
-   `PUT /api/admin/promotions/vouchers/{id}` - Update voucher
-   `DELETE /api/admin/promotions/vouchers/{id}` - Delete voucher
-   `GET /api/admin/promotions/vouchers/stats` - Get voucher statistics
-   `POST /api/admin/promotions/vouchers/bulk` - Bulk operations

### Reports

-   `GET /api/admin/promotions/reports` - Get promotion reports
-   `GET /api/admin/promotions/locations` - Get available locations
-   `GET /api/admin/promotions/customers` - Get customer data

### POS Integration

-   `POST /api/pos/promotions/preview` - Preview promotion application
-   `POST /api/pos/promotions/apply` - Apply promotions to cart
-   `POST /api/pos/promotions/validate` - Validate voucher codes
-   `GET /api/pos/promotions/active` - Get active promotions

## Test Scenarios Covered

### 1. Promotion Creation & Management

-   ✅ Create promotions with multiple conditions and actions
-   ✅ Update promotion details and settings
-   ✅ Delete promotions (with proper cleanup)
-   ✅ Validate promotion data and constraints

### 2. Voucher System

-   ✅ Generate unique voucher codes
-   ✅ Set usage limits and customer restrictions
-   ✅ Track voucher usage and prevent overuse
-   ✅ Handle voucher expiration and activation
-   ✅ Bulk operations on multiple vouchers

### 3. Sales Integration

-   ✅ Apply promotions during POS transactions
-   ✅ Calculate discounts correctly
-   ✅ Handle multiple promotions (stackable/non-stackable)
-   ✅ Validate voucher codes in real-time
-   ✅ Track promotion usage statistics

### 4. Return/Exchange Handling

-   ✅ Prevent promotion application during returns
-   ✅ Apply promotions to exchange transactions
-   ✅ Handle original transaction references
-   ✅ Maintain data integrity across transaction types

### 5. Branch & Location Management

-   ✅ Apply promotions based on branch scope
-   ✅ Handle location-specific promotions
-   ✅ Validate branch permissions

### 6. Permission & Security

-   ✅ Enforce admin-only access to promotion management
-   ✅ Validate user permissions for different operations
-   ✅ Prevent unauthorized access to sensitive data

### 7. Error Handling

-   ✅ Handle invalid promotion data gracefully
-   ✅ Provide meaningful error messages
-   ✅ Validate input data thoroughly
-   ✅ Handle edge cases and boundary conditions

## Expected Test Results

When all tests pass, you should see:

```
✅ Core Promotion Integration Tests passed
✅ Sales Cycle Integration Tests passed
✅ Frontend Integration Tests passed
✅ All Promotion Integration Tests passed!
```

## Troubleshooting

### Common Issues

1. **Database Connection Errors**

    - Ensure SQLite is available
    - Check database configuration in `phpunit.xml`

2. **Permission Errors**

    - Ensure the test script has execute permissions
    - Check file ownership and permissions

3. **Missing Dependencies**

    - Run `composer install` to install all dependencies
    - Ensure all required packages are installed

4. **Test Failures**
    - Check the specific test output for detailed error messages
    - Ensure all required seeders are running
    - Verify database migrations are up to date

### Debug Mode

To run tests in debug mode with more verbose output:

```bash
php artisan test tests/Feature/PromotionIntegration/ --verbose
```

## Coverage Goals

The test suite aims for:

-   **90%+ Code Coverage** on promotion-related classes
-   **100% API Endpoint Coverage** for promotion functionality
-   **100% Critical Path Coverage** for sales/return/exchange integration

## Continuous Integration

These tests are designed to run in CI/CD pipelines:

```yaml
# Example GitHub Actions workflow
- name: Run Promotion Integration Tests
  run: |
      composer install --no-interaction --prefer-dist
      php artisan migrate:fresh --env=testing --force
      php artisan db:seed --class=ConditionAndActionTypesSeeder --env=testing --force
      php artisan test tests/Feature/PromotionIntegration/ --env=testing
```

## Maintenance

### Adding New Tests

When adding new promotion features:

1. Add corresponding test cases to the appropriate test file
2. Update this documentation with new test scenarios
3. Ensure new tests follow the existing naming conventions
4. Add any new seeders or test data as needed

### Updating Tests

When modifying promotion functionality:

1. Update existing tests to reflect changes
2. Add new tests for new features
3. Remove obsolete tests
4. Update documentation accordingly

This comprehensive test suite ensures that the promotion module is robust, reliable, and ready for production use.
