Files
encoach_be_odoo19/encoach_api/controllers/training.py
Talal Sharabi bf3981028b Fix model-controller mismatches and routing issues
- ticket: add user_id, priority, category fields; fix _serialize_ticket -> _serialize
- package: fix is_active -> active (Odoo auto-filter), remove invalid entity_id filter
- walkthrough: add sequence field; fix controller to use name/content instead of title/steps
- users: fix encoach_user_type -> encoach_type, encoach_entity_id -> entity_rel_ids.entity_id
- generation: use EncoachGenerationService class instead of nonexistent ORM model,
  fix /api/exam/level/ route conflict (separate GET and POST URLs)

Made-with: Cursor
2026-03-15 01:08:36 +04:00

118 lines
4.7 KiB
Python

import json
import logging
from odoo import http
from odoo.http import request
from .base import EncoachMixin
_logger = logging.getLogger(__name__)
class TrainingController(EncoachMixin, http.Controller):
# ----------------------------------------------------------- generate
@http.route('/api/training', type='http', auth='public', methods=['POST', 'OPTIONS'], csrf=False, cors='*')
def generate_training(self, **kwargs):
"""Generate personalised training content using FAISS + GPT."""
try:
user = self._authenticate()
if not user:
return self._error_response('Unauthorized', 401)
body = self._get_json_body()
target_user_id = body.get('userID', user.id)
stats = body.get('stats', [])
Training = request.env['encoach.training'].sudo()
training = Training.generate_training(
user_id=int(target_user_id),
stats=stats,
)
return self._json_response({
'id': training.id,
'_id': str(training.id),
})
except Exception:
_logger.exception("Generate training error")
return self._error_response('Internal server error', 500)
# -------------------------------------------------------- get record
@http.route(
'/api/training/<int:tid>', type='http', auth='public',
methods=['GET', 'OPTIONS'], csrf=False, cors='*',
)
def get_training(self, tid, **kwargs):
try:
user = self._authenticate()
if not user:
return self._error_response('Unauthorized', 401)
training = request.env['encoach.training'].sudo().browse(tid)
if not training.exists():
return self._error_response('Training record not found', 404)
return self._json_response({
'_id': str(training.id),
'id': training.id,
'userId': str(training.user_id.id) if training.user_id else None,
'createdAt': training.created_at.isoformat() if getattr(training, 'created_at', None) else (
training.create_date.isoformat() if training.create_date else None
),
'exams': json.loads(training.exams) if getattr(training, 'exams', None) else [],
'tips': json.loads(training.tips) if getattr(training, 'tips', None) else {},
'weakAreas': json.loads(training.weak_areas) if getattr(training, 'weak_areas', None) else [],
})
except Exception:
_logger.exception("Get training error")
return self._error_response('Internal server error', 500)
# ------------------------------------------------------------- tips
@http.route('/api/training/tips', type='http', auth='public', methods=['POST', 'OPTIONS'], csrf=False, cors='*')
def fetch_tips(self, **kwargs):
"""Retrieve contextual tips using FAISS semantic search + GPT."""
try:
user = self._authenticate()
if not user:
return self._error_response('Unauthorized', 401)
body = self._get_json_body()
Training = request.env['encoach.training'].sudo()
tips = Training.fetch_tips(
context=body.get('context', ''),
question=body.get('question', ''),
answer=body.get('answer', ''),
correct_answer=body.get('correct_answer', ''),
)
return self._json_response({'tips': tips})
except Exception:
_logger.exception("Fetch tips error")
return self._error_response('Internal server error', 500)
# ------------------------------------------------------ walkthrough
@http.route('/api/training/walkthrough', type='http', auth='public', methods=['GET', 'OPTIONS'], csrf=False, cors='*')
def get_walkthrough(self, **kwargs):
try:
user = self._authenticate()
if not user:
return self._error_response('Unauthorized', 401)
Walkthrough = request.env['encoach.walkthrough'].sudo()
records = Walkthrough.search([], order='sequence asc')
data = [{
'_id': str(w.id),
'id': w.id,
'title': w.name or '',
'description': '',
'steps': w.content if isinstance(w.content, list) else (json.loads(w.content) if isinstance(w.content, str) else []),
'module': w.module or '',
} for w in records]
return self._json_response(data)
except Exception:
_logger.exception("Get walkthrough error")
return self._error_response('Internal server error', 500)