admin-dashboard-backend/groupTasks/groups/shx-order-voucher-codes/script.py

289 lines
8.2 KiB
Python

import requests
import sys
import json
import subprocess
import sys
import os
import random
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../..")))
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"]
productUrl = json_object["productUrl"]
orderId = json_object["orderId"]
additionalInfo = json_object["additionalInfo"]
if (customerEmail is None
or orderId is None
or customerName is None
or productUrl is None
or additionalInfo is None):
print("Missing required parameters")
sys.exit(1)
customerEmail = customerEmail["value"]
customerName = customerName["value"]
productUrl = productUrl["value"]
orderId = orderId["value"]
additionalInfo = additionalInfo["value"]
# remove the # from the orderId if provided
if orderId.startswith("#"):
orderId = orderId[1:]
generated_discount_code = None
def CreateCrmCustomer():
response = requests.post(
url=f"{crm_endpoint_url}/customer/create",
headers=headers,
json={
"FirstName": customerName,
"Email": customerEmail,
"LeadOrigin": "Shopify Customer added by GroupTask",
"Pipeline": 2,
"DealPhase": 2,
})
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 show_third_voucher(show):
with open("backPage.html", "r") as file:
html = file.read()
if show:
print("Showing third voucher")
html = html.replace("SHOW_THIRD_VOUCHER", "block")
else:
print("Not showing third voucher")
html = html.replace("SHOW_THIRD_VOUCHER", "none")
with open("backPage.html", "w") as file:
file.write(html)
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
thirdVoucher = False
if response.json() == []:
print("Customer not found")
customerId = CreateCrmCustomer()
thirdVoucher = True
else:
if len(response.json()) > 1:
print("Multiple customers found. Don't know which one to use")
sys.exit(1)
customerId = response.json()[0]["Id"]
show_third_voucher(thirdVoucher)
CreateCrmActivityLink(customerId=customerId, thirdVoucher=thirdVoucher)
GetCustomerActivityLinks(customerId=customerId, thirdVoucher=thirdVoucher)
def CreateCrmActivityLink(customerId, thirdVoucher):
print(f"Creating CRM activity link for customer {customerId}")
def req(type, url):
response = requests.post(
url=f"{crm_endpoint_url}/links",
headers=headers,
json={
"CustomerId": customerId,
"Name": f"Shopify Order #{orderId} - {type}",
"Url": url
})
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)
global generated_discount_code
generated_discount_code = utils.create_shopify_discount_code("order_voucher_10_percent")
req("10 % Gutschein", f"{secrets['shopify']['public_url']}/discount/{generated_discount_code}?utm_source=order&utm_medium=qrcode&utm_campaign=ordervouchercodes&utm_content=reedemvouchercode")
req("5 € Gutschein", f"{productUrl}?utm_source=order&utm_medium=qrcode&utm_campaign=ordervouchercodes&utm_content=qualifyforvouchercode")
if thirdVoucher:
req("10 € Gutschein", f"https://docs.google.com/forms/d/e/1FAIpQLSd2GXFbidzazuQnh_Lf2mgeA1npuwHkWjsdmjrxDmSkDQTfew/viewform?entry.347359844={orderId}")
def GetCustomerActivityLinks(customerId, thirdVoucher):
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"
linkGift5 = None
linkGift10 = None
linkGift10Percent = None
for link in data:
if linkGift5 is None and link["Name"].startswith(f"Shopify Order #{orderId} - 5 € Gutschein"):
linkGift5 = link
elif linkGift10 is None and link["Name"].startswith(f"Shopify Order #{orderId} - 10 € Gutschein"):
linkGift10 = link
elif linkGift10Percent is None and link["Name"].startswith(f"Shopify Order #{orderId} - 10 % Gutschein"):
linkGift10Percent = link
if linkGift5 is None or linkGift10Percent is None:
print("Gift links not found")
sys.exit(1)
qr_code_url = secrets["admin_dashboard"]["qr_code_url"]
utils.create_qrcode(f"{qr_code_url}{linkGift5['Id']}", "./5euro.png", "#fdf8ef")
utils.create_qrcode(f"{qr_code_url}{linkGift10Percent['Id']}", "./10percent.png", "#fdf8ef")
if thirdVoucher:
utils.create_qrcode(f"{qr_code_url}{linkGift10['Id']}", "./10euro.png", "#fdf8ef")
def ReplaceHtmlVariables():
print("ReplaceHtmlVariables")
# replace variables in html file
# read html file and replace variables
with open("../../groupsData/shx-order-voucher-codes/texte.json", "r", encoding="utf-8") as json_file:
data = json.load(json_file)
randomTextIndex = random.randint(0, len(data["texts"])-1)
htmlParagraphs = ""
i = 0
for paragraph in data["texts"][randomTextIndex]["paragraphs"]:
startTag = "<p>"
endTag = "</p>"
# first paragraph with span because they have no padding
if i == 0:
startTag = "<span>"
endTag = "</span>"
# add as text before last paragraph
if (additionalInfo != "Keine" and i == len(data["texts"][randomTextIndex]["paragraphs"]) - 1):
htmlParagraphs += f"{startTag}{data['additionalInfo'][additionalInfo]}{endTag}"
htmlParagraphs += f"{startTag}{paragraph.replace('{{CUSTOMER_NAME}}', customerName)}{endTag}"
i += 1
file = open("frontPage.html", "r")
html = file.read()
html = html.replace("{{TEXTE}}", htmlParagraphs)
file.close()
file = open("frontPage.html", "w")
file.write(html)
file.close()
file = open("backPage.html", "r")
html = file.read()
html = html.replace("{{DISCOUNT_CODE}}", generated_discount_code)
file.close()
file = open("backPage.html", "w")
file.write(html)
file.close()
def createPdf(sourceHtml, outputPdf):
command = [
"google-chrome-stable",
"--headless",
"--no-sandbox",
"--disable-gpu",
"--print-to-pdf=" + outputPdf,
"--run-all-compositor-stages-before-draw",
"--virtual-time-budget=10000",
sourceHtml,
]
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
_, stderr = process.communicate()
if process.returncode != 0:
print("Error creating PDF")
print(stderr)
sys.exit(1)
if __name__ == "__main__":
utils.move_files_back_from_old_files()
CheckIfCrmCustomerExists()
ReplaceHtmlVariables()
createPdf("frontPage.html", "finalFrontPage.pdf")
createPdf("backPage.html", "finalBackPage.pdf")
utils.merge_pdfs("finalFrontPage.pdf", "finalBackPage.pdf", "Gutscheine.pdf")
utils.clear_workspace(["5euro.png", "10euro.png", "10percent.png",
"frontPage.html", "backPage.html", "finalBackPage.pdf",
"finalFrontPage.pdf"])