Skip to content

Commit

Permalink
175: Add Work Description to Anticipated EA Schedule. (#2422)
Browse files Browse the repository at this point in the history
Refactors some code for re-use. Exception error handling being more
detailed than generic. Updated report template. Added some useful code
comments.
  • Loading branch information
marklise authored Nov 6, 2024
1 parent 3a24b55 commit 7131708
Show file tree
Hide file tree
Showing 6 changed files with 39 additions and 15 deletions.
2 changes: 1 addition & 1 deletion epictrack-api/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ notes=FIXME,XXX,TODO
ignored-modules=flask_sqlalchemy,sqlalchemy,SQLAlchemy,alembic,scoped_session
ignored-classes=scoped_session
min-similarity-lines=15
disable=C0301,W0511
disable=C0301,W0511, R0917, C0411, R1710, E1101, W4904
good-names=f,id,k,v

[isort]
Expand Down
30 changes: 20 additions & 10 deletions epictrack-api/src/api/reports/anticipated_schedule_report.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Classes for specific report types."""
from datetime import datetime, timedelta

from flask import jsonify
from flask import jsonify, current_app
from pytz import timezone
from sqlalchemy import and_, func, select
from sqlalchemy.dialects.postgresql import INTERVAL
Expand All @@ -28,7 +28,7 @@

from .cdog_client import CDOGClient
from .report_factory import ReportFactory

from api.utils.util import process_data

# pylint:disable=not-callable

Expand All @@ -48,6 +48,7 @@ def __init__(self, filters, color_intensity):
"ea_act",
"substitution_act",
"project_description",
"report_description",
"anticipated_decision_date",
"additional_info",
"ministry_name",
Expand All @@ -66,6 +67,7 @@ def __init__(self, filters, color_intensity):

def _fetch_data(self, report_date):
"""Fetches the relevant data for EA Anticipated Schedule Report"""
current_app.logger.info(f"Fetching data for {self.report_title} report")
start_date = report_date + timedelta(days=-7)
report_date = report_date.astimezone(timezone('US/Pacific'))
eac_decision_by = aliased(Staff)
Expand Down Expand Up @@ -140,6 +142,7 @@ def _fetch_data(self, report_date):
EAAct.name.label("ea_act"),
SubstitutionAct.name.label("substitution_act"),
Project.description.label("project_description"),
Work.report_description.label("report_description"),
(
Event.anticipated_date + func.cast(func.concat(Event.number_of_days, " DAYS"), INTERVAL)
).label("anticipated_decision_date"),
Expand All @@ -166,23 +169,30 @@ def _fetch_data(self, report_date):

def generate_report(self, report_date, return_type):
"""Generates a report and returns it"""
current_app.logger.info(f"Generating {self.report_title} report for {report_date}")
data = self._fetch_data(report_date)
data = self._format_data(data)
data = self._update_staleness(data, report_date)
if return_type == "json" and data:
return {"data": data}, None
if not data:
return {}, None

if return_type == "json" or not data:
return process_data(data, return_type)

api_payload = {
"report_data": data,
"report_title": self.report_title,
"report_date": report_date,
}
template = self.generate_template()
report_client = CDOGClient()
report = report_client.generate_document(
self.report_title, jsonify(api_payload).json, template
)
# Calls out to the common services document generation service. Make sure your envs are set properly.
try:
report_client = CDOGClient()
report = report_client.generate_document(self.report_title, jsonify(api_payload).json, template)
except EnvironmentError as e:
# Fall through to return empty response if CDOGClient fails, but log the error
current_app.logger.error(f"Error initializing CDOGClient: {e}.")
return {}, None

current_app.logger.info(f"Generated {self.report_title} report for {report_date}")
return report, f"{self.report_title}_{report_date:%Y_%m_%d}.pdf"

def _get_next_pcp_query(self, start_date):
Expand Down
7 changes: 7 additions & 0 deletions epictrack-api/src/api/reports/cdog_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ class CDOGClient: # pylint: disable=too-few-public-methods

def __init__(self) -> None:
"""Constructor"""
if not all([
os.environ.get('CDOGS_API_ENDPOINT'),
os.environ.get('CDOGS_TOKEN_END_POINT'),
os.environ.get('CDOGS_CLIENT_ID'),
os.environ.get('CDOGS_CLIENT_SECRET')
]):
raise EnvironmentError("CDOGS environment variables are not set properly.")
self.api_url = os.environ.get('CDOGS_API_ENDPOINT')

def _authorize(self):
Expand Down
Binary file not shown.
7 changes: 3 additions & 4 deletions epictrack-api/src/api/reports/thirty_sixty_ninety_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from api.schemas import response as res
from api.utils.constants import CANADA_TIMEZONE
from api.utils.enums import StalenessEnum
from api.utils.util import process_data

from .report_factory import ReportFactory

Expand Down Expand Up @@ -245,10 +246,8 @@ def generate_report(
data = self._fetch_data(report_date)
data = self._format_data(data)
data = self._update_staleness(data, report_date)
if return_type == "json" and data:
return {"data": data}, None
if not data:
return {}, None
if return_type == "json" or not data:
return process_data(data, return_type)
pdf_stream = BytesIO()
stylesheet = getSampleStyleSheet()
doc = BaseDocTemplate(pdf_stream, pagesize=A4)
Expand Down
8 changes: 8 additions & 0 deletions epictrack-api/src/api/utils/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,3 +53,11 @@ def generate_title(project_name, work_type_name, simple_title=''):
if simple_title:
parts.append(simple_title)
return ' - '.join(parts)


def process_data(data, return_type):
"""Process data based on the return type."""
if return_type == "json" and data:
return {"data": data}, None
if not data:
return {}, None

0 comments on commit 7131708

Please sign in to comment.