generated from MITLibraries/python-cli-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Build framework for creating reports #121
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
869fc58
Build framework for creating reports
jonavellecuerdo dbc967a
Address comments in PR #121
jonavellecuerdo 84652e9
Address comments in PR #121
jonavellecuerdo 1234f7a
Address comments in PR #121
jonavellecuerdo 4b3f41b
Rename 'result_message' -> 'result_message_body'
jonavellecuerdo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| from dsc.reports.base import Report | ||
| from dsc.reports.finalize import FinalizeReport | ||
|
|
||
| __all__ = ["FinalizeReport", "Report"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import datetime | ||
| from abc import ABC, abstractmethod | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from jinja2 import Environment, FileSystemLoader, Template, select_autoescape | ||
|
|
||
| if TYPE_CHECKING: | ||
| import dsc.workflows as workflows # noqa: PLR0402 | ||
|
|
||
|
|
||
| class Report(ABC): | ||
| """A base report class from which other report classes are derived.""" | ||
|
|
||
| def __init__( | ||
| self, workflow_name: str, batch_id: str, events: workflows.WorkflowEvents | ||
| ): | ||
| self.workflow_name = workflow_name | ||
| self.batch_id = batch_id | ||
| self.report_date = datetime.datetime.now(tz=datetime.UTC).strftime( | ||
| "%Y-%m-%d %H:%M:%S" | ||
| ) | ||
| self.events = events | ||
|
|
||
| # configure environment for loading jinja templates | ||
| self.jinja_env = Environment( | ||
| loader=FileSystemLoader(["dsc/templates/html", "dsc/templates/plain_text"]), | ||
| autoescape=select_autoescape(), | ||
| ) | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def jinja_template_plain_text_filename(self) -> str: | ||
| """Plain-text template filename.""" | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def jinja_template_html_filename(self) -> str: | ||
| """HTML template filename.""" | ||
|
|
||
| @property | ||
| def jinja_template_plain_text(self) -> Template: | ||
| return self.jinja_env.get_template(self.jinja_template_plain_text_filename) | ||
|
|
||
| @property | ||
| def jinja_template_html(self) -> Template: | ||
| return self.jinja_env.get_template(self.jinja_template_html_filename) | ||
|
|
||
| @property | ||
| @abstractmethod | ||
| def subject(self) -> str: | ||
| """Subject heading used in report email.""" | ||
|
|
||
| @classmethod | ||
| def from_workflow(cls, workflow: workflows.Workflow) -> Report: | ||
| """Create instance of Report using dsc.workflows.Workflow.""" | ||
| return cls( | ||
| workflow_name=workflow.workflow_name, | ||
| batch_id=workflow.batch_id, | ||
| events=workflow.workflow_events, | ||
| ) | ||
|
|
||
| @abstractmethod | ||
| def create_attachments(self) -> list[tuple]: | ||
| """Create attachments to include in report email.""" | ||
|
|
||
| @abstractmethod | ||
| def to_plain_text(self) -> str: | ||
| """Render plain-text template.""" | ||
|
|
||
| @abstractmethod | ||
| def to_html(self) -> str: | ||
| """Render HTML template.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import csv | ||
| from io import StringIO | ||
|
|
||
| from dsc.reports.base import Report | ||
|
|
||
|
|
||
| class FinalizeReport(Report): | ||
| """Report class for 'finalize' methods. | ||
|
|
||
| This report is used to create an email summarizing the results | ||
| from running the 'finalize' methods, which processes the result | ||
| messages from DSpace Submission Service (DSS) sent to the output | ||
| queue for a given workflow. | ||
|
|
||
| The email created by this report is structured as follows: | ||
|
|
||
| 1. A message summarizing the number of successfully deposited items | ||
| and the number of encountered errors. | ||
|
|
||
| 2. A CSV file included as an attachment describing successfully deposited items, | ||
| which consists of the columns: 'item_identifier' and 'dspace_handle' (i.e., | ||
| the 'ItemHandle' from the DSS result message). Created only if | ||
| any items in Workflow.processed_items have ingested="success". | ||
|
|
||
| 3. A text file included as an attachment logging all errors encountered when | ||
| 'finalize' methods were executed. Created only if any WorkflowEvents.errors exist. | ||
| """ | ||
|
|
||
| @property | ||
| def jinja_template_plain_text_filename(self) -> str: | ||
| """Plain-text template filename.""" | ||
| return "finalize.txt" | ||
|
|
||
| @property | ||
| def jinja_template_html_filename(self) -> str: | ||
| """HTML template filename.""" | ||
| return "finalize.html" | ||
|
|
||
| @property | ||
| def subject(self) -> str: | ||
| return ( | ||
| f"DSpace Submission Results - {self.workflow_name}, batch='{self.batch_id}'" | ||
| ) | ||
|
|
||
| def create_attachments(self) -> list[tuple]: | ||
| """Create file attachments for 'finalize' email. | ||
|
|
||
| This method will create a CSV file of successfully deposited | ||
| items and optionally create a text file of error messages. | ||
| """ | ||
| attachments = [] | ||
|
|
||
| ingested_items = self.get_ingested_items() | ||
| if ingested_items: | ||
| attachments.append( | ||
| ( | ||
| "ingested_items.csv", | ||
| self._write_ingested_items_csv(ingested_items), | ||
| ) | ||
| ) | ||
|
|
||
| if self.events.errors: | ||
| attachments.append( | ||
| ( | ||
| "errors.txt", | ||
| self._write_errors_text_file(), | ||
| ) | ||
| ) | ||
| return attachments | ||
|
|
||
| def get_ingested_items(self) -> list[dict]: | ||
jonavellecuerdo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return [ | ||
| { | ||
| "item_identifier": item["item_identifier"], | ||
| "dspace_handle": item["result_message_body"]["ItemHandle"], | ||
| } | ||
| for item in self.events.processed_items | ||
| if item["ingested"] == "success" | ||
| ] | ||
|
|
||
| def _write_ingested_items_csv(self, ingested_items: list[dict]) -> StringIO: | ||
| """Write ingested items to string buffer. | ||
|
|
||
| This method creates a string buffer with the contents of a CSV | ||
| file describing successfully ingested items. | ||
jonavellecuerdo marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| """ | ||
| csv_buffer = StringIO() | ||
| fieldnames = ingested_items[0].keys() | ||
| writer = csv.DictWriter(csv_buffer, fieldnames=fieldnames) | ||
| writer.writeheader() | ||
| writer.writerows(ingested_items) | ||
| csv_buffer.seek(0) | ||
| return csv_buffer | ||
|
|
||
| def _write_errors_text_file(self) -> StringIO: | ||
| """Write error messages to string buffer. | ||
|
|
||
| This method creates a string buffer with the error messages | ||
| encountered when 'finalize' methods were executed. | ||
| """ | ||
| text_buffer = StringIO() | ||
| for error in self.events.errors: | ||
| text_buffer.write(error + "\n") | ||
| text_buffer.seek(0) | ||
| return text_buffer | ||
|
|
||
| def to_plain_text(self) -> str: | ||
| return self.jinja_template_plain_text.render( | ||
| workflow_name=self.workflow_name, | ||
| batch_id=self.batch_id, | ||
| report_date=self.report_date, | ||
| processed_items=self.events.processed_items, | ||
| errors=self.events.errors, | ||
| ) | ||
|
|
||
| def to_html(self) -> str: | ||
| return self.jinja_template_html.render( | ||
| workflow_name=self.workflow_name, | ||
| batch_id=self.batch_id, | ||
| report_date=self.report_date, | ||
| processed_items=self.events.processed_items, | ||
| errors=self.events.errors, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| <!DOCTYPE html> | ||
| <html lang="en-US"> | ||
| <head> | ||
| <title></title> | ||
| </head> | ||
| <body> | ||
| <p>Hello,</p> | ||
|
|
||
| <div id="content">{% block content %}{% endblock %}</div> | ||
| </body> | ||
|
|
||
| </html> | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| {% extends "base.html" %} | ||
|
|
||
| {% block content %} | ||
|
|
||
| <p><b>Results summary for {{workflow_name}} deposit for batch='{{batch_id}}'</b></p> | ||
| <p>Run date: {{report_date}}</p> | ||
| <p>Results:</p> | ||
|
|
||
| <p>Ingested: {{ processed_items|length }}</p> | ||
| <p>Errors: {{ errors|length }}</p> | ||
|
|
||
| {% endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| Hello, | ||
| {% block content %}{% endblock %} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| {% extends "base.txt" %} | ||
|
|
||
| Results summary for {{workflow_name}} deposit for batch='{{batch_id}}' | ||
| Run date: {{report_date}} | ||
| Results: | ||
|
|
||
| Ingested: {{ processed_items|length }} | ||
| Errors: {{ errors|length }} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.