Skip to content

Commit

Permalink
added sending threshold
Browse files Browse the repository at this point in the history
  • Loading branch information
biagiodistefano committed Jan 10, 2024
1 parent 36f0b44 commit 1a40de3
Show file tree
Hide file tree
Showing 9 changed files with 101 additions and 61 deletions.
1 change: 1 addition & 0 deletions src/api/management/commands/send-messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ def handle(self, *args: t.Any, **options: t.Any) -> None:
a = input("Are you sure you want to send messages? [y/N] ")
if a.lower() != "y":
return
print(f"Sending messages for {party} (dry: {dry})")
send_due_messages(
party, dry=dry, wait=options["wait"], refresh=options["refresh"], force=options["force"]
)
79 changes: 21 additions & 58 deletions src/api/messages.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import logging
from datetime import timedelta
from pathlib import Path

from dateutil.relativedelta import relativedelta
from django.contrib.sites.models import Site
Expand All @@ -10,65 +12,26 @@

logger = logging.getLogger("twilio_whatsapp")

TEMPLATES = {
"Invitation": ("""πŸ³οΈβ€πŸŒˆ *INVITATION: {party}* πŸ³οΈβ€πŸŒˆ

Hi, {name}!
You are invited to *{party}*!
Here's your *personal* link to manage your invitation:
{url}
Don't share this link with anyone else, it's only yours!
(Send "stop" to unsubscribe)""", relativedelta(month=1, hour=1)),

"2-week reminder": ("""πŸ³οΈβ€πŸŒˆ *2-WEEK REMINDER: {party}* πŸ³οΈβ€πŸŒˆ
Hi, {name}!
This is just to remind you that you are invited to *{party}*!
Here's your *personal* link to manage your invitation:
{url}
Don't share this link with anyone else, it's only yours!
(Send "stop" to unsubscribe)""", relativedelta(weeks=2, hour=1)),
"1-week reminder": ("""πŸ³οΈβ€πŸŒˆ *1-WEEK REMINDER: {party}* πŸ³οΈβ€πŸŒˆ
Hi, {name}!
This is just to remind you that you are invited to *{party}*!
Here's your *personal* link to manage your invitation:
{url}
Don't share this link with anyone else, it's only yours!
(Send "stop" to unsubscribe)""", relativedelta(weeks=1, hour=1)),
"Final reminder": ("""πŸ³οΈβ€πŸŒˆ *FINAL REMINDER: {party}* πŸ³οΈβ€πŸŒˆ
Hi, {name}!
This is just to remind you that you are invited to *{party}*!
Here's your *personal* link to manage your invitation:
{url}
Don't share this link with anyone else, it's only yours!
(Send "stop" to unsubscribe)""", relativedelta(days=2, hour=1)),
}


# message_statuses = ["accepted", "scheduled", "canceled", "queued", "sending",
# "sent", "failed", "delivered", "undelivered", "receiving", "received", "read"]
def load_templates():
template_dir = Path(__file__).parent / 'templates' / 'api'
templates = {}
delta_dict = {
"Invitation": (relativedelta(month=1, hour=1), None),
"2-week reminder": (relativedelta(weeks=2, hour=1), timedelta(days=1)),
"1-week reminder": (relativedelta(weeks=1, hour=1), timedelta(days=1)),
"Final reminder": (relativedelta(days=2, hour=1), timedelta(days=1)),
}
for file_path in template_dir.glob('*.txt'):
with file_path.open('r') as file:
content = file.read().strip()
# Use the file stem (without extension) as the key and content as the value
file_stem = file_path.stem
templates[file_stem] = (content, *delta_dict.get(file_stem))
return templates


TEMPLATES = load_templates()


def send_whatsapp_message(to: str, body: str) -> MessageInstance | None:
Expand Down
18 changes: 18 additions & 0 deletions src/api/migrations/0028_message_send_threshold.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.2.7 on 2024-01-10 10:17

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('api', '0027_alter_message_text'),
]

operations = [
migrations.AddField(
model_name='message',
name='send_threshold',
field=models.DurationField(blank=True, null=True),
),
]
4 changes: 3 additions & 1 deletion src/api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ class Message(models.Model):
text = MarkdownField(rendered_field='text_rendered', validator=VALIDATOR_STANDARD, default="", blank=True)
text_rendered = RenderedMarkdownField()
due_at = models.DateTimeField(db_index=True, null=True, blank=True)
send_threshold = models.DurationField(null=True, blank=True)
draft = models.BooleanField(default=True, db_index=True)

class Meta:
Expand Down Expand Up @@ -456,12 +457,13 @@ def create_invite(sender, instance: Party, created: bool, **kwargs):

@receiver(post_save, sender=Party)
def create_party_default_messages(sender, instance: Party, created: bool, **kwargs):
for title, (message, delta) in TEMPLATES.items():
for title, (message, delta, send_threshold) in TEMPLATES.items():
msg_instance, created = Message.objects.get_or_create(party=instance, title=title)
if not created:
continue
msg_instance.text = message
msg_instance.due_at = instance.date_and_time - delta
msg_instance.send_threshold = send_threshold
msg_instance.draft = False
msg_instance.save()

Expand Down
8 changes: 6 additions & 2 deletions src/api/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from celery import shared_task
from django.contrib.sites.models import Site
from django.db.models import Q
from django.db.models import F, Q
from django.shortcuts import reverse
from django.utils import timezone

Expand All @@ -23,7 +23,11 @@ def send_due_messages(
site = Site.objects.get_current()
party_url = f"https://{site.domain}" + reverse('party', kwargs={"edition": party.edition})
sent = []
messages = models.Message.objects.filter(party=party, due_at__lte=timezone.now(), draft=False).order_by("due_at")
current_time = timezone.now()
messages = models.Message.objects.filter(party=party, due_at__lte=current_time, draft=False).exclude(
Q(send_threshold__isnull=False) &
Q(due_at__lt=current_time - F('send_threshold'))
).order_by("due_at")
recipents = _get_recipients(party)
for person in recipents:
for message in messages:
Expand Down
13 changes: 13 additions & 0 deletions src/api/templates/api/1-week reminder.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
πŸ³οΈβ€πŸŒˆ *1-WEEK REMINDER: {party}* πŸ³οΈβ€πŸŒˆ

Hi, {name}!

This is just to remind you that you are invited to *{party}*!

Here's your *personal* link to manage your invitation:

{url}

Don't share this link with anyone else, it's only yours!

(Send "stop" to unsubscribe)
13 changes: 13 additions & 0 deletions src/api/templates/api/2-week reminder.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
πŸ³οΈβ€πŸŒˆ *2-WEEK REMINDER: {party}* πŸ³οΈβ€πŸŒˆ

Hi, {name}!

This is just to remind you that you are invited to *{party}*!

Here's your *personal* link to manage your invitation:

{url}

Don't share this link with anyone else, it's only yours!

(Send "stop" to unsubscribe)
13 changes: 13 additions & 0 deletions src/api/templates/api/Final reminder.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
πŸ³οΈβ€πŸŒˆ *FINAL REMINDER: {party}* πŸ³οΈβ€πŸŒˆ

Hi, {name}!

This is just to remind you that you are invited to *{party}*!

Here's your *personal* link to manage your invitation:

{url}

Don't share this link with anyone else, it's only yours!

(Send "stop" to unsubscribe)
13 changes: 13 additions & 0 deletions src/api/templates/api/Invitation.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
πŸ³οΈβ€πŸŒˆ *INVITATION: {party}* πŸ³οΈβ€πŸŒˆ

Hi, {name}!

You are invited to *{party}*!

Here's your *personal* link to manage your invitation:

{url}

Don't share this link with anyone else, it's only yours!

(Send "stop" to unsubscribe)

0 comments on commit 1a40de3

Please sign in to comment.