5 from .decorators
import *
6 from .misc
import Object
8 class Campaigns(Object
):
9 async def launch_manually(self
, name
, uid
):
10 account
= self
.backend
.accounts
.get_by_uid(uid
)
12 self
.launch(name
, account
)
14 def launch(self
, name
, account
):
15 logging
.debug("Launching all campaigns for %s" % account
)
17 # Update old timestamps first
18 self
.db
.execute("UPDATE campaign_templates \
19 SET launch_at = launch_at + repeat_after \
20 WHERE (launch_at IS NOT NULL AND launch_at <= CURRENT_TIMESTAMP) \
21 AND repeat_after IS NOT NULL")
23 # Launch all campaigns
24 self
.db
.execute("INSERT INTO campaign_emails(account_uid, template, \
25 launch_at, repeat_after, promotional) \
26 SELECT %s, template, COALESCE(launch_at, CURRENT_TIMESTAMP + launch_after), \
27 repeat_after, promotional FROM campaign_templates WHERE name = %s",
30 def _get_campaign_emails(self
, query
, *args
):
31 res
= self
.db
.query(query
, *args
)
34 yield CampaignEmail(self
.backend
, row
.id, data
=row
)
37 with self
.db
.transaction():
38 emails
= self
._get
_campaign
_emails
("SELECT * FROM campaign_emails \
39 WHERE launch_at <= CURRENT_TIMESTAMP ORDER BY launch_at")
46 class CampaignEmail(Object
):
47 def init(self
, id, data
=None):
53 return self
.backend
.accounts
.get_by_uid(self
.data
.account_uid
)
57 return self
.data
.template
60 def repeat_after(self
):
61 return self
.data
.repeat_after
64 def promotional(self
):
65 return self
.data
.promotional
68 def should_be_sent(self
):
69 # Send all non-promotional emails
70 if not self
.promotional
:
73 # For promotional emails, send them if we have consent
74 return self
.account
.consents_to_promotional_emails
77 # Delete if the account does not exist any more
81 logging
.debug("Sending %s to %s" % (self
.template
, self
.account
))
84 if self
.should_be_sent
:
85 self
.backend
.messages
.send_template(self
.template
, account
=self
.account
)
87 # Update this email for the next launch
91 # If this email repeats, we will update the timestamp
93 self
.db
.execute("UPDATE campaign_emails \
94 SET launch_at = launch_at + repeat_after \
95 WHERE id = %s", self
.id)
97 # Otherwise we will delete it
105 self
.db
.execute("DELETE FROM campaign_emails WHERE id = %s", self
.id)