277 lines
7.4 KiB
Python
277 lines
7.4 KiB
Python
import requests
|
|
import sys
|
|
import json
|
|
import subprocess
|
|
import sys
|
|
import os
|
|
import string
|
|
import random
|
|
|
|
import smtplib
|
|
from email.mime.multipart import MIMEMultipart
|
|
from email.mime.text import MIMEText
|
|
|
|
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
|
|
|
|
STATIC_PATH = ""
|
|
|
|
from libs.utils import utils
|
|
|
|
# MAIN
|
|
|
|
# load data from secrets
|
|
secrets = utils.get_secrets()
|
|
|
|
crm_endpoint_url = secrets['admin_dashboard']['url'] + "/api/v1/crm"
|
|
|
|
headers = {
|
|
"X-Api-Key": secrets["admin_dashboard"]["x_api_key"],
|
|
"Content-Type": "application/json"
|
|
}
|
|
|
|
json_object = json.loads(sys.argv[1])
|
|
|
|
customerEmail = json_object["customerEmail"]
|
|
customerName = json_object["customerName"]
|
|
language = json_object["language"]
|
|
companyName = json_object["companyName"]
|
|
websiteURL = json_object["websiteURL"]
|
|
|
|
if (companyName is None
|
|
or customerName is None
|
|
or language is None
|
|
or websiteURL is None):
|
|
print("Missing required parameters")
|
|
sys.exit(1)
|
|
|
|
if(customerEmail is not None):
|
|
customerEmail = customerEmail["value"]
|
|
customerEmail = customerEmail.replace(" ", "")
|
|
if(customerEmail == ""):
|
|
customerEmail = None
|
|
customerName = customerName["value"]
|
|
companyName = companyName["value"]
|
|
language = language["value"]
|
|
websiteURL = websiteURL["value"]
|
|
|
|
|
|
def CreateCrmCustomer():
|
|
response = requests.post(
|
|
url=f"{crm_endpoint_url}/customer/create",
|
|
headers=headers,
|
|
json={
|
|
"FirstName": customerName,
|
|
"Company": companyName,
|
|
"Email": customerEmail,
|
|
"Website": websiteURL,
|
|
"LeadOrigin": "Kaltakquise Email/Contact added by GroupTask",
|
|
"DealPhase": 5,
|
|
})
|
|
|
|
print(f"CreateCrmCustomer response status code {response.status_code}")
|
|
|
|
if response.status_code != 200:
|
|
print(f"CreateCrmCustomer req error {response.status_code}")
|
|
sys.exit(1)
|
|
|
|
return response.json()["Id"]
|
|
|
|
|
|
|
|
def CheckIfCrmCustomerExists():
|
|
print(f"Checking if customer exists: {customerEmail}")
|
|
|
|
response = requests.post(
|
|
url=f"{crm_endpoint_url}/customer",
|
|
headers=headers,
|
|
json={"Email": customerEmail} # Hier json verwenden, um JSON-Daten zu senden
|
|
)
|
|
|
|
print("CheckIfCrmCustomerExists response status code", response.status_code)
|
|
|
|
if response.status_code != 200:
|
|
print(f"CheckIfCrmCustomerExists req error {response.status_code}")
|
|
sys.exit(1)
|
|
|
|
customerId = ""
|
|
# only on first purchase we show the third voucher
|
|
|
|
if response.json() == []:
|
|
print("Customer not found")
|
|
customerId = CreateCrmCustomer()
|
|
|
|
else:
|
|
print("Error: Customer already exists")
|
|
sys.exit(1)
|
|
|
|
if len(response.json()) > 1:
|
|
print("Multiple customers found. Don't know which one to use")
|
|
sys.exit(1)
|
|
|
|
customerId = response.json()[0]["Id"]
|
|
|
|
return customerId
|
|
|
|
|
|
def CreateCrmActivityLink(customerId, linkName, linkUrl):
|
|
print(f"Creating CRM activity link for customer {customerId}")
|
|
|
|
_linkName = f"JNX: SHX-Akquise {linkName}"
|
|
|
|
response = requests.post(
|
|
url=f"{crm_endpoint_url}/links",
|
|
headers=headers,
|
|
json={
|
|
"CustomerId": customerId,
|
|
"Name": _linkName,
|
|
"Url": linkUrl
|
|
})
|
|
|
|
print(f"CreateCrmActivityLink response status code {response.status_code} for {type}")
|
|
|
|
if response.status_code != 200:
|
|
print(f"CreateCrmActivityLink req error {response.status_code}")
|
|
sys.exit(1)
|
|
|
|
response = requests.get(
|
|
url=f"{crm_endpoint_url}/customer/view/{customerId}",
|
|
headers=headers,
|
|
)
|
|
|
|
print(f"GetCustomerActivityLinks response status code {response.status_code}")
|
|
|
|
if response.status_code != 200:
|
|
print(f"GetCustomerActivityLinks req error {response.status_code}")
|
|
sys.exit(1)
|
|
|
|
data = response.json()["Links"]
|
|
|
|
if len(data) == 0:
|
|
print("No links found")
|
|
sys.exit(1)
|
|
|
|
# sort data by creation date
|
|
|
|
data = sorted(data, key=lambda x: x["CreatedAt"], reverse=True)
|
|
|
|
# find the first link that has a name that starts with "Shopify Order #orderId - price € Gutschein"
|
|
|
|
createdLink = None
|
|
|
|
for link in data:
|
|
if link["Name"].startswith(_linkName):
|
|
createdLink = link
|
|
break
|
|
|
|
|
|
if(createdLink is None):
|
|
print(f"Link with name '{_linkName}' not found")
|
|
sys.exit(1)
|
|
|
|
return secrets["admin_dashboard"]["qr_code_url"] + createdLink['Id']
|
|
|
|
|
|
|
|
def sendMail():
|
|
secrets = utils.get_secrets()["email"]
|
|
|
|
# extract the email parameters
|
|
auth_email = secrets["auth_email"]
|
|
from_email_name = "Jan Umbach"#secrets["from_email_name"]
|
|
from_email = "kontakt@jannex.de"#secrets["from_email"]
|
|
password = secrets["password"]
|
|
|
|
# extract the smtp parameters
|
|
smtp_server = secrets["smtp_server"]
|
|
smtp_port = secrets["smtp_port"]
|
|
|
|
receiver_email = customerEmail
|
|
|
|
# create the email multipart message
|
|
msg = MIMEMultipart("alternative")
|
|
msg["From"] = f"{from_email_name} <{from_email}>"
|
|
msg["To"] = receiver_email
|
|
|
|
|
|
|
|
|
|
# load html content from file
|
|
with open(f"{STATIC_PATH}email.txt", "r") as file:
|
|
text = file.read()
|
|
|
|
with open(f"{STATIC_PATH}email.html", "r") as file:
|
|
html = file.read()
|
|
|
|
with open(f"{STATIC_PATH}lang.json", "r") as file:
|
|
languageJson = json.load(file)
|
|
|
|
|
|
msg["Subject"] = languageJson[language]["subject"]
|
|
|
|
# replace placeholders with actual values
|
|
|
|
# loop through all keys in the language json and replace the placeholders in the html file
|
|
for key in languageJson[language]:
|
|
value = languageJson[language][key]
|
|
|
|
value = value.replace("{{customerName}}", customerName)
|
|
|
|
html = html.replace(f"{{{{{key}}}}}", value.replace("\n", "<br>"))
|
|
text = text.replace(f"{{{{{key}}}}}", value)
|
|
|
|
unsubscribe_link = utils.generate_unsubscribe_link(customerId)
|
|
|
|
# add link to list-unsubscribe-header
|
|
msg["List-Unsubscribe"] = f"<{unsubscribe_link}>"
|
|
|
|
html = html.replace("{{footer}}", utils.get_email_footer_html(language, unsubscribe_link))
|
|
text = text.replace("{{footer}}", utils.get_email_footer_text(language, unsubscribe_link))
|
|
|
|
html = html.replace("{{topImageSrc}}", CreateCrmActivityLink(customerId, "EMail Opened", "https://jannex.de/unsubscribed/public/shinnex-generator-preview.png"))
|
|
|
|
html = html.replace("{{CTA_Link}}", CreateCrmActivityLink(customerId, "CTA Clicked (html)", "https://shinnex.de/products/personalisiertes-namensschild?variant=49403793572180"))
|
|
text = text.replace("{{CTA_Link}}", CreateCrmActivityLink(customerId, "CTA Clicked (text)", "https://shinnex.de/products/personalisiertes-namensschild?variant=49403793572180"))
|
|
|
|
print(f"Sending email to {receiver_email}")
|
|
print("------")
|
|
print(text)
|
|
print("------")
|
|
|
|
if(customerEmail is None):
|
|
print("Email not sent because no email address was provided")
|
|
return
|
|
|
|
|
|
# add text and html part to the email
|
|
part1 = MIMEText(text, "plain", "utf-8")
|
|
part2 = MIMEText(html, "html", "utf-8")
|
|
|
|
# Attach the text and html part to the email
|
|
msg.attach(part1)
|
|
msg.attach(part2)
|
|
|
|
# connect to the smtp server and send the email
|
|
try:
|
|
with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
|
|
server.login(auth_email, password)
|
|
server.sendmail(from_email, receiver_email, msg.as_string())
|
|
|
|
print(f"Email sent to {receiver_email}")
|
|
except Exception as e:
|
|
print(f"Error sending email: {e}")
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
utils.move_files_back_from_old_files()
|
|
|
|
if(customerEmail is not None):
|
|
customerId = CheckIfCrmCustomerExists()
|
|
else:
|
|
customerId = CreateCrmCustomer()
|
|
|
|
sendMail()
|
|
|
|
|
|
|
|
utils.clear_workspace(["email.html", "email.txt", "lang.json"]) |