def get_code(choice): ''' Returns Landing Page Code either form clipoard or from template ''' if choice == 2: # Gets code from clipboard and validates if it is HTML page lp_id = api.get_asset_id('landingPage') if lp_id: lp_code = (api.eloqua_asset_get( lp_id, asset_type='landingPage'))[1] else: while True: lp_code = pyperclip.paste() is_html = re.compile(r'<html[\s\S\n]*?</html>', re.UNICODE) if is_html.findall(lp_code): print(f' {SUCCESS}Code copied from clipboard') break print( f' {ERROR}Invalid HTML. Copy valid code and click [Enter]', end='') input(' ') # Modifies landing page code lp_code = clean_custom_css(lp_code) lp_code = add_showhide_css(lp_code) else: # Gets code from template file templates = ['blank-lp', 'lp-template'] with open(file(templates[choice]), 'r', encoding='utf-8') as f: lp_code = f.read() return lp_code
def get_code(): ''' Returns code to be cleaned » code: long str ''' email_id = api.get_asset_id('email') if email_id: try: email = api.eloqua_asset_get(email_id, asset_type='email') except KeyError: print(f' {ERROR}Cannot clean drag & drop e-mail') else: while True: print( f'\n{Fore.WHITE}» [{Fore.YELLOW}CODE{Fore.WHITE}] Copy code [CTRL+C] and click [Enter]', end='') input(' ') code = pyperclip.paste() is_html = re.compile(r'<html[\s\S\n]*?</html>', re.UNICODE) if is_html.findall(code): print( f'{Fore.WHITE}» [{Fore.YELLOW}NAME{Fore.WHITE}] Write or paste new E-mail name:' ) name = api.eloqua_asset_name() email = (name, code) break print(f' {ERROR}Copied code is not correct HTML') return email, email_id
def voucher_list_delete(): ''' Deleted voucher campaign from the list ''' # Gets ID of campaign to be added to thje list while True: print( f'\n{Fore.YELLOW}Please enter ID of the campaign you want to delete from checklist:', end='') campaign_id = input(' ') if campaign_id.lower() == 'q': return False try: int(campaign_id) except (TypeError, ValueError): print(f'{ERROR}Please enter numeric value!') campaign_id = '' continue break # Gets list of already uploaded voucher campaigns uploaded_voucher_shared_list = api.eloqua_asset_get( naming[source_country]['id']['voucher_campaigns'], 'sharedContent', depth='complete') old_voucher_shared_txt = uploaded_voucher_shared_list['contentHtml'] if '"' in old_voucher_shared_txt: old_voucher_shared_txt = old_voucher_shared_txt.replace('"', '"') if old_voucher_shared_txt: old_voucher_shared_dict = json.loads(old_voucher_shared_txt) else: old_voucher_shared_dict = {} # Checks if the new ID is already in the list if campaign_id not in old_voucher_shared_dict.keys(): print( f'\n{Fore.WHITE}» {Fore.RED}Entered campaign is not in the list!') return False else: del old_voucher_shared_dict[campaign_id] new_voucher_shared_txt = json.dumps(old_voucher_shared_dict) # Build shared content data for updating the list of voucher campaigns data = { 'id': uploaded_voucher_shared_list.get('id'), 'name': uploaded_voucher_shared_list.get('name'), 'contentHTML': new_voucher_shared_txt } # Updating list of voucher campaigns to shared content api.eloqua_put_sharedcontent( naming[source_country]['id']['voucher_campaigns'], data=data) print( f'\n{SUCCESS}Campaign ID {Fore.YELLOW}{campaign_id}{Fore.WHITE} deleted from checklist!' ) return True
def voucher_list_print(): ''' Prints voucher campaign list ''' # Gets list of already uploaded voucher campaigns uploaded_voucher_shared_list = api.eloqua_asset_get( naming[source_country]['id']['voucher_campaigns'], 'sharedContent', depth='complete') old_voucher_shared_txt = uploaded_voucher_shared_list['contentHtml'] if '"' in old_voucher_shared_txt: old_voucher_shared_txt = old_voucher_shared_txt.replace('"', '"') if old_voucher_shared_txt: old_voucher_shared_dict = json.loads(old_voucher_shared_txt) else: print( f'\n{Fore.WHITE}» {Fore.YELLOW}There is no voucher campaigns on the list' ) return False print( f'\n{Fore.WHITE}{len(old_voucher_shared_dict.keys()) - 1}{Fore.GREEN} Voucher Campaigns Listed:' ) for element in old_voucher_shared_dict.values(): if isinstance(element, str): continue print(f'{Fore.WHITE}» [ID: {Fore.YELLOW}{element["id"]}{Fore.WHITE}] ' f'{Fore.WHITE}{element["name"]}') return True
def get_form(form_id): ''' Returns validated form code form clipboard ''' # If no ID given via parameters, gets it from user if not form_id: form_id = api.get_asset_id('form') # If there was ID via parameters or given by user if form_id: form_code = (api.eloqua_asset_get(form_id, asset_type='form'))[1] # If input is not valid id else: while True: form_code = pyperclip.paste() is_html = re.compile(r'<form[\s\S\n]*?</script>', re.UNICODE) if is_html.findall(form_code): print(f' {SUCCESS}Code copied from clipboard') break print( f' {ERROR}Copied code is not correct Form HTML, please copy again') input() return form_code
def webinar_module(country): ''' Lets user choose which webinar module utility he wants to use ''' # Create global source_country and load json file with naming convention country_naming_setter(country) # Gets date of last webinar sync last_webinar_sync = api.eloqua_asset_get( naming[source_country]['id']['webinar_sync'], 'sharedContent', depth='complete') last_webinar_sync = last_webinar_sync['contentHtml'] print( f'\n{Fore.WHITE}Last webinar sync was made on {Fore.YELLOW}{last_webinar_sync}' ) # Campaign type chooser print( f'\n{Fore.GREEN}ELQuent.webinar Utilites:' f'\n{Fore.WHITE}[{Fore.YELLOW}1{Fore.WHITE}]\t» [{Fore.YELLOW}Activities{Fore.WHITE}] Uploads attendees as External Activities' f'\n{Fore.WHITE}[{Fore.YELLOW}Q{Fore.WHITE}]\t» [{Fore.YELLOW}Quit to main menu{Fore.WHITE}]' ) while True: print(f'{Fore.YELLOW}Enter number associated with chosen utility:', end='') choice = input(' ') if choice.lower() == 'q': break elif choice == '1': click_to_activity(last_webinar_sync) break else: print(f'{Fore.RED}Entered value does not belong to any utility!') choice = '' return
def voucher_validation(): ''' Validates voucher campaigns stored in the checklist ''' # Gets list of already uploaded voucher campaigns uploaded_voucher_shared_list = api.eloqua_asset_get( naming[source_country]['id']['voucher_campaigns'], 'sharedContent', depth='complete') voucher_shared_txt = uploaded_voucher_shared_list['contentHtml'] if '"' in voucher_shared_txt: voucher_shared_txt = voucher_shared_txt.replace('"', '"') if voucher_shared_txt: voucher_shared_dict = json.loads(voucher_shared_txt) else: print( f'\n{Fore.WHITE}» {Fore.YELLOW}There is no Voucher Campaign on the list' ) return True # Calculate treshold for being off track (12h delay) current_epoch = int(datetime.now().timestamp()) day_delay = current_epoch - 43200000 # Check for errors in checlisted campaigns error = 0 print( f'\n{Fore.GREEN}Validating {Fore.WHITE}{len(voucher_shared_dict.keys()) - 1}{Fore.GREEN} Voucher Campaigns' ) for campaign in voucher_shared_dict.values(): if isinstance(campaign, str): continue print(f'{Fore.WHITE}» [ID: {Fore.YELLOW}{campaign["id"]}{Fore.WHITE}] ' f'{Fore.WHITE}{campaign["name"]}') step_contacts = api.eloqua_get_step_contacts(campaign['voucher_step']) step_entry = [] if step_contacts['elements']: for contact in step_contacts['elements']: step_entry.append(int(contact['stepEntryTime'])) step_entry.sort() if step_entry[0] < day_delay: error += 1 print( f'{Fore.WHITE}» {ERROR}Voucher App frozen in Campaign ID ' f'{Fore.WHITE}{campaign["id"]} {Fore.YELLOW}- {Fore.WHITE}{campaign["name"]}' ) if campaign['error_step']: step_contacts = api.eloqua_get_step_contacts( campaign['error_step']) if step_contacts['elements']: error += 1 print( f'{Fore.WHITE}» {ERROR}Contacts on Error Step in Campaign ID ' f'{Fore.WHITE}{campaign["id"]} {Fore.YELLOW}- {Fore.WHITE}{campaign["name"]}' ) if error: print(f'\n{ERROR}Found {error} Voucher App errors!') return False else: # Gets current datetime to update last_webinar_sync shared list current_sync = datetime.today().strftime('%Y-%m-%d %H:%M') voucher_shared_dict['sync'] = current_sync new_voucher_shared_txt = json.dumps(voucher_shared_dict) # Build shared content data for updating the list of voucher campaigns data = { 'id': uploaded_voucher_shared_list.get('id'), 'name': uploaded_voucher_shared_list.get('name'), 'contentHTML': new_voucher_shared_txt } # Updating list of voucher campaigns to shared content api.eloqua_put_sharedcontent( naming[source_country]['id']['voucher_campaigns'], data=data) print(f'\n{SUCCESS}No problems with Voucher App found') return True
def voucher_list_update(): ''' Adds voucher campaign to the list ''' # Gets ID of campaign to be added to thje list while True: print( f'\n{Fore.YELLOW}Please enter ID of new campaign with the Voucher Code App:', end='') campaign_id = input(' ') if campaign_id.lower() == 'q': return False try: int(campaign_id) except (TypeError, ValueError): print(f'{ERROR}Please enter numeric value!') campaign_id = '' continue break # Gets list of already uploaded voucher campaigns uploaded_voucher_shared_list = api.eloqua_asset_get( naming[source_country]['id']['voucher_campaigns'], 'sharedContent', depth='complete') old_voucher_shared_txt = uploaded_voucher_shared_list['contentHtml'] if '"' in old_voucher_shared_txt: old_voucher_shared_txt = old_voucher_shared_txt.replace('"', '"') if old_voucher_shared_txt: old_voucher_shared_dict = json.loads(old_voucher_shared_txt) else: old_voucher_shared_dict = {} # Checks if the new ID is already in the list if campaign_id in old_voucher_shared_dict.keys(): print( f'\n{Fore.WHITE}» {Fore.RED}Entered campaign is already in the list!' ) return False else: campaign = api.eloqua_asset_get(campaign_id, asset_type='campaign', depth='complete') voucher_campaign_id = campaign['id'] voucher_campaign_name = campaign['name'] voucher_campaign_voucher_step = '' voucher_campaign_error_step = '' for element in campaign['elements']: if element['type'] == 'CampaignWaitAction' and element[ 'name'] == 'Voucher Error': voucher_campaign_error_step = element['id'] if element['type'] == 'CampaignCloudAction' and element[ 'name'] == 'Code Retriever 2.0 Action Service': voucher_campaign_voucher_step = element['id'] # End if there is no step with default naming convention if not voucher_campaign_voucher_step: print( f'\n{Fore.WHITE}» {ERROR}There is no App step called "Code Retriever 2.0 Action Service" on the canvas!' ) return False if not voucher_campaign_error_step: print( f'\n{Fore.WHITE}» {WARNING}There is no Wait step called "Voucher Error" on the canvas.' ) old_voucher_shared_dict[voucher_campaign_id] = { 'id': voucher_campaign_id, 'name': voucher_campaign_name, 'voucher_step': voucher_campaign_voucher_step, 'error_step': voucher_campaign_error_step } new_voucher_shared_txt = json.dumps(old_voucher_shared_dict) # Build shared content data for updating the list of voucher campaigns data = { 'id': uploaded_voucher_shared_list.get('id'), 'name': uploaded_voucher_shared_list.get('name'), 'contentHTML': new_voucher_shared_txt } # Updating list of voucher campaigns to shared content api.eloqua_put_sharedcontent( naming[source_country]['id']['voucher_campaigns'], data=data) print( f'\n{SUCCESS}Campaign {Fore.YELLOW}{voucher_campaign_name}{Fore.WHITE} added to checklist!' ) return True
def campaign_lifespan(): ''' Creates report containg all active campaigns with end date after chosen period ''' # Creates list to store all active multistep campaigns active_campaigns = [] ''' =================================================== Gets IDs of all active multistep campaigns ''' # Builds search query for API campaign_query = f"name='WK{source_country}*'" # Iterates over pages of outcomes page = 1 print(f'\n{Fore.WHITE}[{Fore.YELLOW}SYNC{Fore.WHITE}] ', end='', flush=True) while True: campaigns = api.eloqua_get_assets(campaign_query, asset_type='campaign', page=page, depth='minimal') # Adds active campaigns to a list for campaign in campaigns['elements']: if campaign['currentStatus'] == 'Active' and campaign[ 'isEmailMarketingCampaign'] == 'false': active_campaigns.append(int(campaign['id'])) # Stops iteration when full list is obtained if campaigns['total'] - page * 500 < 0: break # Else increments page to get next part of outcomes page += 1 # Every ten batches draws hyphen for better readability if page % 10 == 0: print(f'{Fore.YELLOW}-', end='', flush=True) print( f'\n{SUCCESS}Exported all {len(active_campaigns)} active multistep campaigns for WK{source_country}' ) ''' =================================================== Exports data of each active multistep campaign ''' # Gets date for file naming today = str(datetime.now())[:10] # Dict of users for id to name swap user_dict = {} # Creates file to save outcomes with open(file('outcome-csv', f'active-campaigns-{today}'), 'w', encoding='utf-8') as f: fieldnames = [ 'Name', 'ID', 'CreatedBy', 'CreatedAt', 'UpdatedAt', 'StartAt', 'EndAt', 'Members' ] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writeheader() # Gets data on each active multistep campaign print(f'\n{Fore.WHITE}[{Fore.YELLOW}SYNC{Fore.WHITE}] ', end='', flush=True) for campaign_id in active_campaigns: campaign = api.eloqua_asset_get(campaign_id, asset_type='campaign', depth='complete') campaign_info = { 'Name': campaign['name'], 'ID': int(campaign['id']), 'CreatedAt': datetime.utcfromtimestamp(int( campaign['createdAt'])).strftime('%Y-%m-%d %H:%M:%S'), 'UpdatedAt': datetime.utcfromtimestamp(int( campaign['updatedAt'])).strftime('%Y-%m-%d %H:%M:%S'), 'StartAt': datetime.utcfromtimestamp(int( campaign['startAt'])).strftime('%Y-%m-%d'), 'EndAt': datetime.utcfromtimestamp(int( campaign['endAt'])).strftime('%Y-%m-%d'), } # Gets user name with least API calls required try: campaign_info['CreatedBy'] = user_dict[campaign['createdBy']] except KeyError: user_dict[campaign['createdBy']] = helper.user_getter( campaign['createdBy']).get('name', campaign['createdBy']) campaign_info['CreatedBy'] = user_dict[campaign['createdBy']] # Gets member count for the campain if any try: campaign_info['Members'] = campaign['memberCount'] except KeyError: campaign_info['Members'] = '0' # Append batch of data to file with open(file('outcome-csv', f'active-campaigns-{today}'), 'a', encoding='utf-8') as f: fieldnames = [ 'Name', 'ID', 'CreatedBy', 'CreatedAt', 'UpdatedAt', 'StartAt', 'EndAt', 'Members' ] writer = csv.DictWriter(f, fieldnames=fieldnames) writer.writerow(campaign_info) # Clears dict for next batch campaign_info = {} print(f'{Fore.GREEN}|', end='', flush=True) print( f'\n{SUCCESS}Saved data of {len(active_campaigns)} campaigns to Outcomes folder' ) lifespan_analytics_menu(today)
def campaign_decision_validator(campaign_data, campaign_json, decision_type): ''' Requires json with campaign data and decision type Possible asset names ['EmailOpened', 'EmailClickthrough', 'EmailSent', 'SubmitForm', 'ContactFilterMembershi', 'ContactListMembership'] Returns a list of IDs of the decisions ''' decision_list = [] for element in campaign_json['elements']: if element['type'] == f'Campaign{decision_type}Rule': # Gathers basic data on decision if 'email' in decision_type.lower(): decision_list.append(element.get('emailId')) elif 'form' in decision_type.lower(): decision_list.append(element.get('formId')) elif 'filter' in decision_type.lower(): decision_list.append(element.get('filterId')) elif 'list' in decision_type.lower(): decision_list.append(element.get('listId')) # Validates whether decision step is set to asset from that campaign if decision_type in ['EmailOpened', 'EmailClickthrough', 'EmailSent']\ and decision_list[-1] not in campaign_data['Email']: connected_asset_name, _ = api.eloqua_asset_get( decision_list[-1], 'email', depth='minimal') if campaign_name_base not in connected_asset_name: print(f'{WARNING}{element.get("name")} ', f'{Fore.YELLOW}» asset not used in this camapign.') validation_errors.append([ element.get('name'), decision_list[-1], '', 'Connected to asset from different campaign' ]) elif decision_type is 'SubmitForm'\ and decision_list[-1] not in campaign_data['Form']: connected_asset_name, _ = api.eloqua_asset_get( decision_list[-1], 'form', depth='minimal') if campaign_name_base not in connected_asset_name: print(f'{WARNING}{element.get("name")} ', f'{Fore.YELLOW}» asset not used in this camapign.') validation_errors.append([ element.get('name'), decision_list[-1], '', 'Connected to asset from different campaign' ]) # Validates whether there are defined outputs if not element.get('outputTerminals'): print(f'{ERROR}{element.get("name")} ' f'{Fore.YELLOW}» no output routes!') validation_errors.append([ element.get('name'), decision_list[-1], '', 'No output routes on canvas' ]) elif len(element['outputTerminals']) == 1: print(f'{WARNING}{element.get("name")} ' f'{Fore.YELLOW}» only one output route.') validation_errors.append([ element.get('name'), decision_list[-1], '', 'Only one output route on canvas' ]) # Validates whether there is correct evaluation period if element.get('evaluateNoAfter') == '0': print(f'{ERROR}{element.get("name")} ' f'{Fore.RED}There is no evaluation period.') validation_errors.append([ element.get('name'), decision_list[-1], '', 'There is no evaluation period set' ]) return decision_list
def click_to_activity(last_webinar_sync): ''' Gets ClickMeeting webinars attendees uploads them to Eloqua as a shared list and adds them to External Activity ''' # Parse last_webinar_sync from string to datetime last_sync = datetime.datetime.strptime(last_webinar_sync, '%Y-%m-%d %H:%M') # Gets current datetime to update last_webinar_sync shared list current_sync = datetime.datetime.today().strftime('%Y-%m-%d %H:%M') # Gets list of already uploaded webinars uploaded_sessions_shared_list = api.eloqua_asset_get( naming[source_country]['id']['uploaded_sessions_list'], 'sharedContent', depth='complete') old_sessions_shared_list = uploaded_sessions_shared_list['contentHtml'] old_sessions_shared_list = old_sessions_shared_list.split(',') ''' =================================================== Get room data ''' print(f'\n{Fore.YELLOW}» Getting rooms since last sync') # Save active rooms active_ids = [] active_names = [] root = click_root + 'conferences/active' response = api.api_request(root, api='click') rooms_active_click = response.json() for room in rooms_active_click: active_ids.append(room['id']) active_names.append(room['name']) active_rooms = list(zip(active_ids, active_names)) # Save inactive rooms inactive_ids = [] inactive_names = [] root = click_root + 'conferences/inactive' response = api.api_request(root, api='click') rooms_inactive_click = response.json() for room in rooms_inactive_click: # Creating datetime version of room end date room_date = room['ends_at'][:10] + ' ' + room['ends_at'][11:16] room_datetime = datetime.datetime.strptime(room_date, '%Y-%m-%d %H:%M') # Skip rooms older then last sync if room_datetime >= last_sync: inactive_ids.append(room['id']) inactive_names.append(room['name']) inactive_rooms = list(zip(inactive_ids, inactive_names)) print( f'{Fore.GREEN}» Imported {len(active_rooms)} active and {len(inactive_rooms)} inactive rooms' ) click_rooms = active_rooms + inactive_rooms ''' =================================================== Get session data ''' print(f'\n{Fore.YELLOW}» Getting sessions') click_sessions = {} # Save all sessions for room in click_rooms: root = f'{click_root}conferences/{room[0]}/sessions' response = api.api_request(root, api='click') if response.status_code == 200: print(f'{Fore.GREEN}|', end='', flush=True) sessions_in_room = response.json() for session in sessions_in_room: # Skip already uploaded sessions if session['id'] not in old_sessions_shared_list: click_session = (session['id'], session['start_date'][:10] + ' ' + session['start_date'][11:16], session['end_date'][:10] + ' ' + session['end_date'][11:16]) click_sessions[click_session] = room else: print(f'{Fore.RED}|', end='', flush=True) print(f'\n{Fore.GREEN}» Imported {len(click_sessions)} sessions') ''' =================================================== Get attendees data ''' print(f'\n{Fore.YELLOW}» Getting attendees') sessions = 0 adresses = [] activities = [] new_sessions_shared_list = [] # Create list of attendees of each session in chosen period for key, value in click_sessions.items(): # click_sessions unpacking session_id, session_start_date, session_end_date = key room_id, room_name = value # Creating datetime version of session_date session_end_datetime = datetime.datetime.strptime( session_end_date, '%Y-%m-%d %H:%M') # Skip already sessions older then last sync if session_end_datetime >= last_sync: root = f'{click_root}conferences/{room_id}/sessions/{session_id}/attendees' response = api.api_request(root, api='click') attendees = response.json() # Create list of attendees attendees_list = [] for attendee in attendees: if attendee['role'] == 'listener' and attendee[ 'email'] is not None: attendees_list.append(attendee['email']) # Deduplicating list of email addresses attendees_list = list(set(attendees_list)) # Filter out corporate and spam e-mails attendees_list = [ att for att in attendees_list if '@wolterskluwer.' not in att.lower() and len(att) > 8 ] # Add this sessions attendees to main attendees list adresses.extend(attendees_list) # Modifying values for Eloqua naming convention room_name = room_name\ .replace(',', '')\ .replace('!', '')\ .replace('-', '')\ .replace('.', '')\ .replace(':', '')\ .replace('?', '')\ .replace('–', '')\ .replace(' ', '-') room_name = room_name[:40] if len(room_name) > 40 else room_name while room_name.endswith('-'): room_name = room_name[:-1] while room_name.startswith('-'): room_name = room_name[1:] session_date = f'{session_start_date[2:4]}-{session_start_date[5:7]}-{session_start_date[8:10]}' # Naming convention for shared list of uploaded attendees activity_name = f'WK{source_country}_{session_date}_{room_name}-{str(session_id)}_webinar' while '--' in activity_name: activity_name = activity_name.replace('--', '-') # Build external activity structured list campaign_id = naming[source_country]['id']['campaign'][ 'External_Activity'] for attendee in attendees_list: # [E-mail, CampaignId, AssetName, AssetType, AssetDate, ActivityType] activities.append([ attendee, campaign_id, activity_name, 'WKPL_Webinar', session_start_date, 'Attended' ]) # Update shared content with newly uploaded session_ids new_sessions_shared_list.append(str(session_id)) # Increment sessions count sessions += 1 print(f'{Fore.GREEN}|', end='', flush=True) else: print(f'{Fore.RED}|', end='', flush=True) if not activities: print(f'\n{Fore.WHITE}» {Fore.RED}No attendees in given timeframe') return print( f'\n{Fore.GREEN}» Imported {len(activities)} attendees from {sessions} sessions' ) ''' =================================================== Upload contacts & activities ''' api.eloqua_create_webinar_activity(adresses, activities) ''' =================================================== Update list of uploaded sessions ''' print(f'\n{Fore.YELLOW}» Saving list of all uploaded webinar sessions') # Creates a string with id's of all uploaded webinar sessions all_sessions_shared_list = \ (',').join(old_sessions_shared_list + new_sessions_shared_list) if all_sessions_shared_list.startswith(','): # in case of no old sessions all_sessions_shared_list = all_sessions_shared_list[1:] # Build shared content data for updating the list of uploaded sessions data = { 'id': uploaded_sessions_shared_list.get('id'), 'name': uploaded_sessions_shared_list.get('name'), 'contentHTML': all_sessions_shared_list } # Updating list of uploaded sessions to shared content api.eloqua_put_sharedcontent( naming[source_country]['id']['uploaded_sessions_list'], data=data) ''' =================================================== Update last sync date ''' print(f'\n{Fore.YELLOW}» Saving last sync date') # Gets date of last webinar sync last_webinar_sync = api.eloqua_asset_get( naming[source_country]['id']['webinar_sync'], 'sharedContent', depth='complete') # Build shared content data for updating the last sync date data = { 'id': last_webinar_sync.get('id'), 'name': last_webinar_sync.get('name'), 'contentHTML': current_sync } # Updating last sync date to shared content api.eloqua_put_sharedcontent(naming[source_country]['id']['webinar_sync'], data=data) print(f'\n{SUCCESS}External Activities uploaded to Eloqua!') return
def redirect_lp(): ''' Allows user to add redirecting script to all landing pages belonging to completed campaigns ''' # Gets redirect base URL redirect_link = naming[source_country]['id']['redirect'] # Doublecheck if user is sure he wants to continue choice = '' while choice.lower() != 'y' and choice.lower() != 'n': print( f'\n{Fore.YELLOW}» {Fore.WHITE}Continue with redirecting ' f'all WK{source_country} completed campaign LPs to:' f'\n {Fore.YELLOW}{redirect_link}{Fore.WHITE}? ({YES}/{NO}):', end=' ') choice = input('') if choice.lower() == 'y': break elif choice.lower() == 'n': return False # Gets list of already redirected or no-LP campaigns redirected_campaigns_shared_list = api.eloqua_asset_get( naming[source_country]['id']['redirected_list'], 'sharedContent', depth='complete') old_redirected_campaigns = redirected_campaigns_shared_list['contentHtml'] old_redirected_campaigns = old_redirected_campaigns.split(',') # Write modifier outcome to csv file with open(file('outcome-csv', f'redirected-campaigns'), 'w', encoding='utf-8') as f: fieldnames = [ 'Campaign ID', 'Campaign Name', 'Landing Page ID', 'Landing Page Name', 'Redirected' ] writer = csv.writer(f) writer.writerow(fieldnames) # Gets list of completed campaigns completed_campaigns = get_completed_campaigns(old_redirected_campaigns) # Gets list of modified landing pages new_redirected_campaigns = put_modified_lp(completed_campaigns) # Creates a string with id's of all redirected campaigns (previously and now) all_redirected_campaigns = \ (',').join(old_redirected_campaigns) + new_redirected_campaigns if all_redirected_campaigns.startswith(','): # in case of no old campaigns all_redirected_campaigns = all_redirected_campaigns[1:] # Build shared content data for updating the list of redirected campaings data = { 'id': redirected_campaigns_shared_list.get('id'), 'name': redirected_campaigns_shared_list.get('name'), 'contentHTML': all_redirected_campaigns } # Updating list of redirected campaigns to shared content api.eloqua_put_sharedcontent( naming[source_country]['id']['redirected_list'], data=data) print(f'\n{SUCCESS}List of redirected campaigns saved to Outcomes folder!') return
def menu(choice=''): ''' Allows to choose ELQuent utility ''' print( f'\n{Fore.GREEN}-----------------------------------------------------------------------------' ) # Loads json file with naming convention with open(file('naming'), 'r', encoding='utf-8') as naming_file: naming = json.load(naming_file) # Builds matrix with available utils utils = { 'clean_folders': (clean_folders, f'Folder{Fore.WHITE}] Clean files in Income/Outcome folders'), 'change_links': (link.link_module, f'Link{Fore.WHITE}] Change utm_track and elqTrack codes in e-mail links' ), 'minify_code': (minifier.minifier_module, f'Minifier{Fore.WHITE}] Minify e-mail HTML code'), 'build_mail': (mail.mail_constructor, f'Mail{Fore.WHITE}] Build e-mail from package in Incomes folder'), 'page_gen': (page.page_gen, f'Page{Fore.WHITE}] Swap or Add Form to a single Landing Page'), 'campaign_gen': (campaign.campaign_module, f'Campaign{Fore.WHITE}] Build various Eloqua campaigns'), 'contacts': (database.contact_list, f'Contacts{Fore.WHITE}] Create contact upload file with correct structure' ), 'validator': (validator.validator_module, f'Validator{Fore.WHITE}] Test and validate assets and campaigns'), 'modifier': (modifier.modifier_module, f'Modifier{Fore.WHITE}] Modify multiple assets at once'), 'webinar': (webinar.webinar_module, f'Webinar{Fore.WHITE}] Upload Webinar attendees & activity'), 'cert': (cert.cert_constructor, f'Certificate{Fore.WHITE}] Create certificates and upload with contacts' ), 'report': (report.report_module, f'Report{Fore.WHITE}] Creates reports on clicks in e-mails'), 'export': (export.export_module, f'Export{Fore.WHITE}] Export and save campaign or activity data'), 'admin': (admin.admin_module, f'Admin{Fore.WHITE}] WKCORP flows') } # Access to all utils for admin if ELOQUA_USER.lower() == 'mateusz.dabrowski': available_utils = utils # Gets dict of utils available for users source country else: utils_list = COUNTRY_UTILS[SOURCE_COUNTRY] if ELOQUA_USER.lower() in naming[SOURCE_COUNTRY]['advanced_users']: utils_list.extend(COUNTRY_UTILS['ADVANCED']) elif ELOQUA_USER.lower() in naming[SOURCE_COUNTRY]['local_admin']: utils_list.extend(COUNTRY_UTILS['ADMIN']) available_utils = {k: v for (k, v) in utils.items() if k in utils_list} util_names = list(available_utils.keys()) # Date format for last sync calculations date_format = '%Y-%m-%d %H:%M' # Validate Voucher App if old last sync if SOURCE_COUNTRY == 'PL' and ELOQUA_USER.lower( ) in naming[SOURCE_COUNTRY]['local_admin']: # Gets list of already uploaded voucher campaigns validator.country_naming_setter(SOURCE_COUNTRY) uploaded_voucher_shared_list = api.eloqua_asset_get( naming[SOURCE_COUNTRY]['id']['voucher_campaigns'], 'sharedContent', depth='complete') voucher_shared_txt = uploaded_voucher_shared_list['contentHtml'] if '"' in voucher_shared_txt: voucher_shared_txt = voucher_shared_txt.replace('"', '"') if voucher_shared_txt: voucher_shared_dict = json.loads(voucher_shared_txt) sync_date = datetime.datetime.strptime(voucher_shared_dict['sync'], date_format) current_date = datetime.datetime.today() sync_delta = current_date - sync_date if sync_delta.days >= 1: validator.voucher_validation() # Gets date of last webinar sync if SOURCE_COUNTRY == 'PL' and 'webinar' in util_names: last_webinar_sync = api.eloqua_asset_get( naming[SOURCE_COUNTRY]['id']['webinar_sync'], 'sharedContent', depth='complete') last_webinar_sync = last_webinar_sync['contentHtml'] sync_date = datetime.datetime.strptime(last_webinar_sync, date_format) current_date = datetime.datetime.today() sync_delta = current_date - sync_date if sync_delta.days >= 7: print( f'\n{ERROR}{sync_delta.days} days since last upload of webinar attendees' ) elif sync_delta.days >= 3: print( f'\n{WARNING}{sync_delta.days} days since last upload of webinar attendees' ) # Lists utils available to chosen user print(f'\n{Fore.GREEN}ELQuent Utilites:') for i, function in enumerate(available_utils.values()): print( f'{Fore.WHITE}[{Fore.YELLOW}{i}{Fore.WHITE}]\t» [{Fore.YELLOW}{function[1]}' ) print( f'{Fore.WHITE}[{Fore.YELLOW}K{Fore.WHITE}]\t» [{Fore.YELLOW}Key{Fore.WHITE}] Show my Eloqua API Key' ) print( f'{Fore.WHITE}[{Fore.YELLOW}Q{Fore.WHITE}]\t» [{Fore.YELLOW}Quit{Fore.WHITE}]' ) # Asks user to choose utility while True: if not choice: print(f'{Fore.YELLOW}Enter number associated with chosen utility:', end='') choice = input(' ') if choice.lower() == 'k': print( f'\n{Fore.YELLOW}Key » {Fore.RESET}Basic {Fore.WHITE}{eloqua_key}\n' ) choice = '' continue if choice.lower() == 'q': print(f'\n{Fore.GREEN}Ahoj!') raise SystemExit try: choice = int(choice) except (TypeError, ValueError): print(f'{Fore.RED}Please enter numeric value!') choice = '' continue if 0 <= choice < len(available_utils): break else: print(f'{Fore.RED}Entered value does not belong to any utility!') choice = '' print( f'\n{Fore.GREEN}-----------------------------------------------------------------------------' ) available_utils.get(util_names[choice])[0](SOURCE_COUNTRY)