Skip to content

Commit

Permalink
Merge pull request #142 from PnX-SI/workshop_notifications
Browse files Browse the repository at this point in the history
Feat: add GeoNature Notifications instead of emails
  • Loading branch information
TheoLechemia authored May 11, 2023
2 parents 63f4dbc + 306e003 commit 40efba3
Show file tree
Hide file tree
Showing 10 changed files with 314 additions and 257 deletions.
20 changes: 12 additions & 8 deletions backend/gn_module_export/blueprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
flash,
copy_current_request_context,
g,
url_for,
)
from flask_cors import cross_origin
from flask_admin.contrib.sqla import ModelView
Expand Down Expand Up @@ -396,18 +397,21 @@ def getOneExportThread(id_export, export_format):
if not export.has_instance_permission(user.id_role):
raise Forbidden

# Test email
# Alternative email in payload
email_to = None
if "email" in data:
email_to = data["email"]
# Test if user have an email
if not user.email and not email_to: # TODO add more test
raise BadRequest("User doesn't have email")
module_conf = current_app.config["EXPORTS"]
if module_conf.get("export_web_url"):
export_url = "{}/{}".format(module_conf.get("export_web_url"))
else:
export_url = url_for(
"media",
filename=module_conf.get("usr_generated_dirname"),
_external=True,
)

generate_export.delay(
export_id=id_export,
export_format=export_format,
filename=export_url,
user=user.id_role,
scheduled=False,
skip_newer_than=None,
)
Expand Down
2 changes: 2 additions & 0 deletions backend/gn_module_export/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ def generate(export_id, export_format, scheduled, skip_newer_than):
generate_export(
export_id,
export_format,
filename="",
user=None,
scheduled=scheduled,
skip_newer_than=skip_newer_than,
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Create export notifications
Revision ID: 4cac712a2ce6
Revises: c2d02e345a06
Create Date: 2023-05-10 17:36:14.073847
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = "4cac712a2ce6"
down_revision = "c2d02e345a06"
branch_labels = None
depends_on = None


CATEGORY_CODE = "EXPORT-DONE"
EMAIL_CONTENT = """
Bonjour,
{% if export_failed == true %}
<p> Votre export <i>{{ export.label }}</i> n'a pas fonctionné correctement.</p>
<p>Veuillez signaler le problème à l'administrateur du site.</p>
{% else %}
<p>
Votre export <i>{{ export.label }}</i> est accessible via le lien suivant :
<a href='{{ url }}'>Téléchargement</a>.
</p>
<p>
Les données de cet export sont associées à la licence <a href='{{ export.licence.name_licence }}'>{{ export.licence.url_licence }}</a>.
Merci de les utiliser en respectant cette licence.
</p>
<p>
<b>Attention</b> : Ce fichier sera supprimé sous {{ nb_keep_day }} jours.
</p>
{% endif %}
"""

DB_CONTENT = """
{% if export_failed == true %}
<p> Votre export <i>{{ export.label }}</i> n'a pas fonctionné correctement.</p>
<p>Veuillez signaler le problème à l'administrateur du site.</p>
{% else %}
<p>Votre export <i>{{ export.label }}</i> est accessible via le lien suivant :
<a href='{{ url }}'>Téléchargement</a>.</p>
<p><b>Attention</b> : Ce fichier sera supprimé sous {{ nb_keep_day }} jours.</p>
<p>
Les données de cet export sont associées à la licence <a href='{{ export.licence.name_licence }}'>{{ export.licence.url_licence }}</a>.
Merci de les utiliser en respectant cette licence.
</p>
{% endif %}
"""


def upgrade():
bind = op.get_bind()
metadata = sa.MetaData(bind=op.get_bind())
notification_category = sa.Table(
"bib_notifications_categories",
metadata,
autoload=True,
schema="gn_notifications",
)

iterator = bind.execute(
notification_category.insert(
values={
"code": CATEGORY_CODE,
"label": "Fichier d'export généré",
"description": "Se déclenche lorsque la génération d'un fichier d'export est terminée",
}
).returning(notification_category.c.code)
)
result = next(iterator)

notification_template = sa.Table(
"bib_notifications_templates",
metadata,
autoload=True,
schema="gn_notifications",
)
values = [
{"code_category": result.code, "code_method": method, "content": content}
for method, content in (("EMAIL", EMAIL_CONTENT), ("DB", DB_CONTENT))
]

bind.execute(notification_template.insert(values=values))
op.execute(
f"""
INSERT INTO
gn_notifications.t_notifications_rules (code_category, code_method)
VALUES
('{CATEGORY_CODE}', 'DB'),
('{CATEGORY_CODE}', 'EMAIL')
"""
)


def downgrade():
bind = op.get_bind()
metadata = sa.MetaData(bind=op.get_bind())
notification_category = sa.Table(
"bib_notifications_categories",
metadata,
autoload=True,
schema="gn_notifications",
)
notification_template = sa.Table(
"bib_notifications_templates",
metadata,
autoload=True,
schema="gn_notifications",
)
notification_rules = sa.Table(
"t_notifications_rules", metadata, autoload=True, schema="gn_notifications"
)

bind.execute(
notification_rules.delete().where(
notification_rules.c.code_category == CATEGORY_CODE
)
)
bind.execute(
notification_template.delete().where(
notification_template.c.code_category == CATEGORY_CODE
)
)
bind.execute(
notification_category.delete().where(
notification_category.c.code == CATEGORY_CODE
)
)
op.execute(
f"""
DELETE FROM
gn_notifications.t_notifications_rules
WHERE
code_category = '{CATEGORY_CODE}'
AND
id_role IS NULL
"""
)
143 changes: 0 additions & 143 deletions backend/gn_module_export/send_mail.py

This file was deleted.

13 changes: 12 additions & 1 deletion backend/gn_module_export/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from .models import Export, ExportSchedules
from .utils_export import export_data_file, ExportGenerationNotNeeded

from geonature.core.notifications.utils import dispatch_notifications

logger = get_task_logger(__name__)

Expand All @@ -29,14 +30,22 @@ def generate_scheduled_exports(self):
generate_export.delay(
export_id=export.id,
export_format=scheduled_export.format,
filename="",
user=None,
scheduled=True,
skip_newer_than=scheduled_export.frequency * 24 * 60,
)


@celery_app.task(bind=True, throws=ExportGenerationNotNeeded)
def generate_export(
self, export_id, export_format, scheduled=False, skip_newer_than=None
self,
export_id,
export_format,
filename,
user=None,
scheduled=False,
skip_newer_than=None,
):
logger.info(f"Generate export {export_id}...")
export = Export.query.get(export_id)
Expand All @@ -48,6 +57,8 @@ def generate_export(
export_data_file(
id_export=export_id,
export_format=export_format,
filename=filename,
user=user,
isScheduler=scheduled,
skip_newer_than=skip_newer_than,
)
Expand Down
Loading

0 comments on commit 40efba3

Please sign in to comment.