# CI/CD Guide

This document explains the Continuous Integration and Continuous Deployment (CI/CD) setup for M1 ERP.

## Table of Contents
- [Overview](#overview)
- [Pre-commit Hooks](#pre-commit-hooks)
- [GitHub Actions](#github-actions)
- [Deployment](#deployment)
- [Code Coverage](#code-coverage)
- [Security Scanning](#security-scanning)
- [Troubleshooting](#troubleshooting)

## Overview

The M1 ERP CI/CD pipeline ensures code quality and safe deployments through:

1. **Pre-commit Hooks** - Run checks before commits
2. **GitHub Actions** - Automated testing on push/PR
3. **Code Coverage** - Track test coverage
4. **Security Scanning** - Check dependencies for vulnerabilities
5. **Deployment Script** - Safe production deployments

## Pre-commit Hooks

### What They Do

Pre-commit hooks run automatically before each `git commit`:

- **PHPStan** - Static analysis on changed PHP files
- **PHPCS** - Coding standards check
- **Documentation Updates** - Auto-update docs timestamps

### Location

`.git/hooks/pre-commit`

### Behavior

If checks fail:
```bash
✗ PHPStan found errors
Run: composer phpstan
# Commit is blocked
```

If checks pass:
```bash
✓ PHPStan passed
✓ Coding standards passed
✅ All checks passed!
# Commit proceeds
```

### Bypass (Emergency Only)

```bash
# Skip hooks (NOT recommended)
git commit --no-verify -m "Emergency fix"
```

**Warning**: Only use `--no-verify` for urgent production fixes. Fix issues immediately after.

### Disable Temporarily

```bash
# Rename hook to disable
mv .git/hooks/pre-commit .git/hooks/pre-commit.disabled

# Re-enable later
mv .git/hooks/pre-commit.disabled .git/hooks/pre-commit
```

## GitHub Actions

### Workflow File

`.github/workflows/ci.yml`

### Triggers

- **Push** to `main` or `develop` branches
- **Pull Requests** to `main` or `develop`

### Jobs

#### 1. Tests Job
**Duration**: ~2-3 minutes  
**PHP Versions**: 8.2, 8.3 (matrix)

**Steps**:
1. Checkout code
2. Setup PHP with extensions
3. Cache Composer dependencies
4. Install dependencies
5. Run PHPUnit tests
6. Upload coverage to Codecov

**Fail Conditions**:
- Any test fails
- Code coverage drops significantly

#### 2. Code Quality Job
**Duration**: ~1-2 minutes  
**PHP Version**: 8.3

**Steps**:
1. Checkout code
2. Setup PHP
3. Install dependencies
4. Run PHPStan
5. Run PHPCS
6. Run PHPMD (warnings only)

**Fail Conditions**:
- PHPStan errors
- PHPCS violations

#### 3. Security Job
**Duration**: <1 minute  
**PHP Version**: 8.3

**Steps**:
1. Checkout code
2. Setup PHP
3. Run `composer audit`

**Fail Conditions**:
- Known security vulnerabilities

### Viewing Results

1. Go to GitHub repository
2. Click "Actions" tab
3. Select workflow run
4. View job logs

### Status Badges

Add to README.md:
```markdown
![CI](https://github.com/YOUR_USERNAME/m1_erp_web/workflows/CI/badge.svg)
```

## Deployment

### Deployment Script

`scripts/deploy.sh`

### Requirements

- SSH access to production server
- rsync installed
- Git repository on main branch
- No uncommitted changes

### Usage

```bash
# Deploy to production
./scripts/deploy.sh
```

### Deployment Process

1. **Pre-deployment Checks**
   - ✓ On main branch
   - ✓ No uncommitted changes
   - ✓ Tests pass
   - ✓ Quality checks pass

2. **Confirmation**
   ```
   Ready to deploy to: mavrixone@merph.mavrixone:/var/www/html
   Continue with deployment? (yes/no):
   ```

3. **Backup**
   - Creates timestamped backup on production
   - Location: `/var/backups/m1_erp/backup_YYYYMMDD_HHMMSS.tar.gz`

4. **File Sync**
   - Rsync files to production
   - Excludes: .git, tests, node_modules, etc.

5. **Production Setup**
   - Install Composer dependencies (--no-dev)
   - Run database migrations
   - Clear caches
   - Set permissions

6. **Completion**
   ```
   ================================
     Deployment Complete! 🎉
   ================================
   ```

### Rollback

If deployment fails:

```bash
# SSH to production
ssh mavrixone@merph.mavrixone

# List backups
ls -lh /var/backups/m1_erp/

# Restore backup
cd /var/www/html
tar -xzf /var/backups/m1_erp/backup_YYYYMMDD_HHMMSS.tar.gz
```

### Configuration

Environment variables (from `.env.production`):
- `PROD_SERVER_HOST` - Production server hostname
- `PROD_SERVER_USER` - SSH username
- `PROD_SERVER_PATH` - Web root path

## Code Coverage

### Local Generation

```bash
# Generate coverage report
composer test:coverage

# Open report
open coverage/index.html
```

### Codecov Integration

1. **Sign up**: https://codecov.io/
2. **Connect repository**: Link your GitHub repo
3. **Automatic**: Coverage uploads automatically from GitHub Actions

### Coverage Badge

```markdown
![Coverage](https://codecov.io/gh/YOUR_USERNAME/m1_erp_web/branch/main/graph/badge.svg)
```

### Coverage Goals

- **Unit Tests**: >80% coverage
- **Critical Code**: >90% coverage
- **Overall**: >70% coverage

## Security Scanning

### Composer Audit

Check for known vulnerabilities:

```bash
composer audit
```

**Output Example**:
```
No security vulnerability advisories found.
```

Or if issues found:
```
Package: foo/bar
Version: 1.0.0
Advisory: https://github.com/advisories/GHSA-xxxx-xxxx-xxxx
Severity: high
```

### Automated Scanning

- Runs in GitHub Actions on every push
- Runs in pre-deployment checks
- Notifies if vulnerabilities found

### Fixing Vulnerabilities

1. **Update Dependencies**
   ```bash
   composer update foo/bar
   ```

2. **Check for Patches**
   ```bash
   composer patches
   ```

3. **If No Fix Available**
   - Evaluate risk
   - Consider alternatives
   - Isolate usage
   - Monitor for updates

## Advanced Tools

### PHP Copy/Paste Detector

Find duplicate code:

```bash
composer phpcpd
```

**Interpretation**:
- **Lines**: Number of duplicated lines
- **Tokens**: Similarity metric
- **Files**: Where duplicates exist

**Action**: Refactor duplicates into reusable functions/classes

### PHPMetrics

Generate code quality dashboard:

```bash
composer metrics

# Open dashboard
open metrics/index.html
```

**Metrics**:
- Cyclomatic complexity
- Maintainability index
- Code violations
- Coupling/cohesion

### Combined Analysis

```bash
# Run all advanced tools
composer quality:advanced
```

## Best Practices

### 1. Commit Frequently
- Small, focused commits
- Descriptive messages
- Run tests before committing

### 2. Use Feature Branches
```bash
git checkout -b feature/new-feature
# Develop feature
git push origin feature/new-feature
# Create pull request
```

### 3. Pull Request Workflow
1. Create feature branch
2. Develop and test locally
3. Push to GitHub
4. Create pull request
5. CI runs automatically
6. Code review
7. Merge when CI passes

### 4. Monitor CI Failures
- Fix immediately
- Don't merge if CI fails
- Investigate root cause

### 5. Regular Deployments
- Deploy during low-traffic hours
- Have rollback plan ready
- Monitor after deployment

## Troubleshooting

### Pre-commit Hook Fails

**Problem**: Hook blocks commit

**Solutions**:
```bash
# Fix issues
composer quality:fix

# Re-run checks
composer quality

# If all else fails (emergency only)
git commit --no-verify
```

### GitHub Actions Fail

**Problem**: CI shows red X

**Steps**:
1. Click on failed job
2. Read error messages
3. Reproduce locally
4. Fix and push again

### Deployment Fails

**Problem**: `deploy.sh` exits with error

**Solutions**:
```bash
# Check SSH access
ssh mavrixone@merph.mavrixone

# Check permissions
ls -la scripts/deploy.sh

# Run with verbose output
bash -x scripts/deploy.sh
```

### Coverage Not Uploading

**Problem**: Codecov shows no data

**Solutions**:
1. Check Codecov token in GitHub secrets
2. Verify `coverage.xml` is generated
3. Check GitHub Actions logs

## Maintenance

### Weekly
- Review failed CI runs
- Update dependencies: `composer update`
- Check security advisories: `composer audit`

### Monthly
- Review code coverage trends
- Analyze PHPMetrics reports
- Update CI/CD documentation

### Quarterly
- Review and update deployment procedures
- Test rollback process
- Audit security practices

## Resources

- GitHub Actions Docs: https://docs.github.com/en/actions
- Codecov Docs: https://docs.codecov.com/
- Composer Security: https://getcomposer.org/doc/07-runtime.md#audit
- PHPUnit Coverage: https://phpunit.de/manual/current/en/code-coverage-analysis.html

---

**Remember**: CI/CD is about confidence. Every check that runs automatically is one less thing that can go wrong in production.
