# Configuration, DevOps & CI/CD

## 1. Fichiers de Configuration (`config/`)

Le projet contient **32 fichiers de configuration**. Tous utilisent `declare(strict_types=1)`.

### Configurations Principales

| Fichier | Description | Variables cles |
|---------|-------------|----------------|
| `app.php` | Configuration application | APP_NAME, APP_ENV, APP_URL, APP_TIMEZONE |
| `database.php` | Connexion MySQL | DB_HOST, DB_DATABASE, DB_USERNAME, DB_PASSWORD |
| `auth.php` | Authentification | Guards: sanctum (API), filament (admin), web (session) |
| `sanctum.php` | API tokens | Routes desactivees, middleware personnalise |
| `queue.php` | File d'attente | QUEUE_CONNECTION (sync/database/redis) |
| `cache.php` | Cache | CACHE_DRIVER (file/redis/memcached) |
| `session.php` | Sessions | SESSION_DRIVER (file) |
| `mail.php` | Emails | MAIL_MAILER, MAIL_HOST, MAIL_PORT |
| `filesystems.php` | Stockage fichiers | MEDIA_DISK (s3/local), AWS_* |
| `broadcasting.php` | Temps reel | BROADCAST_DRIVER (pusher), PUSHER_* |
| `logging.php` | Logs | Monolog, stack channels |
| `cors.php` | CORS | Tout ouvert pour api/* |

### Configurations Metier

| Fichier | Description |
|---------|-------------|
| `settings.php` | Parametres metier globaux |
| `chat.php` | Integration IA Mistral (25+ function tools) |
| `quickbooks.php` | Integration comptabilite QuickBooks |
| `expo-notifications.php` | Push notifications Expo (MySQL storage) |
| `translation.php` | Gestion traductions POEditor |
| `maps.php` | Google Maps static map API |
| `blurhash.php` | Generation de placeholders image |
| `timezones.php` | Mappings de fuseaux horaires |
| `timezones-mobile-mapping.php` | Mappings timezone pour mobile |

### Configurations Admin

| Fichier | Description |
|---------|-------------|
| `filament.php` | Panneau admin (chemin, guard, theme) |
| `filament-authentication.php` | Auth admin |
| `filament-language-switch.php` | Switch de langue admin |
| `filament-fullcalendar.php` | Widget calendrier admin |

### Configurations Tiers

| Fichier | Description |
|---------|-------------|
| `services.php` | Stripe, OAuth providers, PKPass, AWS |
| `sentry.php` | Error tracking et APM |
| `permission.php` | Spatie permissions/roles |
| `activitylog.php` | Activity logging (retention 365 jours) |
| `l5-swagger.php` | Documentation OpenAPI/Swagger |

### Parametres Metier (`config/settings.php`)

```php
return [
    'planning_display_past_days' => 30,       // Jours passes affiches dans le planning
    'bookable_days'              => 60,       // Jours reservables dans le futur
    'coach_booking_remind_at'    => '19:00',  // Heure rappel coach
    'membership_expiry_remind_at'=> '07:00',  // Heure rappel expiration
    'planning_notify_at'         => '08:00',  // Heure notification planning
    'access_logs_notify_at'      => '23:59',  // Heure resume acces
    'coach_revenue_share'        => 0.5,      // Part coach (50%)
    'app_revenue_share'          => 0.7,      // Part app
    'partner_revenue_share'      => 0.3,      // Part partenaire
    'vat'                        => 10,       // TVA par defaut (%)
    'default_course_duration'    => 60,       // Duree cours (min)
    'default_course_capacity'    => 1,        // Capacite par defaut
    'order_validity_days'        => 30,       // Validite commande (jours)
];
```

---

## 2. Variables d'Environnement (.env)

### Variables Critiques

```bash
# Application
APP_NAME="Champion Spirit"
APP_ENV=local|staging|production
APP_DEBUG=true|false
APP_URL=https://api.championspirit.com

# Base de donnees
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=app
DB_USERNAME=championspirit
DB_PASSWORD=superAPIpassw0rd

# Stockage S3
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=championspirit-local
AWS_ENDPOINT=http://minio:9000        # MinIO en dev
AWS_USE_PATH_STYLE_ENDPOINT=true
MEDIA_DISK=s3

# Broadcasting
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=

# Paiements
STRIPE_KEY=
STRIPE_SECRET=
STRIPE_WEBHOOK_SECRET=
NOWPAYMENTS_API_KEY=
NOWPAYMENTS_IPN_SECRET=

# IA
OPENAI_API_KEY=
BOLD_AI_API_KEY=
MISTRAL_MW_API_KEY=

# Notifications
SENDINBLUE_KEY=
SMS_SENDER=CHAMPIONSPIRIT

# OAuth
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
FACEBOOK_CLIENT_ID=
FACEBOOK_CLIENT_SECRET=

# Admin
FILAMENT_DOMAIN=manager.championspirit.com
FILAMENT_PATH=/
FILAMENT_AUTH_GUARD=filament

# Monitoring
SENTRY_LARAVEL_DSN=
SENTRY_TRACES_SAMPLE_RATE=0.1
```

### Environnement de Test (.env.testing)

```bash
APP_ENV=testing
BCRYPT_ROUNDS=4          # Rounds rapides pour tests
CACHE_DRIVER=array
MAIL_MAILER=array
QUEUE_CONNECTION=sync
SESSION_DRIVER=array
TELESCOPE_ENABLED=false
```

---

## 3. CI/CD (GitHub Actions)

### Pipeline Tests (`tests.yml`)

**Declencheur :** Push sur main/develop, Pull Requests

```yaml
Etapes :
1. Setup Ubuntu 22.04
2. Demarrage MySQL service
3. Demarrage Stripe Mock (port 12111)
4. Setup PHP 8.2 (extensions: dom, curl, mbstring, pdo_mysql, gd, imagick, etc.)
5. Cache Composer
6. Composer install
7. Yarn install + build
8. Creation BDD + migration
9. Execution Pest tests
```

### Pipeline Qualite (`quality.yml`)

**Declencheur :** Push sur main/develop, Pull Requests

```yaml
Jobs paralleles :
1. pint     -> composer lint -- --test
2. phpstan  -> composer types -- --ansi --no-interaction
3. composer -> composer validate + composer audit
```

**Controle de concurrence :** Annule les runs en cours sur le meme branch/PR.

---

## 4. Scripts Shell

### gitCheck.sh (Pre-commit obligatoire)

```bash
#!/bin/bash
composer lint --              # Laravel Pint (code style)
composer types -- --ansi --no-interaction --no-progress --error-format=github  # PHPStan
#composer test                 # Pest (desactive)
```

**IMPORTANT :** Ce script DOIT etre execute avant tout commit en dev.

### reloadChanges.sh (Rechargement apres deploiement)

```bash
php artisan cache:clear          # Vider cache
php artisan config:cache         # Reconstruire cache config
php artisan route:cache          # Reconstruire cache routes
php artisan view:clear           # Vider cache vues
service php8.2-fpm reload       # Recharger PHP-FPM
php artisan l5-swagger:generate  # Regenerer doc Swagger
```

### setPermissions.sh (Permissions fichiers)

```bash
chown -R www-data:www-data .    # Proprietaire web
find . -type d -exec chmod 775 {} ;
find . -type f -exec chmod 664 {} ;
chmod 777 storage/logs           # Logs en ecriture totale
chmod 755 *.sh                   # Scripts executables
chmod 755 vendor/bin/*           # Binaires vendor
```

### gitMergeMain.sh (Promotion develop -> main)

```bash
git checkout main
git fetch origin main
git branch backup/origin-main origin/main  # Backup securite
git merge develop
git push --force-with-lease origin main    # Push securise
git checkout develop
```

### exportSandboxSeed.sh (Export BDD sanitisee)

Export complet de la base de donnees avec **anonymisation** :
- Emails utilisateurs -> `staging_user_N@championspirit.com`
- Anonymisation des coaches, employes, invites, enfants, familles
- Formulaires pre-arrivee rediges (nom, adresse, telephone)
- Suppression : chat, notifications, tokens, failed jobs, QuickBooks data
- Export des assets S3/local en bundle ZIP
- Support export vers S3 via AWS CLI

### importSandboxSeed.sh (Import BDD sanitisee)

Import depuis un dump sanitise :
- Option `--assets-only` pour importer uniquement les assets
- Support sync S3 via AWS CLI
- Mode force pour import sans confirmation
- Execute `storage:link` apres import

---

## 5. Git Hooks (Husky)

### Pre-commit (`.husky/pre-commit`)

Execute automatiquement `./gitCheck.sh` avant chaque commit.

### Commit Message (`.husky/commit-msg`)

Valide le format du message de commit via `commitlint`.

### commitlint.config.js

Enforce les **Conventional Commits** :
```
type(scope): description

Types: feat, fix, docs, style, refactor, test, chore, perf, ci, build, revert
```

---

## 6. Qualite de Code

### Laravel Pint (`pint.json`)

```json
{
    "preset": "laravel",
    "rules": {
        "declare_strict_types": true,
        "method_argument_space": {
            "on_multiline": "ensure_fully_multiline"
        },
        "blank_line_before_statement": {
            "statements": ["break", "continue", "declare", "return", "throw", "try"]
        }
    }
}
```

### PHPStan (`phpstan.neon`)

```yaml
level: 7                    # Niveau d'analyse (sur 9)
paths:
  - app/
  - resources/
  - config/
  - database/
  - tests/
parallel:
  processTimeout: 300.0     # Timeout 5 min
```

**Baseline :** `phpstan-baseline.neon` avec 35+ erreurs connues ignorees.

### Scripts Composer

```json
{
    "lint": "pint",
    "types": "phpstan analyse",
    "test": "pest"
}
```

---

## 7. Queues et Workers

### Configuration par defaut

- **Dev :** `sync` (execution synchrone)
- **Prod :** `redis` ou `database`

### Queues QuickBooks (dediees)

| Queue | Usage |
|-------|-------|
| `quickbooks` | Queue principale |
| `quickbooks-wallet` | Transactions wallet |
| `quickbooks-accounts` | Comptes |
| `quickbooks-catalog` | Catalogue produits |
| `quickbooks-customers` | Clients |

**Intervalle de poll :** 10 secondes

### Commande Worker

```bash
php artisan queue:work redis --queue=quickbooks,quickbooks-wallet,quickbooks-accounts,quickbooks-catalog,quickbooks-customers
```

---

## 8. Monitoring (Sentry)

### Configuration (`config/sentry.php`)

```php
'dsn'                    => env('SENTRY_LARAVEL_DSN'),
'traces_sample_rate'     => env('SENTRY_TRACES_SAMPLE_RATE', 0.1),
'profiles_sample_rate'   => 1.0,
'send_default_pii'       => env('SENTRY_SEND_DEFAULT_PII', false),
```

### Breadcrumbs actives
- Logs, cache, Livewire, SQL queries, queue jobs, commandes, requetes HTTP

### Tracing actif
- Queue jobs, SQL, vues, Livewire, HTTP client, Redis

---

## 9. Stockage Fichiers

### Dev (MinIO)

```bash
AWS_ENDPOINT=http://minio:9000
AWS_BUCKET=championspirit-local
AWS_USE_PATH_STYLE_ENDPOINT=true
```

### Prod (Scaleway S3)

```bash
AWS_ENDPOINT=https://s3.fr-par.scw.cloud  # (exemple)
AWS_BUCKET=championspirit-prod
```

### Politique Bucket

Definie dans `scaleway-bucket-policy.json` : politique IAM pour acces S3.

### Collections Media (Spatie)

Les medias sont organises en collections :
- `avatar` : Avatars utilisateurs
- `icon` : Icones (categories, services)
- `pictures` : Photos (produits, activites)
- `banner` : Bannieres promotionnelles
- `attachment` : Pieces jointes chat

---

## 10. Commandes Artisan Planifiees (Scheduler)

| Commande | Cron | Description |
|----------|------|-------------|
| `shop:dashboard:warm-cache` | `00:00` (minuit) | Pre-calcule les widgets du dashboard Shop Manager pour tous les lieux avec un shop manager. Accepte un `place_public_id` optionnel pour cibler un lieu specifique. |

### Cache Dashboard Shop Manager

Le dashboard Shop Manager utilise une strategie de cache a deux niveaux :

| Niveau | TTL | Description |
|--------|-----|-------------|
| **Pre-calcule** (midnight) | 24h | Tous les widgets pour les periodes `today`, `7d`, `14d`, `30d` via `shop:dashboard:warm-cache` |
| **Delta** (on-request) | 5min | Cache `Cache::remember()` dans chaque controleur pour les periodes standard |
| **Dynamique** | 2min | Widgets a haute frequence (recent-activity, inventory-alerts) |
| **Custom** | aucun | Les plages de dates personnalisees (period=custom) ne sont jamais cachees |

**Prefixe de cle :** `shop_dashboard:{place_id}:{widget}:{period}`
**Service :** `DashboardCacheService` (`app/Services/ShopManager/DashboardCacheService.php`)

---

## 11. Base de Donnees

### Configuration Production

```
Connection : MySQL
Collation  : utf8mb4_bin (case-sensitive)
Charset    : utf8mb4
Strict     : true
Engine     : InnoDB
```

### Maintenance

```bash
# Migration
php artisan migrate

# Rollback derniere migration
php artisan migrate:rollback

# Reset + seed
php artisan migrate:fresh --seed

# Export sanitise (sandbox)
./exportSandboxSeed.sh

# Import sanitise
./importSandboxSeed.sh
```
