docs: Actualizar README con documentacion completa de la API

- Informacion general y arquitectura
- Estructura del proyecto
- Diagrama y documentacion de base de datos
- API endpoints completos (Auth, Atencion Clientes, Operador, Supervisor, Reportes)
- Guia de instalacion y configuracion
- Funcionalidades especiales (Observer historial, validaciones)
- Middlewares y seguridad
- Comandos Artisan utiles
- Backup y restauracion
- Troubleshooting

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
SIO Admin
2026-01-18 02:29:11 +00:00
parent de656b70a2
commit 9d29ef3bef

595
README.md
View File

@@ -1,51 +1,578 @@
<p align="center"><img src="https://laravel.com/assets/img/components/logo-laravel.svg"></p>
# SIO Backend - Sistema Integral de Operaciones
<p align="center">
<a href="https://travis-ci.org/laravel/framework"><img src="https://travis-ci.org/laravel/framework.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/d/total.svg" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/v/stable.svg" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://poser.pugx.org/laravel/framework/license.svg" alt="License"></a>
</p>
## Drenax - API REST para Gestion de Servicios
## About Laravel
---
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as:
## Informacion General
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
| Campo | Valor |
|-------|-------|
| Nombre | SIO Backend |
| Framework | Laravel 5.5 |
| PHP | 7.4 |
| Base de Datos | MariaDB 11.8 |
| Puerto Local | 8000 |
| URL Produccion | https://sio-api.consultoria-as.com |
Laravel is accessible, yet powerful, providing tools needed for large, robust applications. A superb combination of simplicity, elegance, and innovation give you tools you need to build any application with which you are tasked.
---
## Learning Laravel
## Arquitectura del Sistema
Laravel has the most extensive and thorough documentation and video tutorial library of any modern web application framework. The [Laravel documentation](https://laravel.com/docs) is thorough, complete, and makes it a breeze to get started learning the framework.
```
┌─────────────────────────────────────────────────────────┐
│ FRONTEND │
│ Angular 8.3.29 + Material │
│ Puerto: 4200 │
└─────────────────────┬───────────────────────────────────┘
│ HTTPS (Cloudflare Tunnel)
┌─────────────────────────────────────────────────────────┐
│ BACKEND (API) │
│ Laravel 5.5 (PHP 7.4) │
│ Puerto: 8000 │
└─────────────────────┬───────────────────────────────────┘
┌─────────────────────────────────────────────────────────┐
│ DATABASE │
│ MariaDB 11.8.3 │
│ Puerto: 3306 │
└─────────────────────────────────────────────────────────┘
```
If you're not in the mood to read, [Laracasts](https://laracasts.com) contains over 900 video tutorials on a range of topics including Laravel, modern PHP, unit testing, JavaScript, and more. Boost the skill level of yourself and your entire team by digging into our comprehensive video library.
---
## Laravel Sponsors
## Estructura del Proyecto
We would like to extend our thanks to the following sponsors for helping fund on-going Laravel development. If you are interested in becoming a sponsor, please visit the Laravel [Patreon page](http://patreon.com/taylorotwell):
```
sio-backend/
├── app/
│ ├── Http/
│ │ ├── Controllers/
│ │ │ ├── AtencionClientes/ # Controladores de servicios
│ │ │ │ ├── ServiciosController.php
│ │ │ │ └── EncuestasController.php
│ │ │ ├── Administrador/ # Controladores admin
│ │ │ │ ├── UsersController.php
│ │ │ │ ├── ClientesController.php
│ │ │ │ └── VehiculosController.php
│ │ │ ├── Operador/ # Controladores operador
│ │ │ │ ├── ServiciosController.php
│ │ │ │ ├── JornadaController.php
│ │ │ │ └── CheckListController.php
│ │ │ ├── Reportes/ # Controladores reportes
│ │ │ ├── SupervisorOperaciones/ # Controladores supervisor
│ │ │ └── Auth/ # Autenticacion
│ │ ├── Middleware/
│ │ │ ├── SentinelACL.php # Control de acceso por roles
│ │ │ └── RequestLogs.php # Logs de peticiones
│ │ └── Requests/ # Form Requests (validaciones)
│ ├── Models/ # Modelos Eloquent
│ │ ├── User.php
│ │ ├── Cliente.php
│ │ ├── ServicioEnc.php
│ │ ├── ServicioDet.php
│ │ ├── ServicioProgreso.php
│ │ ├── ServicioEvidencia.php
│ │ ├── ServicioHistorial.php # Historial de cambios
│ │ └── Vehiculo.php
│ ├── Observers/
│ │ └── ServicioDetObserver.php # Observer para historial
│ ├── Mail/ # Plantillas de correo
│ └── Providers/
├── config/
│ ├── app.php
│ ├── database.php
│ ├── jwt.php # Configuracion JWT
│ └── cors.php # Configuracion CORS
├── database/
│ ├── migrations/ # Migraciones de BD
│ └── seeds/ # Seeders de datos
├── routes/
│ ├── api.php # Rutas principales
│ ├── atencion-clientes-routes.php # Rutas atencion clientes
│ ├── administrador-routes.php # Rutas administrador
│ ├── operador-routes.php # Rutas operador (movil)
│ ├── reportes-routes.php # Rutas reportes
│ └── supervisor-operaciones-routes.php # Rutas supervisor
├── storage/
│ ├── app/public/ # Archivos publicos (evidencias)
│ └── logs/laravel.log # Logs de la aplicacion
└── .env # Variables de entorno
```
- **[Vehikl](http://vehikl.com)**
- **[Tighten Co.](https://tighten.co)**
- **[British Software Development](https://www.britishsoftware.co)**
- **[Styde](https://styde.net)**
- [Fragrantica](https://www.fragrantica.com)
- [SOFTonSOFA](https://softonsofa.com/)
---
## Contributing
## Base de Datos
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](http://laravel.com/docs/contributions).
### Diagrama de Tablas Principales
## Security Vulnerabilities
```
┌──────────────┐ ┌──────────────────┐ ┌──────────────┐
│ users │ │ servicios_enc │ │ clientes │
├──────────────┤ ├──────────────────┤ ├──────────────┤
│ id │◄────│ usuario_agenda_id│ │ id │
│ email │ │ cliente_id │────►│ nombre │
│ nombre │ │ fecha_agenda │ │ telefono │
│ tipo_empleado│ │ sucursal_id │ │ email │
└──────────────┘ └────────┬─────────┘ └──────────────┘
│ 1:N
┌──────────────────┐
│ servicios_det │
├──────────────────┤
│ id │
│ servicio_enc_id │
│ operador_id │────► users
│ vehiculo_id │────► cat_vehiculos
│ estatus_servicio │────► cat_estatus_servicios
│ fecha_solicitud │
│ costo_servicio │
└────────┬─────────┘
┌───────────────┼───────────────┐
▼ ▼ ▼
┌─────────────────┐ ┌───────────────┐ ┌────────────────────┐
│servicios_progreso│ │servicios_ │ │servicios_historial │
├─────────────────┤ │evidencias │ ├────────────────────┤
│ fecha_ini │ ├───────────────┤ │ campo │
│ fecha_fin │ │ foto │ │ valor_anterior │
│ firma │ │ tipo │ │ valor_nuevo │
│ litraje │ └───────────────┘ │ usuario_id │
└─────────────────┘ └────────────────────┘
```
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell at taylor@laravel.com. All security vulnerabilities will be promptly addressed.
### Tablas del Sistema
## License
| Tabla | Registros | Descripcion |
|-------|-----------|-------------|
| users | 419 | Usuarios del sistema |
| clientes | 81,853 | Clientes registrados |
| clientes_domicilios | 83,637 | Direcciones de clientes |
| servicios_enc | 129,750 | Encabezados de servicios |
| servicios_det | 123,317 | Detalle de servicios |
| servicios_progreso | 114,219 | Progreso de servicios |
| servicios_evidencias | 180,861 | Evidencias fotograficas |
| servicios_historial | - | Historial de cambios |
| cat_vehiculos | 100 | Catalogo de vehiculos |
| cat_servicios | 64 | Catalogo de servicios |
| cat_estatus_servicios | 7 | Estados de servicio |
| cat_formas_pagos | 10 | Formas de pago |
| cat_origenes | 18 | Origenes de servicio |
| roles | 10 | Roles de usuario |
| sucursales | 4 | Sucursales |
The Laravel framework is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).
### Tipos de Empleados
| ID | Tipo |
|----|------|
| 1 | Administrador |
| 2 | Operador |
| 3 | Auxiliar |
| 5 | Atencion a Clientes |
| 6 | Supervisor de Operaciones |
### Estatus de Servicios
| ID | Nombre | Color |
|----|--------|-------|
| 1 | Realizado | #04B404 (Verde) |
| 2 | Reprogramado | #FF8000 (Naranja) |
| 3 | Cancelado | #B40404 (Rojo) |
| 4 | Pendiente | #FFFF00 (Amarillo) |
| 5 | Negativo | #FE2E2E (Rojo claro) |
| 6 | En Proceso | Azul |
| 7 | Sin Asignar | Gris |
---
## API Endpoints
### Autenticacion
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| POST | /api/login | Iniciar sesion |
| GET | /api/refresh | Refrescar token JWT |
| POST | /api/recoverpassword | Recuperar contrasena |
| POST | /api/updatepassword | Actualizar contrasena |
### Atencion a Clientes (`/api/atencionclientes/`)
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| GET | /solicitud_servicios | Listar servicios |
| POST | /solicitud_servicios | Crear servicio |
| GET | /solicitud_servicios/{id} | Ver servicio |
| PUT | /solicitud_servicios/{id} | Actualizar servicio |
| POST | /solicitud_servicios/agenda | Obtener agenda por fecha |
| GET | /solicitud_servicios/cat_servicios | Catalogo de servicios |
| GET | /solicitud_servicios/estatus_servicios | Catalogo de estatus |
| GET | /solicitud_servicios/clientes | Listar clientes |
| GET | /solicitud_servicios/operadores | Listar operadores |
| GET | /solicitud_servicios/vehiculos | Listar vehiculos |
| GET | /solicitud_servicios/{id}/historial | Ver historial de cambios |
### Operador - App Movil (`/api/operador/`)
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| GET | /checklist | Obtener checklist del vehiculo |
| GET | /checklist/vehiculos | Obtener vehiculos disponibles |
| POST | /checklist | Enviar checklist completado |
| POST | /iniciarjornada | Iniciar jornada laboral |
| POST | /finalizarjornada/{id} | Finalizar jornada |
| GET | /solicitud_servicios | Obtener servicios asignados |
| GET | /solicitud_servicios/{id} | Detalle de servicio |
| POST | /solicitud_servicios/iniciar | Iniciar servicio |
| POST | /solicitud_servicios/finalizar-new | Finalizar servicio |
| POST | /solicitud_servicios/verificar/servicios | Verificar servicios |
| GET | /servicios/diasiguiente | Servicios del dia siguiente |
| POST | /vehiculos_incidencias | Reportar incidencia vehiculo |
### Supervisor de Operaciones (`/api/supervisoroperaciones/`)
| Metodo | Endpoint | Descripcion |
|--------|----------|-------------|
| GET | /asesores | Listar operadores |
| GET | /asesores/{id}/servicios | Servicios de un operador |
| POST | /iniciarjornada | Iniciar jornada supervisor |
| POST | /finalizarjornada/{id} | Finalizar jornada |
### Administrador (`/api/administrador/`)
- Gestion de usuarios
- Gestion de catalogos (clientes, vehiculos, servicios)
- Configuraciones del sistema
### Reportes (`/api/reportes/`)
- Reportes de servicios por periodo
- Productividad por operador
- Encuestas de satisfaccion
- Capacidad aprovechada
---
## Instalacion
### Requisitos
- PHP 7.4
- Composer
- MariaDB 10+ / MySQL 5.7+
- Extensiones PHP: mbstring, xml, curl, mysql, gd, bcmath, zip
### Pasos de Instalacion
```bash
# Clonar repositorio
git clone https://git.consultoria-as.com/consultoria-as/Sio-Back.git
cd Sio-Back
# Instalar dependencias
composer install --no-dev --optimize-autoloader
# Copiar archivo de configuracion
cp .env.example .env
# Generar clave de aplicacion
php artisan key:generate
# Configurar permisos
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache
# Ejecutar migraciones
php artisan migrate
# (Opcional) Ejecutar seeders
php artisan db:seed
```
### Configuracion del Archivo .env
```env
APP_NAME=SIO
APP_ENV=production
APP_DEBUG=false
APP_URL=https://sio-api.consultoria-as.com
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=sio_database
DB_USERNAME=sio_user
DB_PASSWORD=tu_password
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=correo@gmail.com
MAIL_PASSWORD=app_password
MAIL_ENCRYPTION=tls
AMBIENTE=PROD
```
### Ejecutar en Desarrollo
```bash
php artisan serve --host=0.0.0.0 --port=8000
```
### Ejecutar en Produccion
Se recomienda usar Nginx o Apache. Ejemplo de configuracion Nginx:
```nginx
server {
listen 80;
server_name sio-api.consultoria-as.com;
root /var/www/sio-backend/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
}
```
---
## Funcionalidades Especiales
### Historial de Cambios (Observer)
El sistema registra automaticamente todos los cambios realizados a los servicios mediante un Observer de Eloquent.
**Modelo:** `app/Models/ServicioHistorial.php`
**Observer:** `app/Observers/ServicioDetObserver.php`
**Campos rastreados:**
- estatus_servicio_id
- operador_id
- vehiculo_id
- auxiliar_1, auxiliar_2, auxiliar_3
- costo_servicio
- fecha_solicitud
- duracion
- comentarios
- comentarios_cancelacion
**Estructura de la tabla:**
```sql
CREATE TABLE servicios_historial (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
servicio_det_id INT UNSIGNED NOT NULL,
usuario_id INT UNSIGNED NOT NULL,
campo VARCHAR(100) NOT NULL,
valor_anterior TEXT,
valor_nuevo TEXT,
accion ENUM('crear', 'actualizar', 'eliminar') DEFAULT 'actualizar',
ip_address VARCHAR(45),
created_at TIMESTAMP,
updated_at TIMESTAMP
);
```
### Validacion de Disponibilidad
Antes de asignar operador/vehiculo, el sistema valida:
- Que no esten asignados a otro servicio en el mismo horario
- Disponibilidad de auxiliares
- Conflictos de tiempo
### Encuestas de Satisfaccion
- **Encuesta Domestico:** 12 preguntas
- **Encuesta Empresarial:** 13 preguntas
---
## Middlewares
### SentinelACL
Control de acceso basado en roles usando Cartalyst Sentinel.
```php
// Rutas protegidas por rol
Route::middleware(['jwt', 'acl:administrador'])->group(function () {
// Solo administradores
});
```
### RequestLogs
Registra todas las peticiones HTTP para auditoria.
---
## Comandos Artisan Utiles
```bash
# Limpiar cache
php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
# Optimizar para produccion
php artisan config:cache
php artisan route:cache
# Migraciones
php artisan migrate # Ejecutar migraciones
php artisan migrate:rollback # Revertir ultima migracion
php artisan migrate:fresh --seed # Recrear BD con seeders
# Generar documentacion de rutas
php artisan route:list
# Logs
tail -f storage/logs/laravel.log
```
---
## Backup y Restauracion
### Crear Backup
```bash
mysqldump -u sio_user -p sio_database > backup_$(date +%Y%m%d_%H%M%S).sql
```
### Restaurar Backup
```bash
mysql -u sio_user -p sio_database < backup_XXXXXXXX.sql
```
---
## Seguridad
### Autenticacion JWT
El sistema usa JSON Web Tokens para autenticacion stateless.
**Header requerido:**
```
Authorization: Bearer {token}
```
### CORS
Configurado en `config/cors.php` para permitir peticiones del frontend.
### Validaciones
Todas las peticiones son validadas mediante Form Requests en `app/Http/Requests/`.
---
## Troubleshooting
### Error 500 - Internal Server Error
```bash
# Verificar permisos
chmod -R 775 storage bootstrap/cache
# Verificar logs
tail -f storage/logs/laravel.log
# Limpiar cache
php artisan cache:clear
php artisan config:clear
```
### Error 422 - Unprocessable Entity
- Verificar datos enviados en la peticion
- Revisar validaciones en el Form Request correspondiente
### Error de conexion a BD
- Verificar credenciales en `.env`
- Confirmar que MariaDB este ejecutandose
- Verificar permisos del usuario de BD
### CORS bloqueado
- Verificar configuracion en `config/cors.php`
- Agregar dominio del frontend a la lista de origenes permitidos
---
## Tecnologias Utilizadas
- **Laravel 5.5** - Framework PHP
- **PHP 7.4** - Lenguaje de programacion
- **MariaDB** - Base de datos
- **Cartalyst Sentinel** - Autenticacion y roles
- **JWT** - Tokens de autenticacion
- **Eloquent ORM** - Mapeo objeto-relacional
- **DOMPDF** - Generacion de PDFs
- **Maatwebsite Excel** - Exportacion a Excel
---
## Estructura de Respuestas API
### Respuesta Exitosa
```json
{
"success": true,
"data": { ... },
"message": "Operacion exitosa"
}
```
### Respuesta de Error
```json
{
"success": false,
"error": "Mensaje de error",
"code": 400
}
```
### Respuesta Paginada
```json
{
"success": true,
"data": [ ... ],
"meta": {
"current_page": 1,
"last_page": 10,
"per_page": 15,
"total": 150
}
}
```
---
## Contacto
| Campo | Valor |
|-------|-------|
| Sistema | SIO (Sistema Integral de Operaciones) |
| Empresa | Drenax |
| Dominio | consultoria-as.com |
---
**Version:** 1.0
**Ultima actualizacion:** 2026-01-17