adding rest of database query functions

This commit is contained in:
Khalim Conn-Kowlessar 2024-10-02 14:39:04 +01:00
parent aadcc56d32
commit 6bc2ee0a6c

View file

@ -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