import datetime from flask import Blueprint, jsonify from flask_jwt_extended import jwt_required, get_jwt_identity from .database import db, MilkBatch, User from sqlalchemy import func # For sum overview_bp = Blueprint('overview', __name__, url_prefix='/api/overview') @overview_bp.route('', methods=['GET']) @jwt_required() def get_overview(): current_user_id = get_jwt_identity() user = User.query.get(current_user_id) if not user: return jsonify({"error": "User not found"}), 404 # Find active (not deleted, not empty, not expired) batches active_batches = MilkBatch.query.filter( MilkBatch.user_id == current_user_id, MilkBatch.is_deleted == False, MilkBatch.remaining_volume > 0.001, MilkBatch.expiry_date >= datetime.date.today() ).order_by(MilkBatch.expiry_date.asc()).all() total_volume_ml = 0 total_items_approx = 0 nearest_expiry_info = None for batch in active_batches: # Sum total volume in ml if batch.volume_unit == 'L': total_volume_ml += batch.remaining_volume * 1000 else: # Assumed ml total_volume_ml += batch.remaining_volume total_items_approx += batch.remaining_items_approx # Capture the first one (soonest expiry) if not nearest_expiry_info: nearest_expiry_info = batch.to_dict() total_quantity_liters = total_volume_ml / 1000.0 # Basic low stock check (can be enhanced in push notification logic) is_low_stock = False if user.low_stock_threshold_value is not None and user.low_stock_threshold_unit: threshold_value = user.low_stock_threshold_value threshold_unit = user.low_stock_threshold_unit try: if threshold_unit == 'items': if total_items_approx <= threshold_value: is_low_stock = True else: # ml or L # Convert threshold to ml if needed threshold_ml = convert_volume(threshold_value, threshold_unit, 'ml') if total_volume_ml <= threshold_ml: is_low_stock = True except ValueError: print(f"Warning: Invalid low stock threshold units for user {current_user_id}") overview_data = { "totalQuantityLiters": round(total_quantity_liters, 2), "totalQuantityItemsApprox": round(total_items_approx), "nearestExpiry": nearest_expiry_info, # Full batch dict or null "isLowStock": is_low_stock, # Simple flag based on settings # "estimatedFinishDate": "N/A" # Requires historical analysis - skip for now } return jsonify(overview_data), 200