import requests import sys import json import subprocess import sys import os import string 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"] if (customerEmail is None or orderId is None or customerName is None or productUrl is None): print("Missing required parameters") sys.exit(1) customerEmail = customerEmail["value"] customerName = customerName["value"] productUrl = productUrl["value"] orderId = orderId["value"] # remove the # from the orderId if provided if orderId.startswith("#"): orderId = orderId[1:] discountCode = 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", }) 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) # create shopify discount code # this function will retry 3 times to create a new discount code if the random generate code already exists def createShopifyDiscountCode(retries): # generate random code characters = string.ascii_uppercase + string.digits discount_code = "".join(random.choice(characters) for _ in range(12)) # load data from secrets shopify_secrets = secrets["shopify"] shopify_url = shopify_secrets["store_url"] x_shopify_app_access_token = shopify_secrets["x_shopify_app_access_token"] shopify_discount_code_price_rule = shopify_secrets["discount_price_rules"]["order_voucher_10_percent"] response = requests.post( url=f"{shopify_url}/admin/api/2024-01/price_rules/{shopify_discount_code_price_rule}/discount_codes.json", headers={ "X-Shopify-Access-Token": x_shopify_app_access_token, "Content-Type": "application/json" }, json={ "discount_code": {"code": discount_code} }) retries += 1 if retries >= 3: sys.exit("Error, tried 3 times to create discount code") if response.status_code == 422: print("Failed to create code, response status code 422. Trying to generate new discount code") createShopifyDiscountCode(retries) if response.status_code != 201: sys.exit(f"Failed to create discount code, status code: {response.status_code}") print(f"Created discount code: {discount_code}") global discountCode discountCode = discount_code 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) createShopifyDiscountCode(0) req("10 % Gutschein", f"{secrets['shopify']['public_url']}/discount/{discountCode}?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 = "
" endTag = "
" # first paragraph with span because they have no padding if i == 0: startTag = "" 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}}", discountCode) 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"])