# CLAUDE.md

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

## What this project is

**SoftConteo** is a Laravel-based electoral vote-counting system (sistema de conteo de votos). Digitadores (data-entry operators) enter vote tallies from physical polling records; administrators manage polling locations, candidates, and user assignments; a superadmin manages all of the above plus user accounts.

## Commands

### Full dev environment (PHP server + queue + log watcher + Vite in parallel)
```bash
composer run dev
```

### Individual services
```bash
php artisan serve          # Laravel dev server
npm run dev               # Vite HMR
```

### Build
```bash
npm run build             # Production Vite assets
```

### Tests
```bash
composer run test         # PHPUnit (uses in-memory SQLite, see phpunit.xml)
php artisan test --filter TestName  # Single test
```

### Code style
```bash
./vendor/bin/pint         # Laravel Pint (PHP formatter)
```

### First-time setup
```bash
composer run setup        # composer install + npm install + key:generate + migrate + npm run build
```

## Architecture

### Authentication & authorization
- Uses a custom `Usuario` model (not the standard Laravel `User`) — the `config/auth.php` providers reference `App\Models\Usuario`. The file `app/Models/User.php` is the unused Laravel skeleton stub; ignore it.
- Three roles: `superadmin`, `administrador`, `digitador` — stored in a `rols` table via a BelongsTo on `Usuario`.
- Route-level enforcement via the `VerificarRol` middleware, applied as `middleware('rol:superadmin,administrador')` on route groups in [routes/web.php](routes/web.php).
- Helper methods on `Usuario`: `esSuperadmin()`, `esAdministrador()`, `esDigitador()`, `tieneRol(string)`.
- The `ForzarCambioPassword` middleware redirects digitadores to `/cambiar-password` when `usuario.password_changed` is `false`. It fires on every authenticated request except the password-change routes and logout. Admins/superadmins are exempt.

### Data model
```
Partido ──< Candidato ──< DetalleVoto >── RegistroConteo ──> Mesa ──> LocalVotacion
                                                           └─> Usuario (digitador)
LocalVotacion ──< Mesa
LocalVotacion ──< AsignacionDigitador >── Usuario (digitador)
Departamento ──< Provincia ──< Distrito ──< LocalVotacion
```
- `RegistroConteo` is the central entity: one record per `Mesa` per session. Its `store` controller action validates that total votes match `mesa.cantidad_electores` (when set), then wraps `DetalleVoto` creation in a DB transaction.
- `Mesa` belongs to `LocalVotacion` and has `scopeActivo()`. Its required columns come from its ballot (`actasRequeridas()`, see Cédula below); `actaCompleta()` / `digitable()` / `estadoDigitacion()` (`sin-cedula|registrada|registrando|parcial|libre`) use them. A mesa cannot be deleted if it already has a `RegistroConteo`.
- Soft deletes are on `Usuario`, `RegistroConteo`, `LocalVotacion`, `Mesa`, and `Candidato`.
- `AsignacionDigitador` has no timestamps and enforces a **one-active-assignment-per-digitador** constraint (checked in create, update, and toggle actions).
- Most models expose a `scopeActivo($query)` scope; always use it when listing records for selection dropdowns or vote-entry forms.
- `Candidato` has `numero_orden` for display ordering on the vote-entry form; candidates are always fetched `orderBy('numero_orden')`.

### Elecciones (per-election data)
Every electoral process is a row in `elecciones` (`App\Models\Eleccion`): `tipo` (presidencial/erm), `estado` (`preparacion` / `abierta` / `cerrada`), `activa` (exactly one), plus the ERM ballot columns (`actas_erm`, `actas_nombres`). Superadmin manages them in **Configuración** (`/configuracion?tab=eleccion|historial|empresa`); `EleccionController` only has the actions. Rule: a new election can't be created or another activated while the active one isn't `cerrada` (enforced server-side).
- **Per election** (trait `App\Models\Concerns\PerteneceAEleccion`): `LocalVotacion`, `Mesa`, `Candidato`, `AsignacionDigitador`, `Personero`, `RegistroConteo` (`DetalleVoto` follows its registro). The trait adds a global scope `eleccion` (only the active election is visible, including inside relations, `whereHas`, `withCount` and route model binding) and fills `eleccion_id` on `creating`. **Global**: `Usuario`, `Partido`, ubigeo, `Configuracion`.
- `App\Support\EleccionActual::get()/id()` resolves the active election (cached per request; `Eleccion` saves clear it). `ProcesoElectoral` reads type/actas from it.
- Not covered by the trait — handle manually: `Model::insert()` (set `eleccion_id`), and `unique`/`exists` validation rules on those tables (add `->where('eleccion_id', EleccionActual::id())`).
- To read another election's rows use `Model::deEleccion($id)` (removes the scope). `Eleccion` relations already remove it.
- Middleware `eleccion:{activa|editable|abierta}` (`EstadoEleccion`): admin group needs an active election, imports need it not closed, digitación/registrar/eliminar conteos need it `abierta`.
- `App\Support\CopiarEleccion` copies locales+mesas, asignaciones, personeros and candidatos from a previous election (never conteos) when creating a new one.
- The migration `2026_09_30_000002` moved all pre-existing data into an initial active+open election built from the old `configuraciones` keys.

### Cédula de votación (per election, per place)
`App\Support\Cedula` resolves which columns and options each mesa sees. Each column has an **alcance** (`Eleccion::alcance($tipo)`, stored in `elecciones.actas_alcance`; default `ProcesoElectoral::alcancePorDefecto`: every ERM column **per distrito** (each district has its own ballot and starts blank), presidencial→todos; sharing a column per provincia/departamento is optional). Column names use `ProcesoElectoral::ambitoNatural` (regional→departamento, consejero/provincial→provincia, distrital→distrito), e.g. "Alcalde Provincial · Maynas".
- `eleccion_partido`: parties in the election + their ballot order (`Cedula::orden()`). `partidos.numero_orden` / `partidos.actas` are no longer used.
- `cedula_partidos`: (eleccion, tipo_acta, ambito, ubigeo_id, partido) — the list of a column in a place. Alcance `todos` uses all election parties (presidencial: active candidatos).
- `Cedula::deMesa($mesa)` / `deDistrito($id)` → `[tipo => [ids]]`, only columns with options: a column without parties for that place is not part of the mesa (hidden, rejected on save, not needed to complete). The digitador form renders the union for his locales and JS filters per mesa (`mesa.cedula`, `mesa.columnas` from `DigitacionMesaController`).
- Results (`ResultadosElectorales`) list `Cedula::paraResultados($tipo, $localIds)`.
- UI: Configuración → **Cédula de votación** tab (`CedulaController`, superadmin; Excel matrix plantilla/importar). Static caches: call `Cedula::limpiar()` after writing those tables (Eleccion/Partido/Candidato saves already do).

### Ubigeo geographic hierarchy
`Departamento → Provincia → Distrito` — stored in three separate tables with `idDepartamento`, `idProvincia`, `idDistrito` PKs. `LocalVotacion` links to `Distrito` via `distrito_id`. Two separate controllers handle ubigeo:
- `UbigeoController` — read-only JSON API endpoints under `/api/ubigeo/` that power cascading selects on admin forms (accessible to `administrador` + `superadmin`).
- `UbigeoCrudController` — full CRUD for managing the ubigeo catalog itself (superadmin only, under `/ubigeo/`).

### Controllers → Views flow
Each controller lives in [app/Http/Controllers/](app/Http/Controllers/) and follows the redirect-with-`session('success'/'error')` pattern for feedback. Views are Blade templates in [resources/views/](resources/views/) with a shared `app.blade.php` layout. A reusable `components/table.blade.php` component is used across index pages.

Many controllers (`LocalVotacionController`, `MesaController`, `AsignacionDigitadorController`, `DashboardController`) return either a Blade `View` or a `JsonResponse` depending on `$request->ajax()` — this dual-response pattern is used for in-page modals and live-refresh panels without a full page reload.

Two reusable Blade components live under `resources/views/components/`:
- `table.blade.php` — shared table wrapper used across index pages.
- `form-error.blade.php` — renders a field-level validation error for a named input via `<x-form-error name="field" />`.

**Route ordering gotcha**: `/registros/crear` must be declared before `/registros/{registro}` in [routes/web.php](routes/web.php) to prevent the literal string "crear" being captured as the `{registro}` parameter.

### Excel import/export
`LocalVotacionController`, `MesaController`, and `UsuarioController` use `phpoffice/phpspreadsheet` for:
- `plantilla()` / `plantillaGlobal()` — download a pre-filled `.xlsx` template.
- `import()` / `importGlobal()` — upload and parse the template, reporting row-level errors via `session()->flash('import_errors', [...])`.
- `destroyBulk()` / `destroyAll()` — bulk-delete records (also available on `LocalVotacionController` and `MesaController`).

Import errors are surfaced in the view separately from the `success` flash. When writing new import logic, cache all lookup tables before the row loop (see the ubigeo-cache pattern in `LocalVotacionController::import()`).

### Toggle (enable/disable) pattern
`LocalVotacion`, `Mesa`, and `AsignacionDigitador` each expose a `PATCH /{resource}/{id}/toggle` route that flips the record's `activo` boolean (or `estado` on asignaciones). Always call `scopeActivo()` when querying these models for dropdowns or vote-entry forms.

### Configuracion (system settings)
`Configuracion` is a key-value table (`clave` string PK, no timestamps). Superadmin can edit empresa name, logo, and sidebar colors. The electoral process settings (type, ERM columns) are no longer here — they live on each `Eleccion`. PDF buttons can be hidden per module (`Configuracion::PDF_MODULOS`, keys `pdf_{modulo}`, default visible): wrap buttons in `@if(Configuracion::pdfVisible('modulo'))` and protect the route with `middleware('pdf:modulo')`. `AppServiceProvider` registers a view composer that injects `$_cfg` (the full config array) into `layouts.app` and `cambiar-password`. Access config values in those views via `$_cfg['clave']`; elsewhere use `Configuracion::get('clave')` or `Configuracion::set('clave', $valor)`.

### Blade layout sections
`app.blade.php` defines these `@yield` slots that every view must/can fill:
- `page-title` — H1 in the top bar (required)
- `page-subtitle` — small caption below the title (optional)
- `page-actions` — right-side action buttons in the header (optional)
- `content` — main page body (required)

### Frontend stack
- **Tailwind CSS v4** via `@tailwindcss/vite` (no config file — uses CSS-first approach)
- **Alpine.js v3** loaded from CDN (`defer` script in `app.blade.php`)
- **SweetAlert2** bundled via Vite (`resources/js/app.js`); toast notifications are triggered from `window._toast` set by Blade before the script runs

### File uploads
Voting-record images (`actas`) are stored on the `public` disk under `actas/{year}/local-{id}/` and retrieved via `Storage::url()`. Run `php artisan storage:link` once after setup if images are not served correctly.

### Dashboard
`DashboardController` branches on role and renders two separate views:
- `dashboard/index.blade.php` — admins and superadmins; site-wide statistics filterable by departamento/provincia/distrito via AJAX.
- `dashboard/digitador.blade.php` — digitadores; shows only their assigned locales and recent records.

## Key files to know

| File | Purpose |
|------|---------|
| [routes/web.php](routes/web.php) | All route definitions with middleware groups |
| [app/Http/Middleware/VerificarRol.php](app/Http/Middleware/VerificarRol.php) | RBAC middleware |
| [app/Http/Middleware/ForzarCambioPassword.php](app/Http/Middleware/ForzarCambioPassword.php) | Redirects digitadores without `password_changed` |
| [app/Models/Usuario.php](app/Models/Usuario.php) | Authenticatable user model with role relationship |
| [app/Models/Configuracion.php](app/Models/Configuracion.php) | Key-value system settings table |
| [app/Http/Controllers/RegistroConteoController.php](app/Http/Controllers/RegistroConteoController.php) | Core vote-entry logic including transaction wrapping |
| [app/Http/Controllers/ReporteController.php](app/Http/Controllers/ReporteController.php) | Vote-result reports filtered by departamento/provincia/distrito/local |
| [app/Http/Controllers/UbigeoCrudController.php](app/Http/Controllers/UbigeoCrudController.php) | Superadmin CRUD for the Departamento/Provincia/Distrito catalog |
| [app/Providers/AppServiceProvider.php](app/Providers/AppServiceProvider.php) | Injects `$_cfg` into layout and password-change views |
| [database/migrations/](database/migrations/) | Schema history |
| [config/auth.php](config/auth.php) | Auth provider configuration pointing to `Usuario` |
