34 lines
1.4 KiB
Python
34 lines
1.4 KiB
Python
from datetime import datetime, UTC
|
||
|
||
from flask import jsonify
|
||
|
||
from models import UserEvents
|
||
|
||
|
||
class EventManager:
|
||
def __init__(self, db):
|
||
self.db = db
|
||
|
||
def get_user_events(self, chat_id):
|
||
"""Режим GET: возвращает список действий пользователя."""
|
||
events = UserEvents.query.filter_by(chat_id=chat_id).order_by(UserEvents.timestamp.desc()).all()
|
||
return [{'action': event.action, 'timestamp': event.timestamp.isoformat()} for event in events]
|
||
|
||
def log_user_action(self, chat_id, action):
|
||
"""Режим WRITE: сохраняет действие пользователя."""
|
||
event = UserEvents(chat_id=chat_id, action=action, timestamp=datetime.now(UTC))
|
||
self.db.session.add(event)
|
||
self.db.session.commit()
|
||
|
||
def handle_request(self, chat_id, request_type, action=None):
|
||
"""Обрабатывает запросы в режимах GET и WRITE."""
|
||
if request_type == 'GET':
|
||
return jsonify({'events': self.get_user_events(chat_id)})
|
||
elif request_type == 'WRITE':
|
||
if action:
|
||
self.log_user_action(chat_id, action)
|
||
return jsonify({'message': 'Действие сохранено'}), 200
|
||
else:
|
||
return jsonify({'error': 'Не указано действие'}), 400
|
||
else:
|
||
return jsonify({'error': 'Неверный тип запроса'}), 400 |