# Water Billing System - Deployment Checklist

Complete this checklist before going live with the water billing system.

## Pre-Deployment

### Server Requirements
- [ ] PHP 8.4+ installed
- [ ] MySQL 8.0+ or MariaDB 10.5+ installed
- [ ] Composer 2.0+ installed
- [ ] Web server (Apache/Nginx) configured
- [ ] SSL certificate installed (required for production)
- [ ] 2GB+ free disk space available

### Environment Setup
- [ ] `.env` file created (copy from `.env.example`)
- [ ] `APP_KEY` generated (`php artisan key:generate`)
- [ ] Database credentials configured in `.env`
- [ ] `APP_URL` set to production domain
- [ ] `APP_DEBUG` set to `false`
- [ ] `MAIL_FROM_ADDRESS` configured for notifications

### Database Configuration
- [ ] Database user created with appropriate permissions
- [ ] Database character set set to UTF-8
- [ ] Backups scheduled (recommended: daily)
- [ ] Database replication configured (if using multiple servers)

## Installation Steps

### 1. Code Deployment
```bash
# Upload files via Git or FTP to /var/www/html/billing.happyimart.com/
# Or clone from repository:
git clone <repository-url> /var/www/html/billing.happyimart.com

# Set proper permissions
sudo chown -R www-data:www-data /var/www/html/billing.happyimart.com
sudo chmod -R 775 /var/www/html/billing.happyimart.com/storage
sudo chmod -R 775 /var/www/html/billing.happyimart.com/bootstrap/cache
```

### 2. Install Dependencies
```bash
cd /var/www/html/billing.happyimart.com
composer install --no-dev --optimize-autoloader
```

### 3. Database Migration
```bash
php artisan migrate --force
# Output: 7 migrations completed (tenants, settings, tiers, clients, meter_readings, billings, payments)
```

### 4. Create Initial Tenant
```bash
php artisan tinker

# Inside tinker:
$tenant = App\Models\Tenant::create([
    'name' => 'Your Property Name',
    'slug' => 'property-slug',
]);

$setting = $tenant->settings()->create([
    'app_name' => 'Water Billing System',
    'app_email' => 'billing@example.com',
    'app_phone' => '+63-XXX-XXX-XXXX',
    'app_address' => 'Your Address',
    'currency' => 'PHP',
    'timezone' => 'Asia/Manila',
]);

exit
```

### 5. Create Admin User
```bash
php artisan tinker

# Inside tinker:
$user = App\Models\User::create([
    'tenant_id' => 1,
    'name' => 'Admin User',
    'email' => 'admin@example.com',
    'password' => Hash::make('secure-password-here'),
    'email_verified_at' => now(),
]);

exit
```

### 6. Create Pricing Tiers
```bash
php artisan tinker

# Inside tinker:
$tenant = App\Models\Tenant::first();

$tenant->tiers()->createMany([
    [
        'name' => 'Basic',
        'description' => '0-10 cubic meters',
        'price_per_unit' => 50.00,
        'min_units' => 0,
        'max_units' => 10,
        'order' => 1,
    ],
    [
        'name' => 'Standard',
        'description' => '11-20 cubic meters',
        'price_per_unit' => 60.00,
        'min_units' => 11,
        'max_units' => 20,
        'order' => 2,
    ],
    [
        'name' => 'Premium',
        'description' => '21+ cubic meters',
        'price_per_unit' => 75.00,
        'min_units' => 21,
        'max_units' => null,
        'order' => 3,
    ],
]);

exit
```

## Post-Deployment

### Web Server Configuration

#### Apache (.htaccess)
- [ ] `.htaccess` file present in `/var/www/html/billing.happyimart.com/public/`
- [ ] `mod_rewrite` enabled
- [ ] Directory permissions set correctly (755 for directories, 644 for files)

#### Nginx (example)
```nginx
server {
    listen 443 ssl http2;
    server_name billing.happyimart.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    root /var/www/html/billing.happyimart.com/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # Deny access to sensitive files
    location ~ /\.env {
        deny all;
    }
}
```

### Security Hardening

#### File Permissions
```bash
# Application files (read-only for web server)
sudo chown -R www-data:www-data /var/www/html/billing.happyimart.com
sudo find /var/www/html/billing.happyimart.com -type f -exec chmod 644 {} \;
sudo find /var/www/html/billing.happyimart.com -type d -exec chmod 755 {} \;

# Writable directories
sudo chmod -R 775 /var/www/html/billing.happyimart.com/storage
sudo chmod -R 775 /var/www/html/billing.happyimart.com/bootstrap/cache
```

#### SSL/TLS
- [ ] SSL certificate installed (Let's Encrypt recommended)
- [ ] HTTPS enforced (redirect HTTP → HTTPS)
- [ ] HSTS header enabled
- [ ] TLS 1.2+ enforced

#### Application Security
- [ ] `APP_DEBUG` set to `false`
- [ ] Session timeout configured (recommend 30 minutes for sensitive data)
- [ ] CSRF protection enabled (default in Laravel)
- [ ] SQL injection protection via ORM (using Eloquent)
- [ ] XSS protection via Blade escaping (default)
- [ ] Rate limiting enabled for API endpoints

#### Database Security
- [ ] Database user has minimal required permissions
- [ ] Database backups encrypted
- [ ] Database accessible only from application server
- [ ] Sensitive columns encrypted (payment info, SMS credentials)

### Email Configuration

#### Gmail SMTP
```env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-email@gmail.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=billing@yourcompany.com
MAIL_FROM_NAME="Water Billing System"
```

#### Custom SMTP Server
```env
MAIL_MAILER=smtp
MAIL_HOST=mail.yourserver.com
MAIL_PORT=587
MAIL_USERNAME=billing@yourserver.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=billing@yourserver.com
MAIL_FROM_NAME="Water Billing System"
```

- [ ] Test email sending: `php artisan tinker` → `Mail::raw('Test', fn($msg) => $msg->to('test@example.com'));`

### SMS Gateway Configuration (Optional)

#### Twilio
```env
SMS_PROVIDER=twilio
SMS_API_KEY=your_twilio_account_sid
SMS_API_SECRET=your_twilio_auth_token
```

#### Semaphore
```env
SMS_PROVIDER=semaphore
SMS_API_KEY=your_semaphore_api_key
SMS_API_SECRET=
```

### Payment Gateway Configuration (Optional)

#### Stripe
```env
PAYMENT_GATEWAY=stripe
PAYMENT_API_KEY=pk_live_your_stripe_key
PAYMENT_API_SECRET=sk_live_your_stripe_secret
```

#### PayMongo
```env
PAYMENT_GATEWAY=paymongo
PAYMENT_API_KEY=pk_live_your_paymongo_key
PAYMENT_API_SECRET=sk_live_your_paymongo_secret
```

### Monitoring & Logging

#### Application Logs
- [ ] Log rotation configured (rotate daily)
- [ ] Log level set to appropriate environment level
- [ ] Logs stored outside web root
- [ ] Log monitoring tool configured (optional)

#### Monitor Commands
```bash
# Check application status
tail -f /var/www/html/billing.happyimart.com/storage/logs/laravel.log

# Monitor database connections
mysql -u root -p -e "SHOW PROCESSLIST;"

# Check disk space
df -h /var/www/html/billing.happyimart.com

# Check memory usage
free -h
```

#### Scheduled Tasks (Cron)
```bash
# Add to crontab (required for Laravel scheduler)
* * * * * cd /var/www/html/billing.happyimart.com && php artisan schedule:run >> /dev/null 2>&1

# Test cron is working
php artisan schedule:test
```

### Backup Strategy

#### Database Backups
```bash
# Daily backup script
#!/bin/bash
BACKUP_DIR="/backups/database"
DATE=$(date +\%Y\%m\%d_\%H\%M\%S)

mysqldump -u root -p'password' billing_db | gzip > $BACKUP_DIR/backup_$DATE.sql.gz

# Keep last 30 days
find $BACKUP_DIR -type f -mtime +30 -delete
```

#### File Backups
- [ ] Application files backed up weekly
- [ ] Uploaded files (if any) backed up daily
- [ ] Backups stored on separate server/disk
- [ ] Backup integrity verified regularly

### API Key Management

#### Generate API Tokens (for mobile app)
```bash
php artisan tinker

# Create token for mobile app
$token = App\Models\User::first()->createToken('mobile-app')->plainTextToken;
echo $token;

exit
```

Store this token securely in your mobile app's configuration.

## Testing Checklist

### Functionality Testing
- [ ] User login/logout works
- [ ] Dashboard displays correct metrics
- [ ] Client creation and editing works
- [ ] Meter reading submission works
- [ ] Billing auto-generation triggers on approval
- [ ] Billing PDF generation works
- [ ] Billing thermal printer format works
- [ ] Payment recording works
- [ ] Settings can be updated
- [ ] Search and filtering works

### Performance Testing
- [ ] Page load time < 2 seconds
- [ ] Database queries optimized (check with Laravel debugbar)
- [ ] Memory usage < 256MB per process
- [ ] No N+1 query problems
- [ ] Caching enabled for database queries

### Security Testing
- [ ] CSRF tokens present on all forms
- [ ] SQL injection attempts blocked
- [ ] XSS attempts blocked
- [ ] Unauthorized access blocked
- [ ] Sensitive data not logged
- [ ] API endpoints require authentication
- [ ] Rate limiting works on API
- [ ] File upload validation works

### API Testing
```bash
# Test API endpoints with cURL
curl -H "Authorization: Bearer YOUR_TOKEN" \
     https://billing.happyimart.com/api/meter-readings/client/1

# Test all 4 API endpoints:
# 1. GET /api/meter-readings/client/{id}
# 2. POST /api/meter-readings/submit
# 3. GET /api/meter-readings/{id}/history
# 4. GET /api/billings/client/{id}
```

### Load Testing (Optional)
- [ ] Test with 100 concurrent users
- [ ] Monitor database connection pool
- [ ] Verify error handling under load
- [ ] Check memory leaks

## Go-Live Checklist

### Final Verification
- [ ] All tests pass
- [ ] No console errors
- [ ] No database errors
- [ ] Email notifications working
- [ ] SMS notifications working (if configured)
- [ ] Payment processing working (if configured)
- [ ] Backups running successfully

### Launch Steps
1. [ ] Send system access credentials to administrators
2. [ ] Train staff on using the system
3. [ ] Create first wave of test clients
4. [ ] Verify billing generation end-to-end
5. [ ] Monitor system during first 24 hours
6. [ ] Communicate system access to water customers
7. [ ] Enable SMS/Email notifications to customers

### Post-Launch Monitoring
- [ ] Monitor error logs daily for first week
- [ ] Monitor performance metrics
- [ ] Collect user feedback
- [ ] Fix any critical bugs immediately
- [ ] Schedule regular security audits (quarterly)

## Emergency Procedures

### System Down
1. Check server status: `systemctl status nginx` or `systemctl status apache2`
2. Check PHP-FPM: `systemctl status php8.4-fpm`
3. Check database: `mysql -u root -p -e "SELECT 1;"`
4. Check disk space: `df -h`
5. Check memory: `free -h`
6. Check error logs: `tail -100 /var/www/html/billing.happyimart.com/storage/logs/laravel.log`

### Database Corruption
```bash
# Repair tables (MySQL)
mysqlcheck -u root -p -r billing_db

# Restore from backup
mysql -u root -p billing_db < /backups/database/backup_latest.sql.gz
```

### Lost Admin Password
```bash
php artisan tinker

$user = App\Models\User::first();
$user->password = Hash::make('new-password');
$user->save();

exit
```

## Performance Optimization Checklist

### Database
- [ ] Indexes created on frequently queried columns (client_id, tenant_id, billing_date)
- [ ] Eloquent eager loading used (with() instead of N+1 queries)
- [ ] Database query logging enabled for optimization
- [ ] Connection pooling configured if needed

### Application
- [ ] Config caching enabled: `php artisan config:cache`
- [ ] Route caching enabled: `php artisan route:cache`
- [ ] Query caching enabled for frequently accessed data
- [ ] View caching enabled: `php artisan view:cache`

### Server
- [ ] OPcache configured for PHP
- [ ] Gzip compression enabled
- [ ] Browser caching headers configured
- [ ] CDN configured for static assets (if needed)

## Maintenance Schedule

### Daily
- [ ] Check error logs
- [ ] Monitor disk space
- [ ] Monitor application uptime

### Weekly
- [ ] Database integrity check
- [ ] Backup verification
- [ ] Performance metrics review

### Monthly
- [ ] Security audit
- [ ] Dependency updates check
- [ ] User feedback review

### Quarterly
- [ ] Full security assessment
- [ ] Load testing
- [ ] Disaster recovery drill

## Support & Documentation

- Documentation available in: [SYSTEM_DOCUMENTATION.md](SYSTEM_DOCUMENTATION.md)
- API Documentation: [API_DOCUMENTATION.md](API_DOCUMENTATION.md)
- Quick Start Guide: [QUICK_START.md](QUICK_START.md)
- Project Summary: [PROJECT_SUMMARY.md](PROJECT_SUMMARY.md)
- File Listing: [FILES_LISTING.md](FILES_LISTING.md)

## Sign-Off

- [ ] System Administrator: _________________ Date: _______
- [ ] Database Administrator: _________________ Date: _______
- [ ] Project Manager: _________________ Date: _______
- [ ] IT Security Officer: _________________ Date: _______

**System Ready for Production:** ☐ YES ☐ NO

**Notes:** _________________________________________________________________

---

**Last Updated:** January 3, 2026  
**System Version:** 1.0.0  
**Prepared By:** Development Team
