Compare commits
2 Commits
be10a888fb
...
02d17a046e
| Author | SHA1 | Date | |
|---|---|---|---|
| 02d17a046e | |||
| ffe298a544 |
860
API_DOCUMENTATION.md
Normal file
860
API_DOCUMENTATION.md
Normal file
@@ -0,0 +1,860 @@
|
||||
# 📚 Documentación API - Syntria
|
||||
|
||||
## 🔐 Autenticación
|
||||
|
||||
Todos los endpoints (excepto `/api/auth/login` y `/api/auth/register`) requieren autenticación mediante token JWT en el header:
|
||||
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 AUTH - Autenticación
|
||||
|
||||
### 1. Login
|
||||
**POST** `/api/auth/login`
|
||||
|
||||
Inicia sesión y obtiene el token de acceso.
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"username": "admin",
|
||||
"password": "admin123"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
||||
"token_type": "bearer",
|
||||
"user": {
|
||||
"id": 1,
|
||||
"username": "admin",
|
||||
"email": "admin@syntria.com",
|
||||
"full_name": "Administrador",
|
||||
"role": "admin",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `401 Unauthorized` - Usuario o contraseña incorrectos
|
||||
|
||||
---
|
||||
|
||||
### 2. Registro
|
||||
**POST** `/api/auth/register`
|
||||
|
||||
Crea una nueva cuenta de usuario.
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"username": "nuevo_usuario",
|
||||
"password": "password123",
|
||||
"email": "usuario@email.com",
|
||||
"full_name": "Usuario Nuevo",
|
||||
"role": "mechanic"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 2,
|
||||
"username": "nuevo_usuario",
|
||||
"email": "usuario@email.com",
|
||||
"full_name": "Usuario Nuevo",
|
||||
"role": "mechanic",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `400 Bad Request` - Usuario ya existe
|
||||
|
||||
---
|
||||
|
||||
### 3. Obtener Mi Perfil
|
||||
**GET** `/api/auth/me`
|
||||
|
||||
Obtiene la información del usuario autenticado.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"username": "admin",
|
||||
"email": "admin@syntria.com",
|
||||
"full_name": "Administrador",
|
||||
"role": "admin",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 👥 USERS - Gestión de Usuarios
|
||||
|
||||
### 1. Listar Usuarios (Admin)
|
||||
**GET** `/api/users`
|
||||
|
||||
Lista todos los usuarios del sistema.
|
||||
|
||||
**Query Params:**
|
||||
- `skip` (int, default: 0) - Paginación
|
||||
- `limit` (int, default: 100) - Límite de resultados
|
||||
- `active_only` (bool, default: true) - Solo usuarios activos
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"username": "admin",
|
||||
"email": "admin@syntria.com",
|
||||
"full_name": "Administrador",
|
||||
"role": "admin",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"username": "mecanico",
|
||||
"email": "mecanico@syntria.com",
|
||||
"full_name": "Mecánico",
|
||||
"role": "mechanic",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `403 Forbidden` - No tienes permisos (solo admin)
|
||||
|
||||
---
|
||||
|
||||
### 2. Obtener Usuario por ID (Admin)
|
||||
**GET** `/api/users/{user_id}`
|
||||
|
||||
Obtiene un usuario específico.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 2,
|
||||
"username": "mecanico",
|
||||
"email": "mecanico@syntria.com",
|
||||
"full_name": "Mecánico",
|
||||
"role": "mechanic",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `403 Forbidden` - No tienes permisos
|
||||
- `404 Not Found` - Usuario no encontrado
|
||||
|
||||
---
|
||||
|
||||
### 3. Crear Usuario (Admin)
|
||||
**POST** `/api/users`
|
||||
|
||||
Crea un nuevo usuario.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"username": "nuevo_mecanico",
|
||||
"password": "password123",
|
||||
"email": "mecanico2@syntria.com",
|
||||
"full_name": "Mecánico 2",
|
||||
"role": "mechanic"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 3,
|
||||
"username": "nuevo_mecanico",
|
||||
"email": "mecanico2@syntria.com",
|
||||
"full_name": "Mecánico 2",
|
||||
"role": "mechanic",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `400 Bad Request` - Usuario ya existe o email en uso
|
||||
- `403 Forbidden` - No tienes permisos
|
||||
|
||||
---
|
||||
|
||||
### 4. Actualizar Usuario (Admin)
|
||||
**PUT** `/api/users/{user_id}`
|
||||
|
||||
Actualiza información de un usuario.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"email": "nuevo_email@syntria.com",
|
||||
"full_name": "Nombre Actualizado",
|
||||
"role": "admin"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 2,
|
||||
"username": "mecanico",
|
||||
"email": "nuevo_email@syntria.com",
|
||||
"full_name": "Nombre Actualizado",
|
||||
"role": "admin",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `400 Bad Request` - Email ya en uso
|
||||
- `403 Forbidden` - No tienes permisos
|
||||
- `404 Not Found` - Usuario no encontrado
|
||||
|
||||
---
|
||||
|
||||
### 5. Inactivar Usuario (Admin)
|
||||
**PATCH** `/api/users/{user_id}/deactivate`
|
||||
|
||||
Inactiva un usuario (soft delete).
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"message": "Usuario inactivado correctamente",
|
||||
"user_id": 2
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `400 Bad Request` - No puedes inactivar tu propio usuario
|
||||
- `403 Forbidden` - No tienes permisos
|
||||
- `404 Not Found` - Usuario no encontrado
|
||||
|
||||
---
|
||||
|
||||
### 6. Activar Usuario (Admin)
|
||||
**PATCH** `/api/users/{user_id}/activate`
|
||||
|
||||
Reactiva un usuario inactivo.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"message": "Usuario activado correctamente",
|
||||
"user_id": 2
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `403 Forbidden` - No tienes permisos
|
||||
- `404 Not Found` - Usuario no encontrado
|
||||
|
||||
---
|
||||
|
||||
### 7. Cambiar Contraseña de Usuario (Admin)
|
||||
**PATCH** `/api/users/{user_id}/password`
|
||||
|
||||
Cambia la contraseña de cualquier usuario.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"new_password": "nueva_password123"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"message": "Contraseña actualizada correctamente"
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `403 Forbidden` - No tienes permisos
|
||||
- `404 Not Found` - Usuario no encontrado
|
||||
|
||||
---
|
||||
|
||||
### 8. Actualizar Mi Perfil
|
||||
**PUT** `/api/users/me`
|
||||
|
||||
Actualiza tu propio perfil.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"email": "mi_nuevo_email@syntria.com",
|
||||
"full_name": "Mi Nuevo Nombre"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"username": "admin",
|
||||
"email": "mi_nuevo_email@syntria.com",
|
||||
"full_name": "Mi Nuevo Nombre",
|
||||
"role": "admin",
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `400 Bad Request` - Email ya en uso
|
||||
|
||||
---
|
||||
|
||||
### 9. Cambiar Mi Contraseña
|
||||
**PATCH** `/api/users/me/password`
|
||||
|
||||
Cambia tu propia contraseña.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"current_password": "password_actual",
|
||||
"new_password": "nueva_password123"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"message": "Contraseña actualizada correctamente"
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `400 Bad Request` - Contraseña actual incorrecta
|
||||
|
||||
---
|
||||
|
||||
## 📋 CHECKLISTS - Plantillas de Inspección
|
||||
|
||||
### 1. Listar Checklists
|
||||
**GET** `/api/checklists`
|
||||
|
||||
Lista todas las plantillas de inspección.
|
||||
|
||||
**Query Params:**
|
||||
- `skip` (int, default: 0)
|
||||
- `limit` (int, default: 100)
|
||||
- `active_only` (bool, default: false) - Solo activas
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Inspección Pre-Entrega",
|
||||
"description": "Checklist para vehículos antes de entrega",
|
||||
"ai_mode": "off",
|
||||
"scoring_enabled": true,
|
||||
"logo_url": null,
|
||||
"max_score": 100,
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z",
|
||||
"creator_id": 1
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Crear Checklist (Admin)
|
||||
**POST** `/api/checklists`
|
||||
|
||||
Crea una nueva plantilla de inspección.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"name": "Inspección de Mantenimiento",
|
||||
"description": "Checklist para mantenimiento preventivo",
|
||||
"ai_mode": "off",
|
||||
"scoring_enabled": true,
|
||||
"logo_url": null
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 2,
|
||||
"name": "Inspección de Mantenimiento",
|
||||
"description": "Checklist para mantenimiento preventivo",
|
||||
"ai_mode": "off",
|
||||
"scoring_enabled": true,
|
||||
"logo_url": null,
|
||||
"max_score": 0,
|
||||
"is_active": true,
|
||||
"created_at": "2025-11-19T00:00:00Z",
|
||||
"creator_id": 1
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `403 Forbidden` - No tienes permisos
|
||||
|
||||
---
|
||||
|
||||
## ❓ QUESTIONS - Preguntas del Checklist
|
||||
|
||||
### 1. Crear Pregunta (Admin)
|
||||
**POST** `/api/questions`
|
||||
|
||||
Agrega una pregunta a un checklist.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"checklist_id": 1,
|
||||
"section": "Motor",
|
||||
"text": "¿El nivel de aceite es correcto?",
|
||||
"type": "pass_fail",
|
||||
"points": 5,
|
||||
"options": null,
|
||||
"order": 1,
|
||||
"allow_photos": true,
|
||||
"max_photos": 3,
|
||||
"requires_comment_on_fail": true
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"checklist_id": 1,
|
||||
"section": "Motor",
|
||||
"text": "¿El nivel de aceite es correcto?",
|
||||
"type": "pass_fail",
|
||||
"points": 5,
|
||||
"options": null,
|
||||
"order": 1,
|
||||
"allow_photos": true,
|
||||
"max_photos": 3,
|
||||
"requires_comment_on_fail": true,
|
||||
"created_at": "2025-11-19T00:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔍 INSPECTIONS - Inspecciones Realizadas
|
||||
|
||||
### 1. Listar Inspecciones
|
||||
**GET** `/api/inspections`
|
||||
|
||||
Lista las inspecciones realizadas.
|
||||
|
||||
**Query Params:**
|
||||
- `skip` (int, default: 0)
|
||||
- `limit` (int, default: 100)
|
||||
- `vehicle_plate` (string) - Filtrar por patente
|
||||
- `status` (string) - Filtrar por estado (draft, completed, inactive)
|
||||
- `show_inactive` (bool, default: false) - Mostrar inactivas
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
[
|
||||
{
|
||||
"id": 1,
|
||||
"checklist_id": 1,
|
||||
"mechanic_id": 2,
|
||||
"or_number": "OR-12345",
|
||||
"vehicle_plate": "ABC123",
|
||||
"vehicle_brand": "Toyota",
|
||||
"vehicle_model": "Corolla",
|
||||
"vehicle_km": 50000,
|
||||
"client_name": "Juan Pérez",
|
||||
"score": 85,
|
||||
"max_score": 100,
|
||||
"percentage": 85.0,
|
||||
"flagged_items_count": 2,
|
||||
"status": "completed",
|
||||
"started_at": "2025-11-19T10:00:00Z",
|
||||
"completed_at": "2025-11-19T11:00:00Z",
|
||||
"created_at": "2025-11-19T10:00:00Z"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Crear Inspección
|
||||
**POST** `/api/inspections`
|
||||
|
||||
Inicia una nueva inspección.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"checklist_id": 1,
|
||||
"or_number": "OR-12345",
|
||||
"vehicle_plate": "ABC123",
|
||||
"vehicle_brand": "Toyota",
|
||||
"vehicle_model": "Corolla",
|
||||
"vehicle_km": 50000,
|
||||
"client_name": "Juan Pérez"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"checklist_id": 1,
|
||||
"mechanic_id": 2,
|
||||
"or_number": "OR-12345",
|
||||
"vehicle_plate": "ABC123",
|
||||
"vehicle_brand": "Toyota",
|
||||
"vehicle_model": "Corolla",
|
||||
"vehicle_km": 50000,
|
||||
"client_name": "Juan Pérez",
|
||||
"score": 0,
|
||||
"max_score": 100,
|
||||
"percentage": 0.0,
|
||||
"flagged_items_count": 0,
|
||||
"status": "draft",
|
||||
"started_at": "2025-11-19T10:00:00Z",
|
||||
"created_at": "2025-11-19T10:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Completar Inspección
|
||||
**POST** `/api/inspections/{inspection_id}/complete`
|
||||
|
||||
Marca una inspección como completada y calcula el score.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"status": "completed",
|
||||
"score": 85,
|
||||
"percentage": 85.0,
|
||||
"flagged_items_count": 2,
|
||||
"completed_at": "2025-11-19T11:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. Inactivar Inspección (Admin)
|
||||
**PATCH** `/api/inspections/{inspection_id}/deactivate`
|
||||
|
||||
Inactiva una inspección (soft delete).
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"message": "Inspección inactivada correctamente",
|
||||
"inspection_id": 1
|
||||
}
|
||||
```
|
||||
|
||||
**Errores:**
|
||||
- `403 Forbidden` - No tienes permisos (solo admin)
|
||||
- `404 Not Found` - Inspección no encontrada
|
||||
|
||||
---
|
||||
|
||||
## 📝 ANSWERS - Respuestas de Inspección
|
||||
|
||||
### 1. Crear Respuesta
|
||||
**POST** `/api/answers`
|
||||
|
||||
Registra una respuesta a una pregunta de inspección.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"inspection_id": 1,
|
||||
"question_id": 1,
|
||||
"answer_value": "pass",
|
||||
"answer_text": null,
|
||||
"is_flagged": false,
|
||||
"comments": null,
|
||||
"photos": []
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"id": 1,
|
||||
"inspection_id": 1,
|
||||
"question_id": 1,
|
||||
"answer_value": "pass",
|
||||
"answer_text": null,
|
||||
"is_flagged": false,
|
||||
"points_earned": 5,
|
||||
"comments": null,
|
||||
"photos": [],
|
||||
"created_at": "2025-11-19T10:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🤖 AI - Análisis con Inteligencia Artificial
|
||||
|
||||
### 1. Analizar Foto con IA
|
||||
**POST** `/api/ai/analyze`
|
||||
|
||||
Analiza una foto usando IA y devuelve sugerencias.
|
||||
|
||||
**Headers:**
|
||||
```
|
||||
Authorization: Bearer {token}
|
||||
Content-Type: application/json
|
||||
```
|
||||
|
||||
**Body:**
|
||||
```json
|
||||
{
|
||||
"photo_base64": "data:image/jpeg;base64,/9j/4AAQSkZJRg...",
|
||||
"question_text": "¿El nivel de aceite es correcto?",
|
||||
"question_type": "pass_fail",
|
||||
"section": "Motor"
|
||||
}
|
||||
```
|
||||
|
||||
**Response 200:**
|
||||
```json
|
||||
{
|
||||
"analysis": {
|
||||
"answer_value": "fail",
|
||||
"confidence": 0.85,
|
||||
"explanation": "El nivel de aceite está por debajo del mínimo recomendado",
|
||||
"is_flagged": true,
|
||||
"comments": "Se requiere rellenar aceite urgentemente"
|
||||
},
|
||||
"model_used": "gpt-4-vision-preview",
|
||||
"timestamp": "2025-11-19T10:30:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Códigos de Estado HTTP
|
||||
|
||||
- `200 OK` - Solicitud exitosa
|
||||
- `201 Created` - Recurso creado exitosamente
|
||||
- `400 Bad Request` - Datos inválidos o faltantes
|
||||
- `401 Unauthorized` - No autenticado o token inválido
|
||||
- `403 Forbidden` - No tienes permisos para esta acción
|
||||
- `404 Not Found` - Recurso no encontrado
|
||||
- `500 Internal Server Error` - Error del servidor
|
||||
|
||||
---
|
||||
|
||||
## 🔐 Roles y Permisos
|
||||
|
||||
### Admin
|
||||
- ✅ Gestionar usuarios (crear, editar, inactivar)
|
||||
- ✅ Gestionar checklists y preguntas
|
||||
- ✅ Ver todas las inspecciones
|
||||
- ✅ Crear inspecciones
|
||||
- ✅ Inactivar inspecciones
|
||||
- ✅ Acceso completo a configuración de IA
|
||||
|
||||
### Mechanic (Mecánico)
|
||||
- ✅ Ver sus propias inspecciones
|
||||
- ✅ Crear y completar inspecciones
|
||||
- ✅ Responder preguntas de inspección
|
||||
- ✅ Usar análisis con IA
|
||||
- ✅ Actualizar su propio perfil
|
||||
- ❌ No puede gestionar usuarios
|
||||
- ❌ No puede gestionar checklists
|
||||
|
||||
---
|
||||
|
||||
## 💡 Ejemplos de Uso
|
||||
|
||||
### Flujo Completo: Crear y Completar Inspección
|
||||
|
||||
```bash
|
||||
# 1. Login
|
||||
curl -X POST http://localhost:8000/api/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"username": "mecanico",
|
||||
"password": "mec123"
|
||||
}'
|
||||
|
||||
# Guardar el token de la respuesta
|
||||
TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
|
||||
|
||||
# 2. Crear inspección
|
||||
curl -X POST http://localhost:8000/api/inspections \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"checklist_id": 1,
|
||||
"or_number": "OR-12345",
|
||||
"vehicle_plate": "ABC123",
|
||||
"vehicle_brand": "Toyota",
|
||||
"vehicle_model": "Corolla",
|
||||
"vehicle_km": 50000,
|
||||
"client_name": "Juan Pérez"
|
||||
}'
|
||||
|
||||
# Guardar inspection_id de la respuesta
|
||||
INSPECTION_ID=1
|
||||
|
||||
# 3. Responder preguntas
|
||||
curl -X POST http://localhost:8000/api/answers \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"inspection_id": '$INSPECTION_ID',
|
||||
"question_id": 1,
|
||||
"answer_value": "pass",
|
||||
"is_flagged": false,
|
||||
"points_earned": 5
|
||||
}'
|
||||
|
||||
# 4. Completar inspección
|
||||
curl -X POST http://localhost:8000/api/inspections/$INSPECTION_ID/complete \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Testing con Postman
|
||||
|
||||
1. Importa la colección de Postman (disponible en `/docs/postman`)
|
||||
2. Configura la variable de entorno `base_url` a `http://localhost:8000`
|
||||
3. Ejecuta el request de Login
|
||||
4. El token se guardará automáticamente en la variable `token`
|
||||
5. Los demás requests usarán el token automáticamente
|
||||
|
||||
---
|
||||
|
||||
## 📖 Documentación Interactiva
|
||||
|
||||
Accede a la documentación interactiva de Swagger:
|
||||
- **Swagger UI**: `http://localhost:8000/docs`
|
||||
- **ReDoc**: `http://localhost:8000/redoc`
|
||||
|
||||
Puedes probar todos los endpoints directamente desde el navegador.
|
||||
@@ -1,5 +1,4 @@
|
||||
from pydantic_settings import BaseSettings
|
||||
from typing import Optional
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# Database
|
||||
@@ -11,7 +10,7 @@ class Settings(BaseSettings):
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 10080 # 7 días
|
||||
|
||||
# OpenAI
|
||||
OPENAI_API_KEY: Optional[str] = None
|
||||
OPENAI_API_KEY: str | None = None
|
||||
|
||||
# Environment
|
||||
ENVIRONMENT: str = "development"
|
||||
|
||||
@@ -96,6 +96,230 @@ def get_me(current_user: models.User = Depends(get_current_user)):
|
||||
return current_user
|
||||
|
||||
|
||||
# ============= USER ENDPOINTS =============
|
||||
@app.get("/api/users", response_model=List[schemas.User])
|
||||
def get_users(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
active_only: bool = True,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede ver todos los usuarios
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para ver usuarios")
|
||||
|
||||
query = db.query(models.User)
|
||||
if active_only:
|
||||
query = query.filter(models.User.is_active == True)
|
||||
|
||||
return query.offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
@app.get("/api/users/{user_id}", response_model=schemas.User)
|
||||
def get_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede ver otros usuarios
|
||||
if current_user.role != "admin" and current_user.id != user_id:
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para ver este usuario")
|
||||
|
||||
user = db.query(models.User).filter(models.User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@app.post("/api/users", response_model=schemas.User)
|
||||
def create_user(
|
||||
user: schemas.UserCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede crear usuarios
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para crear usuarios")
|
||||
|
||||
# Verificar si usuario existe
|
||||
db_user = db.query(models.User).filter(models.User.username == user.username).first()
|
||||
if db_user:
|
||||
raise HTTPException(status_code=400, detail="Usuario ya existe")
|
||||
|
||||
# Verificar si email existe
|
||||
if user.email:
|
||||
db_email = db.query(models.User).filter(models.User.email == user.email).first()
|
||||
if db_email:
|
||||
raise HTTPException(status_code=400, detail="Email ya está en uso")
|
||||
|
||||
# Crear usuario
|
||||
hashed_password = get_password_hash(user.password)
|
||||
db_user = models.User(
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
full_name=user.full_name,
|
||||
role=user.role,
|
||||
password_hash=hashed_password,
|
||||
is_active=True
|
||||
)
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
@app.put("/api/users/{user_id}", response_model=schemas.User)
|
||||
def update_user(
|
||||
user_id: int,
|
||||
user_update: schemas.UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede actualizar otros usuarios
|
||||
if current_user.role != "admin" and current_user.id != user_id:
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para actualizar este usuario")
|
||||
|
||||
db_user = db.query(models.User).filter(models.User.id == user_id).first()
|
||||
if not db_user:
|
||||
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
||||
|
||||
# Actualizar campos
|
||||
if user_update.email is not None:
|
||||
# Verificar si email está en uso
|
||||
existing = db.query(models.User).filter(
|
||||
models.User.email == user_update.email,
|
||||
models.User.id != user_id
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Email ya está en uso")
|
||||
db_user.email = user_update.email
|
||||
|
||||
if user_update.full_name is not None:
|
||||
db_user.full_name = user_update.full_name
|
||||
|
||||
# Solo admin puede cambiar roles
|
||||
if user_update.role is not None:
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para cambiar roles")
|
||||
db_user.role = user_update.role
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
@app.patch("/api/users/{user_id}/deactivate")
|
||||
def deactivate_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede inactivar usuarios
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para inactivar usuarios")
|
||||
|
||||
# No permitir auto-inactivación
|
||||
if current_user.id == user_id:
|
||||
raise HTTPException(status_code=400, detail="No puedes inactivar tu propio usuario")
|
||||
|
||||
db_user = db.query(models.User).filter(models.User.id == user_id).first()
|
||||
if not db_user:
|
||||
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
||||
|
||||
db_user.is_active = False
|
||||
db.commit()
|
||||
|
||||
return {"message": "Usuario inactivado correctamente", "user_id": user_id}
|
||||
|
||||
|
||||
@app.patch("/api/users/{user_id}/activate")
|
||||
def activate_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede activar usuarios
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para activar usuarios")
|
||||
|
||||
db_user = db.query(models.User).filter(models.User.id == user_id).first()
|
||||
if not db_user:
|
||||
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
||||
|
||||
db_user.is_active = True
|
||||
db.commit()
|
||||
|
||||
return {"message": "Usuario activado correctamente", "user_id": user_id}
|
||||
|
||||
|
||||
@app.patch("/api/users/{user_id}/password")
|
||||
def change_user_password(
|
||||
user_id: int,
|
||||
password_update: schemas.AdminPasswordUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede cambiar contraseñas de otros usuarios
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para cambiar contraseñas")
|
||||
|
||||
db_user = db.query(models.User).filter(models.User.id == user_id).first()
|
||||
if not db_user:
|
||||
raise HTTPException(status_code=404, detail="Usuario no encontrado")
|
||||
|
||||
# Cambiar contraseña
|
||||
db_user.password_hash = get_password_hash(password_update.new_password)
|
||||
db.commit()
|
||||
|
||||
return {"message": "Contraseña actualizada correctamente"}
|
||||
|
||||
|
||||
@app.patch("/api/users/me/password")
|
||||
def change_my_password(
|
||||
password_update: schemas.UserPasswordUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Verificar contraseña actual
|
||||
if not verify_password(password_update.current_password, current_user.password_hash):
|
||||
raise HTTPException(status_code=400, detail="Contraseña actual incorrecta")
|
||||
|
||||
# Cambiar contraseña
|
||||
current_user.password_hash = get_password_hash(password_update.new_password)
|
||||
db.commit()
|
||||
|
||||
return {"message": "Contraseña actualizada correctamente"}
|
||||
|
||||
|
||||
@app.put("/api/users/me", response_model=schemas.User)
|
||||
def update_my_profile(
|
||||
user_update: schemas.UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Actualizar email
|
||||
if user_update.email is not None:
|
||||
# Verificar si email está en uso
|
||||
existing = db.query(models.User).filter(
|
||||
models.User.email == user_update.email,
|
||||
models.User.id != current_user.id
|
||||
).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=400, detail="Email ya está en uso")
|
||||
current_user.email = user_update.email
|
||||
|
||||
# Actualizar nombre
|
||||
if user_update.full_name is not None:
|
||||
current_user.full_name = user_update.full_name
|
||||
|
||||
# No permitir cambio de rol desde perfil
|
||||
db.commit()
|
||||
db.refresh(current_user)
|
||||
return current_user
|
||||
|
||||
|
||||
# ============= CHECKLIST ENDPOINTS =============
|
||||
@app.get("/api/checklists", response_model=List[schemas.Checklist])
|
||||
def get_checklists(
|
||||
@@ -233,11 +457,16 @@ def get_inspections(
|
||||
limit: int = 100,
|
||||
vehicle_plate: str = None,
|
||||
status: str = None,
|
||||
show_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
query = db.query(models.Inspection)
|
||||
|
||||
# Por defecto, solo mostrar inspecciones activas
|
||||
if not show_inactive:
|
||||
query = query.filter(models.Inspection.is_active == True)
|
||||
|
||||
# Mecánicos solo ven sus inspecciones
|
||||
if current_user.role == "mechanic":
|
||||
query = query.filter(models.Inspection.mechanic_id == current_user.id)
|
||||
@@ -346,6 +575,32 @@ def complete_inspection(
|
||||
return inspection
|
||||
|
||||
|
||||
@app.patch("/api/inspections/{inspection_id}/deactivate")
|
||||
def deactivate_inspection(
|
||||
inspection_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: models.User = Depends(get_current_user)
|
||||
):
|
||||
# Solo admin puede inactivar
|
||||
if current_user.role != "admin":
|
||||
raise HTTPException(status_code=403, detail="No tienes permisos para inactivar inspecciones")
|
||||
|
||||
inspection = db.query(models.Inspection).filter(
|
||||
models.Inspection.id == inspection_id
|
||||
).first()
|
||||
|
||||
if not inspection:
|
||||
raise HTTPException(status_code=404, detail="Inspección no encontrada")
|
||||
|
||||
inspection.is_active = False
|
||||
inspection.status = "inactive"
|
||||
|
||||
db.commit()
|
||||
db.refresh(inspection)
|
||||
|
||||
return {"message": "Inspección inactivada correctamente", "inspection_id": inspection_id}
|
||||
|
||||
|
||||
# ============= ANSWER ENDPOINTS =============
|
||||
@app.post("/api/answers", response_model=schemas.Answer)
|
||||
def create_answer(
|
||||
|
||||
@@ -87,7 +87,8 @@ class Inspection(Base):
|
||||
flagged_items_count = Column(Integer, default=0)
|
||||
|
||||
# Estado
|
||||
status = Column(String(20), default="draft") # draft, completed
|
||||
status = Column(String(20), default="draft") # draft, completed, inactive
|
||||
is_active = Column(Boolean, default=True)
|
||||
|
||||
# Firma
|
||||
signature_data = Column(Text) # Base64 de la firma
|
||||
|
||||
@@ -12,6 +12,18 @@ class UserBase(BaseModel):
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
email: Optional[EmailStr] = None
|
||||
full_name: Optional[str] = None
|
||||
role: Optional[str] = None
|
||||
|
||||
class UserPasswordUpdate(BaseModel):
|
||||
current_password: str
|
||||
new_password: str
|
||||
|
||||
class AdminPasswordUpdate(BaseModel):
|
||||
new_password: str
|
||||
|
||||
class UserLogin(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
|
||||
@@ -331,7 +331,7 @@ function DashboardPage({ user, setUser }) {
|
||||
onStartInspection={setActiveInspection}
|
||||
/>
|
||||
) : activeTab === 'inspections' ? (
|
||||
<InspectionsTab inspections={inspections} user={user} />
|
||||
<InspectionsTab inspections={inspections} user={user} onUpdate={loadData} />
|
||||
) : activeTab === 'settings' ? (
|
||||
<SettingsTab user={user} />
|
||||
) : activeTab === 'users' ? (
|
||||
@@ -996,17 +996,25 @@ function ChecklistsTab({ checklists, user, onChecklistCreated, onStartInspection
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{user.role === 'admin' && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedChecklist(checklist)
|
||||
setShowQuestionsModal(true)
|
||||
}}
|
||||
className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 transition"
|
||||
>
|
||||
Gestionar Preguntas
|
||||
</button>
|
||||
<>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedChecklist(checklist)
|
||||
setShowQuestionsModal(true)
|
||||
}}
|
||||
className="px-4 py-2 bg-gradient-to-r from-purple-600 to-indigo-600 text-white rounded-lg hover:from-purple-700 hover:to-indigo-700 transition-all transform hover:scale-105 shadow-lg"
|
||||
>
|
||||
Gestionar Preguntas
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onStartInspection(checklist)}
|
||||
className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-lg hover:from-green-600 hover:to-emerald-600 transition-all transform hover:scale-105 shadow-lg"
|
||||
>
|
||||
Nueva Inspección
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{user.role === 'mechanic' && (
|
||||
{(user.role === 'mechanic' || user.role === 'mecanico') && (
|
||||
<button
|
||||
onClick={() => onStartInspection(checklist)}
|
||||
className="px-4 py-2 bg-gradient-to-r from-green-500 to-emerald-500 text-white rounded-lg hover:from-green-600 hover:to-emerald-600 transition-all transform hover:scale-105 shadow-lg"
|
||||
@@ -1153,9 +1161,10 @@ function ChecklistsTab({ checklists, user, onChecklistCreated, onStartInspection
|
||||
)
|
||||
}
|
||||
|
||||
function InspectionDetailModal({ inspection, onClose }) {
|
||||
function InspectionDetailModal({ inspection, user, onClose, onUpdate }) {
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [inspectionDetail, setInspectionDetail] = useState(null)
|
||||
const [isInactivating, setIsInactivating] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const loadInspectionDetails = async () => {
|
||||
@@ -1419,19 +1428,55 @@ function InspectionDetailModal({ inspection, onClose }) {
|
||||
|
||||
{/* Footer */}
|
||||
<div className="border-t p-4 bg-gray-50">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="w-full px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition"
|
||||
>
|
||||
Cerrar
|
||||
</button>
|
||||
<div className="flex gap-3">
|
||||
{user?.role === 'admin' && (
|
||||
<>
|
||||
<button
|
||||
onClick={async () => {
|
||||
if (confirm('¿Deseas inactivar esta inspección?')) {
|
||||
setIsInactivating(true)
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
const API_URL = import.meta.env.VITE_API_URL || ''
|
||||
const response = await fetch(`${API_URL}/api/inspections/${inspection.id}/deactivate`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Authorization': `Bearer ${token}` }
|
||||
})
|
||||
if (response.ok) {
|
||||
alert('Inspección inactivada correctamente')
|
||||
onUpdate && onUpdate()
|
||||
onClose()
|
||||
} else {
|
||||
alert('Error al inactivar la inspección')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error)
|
||||
alert('Error al inactivar la inspección')
|
||||
}
|
||||
setIsInactivating(false)
|
||||
}
|
||||
}}
|
||||
disabled={isInactivating}
|
||||
className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition disabled:opacity-50"
|
||||
>
|
||||
{isInactivating ? 'Inactivando...' : 'Inactivar'}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="flex-1 px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition"
|
||||
>
|
||||
Cerrar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function InspectionsTab({ inspections, user }) {
|
||||
function InspectionsTab({ inspections, user, onUpdate }) {
|
||||
const [selectedInspection, setSelectedInspection] = useState(null)
|
||||
|
||||
if (inspections.length === 0) {
|
||||
@@ -1494,7 +1539,9 @@ function InspectionsTab({ inspections, user }) {
|
||||
{selectedInspection && (
|
||||
<InspectionDetailModal
|
||||
inspection={selectedInspection}
|
||||
user={user}
|
||||
onClose={() => setSelectedInspection(null)}
|
||||
onUpdate={onUpdate}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
Reference in New Issue
Block a user