2024-11-27 08:36:52 -08:00
|
|
|
import json
|
|
|
|
|
|
2017-05-12 14:06:29 +01:00
|
|
|
from flask import current_app
|
|
|
|
|
|
2024-11-27 08:36:52 -08:00
|
|
|
from app import redis_store
|
2017-07-19 13:50:29 +01:00
|
|
|
from app.config import QueueNames
|
2021-03-10 13:55:06 +00:00
|
|
|
from app.dao.services_dao import (
|
|
|
|
|
dao_fetch_active_users_for_service,
|
|
|
|
|
dao_fetch_service_by_id,
|
|
|
|
|
)
|
2017-05-12 14:06:29 +01:00
|
|
|
from app.dao.templates_dao import dao_get_template_by_id
|
2024-01-16 07:37:21 -05:00
|
|
|
from app.enums import KeyType, TemplateType
|
2021-03-10 13:55:06 +00:00
|
|
|
from app.notifications.process_notifications import (
|
|
|
|
|
persist_notification,
|
|
|
|
|
send_notification_to_queue,
|
|
|
|
|
)
|
2017-05-12 14:06:29 +01:00
|
|
|
|
|
|
|
|
|
2023-08-29 14:54:30 -07:00
|
|
|
def send_notification_to_service_users(
|
|
|
|
|
service_id, template_id, personalisation=None, include_user_fields=None
|
|
|
|
|
):
|
2017-11-28 13:49:14 +00:00
|
|
|
personalisation = personalisation or {}
|
|
|
|
|
include_user_fields = include_user_fields or []
|
2017-05-12 14:06:29 +01:00
|
|
|
template = dao_get_template_by_id(template_id)
|
|
|
|
|
service = dao_fetch_service_by_id(service_id)
|
|
|
|
|
active_users = dao_fetch_active_users_for_service(service.id)
|
2023-08-29 14:54:30 -07:00
|
|
|
notify_service = dao_fetch_service_by_id(current_app.config["NOTIFY_SERVICE_ID"])
|
2017-05-12 14:06:29 +01:00
|
|
|
|
|
|
|
|
for user in active_users:
|
|
|
|
|
personalisation = _add_user_fields(user, personalisation, include_user_fields)
|
|
|
|
|
notification = persist_notification(
|
|
|
|
|
template_id=template.id,
|
|
|
|
|
template_version=template.version,
|
2024-04-01 15:12:33 -07:00
|
|
|
recipient=(
|
|
|
|
|
user.email_address
|
|
|
|
|
if template.template_type == TemplateType.EMAIL
|
|
|
|
|
else user.mobile_number
|
|
|
|
|
),
|
2017-05-12 14:06:29 +01:00
|
|
|
service=notify_service,
|
|
|
|
|
personalisation=personalisation,
|
|
|
|
|
notification_type=template.template_type,
|
|
|
|
|
api_key_id=None,
|
2024-01-18 10:28:50 -05:00
|
|
|
key_type=KeyType.NORMAL,
|
2023-08-29 14:54:30 -07:00
|
|
|
reply_to_text=notify_service.get_default_reply_to_email_address(),
|
2017-05-12 14:06:29 +01:00
|
|
|
)
|
2024-11-27 08:36:52 -08:00
|
|
|
redis_store.set(
|
|
|
|
|
f"email-personalisation-{notification.id}",
|
|
|
|
|
json.dumps(personalisation),
|
|
|
|
|
ex=24 * 60 * 60,
|
|
|
|
|
)
|
|
|
|
|
redis_store.set(
|
|
|
|
|
f"email-recipient-{notification.id}", notification.to, ex=24 * 60 * 60
|
|
|
|
|
)
|
|
|
|
|
|
2023-08-25 12:09:00 -07:00
|
|
|
send_notification_to_queue(notification, queue=QueueNames.NOTIFY)
|
2024-11-27 10:56:13 -08:00
|
|
|
|
2017-05-12 14:06:29 +01:00
|
|
|
|
|
|
|
|
def _add_user_fields(user, personalisation, fields):
|
|
|
|
|
for field in fields:
|
|
|
|
|
personalisation[field] = getattr(user, field)
|
|
|
|
|
return personalisation
|