Frontend v1.0.68:
- Agregada funcionalidad de edición de checklists
- Nuevo modal para editar nombre, descripción, modo IA y scoring
- Botón "✏️ Editar" en cada checklist (solo admins)
- Mejora en la gestión de checklists en el panel de administración
Backend v1.0.68:
- Actualización de versión para sincronizar con frontend
- Endpoint PUT /api/checklists/{id} ya soportaba la funcionalidad
This commit is contained in:
132
.github/copilot-instructions.md
vendored
Normal file
132
.github/copilot-instructions.md
vendored
Normal file
@@ -0,0 +1,132 @@
|
||||
# No olvides dar lo comentarios de los cambios que se hicieron para el backend y el front en para los comentarios de git
|
||||
# Siempre actuliza la version del front y del back la version del front esta en el archivo package.json y la del backend en el archivo main.py en una variable llamada BACKEND_VERSION
|
||||
|
||||
# Ayudetec - Intelligent Checklist System for Automotive Workshops
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
**Tech Stack**: FastAPI (Python 3.11) + React 18 + PostgreSQL 15 + MinIO/S3
|
||||
**Deployment**: Docker Compose for dev, Docker Stack for production
|
||||
**Key Feature**: AI-powered inspection analysis with OpenAI/Gemini integration
|
||||
|
||||
### Service Structure
|
||||
- `backend/` - FastAPI monolith with JWT auth, S3 file storage, PDF generation
|
||||
- `frontend/` - React SPA with Vite, TailwindCSS, client-side routing
|
||||
- `postgres` - Main data store with checklist templates, inspections, answers
|
||||
- MinIO/S3 - Image and PDF storage (configurable endpoint)
|
||||
|
||||
### Core Data Model
|
||||
**Users** (`role`: admin/mechanic/asesor) → **Checklists** (templates with questions) → **Inspections** (mechanic executions) → **Answers** (responses with photos/scores)
|
||||
|
||||
- **Permissions**: `ChecklistPermission` table controls mechanic access (empty = global access)
|
||||
- **Nested Questions**: 5-level deep conditional subquestions via `parent_question_id` + `show_if_answer`
|
||||
- **Scoring**: Auto-calculated from answer points, stored in `Inspection.score/percentage`
|
||||
- **Question Types**: boolean, single_choice, multiple_choice, scale, text, number, date, time (config in `Question.options` JSON)
|
||||
|
||||
## Development Workflows
|
||||
|
||||
### Running Locally
|
||||
```powershell
|
||||
docker-compose up -d # Start all services
|
||||
docker-compose logs backend # Debug backend issues
|
||||
```
|
||||
**URLs**: Frontend `http://localhost:5173`, Backend API `http://localhost:8000/docs`
|
||||
|
||||
### Database Initialization
|
||||
Use `init_users.py` to create default admin/mechanic users:
|
||||
```powershell
|
||||
docker-compose exec backend python init_users.py
|
||||
```
|
||||
**Default credentials**: `admin/admin123`, `mecanico/mec123`
|
||||
|
||||
### Migrations
|
||||
Manual SQL scripts in `migrations/` - run via:
|
||||
```powershell
|
||||
docker-compose exec backend python -c "
|
||||
from app.core.database import engine
|
||||
with open('migrations/your_migration.sql') as f:
|
||||
engine.execute(f.read())
|
||||
"
|
||||
```
|
||||
|
||||
### Building for Production
|
||||
```powershell
|
||||
.\build-and-push.ps1 # Builds images, pushes to Docker Hub (configured in script)
|
||||
```
|
||||
Then deploy with `docker-compose.prod.yml` or `docker-stack.yml` (Swarm mode)
|
||||
|
||||
## Project-Specific Conventions
|
||||
|
||||
### API Architecture (`backend/app/main.py`)
|
||||
- **Single 2800+ line file** - all endpoints in main.py (no routers/controllers split)
|
||||
- Auth via `get_current_user()` dependency returning `models.User`
|
||||
- File uploads use boto3 S3 client configured from `app/core/config.py` (MinIO compatible)
|
||||
- PDF generation inline with ReportLab (starts ~line 1208, function `generate_pdf`)
|
||||
|
||||
### AI Integration Modes (see `AI_FUNCTIONALITY.md`)
|
||||
- `ai_mode` on Checklist: `"off"` (manual) | `"assisted"` (suggestions) | `"copilot"` (auto-complete)
|
||||
- AI analysis triggered on photo upload, stored in `Answer.ai_analysis` JSON
|
||||
- Webhook notifications to n8n on completion: `send_completed_inspection_to_n8n()`
|
||||
|
||||
### Frontend Patterns (`frontend/src/App.jsx`)
|
||||
- **5400+ line single-file component** - all views in App.jsx (Login, Dashboard, Admin panels)
|
||||
- Auth state in `localStorage` (token + user object)
|
||||
- API calls use `fetch()` with `import.meta.env.VITE_API_URL` base
|
||||
- Signature capture via `react-signature-canvas` (saved as base64)
|
||||
|
||||
### Permission Model
|
||||
When fetching checklists:
|
||||
- Admins see all checklists
|
||||
- Mechanics only see checklists with either:
|
||||
- No `ChecklistPermission` records (global access), OR
|
||||
- A permission record linking that mechanic
|
||||
- Implement via JOIN in `GET /api/checklists` endpoint
|
||||
|
||||
### Environment Variables
|
||||
Critical settings in `.env`:
|
||||
- `DATABASE_URL` - Postgres connection string
|
||||
- `SECRET_KEY` - JWT signing (min 32 chars)
|
||||
- `OPENAI_API_KEY` / `GEMINI_API_KEY` - Optional for AI features
|
||||
- `MINIO_*` vars - S3-compatible storage (MinIO/AWS S3)
|
||||
- `NOTIFICACION_ENDPOINT` - n8n webhook for inspection events
|
||||
- `ALLOWED_ORIGINS` - Comma-separated CORS origins
|
||||
|
||||
## Key Integration Points
|
||||
|
||||
### S3/MinIO Storage
|
||||
- Configured globally in `main.py` via `boto3.client()` + `Config(signature_version='s3v4')`
|
||||
- Two buckets: `MINIO_IMAGE_BUCKET` (photos), `MINIO_PDF_BUCKET` (reports)
|
||||
- Upload pattern: generate UUID filename, `s3_client.upload_fileobj()`, store URL in DB
|
||||
|
||||
### PDF Generation
|
||||
- ReportLab library generates inspection reports with photos, signatures, scoring
|
||||
- Triggered on inspection completion, stored to S3, URL saved in `Inspection.pdf_url`
|
||||
- Uses checklist logo from `Checklist.logo_url` if available
|
||||
|
||||
### Webhook Notifications
|
||||
When `Question.send_notification = true`, answering triggers `send_answer_notification()` to `NOTIFICACION_ENDPOINT`
|
||||
On inspection completion, sends full data via `send_completed_inspection_to_n8n()`
|
||||
|
||||
## Common Gotchas
|
||||
|
||||
- **No Alembic auto-migrations** - use manual SQL scripts in `migrations/`
|
||||
- **Token expiry is 7 days** - set in `config.ACCESS_TOKEN_EXPIRE_MINUTES = 10080`
|
||||
- **Photos stored as S3 URLs** - not base64 in DB (except signatures)
|
||||
- **Nested questions limited to 5 levels** - enforced in `Question.depth_level`
|
||||
- **PowerShell scripts** - Windows-first project (see `.ps1` build scripts)
|
||||
- **Frontend has no state management** - uses React `useState` only, no Redux/Context
|
||||
|
||||
## Checklist Management
|
||||
|
||||
### Editing Checklists
|
||||
- Admins can edit checklist name, description, AI mode, and scoring settings via "✏️ Editar" button
|
||||
- Edit modal (`showEditChecklistModal`) uses PUT `/api/checklists/{id}` endpoint
|
||||
- Backend endpoint supports partial updates via `exclude_unset=True` in Pydantic model
|
||||
- Logo and permissions have separate management modals for focused UI
|
||||
|
||||
## Example Tasks
|
||||
|
||||
**Add new question type**: Update `Question.type` validation, modify `QuestionTypeEditor.jsx` UI, handle in `QuestionAnswerInput.jsx`
|
||||
**Change scoring logic**: Edit `backend/app/main.py` answer submission endpoint, recalculate `Inspection.score`
|
||||
**Add new user role**: Update `User.role` enum, modify `get_current_user()` checks, adjust frontend role conditionals in `App.jsx`
|
||||
**Edit checklist properties**: Use existing PUT endpoint, add fields to `editChecklistData` state, update modal form
|
||||
@@ -204,7 +204,7 @@ def send_completed_inspection_to_n8n(inspection, db):
|
||||
# No lanzamos excepción para no interrumpir el flujo normal
|
||||
|
||||
|
||||
BACKEND_VERSION = "1.0.67"
|
||||
BACKEND_VERSION = "1.0.68"
|
||||
app = FastAPI(title="Checklist Inteligente API", version=BACKEND_VERSION)
|
||||
|
||||
# S3/MinIO configuration
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "checklist-frontend",
|
||||
"private": true,
|
||||
"version": "1.0.67",
|
||||
"version": "1.0.68",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1735,6 +1735,7 @@ function ChecklistsTab({ checklists, user, onChecklistCreated, onStartInspection
|
||||
const [showCreateModal, setShowCreateModal] = useState(false)
|
||||
const [showQuestionsModal, setShowQuestionsModal] = useState(false)
|
||||
const [showEditPermissionsModal, setShowEditPermissionsModal] = useState(false)
|
||||
const [showEditChecklistModal, setShowEditChecklistModal] = useState(false)
|
||||
const [showLogoModal, setShowLogoModal] = useState(false)
|
||||
const [selectedChecklist, setSelectedChecklist] = useState(null)
|
||||
const [creating, setCreating] = useState(false)
|
||||
@@ -1752,6 +1753,12 @@ function ChecklistsTab({ checklists, user, onChecklistCreated, onStartInspection
|
||||
scoring_enabled: true,
|
||||
mechanic_ids: []
|
||||
})
|
||||
const [editChecklistData, setEditChecklistData] = useState({
|
||||
name: '',
|
||||
description: '',
|
||||
ai_mode: 'off',
|
||||
scoring_enabled: true
|
||||
})
|
||||
const [editPermissionsData, setEditPermissionsData] = useState({
|
||||
mechanic_ids: []
|
||||
})
|
||||
@@ -1875,6 +1882,39 @@ function ChecklistsTab({ checklists, user, onChecklistCreated, onStartInspection
|
||||
}
|
||||
}
|
||||
|
||||
const handleEditChecklist = async (e) => {
|
||||
e.preventDefault()
|
||||
setUpdating(true)
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('token')
|
||||
const API_URL = import.meta.env.VITE_API_URL || ''
|
||||
|
||||
const response = await fetch(`${API_URL}/api/checklists/${selectedChecklist.id}`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(editChecklistData),
|
||||
})
|
||||
|
||||
if (response.ok) {
|
||||
setShowEditChecklistModal(false)
|
||||
setSelectedChecklist(null)
|
||||
setEditChecklistData({ name: '', description: '', ai_mode: 'off', scoring_enabled: true })
|
||||
onChecklistCreated() // Reload checklists
|
||||
} else {
|
||||
alert('Error al actualizar checklist')
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error)
|
||||
alert('Error al actualizar checklist')
|
||||
} finally {
|
||||
setUpdating(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleUploadLogo = async (e) => {
|
||||
const file = e.target.files[0]
|
||||
if (!file) return
|
||||
@@ -2078,9 +2118,25 @@ function ChecklistsTab({ checklists, user, onChecklistCreated, onStartInspection
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{user.role === 'admin' && (
|
||||
<>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedChecklist(checklist)
|
||||
setEditChecklistData({
|
||||
name: checklist.name,
|
||||
description: checklist.description || '',
|
||||
ai_mode: checklist.ai_mode || 'off',
|
||||
scoring_enabled: checklist.scoring_enabled ?? true
|
||||
})
|
||||
setShowEditChecklistModal(true)
|
||||
}}
|
||||
className="px-3 py-2 bg-gradient-to-r from-indigo-500 to-purple-500 text-white rounded-lg hover:from-indigo-600 hover:to-purple-600 transition-all transform hover:scale-105 shadow-lg text-sm"
|
||||
title="Editar checklist"
|
||||
>
|
||||
✏️ Editar
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSelectedChecklist(checklist)
|
||||
@@ -2381,6 +2437,106 @@ function ChecklistsTab({ checklists, user, onChecklistCreated, onStartInspection
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Modal Editar Checklist */}
|
||||
{showEditChecklistModal && selectedChecklist && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
||||
<div className="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
|
||||
<div className="p-6">
|
||||
<h2 className="text-2xl font-bold text-gray-900 mb-4">✏️ Editar Checklist</h2>
|
||||
|
||||
<form onSubmit={handleEditChecklist} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Nombre del Checklist *
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={editChecklistData.name}
|
||||
onChange={(e) => setEditChecklistData({ ...editChecklistData, name: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
|
||||
placeholder="Ej: Inspección Pre-entrega"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Descripción
|
||||
</label>
|
||||
<textarea
|
||||
value={editChecklistData.description}
|
||||
onChange={(e) => setEditChecklistData({ ...editChecklistData, description: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
|
||||
rows="3"
|
||||
placeholder="Descripción del checklist..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">
|
||||
Modo IA
|
||||
</label>
|
||||
<select
|
||||
value={editChecklistData.ai_mode}
|
||||
onChange={(e) => setEditChecklistData({ ...editChecklistData, ai_mode: e.target.value })}
|
||||
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
|
||||
>
|
||||
<option value="off">❌ Desactivado (Manual)</option>
|
||||
<option value="assisted">💡 Asistido (Sugerencias)</option>
|
||||
<option value="copilot">🤖 Copiloto (Auto-completar)</option>
|
||||
</select>
|
||||
<p className="mt-1 text-xs text-gray-500">
|
||||
{editChecklistData.ai_mode === 'off' && '❌ El mecánico completa todo manualmente'}
|
||||
{editChecklistData.ai_mode === 'assisted' && '💡 IA sugiere respuestas, el mecánico confirma'}
|
||||
{editChecklistData.ai_mode === 'copilot' && '🤖 IA completa automáticamente, el mecánico revisa'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={editChecklistData.scoring_enabled}
|
||||
onChange={(e) => setEditChecklistData({ ...editChecklistData, scoring_enabled: e.target.checked })}
|
||||
className="w-4 h-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500"
|
||||
/>
|
||||
<label className="ml-2 text-sm text-gray-700">
|
||||
Habilitar sistema de puntuación
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
|
||||
<p className="text-sm text-blue-800">
|
||||
ℹ️ Los cambios se aplicarán inmediatamente. Las inspecciones existentes no se verán afectadas.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-3 pt-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setShowEditChecklistModal(false)
|
||||
setSelectedChecklist(null)
|
||||
setEditChecklistData({ name: '', description: '', ai_mode: 'off', scoring_enabled: true })
|
||||
}}
|
||||
className="flex-1 px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition"
|
||||
disabled={updating}
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="flex-1 px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition disabled:opacity-50"
|
||||
disabled={updating}
|
||||
>
|
||||
{updating ? 'Guardando...' : 'Guardar Cambios'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Modal Editar Permisos */}
|
||||
{showEditPermissionsModal && selectedChecklist && (
|
||||
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
|
||||
|
||||
@@ -14,7 +14,7 @@ notepad++.exe $tempFile | Out-Null
|
||||
|
||||
# Verificar que el archivo tenga contenido
|
||||
if (-not (Test-Path $tempFile) -or (Get-Item $tempFile).Length -eq 0) {
|
||||
Write-Host "No se ingresó ningún mensaje. Abortando..." -ForegroundColor Red
|
||||
Write-Host "No se ingreso ningun mensaje. Abortando..." -ForegroundColor Red
|
||||
Remove-Item $tempFile -ErrorAction SilentlyContinue
|
||||
exit
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user