51 lines
2.2 KiB
Python
51 lines
2.2 KiB
Python
from flask import Blueprint, request, jsonify
|
|
from flask_jwt_extended import jwt_required, get_jwt_identity
|
|
from .database import db, User
|
|
|
|
profile_bp = Blueprint('profile', __name__, url_prefix='/api/user/profile')
|
|
|
|
@profile_bp.route('', methods=['GET'])
|
|
@jwt_required()
|
|
def get_user_profile():
|
|
current_user_id = get_jwt_identity()
|
|
user = User.query.get(current_user_id)
|
|
if not user: return jsonify({"error": "User not found"}), 404
|
|
return jsonify(user.to_dict()), 200
|
|
|
|
@profile_bp.route('', methods=['PUT'])
|
|
@jwt_required()
|
|
def update_user_profile():
|
|
current_user_id = get_jwt_identity()
|
|
user = User.query.get(current_user_id)
|
|
if not user: return jsonify({"error": "User not found"}), 404
|
|
|
|
data = request.get_json()
|
|
if not data: return jsonify({"error": "Request must be JSON"}), 400
|
|
|
|
try:
|
|
# Update settings if provided in the request body
|
|
if 'expiryWarningDays' in data:
|
|
user.expiry_warning_days = int(data['expiryWarningDays'])
|
|
if 'lowStockThresholdValue' in data: # Allow setting to null/None
|
|
user.low_stock_threshold_value = float(data['lowStockThresholdValue']) if data['lowStockThresholdValue'] is not None else None
|
|
if 'lowStockThresholdUnit' in data:
|
|
unit = data['lowStockThresholdUnit']
|
|
if unit in ['ml', 'L', 'items', None]: # Allow None
|
|
user.low_stock_threshold_unit = unit
|
|
else: raise ValueError("Invalid lowStockThresholdUnit")
|
|
|
|
if 'notificationsEnabled' in data:
|
|
notif_settings = data['notificationsEnabled']
|
|
user.notify_expiry_warning = bool(notif_settings.get('expiry', user.notify_expiry_warning))
|
|
user.notify_expired_alert = bool(notif_settings.get('expired', user.notify_expired_alert))
|
|
user.notify_low_stock = bool(notif_settings.get('lowStock', user.notify_low_stock))
|
|
|
|
db.session.commit()
|
|
return jsonify(user.to_dict()), 200
|
|
except (ValueError, TypeError) as e:
|
|
db.session.rollback()
|
|
return jsonify({"error": f"Invalid data format: {e}"}), 400
|
|
except Exception as e:
|
|
db.session.rollback()
|
|
print(f"Error updating profile: {e}")
|
|
return jsonify({"error": "Database error occurred."}), 500 |