# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## System Overview

**SolisGE/Sagu** is a comprehensive educational management system built on the MIOLO 2.0 PHP framework. The system is proprietary software developed and maintained by Solis Soluções Livres Ltda.

- **Framework**: MIOLO 2.0 (version 2.0.847)
- **Primary Language**: PHP 5+
- **Database**: PostgreSQL (primary), with support for MySQL, SQLite, Oracle, Firebird, MSSQL
- **Web Server**: Apache with mod_rewrite
- **Architecture**: Modular MVC-like pattern with XML configuration

## High-Level Architecture

### Core Framework (MIOLO 2.0)

The MIOLO framework provides the foundation with these key components:

- **Entry Point**: `html/index.php` loads `classes/miolo.class` and calls `$MIOLO->HandlerRequest()`
- **URL Routing**: Apache mod_rewrite redirects all requests to `index.php` which parses module/action from URL
- **Configuration**: XML-based in `etc/miolo.conf` - defines database connections, authentication, theme, modules
- **Database Abstraction**: `classes/database/` provides multi-database support through `mdatabase`, `mquery`, `mtransaction`
- **Persistence Layer**: ORM-like system in `classes/persistence/` with XML mapping configurations
- **UI Framework**: Component-based system in `classes/ui/` with theme support (currently sbootstrap5)
- **Authentication**: `classes/security/` handles authentication (database or LDAP) and permissions

### Modular Architecture

The system is organized into business domain modules under `modules/`:

**Core Modules:**
- `basic` - Core functionality, base classes, shared utilities (version 4.66.01)
- `admin` - User administration, authentication, permissions
- `sagu2` - Main menu system and common handlers
- `api` - REST API using Slim framework (separate stack)

**Business Modules:**
- `academic` - Academic management (courses, enrollments, grades)
- `finance` - Financial operations (payments, invoices, billing)
- `humanResources` - HR management
- `selectiveProcess` - Admission processes
- `protocol` - Document protocol system
- `institutional` - Institutional data
- `training`, `research`, `residency` - Specialized academic programs
- `gnuteca` - Library management integration

### Module Structure Pattern

Each module follows this standard directory structure:

```
module_name/
├── handlers/          # Request handlers (controllers) - .inc files
├── forms/            # Form/view classes - .class files
├── classes/          # Business logic and model classes
├── db/               # Database migration files
├── sql/              # SQL schema and data scripts
├── types/            # Custom type definitions
├── reports/          # JasperReports .jrxml templates
├── webservices/      # SOAP/REST service definitions
├── service/          # Service layer classes
└── VERSION           # Module version number
```

### Request Flow

1. Apache receives request and rewrites to `html/index.php`
2. MIOLO class initializes, loads configuration from `etc/miolo.conf`
3. `modules.inc` is loaded, initializing autoloader and authentication
4. Framework parses URL to determine: module, action, function
5. Corresponding handler file is loaded: `modules/{module}/handlers/{action}.inc`
6. Handler creates form objects, processes business logic, returns response
7. UI components render using theme system (sbootstrap5)

### Database Architecture

- **Connection Management**: Each module has its own database connection defined in `etc/miolo.conf`
- **Database Layer**: `classes/database/mdatabase.class` provides abstraction
- **Query Builder**: `mquery.class` and `msql.class` for building database-agnostic queries
- **Transactions**: `mtransaction.class` handles transaction management
- **Schema Management**: SQL scripts in `modules/{module}/sql/` for schema
- **Migrations**: Migration files in `modules/{module}/db/`

### Authentication & Authorization

- **Auth System**: Configured in `etc/miolo.conf` under `<login>` section
- **Default**: Database authentication via `mauthDB` class in admin module
- **LDAP Support**: Can use `mauthLdap` with configuration in miolo.conf
- **Permissions**: `mpermssagu` class manages access control
- **Access Levels**: Defined constants in `modules.inc`:
  - `A_ACCESS/A_QUERY` (1) - Read access
  - `A_INSERT` (3), `A_DELETE` (5), `A_UPDATE` (9), `A_EXECUTE` (17)
  - `A_ADMIN/A_SYSTEM` (31) - Full administrative access
  - `A_DEVELOP` (32) - Developer access

### Persistence Layer

The system uses an XML-based ORM-like persistence layer:

- **Factory**: `persistentmanagerfactory.class` creates manager instances
- **Manager**: `persistentmanager.class` handles CRUD operations
- **Objects**: Business classes extend `persistentobject.class`
- **Mapping**: XML files define object-to-database mappings
- **Criteria**: Query building via `persistence/criteria/` classes

## Development Workflows

### Working with Modules

When modifying or creating module functionality:

1. **Handlers** (`.inc` files) - Entry points for requests, typically include business logic
2. **Forms** (`.class` files) - UI components, create forms and handle user interaction
3. **Business Classes** - In `classes/`, extend `PersistentObject` for database entities
4. **Database Changes** - Add SQL to `sql/` directory and migrations to `db/`

### Configuration Files

- **Main Config**: `etc/miolo.conf` - Database connections, theme, auth, module settings
- **Module Configs**: `etc/miolo/{module}.conf` - Module-specific settings
- **Per-module**: Check module's `etc/` directory for additional configs

### Database Connections

Each module can have its own database connection. Check `etc/miolo.conf` under `<db>` section:

```xml
<db>
    <module_name>
        <system>postgres</system>
        <host>database.solis.com.br</host>
        <port>5433</port>
        <name>database_name</name>
        <user>username</user>
        <password>password</password>
    </module_name>
</db>
```

### API Module (Slim Framework)

The `modules/api/` module is a separate REST API stack:

- Built with Slim Framework 3.x
- Has its own `composer.json` and `Dockerfile`
- JWT authentication via firebase/php-jwt
- PSR-7 middleware architecture
- Separate from main MIOLO request flow

### Report Generation

Reports use JasperReports via PHPJasper:

- Templates in `.jrxml` format in module `reports/` directories
- PHPJasper wrapper in `modules/basic/classes/phpjasper/`
- JasperStarter Java binary handles compilation and execution
- Default templates: `relatorio_generico_paisagem.jrxml` (landscape), `relatorio_generico_retrato.jrxml` (portrait)

### File Organization Conventions

- **Handlers**: Use `.inc` extension, contain procedural code
- **Classes**: Use `.class` extension (not `.php`), contain class definitions
- **Autoloading**: Configured via `sAutoload.class` defined in `modules.inc`
- **Encoding**: UTF-8 (BASE_ENCODING constant)
- **Database Booleans**: Use `DB_TRUE` ('t'), `DB_FALSE` ('f'), `DB_ALL` ('a') constants

## Key Classes and Utilities

### MIOLO Core (classes/)

- `miolo.class` - Framework core, singleton instance
- `database/mdatabase.class` - Database connection manager
- `database/mquery.class` - Query builder
- `persistence/persistentmanager.class` - ORM manager
- `ui/` - UI component library

### SAGU Utilities (modules/basic/classes/)

- `sAutoload.class` - Class autoloader
- `SAGU` class - System utilities and helpers
- Vendor libraries in `vendor/`:
  - OAuth2/Keycloak integration
  - Google API client
  - CakePHP database utilities
  - Phinx migrations
  - Monolog logging

### Third-Party Integrations

- **PHPMailer** - Email sending (`modules/basic/classes/PHPMailer/`)
- **TCPDF/FPDI** - PDF generation (`modules/basic/classes/TCPDF/`, `FPDI/`)
- **PHPJasper** - JasperReports integration
- **php-webdriver** - Selenium WebDriver for testing
- **OAuth2/JWT** - Authentication tokens
- **Google API Client** - Google services integration

## Important Notes

### Browser Support

The system explicitly blocks Internet Explorer. Browser detection in `html/index.php` requires modern browsers (Chrome, Firefox, Safari, Edge, Opera).

### Session Management

- Sessions configured in `etc/miolo.conf` under `<session>`
- Default timeout: 300 seconds (5 minutes)
- Can use file-based or database-based session storage

### Security Considerations

- **Authentication Hash**: Cookie-based auth via `authenticationHash` for SSO
- **Auto-login**: Development feature via `login.autoLoginUser` config
- **Allowed Actions**: Some actions bypass authentication check via `SAGU::isAllowedAction()`
- **Password Hashing**: MD5 by default (legacy), configurable via `<login><method>`

### Debugging

Debug configuration in `etc/miolo.conf`:

```xml
<options>
    <debug>1</debug>
    <debugmode>0</debugmode>
    <sagudebugmode>0</sagudebugmode>
    <sqltabledump>0</sqltabledump>
</options>
```

### Version Information

- MIOLO Framework: 2.0.847 (`VERSION` file in root)
- Basic Module: 4.66.01 (`modules/basic/VERSION`)
- Branch: Stored in `modules/basic/BRANCHE`

## Testing

PHP WebDriver tests can be found in `modules/basic/php-webdriver/` for Selenium-based integration testing.

## Common Patterns

### Creating a New Handler

Handlers are the entry point for requests. Create in `modules/{module}/handlers/{name}.inc`:

```php
<?php
$MIOLO->trace('file:' . $_SERVER['SCRIPT_NAME']);

$function = MIOLO::_request('function');

switch ($function) {
    case 'action1':
        // Handle action
        break;
    default:
        // Default action
        break;
}
?>
```

### Database Access Pattern

```php
// Get database connection for module
$db = $MIOLO->getDatabase('module_name');

// Create query
$query = new MQuery();
$query->addFrom('table_name');
$query->addWhere('column = ?', $value);

// Execute
$result = $db->query($query);
```

### Using Persistence Layer

Business objects extend PersistentObject and use XML mapping for database operations:

```php
$manager = $MIOLO->persistence->getManager('business', 'ObjectClass', 'module_name');
$object = $manager->get($id);
$object->property = $value;
$manager->save($object);
```
