aboutsummaryrefslogtreecommitdiff
path: root/jb/managers/email_manager.py
blob: e740e20b742915b3cf34edf10f833d916ce8300d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import requests

from jb.config import settings

MAUTIC_BASE_URL = "https://mail.jamesbillings67.com"
EMAIL_TEMPLATE_ID = 1
auth_headers = {"Authorization": f"Basic {settings.mautic_api_key.get_secret_value()}"}


def get_or_create_contact(email: str, amt_worker_id: str | None = None):
    # amt_worker_id = "A2Z2FRA128FNW"
    body = {"email": email}
    if amt_worker_id:
        body["amt_worker_id"] = amt_worker_id
    res = requests.post(
        url=f"{MAUTIC_BASE_URL}/api/contacts/new",
        json=body,
        headers=auth_headers,
    ).json()
    contact_id = res["contact"]["id"]
    return contact_id


def send_login_email_from_url(mautic_url: str, magic_link: str) -> None:
    email_tokens = {
        "magic_link": magic_link,
    }
    body = {"tokens": email_tokens}
    response = requests.post(url=mautic_url, json=body, headers=auth_headers)
    try:
        response.raise_for_status()
    except requests.exceptions.HTTPError:
        print(f"Failed to send email. Status code: {response.status_code}")
        print(response.text)
        raise
    d = response.json()
    assert d.get("success"), f"Failed to send email: {d.get('failed')}"
    print("Email sent successfully")


def send_login_email(email: str, magic_token: str):
    contact_id = get_or_create_contact(email=email)
    mautic_url = (
        f"{MAUTIC_BASE_URL}/api/emails/{EMAIL_TEMPLATE_ID}/contact/{contact_id}/send"
    )
    magic_link = f"{settings.base_url}auth/magic-link/?token={magic_token}"
    return send_login_email_from_url(mautic_url, magic_link)


def send_amt_link_email(email: str, magic_token: str):
    # Don't actually associate the email with the worker ID
    #  until they click the link
    contact_id = get_or_create_contact(email=email)
    mautic_url = (
        f"{MAUTIC_BASE_URL}/api/emails/{EMAIL_TEMPLATE_ID}/contact/{contact_id}/send"
    )
    magic_link = f"{settings.base_url}auth/link-amt/?token={magic_token}"
    return send_login_email_from_url(mautic_url, magic_link)