From 6bc2ee0a6cdfc2586b7c64672debe8067f69ab4e Mon Sep 17 00:00:00 2001 From: Khalim Conn-Kowlessar Date: Wed, 2 Oct 2024 14:39:04 +0100 Subject: [PATCH] adding rest of database query functions --- backend/Outputs.py | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/backend/Outputs.py b/backend/Outputs.py index a846965b..0be2ad3b 100644 --- a/backend/Outputs.py +++ b/backend/Outputs.py @@ -2,7 +2,7 @@ from sqlalchemy.orm import sessionmaker from backend.app.db.connection import db_engine from backend.app.db.models.portfolio import PropertyModel, PropertyDetailsEpcModel -from backend.app.db.models.recommendations import Recommendation, Plan, PlanRecommendations, Scenario +from backend.app.db.models.recommendations import Recommendation, Plan, PlanRecommendations class Outputs: @@ -28,7 +28,6 @@ class Outputs: def get_properties_from_db(self): # Get properties and their details for a specific portfolio - self.session.begin() properties_query = self.session.query( PropertyModel, PropertyDetailsEpcModel @@ -47,13 +46,10 @@ class Outputs: for prop in properties_query ] - self.session.close() return properties_data def get_plans_from_db(self): - self.session.begin() - plans_query = self.session.query(Plan).all() # Transform plans data to include all fields dynamically plans_data = [ @@ -61,9 +57,36 @@ class Outputs: for plan in plans_query ] - self.session.close() return plans_data + def get_recommendations_from_db(self, plan_ids): + # Get recommendations through PlanRecommendations for those plans and that are default + recommendations_query = self.session.query( + Recommendation, + Plan.scenario_id + ).join( + PlanRecommendations, Recommendation.id == PlanRecommendations.recommendation_id + ).join( + Plan, Plan.id == PlanRecommendations.plan_id # Join with Plan to access scenario_id + ).filter( + PlanRecommendations.plan_id.in_(plan_ids), + Recommendation.default == True # Filtering for default recommendations + ).all() + + # Transform recommendations data to include all fields dynamically and include scenario_id + recommendations_data = [ + { + **{ + col.name: getattr(rec.Recommendation, col.name) if + hasattr(rec, 'Recommendation') else getattr(rec, col.name) + for col in Recommendation.__table__.columns + }, + "Scenario ID": rec.scenario_id + } for rec in recommendations_query + ] + + return recommendations_data + def export_mds(self): """ This function will export the data in the MDS format @@ -88,12 +111,16 @@ class Outputs: - Kwh savings """ + self.session.begin() properties_data = self.get_properties_from_db() plans_data = self.get_plans_from_db() plan_ids = [plan['id'] for plan in plans_data] + recommendations_data = self.get_recommendations_from_db(plan_ids) + self.session.close() + def export(self): """ This function will export the data in the required format