Files
checklist/.github/copilot-instructions.md
gitea 0117ba34f8 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
2025-11-27 11:19:48 -03:00

133 lines
6.2 KiB
Markdown

# 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