def Setup(self): self.mailer.setDisplayName("MakeICT Events") self.mailer.setFromAddress("*****@*****.**") self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) self.processed_filename = "followup_processed.txt"
def Setup(self): self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) self.processed_filename = "followup_processed.txt" self.discourse_api = DiscourseClient( self.config.get('discourse_api', 'site'), api_username=self.config.get('discourse_api', 'username'), api_key=self.config.get('discourse_api', 'key')) self.member_levels = [ 'Monthly', '6 months', '12 months', "Scholarship (monthly)", "Scholarship (6 months)", "Scholarship (12 months)" ] self.group_name = 'MakeICT_Members' self.member_group_id = \ self.discourse_api._get("/groups/{0}.json".format(self.group_name))['group']['id']
class ChildScript(Script): def Setup(self): self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) self.processed_filename = "followup_processed.txt" def Run(self): cutoff_date = self.WA_API.DateTimeToWADate(datetime.now() - timedelta(days=180)) inactive_contacts = self.WA_API.GetFilteredContacts( "'Profile+last+updated'+le+%s+and+'Last+login+date'+le+%s+and+'Membership+level+ID'+eq+813239" % (cutoff_date, cutoff_date)) for contact in inactive_contacts: print(contact, '\n') ids = [contact['Id'] for contact in inactive_contacts] print(ids) for id in ids: try: self.WA_API.UpdateContactField(int(id), "Archived", True) except Exception as e: print("issue with user id:", id) print(e)
class ChildScript(Script): def SendSurveys(self): processed_ids = self.ReadProcessedIDs() print(processed_ids) start_date = (datetime.now() - timedelta(days=7)).replace(hour=0, minute=0, second=0) end_date = (datetime.now() - timedelta(days=1)).replace(hour=23, minute=59, second=59) print(start_date.strftime("%Y-%m-%dT%H:%M:%S%z")) print(end_date.strftime("%Y-%m-%dT%H:%M:%S%z")) events = self.WA_API.GetEventsByDate( start_date.strftime("%Y-%m-%dT%H:%M:%S%z"), end_date.strftime("%Y-%m-%dT%H:%M:%S%z")) for event in events: encoded_name = urllib.parse.quote_plus(event["Name"]) survey_link = "https://docs.google.com/forms/d/e/1FAIpQLSew_pFQ26mvqMUUWUHFsVZHWikXuAsuupSNVmhJv3kvYxHbDw/viewform?entry.1220350320=%s" % ( encoded_name) attended_registrants = self.WA_API.GetRegistrantsByEventID( event["Id"], checked_in=True) template = open(self.config.get('files', 'classSurveyRequest'), 'r') reg_info = [] for r in attended_registrants: flattened_reg_fields = { field["SystemCode"]: field["Value"] for field in r['RegistrationFields'] } flattened_reg_fields['Id'] = r['Id'] print(r['Id']) reg_info.append(flattened_reg_fields) for reg in reg_info: if not reg['Email']: print("Email is missing from registration!") continue if reg['Id'] in processed_ids: print("This registration has already been processed!") continue # for field in reg: # print(field, reg[field]) print(reg['Email']) replacements = { 'FirstName': reg['FirstName'], 'EventName': event['Name'].strip(), 'SurveyLink': survey_link, # 'EventDate':event['Startdate'].strftime(self.time_format_string), } self.mailer.SendTemplate(reg['Email'], template, replacements, test=self.config.getboolean( "script", "debug")) self.WriteProcessedID(reg['Id']) print(event["Name"]) print(survey_link) def WriteProcessedID(self, id): with open(self.processed_filename, 'a') as f: f.write(str(id) + '\n') def ReadProcessedIDs(self): with open(self.processed_filename, 'r') as f: id_list = [int(line.rstrip('\n')) for line in f] return id_list def Setup(self): self.mailer.setDisplayName("MakeICT Events") self.mailer.setFromAddress("*****@*****.**") self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) self.processed_filename = "followup_processed.txt" def Run(self): self.SendSurveys()
import logging, time, traceback, os, sys from datetime import datetime, date from datetime import timedelta from dateutil import tz import urllib import configparser #import MySQLdb # from WildApricotAPI.WildApricotAPI import WaApiClient from wildapricot_api import WaApiClient from mailer import MailBot #from Database import Database #os.chdir(config.get('files', 'installDirectory')) WA_API = WaApiClient() tzlocal = tz.gettz('CST') class PayCalc(): def __init__(self, api_key): self.options = {"API_key": api_key} while (not WA_API.ConnectAPI(self.options["API_key"])): time.sleep(5) script_start_time = datetime.now() #db = Database() #current_db = db.GetAll() #for entry in current_db:
import logging, time, traceback, os, sys from datetime import datetime from datetime import timedelta from dateutil import tz import urllib import configparser #import MySQLdb from wildapricot_api import WaApiClient from mailer import MailBot #from Database import Database #os.chdir(config.get('files', 'installDirectory')) WA_API = WaApiClient() tzlocal = tz.gettz('CST') class AuthConv(): def __init__(self, api_key): self.options = {"API_key": api_key} while (not WA_API.ConnectAPI(self.options["API_key"])): time.sleep(5) self.working_file_name = 'unprocessed_id_list.txt' def SendEmail(self, to_address, template, replacements): template.seek(0) t = template.read().format(**replacements) subject = t.split('----')[0]
class ChildScript(Script): def Setup(self): self.mailer.setDisplayName("MakeICT Events") self.mailer.setFromAddress("*****@*****.**") self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) # def CheckPendingPayment(self, registration): # for field in registration["RegistrationFields"]: # if field["FieldName"] == "StorageBinNumber": # if field["Value"] == "PendingPayment": # return True # return False def FilterClassesWithNoCheckinVolunteer(self, events): if events == False: return False no_checkin_events = [] for event in events: no_checkin_volunteer = True if event["Tags"]: for tag in event["Tags"]: split_tag = tag.split(':') if split_tag[0] == 'checkin': no_checkin_volunteer = False #print(event) if no_checkin_volunteer: no_checkin_events.append(event) print(event['Name'].strip() + " has no checkin volunteer.") return no_checkin_events def SendWaiverReminders(self, events): unwaivered_registrants = [] for event in events: registrants = self.WA_API.GetRegistrantsByEventID(event['Id']) if registrants == False: return False # print(event) print('\n' + event["Name"].strip() + "(" + event["StartDate"] + ")" + ": " + str(event["PendingRegistrationsCount"])) for registrant in registrants: print(registrant['Contact']['Name']) def GetSubField(object, field, subfield): try: list_comp = [ f["Value"] for f in object[field] if f["FieldName"] == subfield ] print(list_comp) return list_comp[0] except IndexError: print("Field '%s' Not Found" % subfield) def GetRegistrationField(registration, field): return GetSubField(registration, "RegistrationFields", field) if not GetRegistrationField( registrant, "WaiverDate") and not GetRegistrationField( registrant, "WaiverLink"): contact = self.WA_API.GetContactById( registrant['Contact']['Id']) def GetContactField(contact, field): return GetSubField(contact, "FieldValues", field) if not GetContactField( contact, "WaiverDate") and not GetContactField( contact, "WaiverLink"): unwaivered_registrants.append(registrant) #print(registrant['RegistrationFields']) #print (registrant) for ur in unwaivered_registrants: registrantEmail = [ field['Value'] for field in ur['RegistrationFields'] if field['SystemCode'] == 'Email' ] registration_date = self.WA_API.WADateToDateTime( ur['RegistrationDate']) event_start_date = self.WA_API.WADateToDateTime( ur['Event']['StartDate']) time_before_class = event_start_date - datetime.now(self.tzlocal) registration_time_before_class = event_start_date - registration_date time_since_registration = datetime.now( self.tzlocal) - registration_date split_name = ur['Contact']['Name'].split(',') registrant_first_name = split_name[1].strip() registrant_last_name = split_name[0].strip() toEmail = registrantEmail template = open(self.config.get('files', 'waiverReminder'), 'r') replacements = { "FirstName": ur['Contact']['Name'].split(',')[1], "EventName": ur['Event']['Name'].strip(), "EventDate": event_start_date.strftime(self.time_format_string), "UserID": ur['Contact']['Id'], } template.seek(0) subject = template.read().format(**replacements).split('----')[0] success = self.mailer.SendTemplate( toEmail, template, replacements, self.config.getboolean("script", "debug")) # Set registration's WaiverDate Field so that we don't spam the registrant with requests for field in ur["RegistrationFields"]: if field["FieldName"] == "WaiverDate": field["Value"] = "WaiverRequested" self.WA_API._make_api_request( 'https://api.wildapricot.org/v2.1/accounts/84576/EventRegistrations/%d' % (ur['Id']), ur, method="PUT") print("Send waiver reminder email to %s:%d\n" % (ur['Contact']['Name'], ur['Contact']['Id'])) self.db.AddLogEntry( ur['Event']['Name'].strip(), registrant_first_name + ' ' + registrant_last_name, registrantEmail[0], action="Send email with subject `%s`" % (subject.strip())) def ProcessUnpaidRegistrants(self, events): unpaid_registrants = [] for event in events: if event["PendingRegistrationsCount"] > 0: registrants = self.WA_API.GetRegistrantsByEventID(event['Id']) if registrants == False: return False #print(event) #print(event["Name"].strip() + "(" + event["StartDate"] + ")" + ": " + str(event["PendingRegistrationsCount"])) for registrant in registrants: #print(registrant['PaidSum']) if registrant['PaidSum'] != registrant['RegistrationFee']: unpaid_registrants.append(registrant) #print(registrant['RegistrationFields']) #print (registrant) #print ("lost fees: " + str(total_lost_fees)) #return unpaid_registrants for ur in unpaid_registrants: registrantEmail = [ field['Value'] for field in ur['RegistrationFields'] if field['SystemCode'] == 'Email' ] registration_date = self.WA_API.WADateToDateTime( ur['RegistrationDate']) event_start_date = self.WA_API.WADateToDateTime( ur['Event']['StartDate']) time_before_class = event_start_date - datetime.now(self.tzlocal) registration_time_before_class = event_start_date - registration_date time_since_registration = datetime.now( self.tzlocal) - registration_date split_name = ur['Contact']['Name'].split(',') registrant_first_name = split_name[1].strip() registrant_last_name = split_name[0].strip() if registration_time_before_class > (self.unpaid_cutoff + self.unpaid_buffer): drop_date = event_start_date - self.unpaid_cutoff elif registration_time_before_class > self.unpaid_buffer: drop_date = registration_date + self.unpaid_buffer else: drop_date = event_start_date - self.noshow_drop toEmail = registrantEmail needs_email = False delete_registration = False db_entry = self.db.GetEntryByRegistrationID(ur['Id']) if not db_entry: new_registration = True else: new_registration = False if not self.WA_API.CheckPendingPayment(ur): if (time_since_registration > self.nag_buffer): if new_registration: if (registration_date < self.enforcement_date): template = open( self.config.get('files', 'pre-warningTemplate'), 'r') else: template = open( self.config.get('files', 'warningTemplate'), 'r') needs_email = True elif time_since_registration > self.unpaid_buffer: if time_before_class < self.unpaid_cutoff: if (registration_date > self.enforcement_date): template = open( self.config.get('files', 'cancellationTemplate'), 'r') needs_email = True delete_registration = True if needs_email: replacements = { "FirstName": ur['Contact']['Name'].split(',')[1], "EventName": ur['Event']['Name'].strip(), "EventDate": event_start_date.strftime(self.time_format_string), "UnpaidDropDate": drop_date.strftime(self.time_format_string), "EnforcementDate": self.enforcement_date.strftime('%B %d, %Y'), "CancellationWindow": self.unpaid_cutoff.days } template.seek(0) subject = template.read().format( **replacements).split('----')[0] success = self.mailer.SendTemplate( toEmail, template, replacements, self.config.getboolean("script", "debug")) # perform actions indicated in email if new_registration: print("Sent nag email to %s:%d\n" % (ur['Contact']['Name'], ur['Contact']['Id'])) self.db.AddEntry(registrant_first_name, registrant_last_name, registrantEmail[0], ur['Contact']['Id'], ur['Id']) self.db.AddLogEntry( ur['Event']['Name'].strip(), registrant_first_name + ' ' + registrant_last_name, registrantEmail[0], action= "Add unpaid registration to nag database.") self.db.SetFirstNagSent(ur['Id']) elif delete_registration: print('Deleting registration %d and notifying %s' % (ur['Id'], ur['Contact']['Name'])) if (not self.config.getboolean("script", "debug")): self.WA_API.DeleteRegistration(ur['Id']) self.db.AddLogEntry(ur['Event']['Name'].strip(), ur['Contact']['Name'], registrantEmail[0], action="Delete registration") self.db.SetRegistrationDeleted(ur['Id']) self.db.AddLogEntry( ur['Event']['Name'].strip(), registrant_first_name + ' ' + registrant_last_name, registrantEmail[0], action="Send email with subject `%s`" % (subject.strip())) def SendEventReminders(self, events): if events: for event in events: event_start_date = self.WA_API.WADateToDateTime( event['StartDate']) time_before_class = event_start_date - datetime.now( self.tzlocal) if not self.db.GetEntryByEventID(event['Id']): print("event '%s' not in database" % event['Name'].strip()) for tag in event['Tags']: split_tag = tag.split(':') if split_tag[0] == 'instructor_name': instructor_name = ' '.join(split_tag[1:]) elif split_tag[0] == 'instructor_email': instructor_email = ' '.join(split_tag[1:]) if (instructor_email): template = open( self.config.get('files', 'classConfirmation'), 'r') replacements = { 'FirstName': instructor_name.split()[0], 'EventName': event['Name'].strip(), 'EventDate': event_start_date.strftime(self.time_format_string), } self.mailer.SendTemplate( instructor_email, template, replacements, self.config.getboolean("script", "debug")) self.db.AddLogEntry( event['Name'].strip(), instructor_name, instructor_email, action="Send class confirmation email") self.db.AddEventToDB(event['Id']) self.db.AddLogEntry(event['Name'].strip(), None, None, action="Add event `%s` to database" % (event['Name'].strip())) index = 1 for r in self.reminders_days: needs_email = False if time_before_class < r: if index == 1: if not self.db.GetFirstEventNagSent( event['Id'] ) and time_before_class > self.reminders_days[ index]: print("send first event reminder email for " + event['Name'].strip()) self.db.SetFirstEventNagSent(event['Id']) template = open( self.config.get('files', 'eventReminder'), 'r') needs_email = True if index == 2: if not self.db.GetSecondEventNagSent( event['Id'] ) and time_before_class > self.reminders_days[ index]: print("send second event reminder email for " + event['Name'].strip()) self.db.SetSecondEventNagSent(event['Id']) template = open( self.config.get('files', 'eventReminder'), 'r') needs_email = True if index == 3: if not self.db.GetThirdEventNagSent(event['Id']): print("send third event reminder email for " + event['Name']) self.db.SetThirdEventNagSent(event['Id']) template = open( self.config.get('files', 'eventReminder'), 'r') needs_email = True if needs_email: registrants = self.WA_API.GetRegistrantsByEventID( event['Id']) if registrants: for r in registrants: registrantEmail = [ field['Value'] for field in r['RegistrationFields'] if field['SystemCode'] == 'Email' ] registration_date = self.WA_API.WADateToDateTime( r['RegistrationDate']) registration_time_before_class = event_start_date - registration_date time_since_registration = datetime.now( self.tzlocal) - registration_date registrant_first_name = r['Contact'][ 'Name'].split(',')[1] registrant_last_name = r['Contact'][ 'Name'].split(',')[0] toEmail = registrantEmail replacements = { 'FirstName': registrant_first_name, 'EventName': event['Name'].strip(), 'EventDate': event_start_date.strftime( self.time_format_string), 'ReminderNumber': index } self.mailer.SendTemplate( toEmail, template, replacements, self.config.getboolean("script", "debug")) self.db.AddLogEntry( event['Name'].strip(), registrant_first_name + ' ' + registrant_last_name, registrantEmail[0], action="Send event reminder email") else: print("Failed to get registrant list") index += 1 def ProcessEventsWithNoCheckinVolunteer(self, events): filtered_events = self.FilterClassesWithNoCheckinVolunteer(events) for event in filtered_events: pass def Run(self): self.tzlocal = tz.gettz('CST') self.db = Database(self.config.get('database', 'name'), self.config.get('database', 'username'), self.config.get('database', 'password')) #current_db = self.db.GetAll() # for entry in current_db: # print (entry) # print(self.config.items('api')) # print(self.config.items('thresholds')) self.time_format_string = '%B %d, %Y at %I:%M%p' self.unpaid_cutoff = timedelta( days=self.config.getint('thresholds', 'unpaidCutOff')) self.unpaid_buffer = timedelta( hours=self.config.getint('thresholds', 'unpaidBuffer')) self.noshow_drop = timedelta( minutes=self.config.getint('thresholds', 'noShowDrop')) # self.poll_interval = self.config.getint('api','pollInterval') self.nag_buffer = timedelta( minutes=self.config.getint('thresholds', 'nagBuffer')) self.enforcement_date = datetime.strptime( self.config.get('thresholds', 'enforcementDate'), '%m-%d-%y %z') self.reminders = len( self.config.get('thresholds', 'reminderDays').split(',')) self.reminders_days = [] for r in self.config.get('thresholds', 'reminderDays').split(','): self.reminders_days.append(timedelta(days=int(r))) self.mailer.setDisplayName(self.config.get('email', 'displayName')) self.mailer.setAdminAddress(self.config.get('email', 'adminAddress')) api_call_failures = 0 upcoming_events = self.WA_API.GetUpcomingEvents() if upcoming_events == False: api_call_failures += 1 print("API call Failures: %d" % (api_call_failures)) else: self.ProcessUnpaidRegistrants(upcoming_events) self.SendWaiverReminders(upcoming_events) self.SendEventReminders(upcoming_events)
class ChildScript(Script): def Setup(self): self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) self.processed_filename = "followup_processed.txt" self.discourse_api = DiscourseClient( self.config.get('discourse_api', 'site'), api_username=self.config.get('discourse_api', 'username'), api_key=self.config.get('discourse_api', 'key')) self.member_levels = [ 'Monthly', '6 months', '12 months', "Scholarship (monthly)", "Scholarship (6 months)", "Scholarship (12 months)" ] self.group_name = 'MakeICT_Members' self.member_group_id = \ self.discourse_api._get("/groups/{0}.json".format(self.group_name))['group']['id'] def SyncUser(self, d_user, wa_contacts): # print(self.discourse_api.user_emails(d_user['user']['username'])) print(d_user['username'], ':', d_user['emails'], ':', [c['Email'] for c in wa_contacts]) is_member = False is_active = False # assert wa_contacts['Email'] in d_user['user']['emails'] for contact in wa_contacts: try: is_member = contact['MembershipLevel'][ 'Name'] in self.member_levels except KeyError: print("No WA membership level found") try: is_active = contact['Status'] == 'Active' and contact[ 'MembershipEnabled'] except KeyError: print("WA contact is not active") # If an active WildApricot account is found, stop looking and sync if is_member and is_active: break if is_member and is_active: print("User is an active member, adding user to group") try: if d_user['primary_group_id'] == self.member_group_id: print("User is already in group") return else: print("User is not in group") except KeyError: print("User has no primary group") try: self.discourse_api.add_group_member(self.member_group_id, d_user['username']) except DiscourseClientError: print("Failed to add user to group") else: print("user is not an active member") if (self.member_group_id == d_user['primary_group_id']): print("removing user from group") self.discourse_api.delete_group_member(self.member_group_id, d_user['id']) else: print("user is not in group") def SyncUsers(self, disc_users, wa_users): for u in disc_users: # if u['user']['username'] != '': # continue u = self.discourse_api.user_all(u['user']['id']) emails = self.discourse_api.user_emails(u['username']) email_list = [emails['email']] email_list += emails['secondary_emails'] u['emails'] = email_list found_contacts = [] for contact in wa_users: if contact['Email'] in u['emails']: print("Found WA user for %s" % contact['Email']) found_contacts.append(contact) self.SyncUser(u, found_contacts) time.sleep(2) def SyncAllUsers(self): response = self.discourse_api._get( '/directory_items.json?period=all&order=post_count') discourse_users = response['directory_items'] while response['meta']['total_rows_directory_items'] > len( discourse_users): response = self.discourse_api._get( response['meta']['load_more_directory_items']) discourse_users += response['directory_items'] print(response['meta']['total_rows_directory_items']) print(len(discourse_users)) wa_contacts = self.WA_API.GetAllContacts() self.SyncUsers(discourse_users, wa_contacts) def SyncNewUsers(self): discourse_users = self.discourse_api.list_users("new") wa_contacts = self.WA_API.GetAllContacts() self.SyncUsers(discourse_users, wa_contacts) def Run(self): self.SyncAllUsers()
script_start_time = datetime.now() #db = Database() #current_db = db.GetAll() #for entry in current_db: # print (entry) config = configparser.SafeConfigParser() config.read('config.ini') print(config.items('api')) print(config.items('thresholds')) MCP_API = McpApiClient(config.get('mcp_api', 'server')) MCP_API.authenticate_with_contact_credentials( config.get('mcp_api', 'username'), config.get('mcp_api', 'password')) WA_API = WaApiClient() tzlocal = tz.gettz('CST') time_format_string = '%B %d, %Y at %I:%M%p' unpaid_cutoff = timedelta(days=config.getint('thresholds', 'unpaidCutOff')) unpaid_buffer = timedelta(hours=config.getint('thresholds', 'unpaidBuffer')) noshow_drop = timedelta(minutes=config.getint('thresholds', 'noShowDrop')) poll_interval = config.getint('api', 'pollInterval') nag_buffer = timedelta(minutes=config.getint('thresholds', 'nagBuffer')) enforcement_date = datetime.strptime( config.get('thresholds', 'enforcementDate'), '%m-%d-%y %z') reminders = len(config.get('thresholds', 'reminderDays').split(',')) reminders_days = [] #for r in config.get('thresholds', 'reminderDays').split(','): # reminders_days.append(timedelta(days=int(r)))
def Setup(self): self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5)
class ChildScript(Script): def Setup(self): self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) def SetWaiverDate(self, contact_ID, date): self.WA_API.UpdateContactField(contact_ID, 'WaiverDate', date) def SetDOB(self, contact_ID, date): self.WA_API.UpdateContactField(contact_ID, 'DOB', date) def GetWaiverlessMembers(self): contacts = self.WA_API.GetAllContacts() waiverless_members = [] for contact in contacts: flattened_contact_fields = { field["SystemCode"]: field["Value"] for field in contact['FieldValues'] } if flattened_contact_fields["IsMember"]: if flattened_contact_fields["MembershipLevelId"] != 813239: # check for oldWaiverLink, Waiverlink, and WaiverDate field, respectively # if not flattened_contact_fields["custom-7903153"]: if flattened_contact_fields["custom-7973495"].strip( ) == '' and flattened_contact_fields[ "custom-9876059"].strip() == '': waiverless_members.append(contact) for member in waiverless_members: print(member['FirstName'], member['LastName']) print(len(waiverless_members)) def Run(self): # self.GetWaiverlessMembers() # assert 1==2, "math fail!" script_start_time = datetime.now() time_format_string = '%B %d, %Y at %I:%M%p' sw = smartwaiver.Smartwaiver(self.config.get('smartwaiver', 'api_key')) # templates = sw.get_waiver_templates() # for template in templates: # print(template.template_id + ': ' + template.title) # Get a list of recent signed waivers for this account summaries = sw.get_waiver_summaries(100) for summary in summaries: print("====================================") print(summary.waiver_id + ': ' + summary.title) WA_ID = None print(summary.first_name, summary.last_name) for tag in summary.tags: if tag.split(' ')[0] == 'WA_ID': WA_ID = int(tag.split(' ')[1]) sw_fails = 0 while (1): try: waiver = sw.get_waiver(summary.waiver_id, True) break except (smartwaiver.exceptions.SmartwaiverHTTPException, smartwaiver.exceptions.SmartwaiverSDKException): print("Smartwaiver Error") sw_fails += 1 if sw_fails > 3: raise else: time.sleep(5) continue contact = None if not WA_ID and summary.is_minor: print("Skipping untagged minor waiver") continue else: while (1): try: #Pull contact's info from WA if it exists if WA_ID: contact = self.WA_API.GetContactById(WA_ID) else: contact = self.WA_API.GetContactByEmail( waiver.email)[0] WA_ID = contact['Id'] break #print(contact) #If query returns no contact except IndexError: print("Contact does not exist") break except TypeError: print("Failed to connect to WA") time.sleep(60) continue if not contact: continue #If waiver date is not newer than what is currently on the WA profile, don't update saved_waiver_date = [ field['Value'] for field in contact['FieldValues'] if field['FieldName'] == "WaiverDate" ][0] print(contact['Email']) print("saved waiver date:", saved_waiver_date) print("summary created_on date:", summary.created_on) if saved_waiver_date and saved_waiver_date.strip() != '': print("Has waiver date") if datetime.strptime(saved_waiver_date, "%Y-%m-%d %H:%M:%S") >= datetime.strptime( summary.created_on, "%Y-%m-%d %H:%M:%S"): continue #update WA account waiver date with the current waiver's date print('.' + summary.dob + '.') waiver_DOB = datetime.strptime(summary.dob, "%Y-%m-%d") WA_DOB = waiver_DOB.strftime("%d %b %Y") #print(WA_DOB) #print(WA_ID, ":", waiver_date) #print(waiver_DOB) #print(type(WA_ID)) #print(type(waiver_date)) self.SetWaiverDate(WA_ID, summary.created_on) time.sleep(3) self.SetDOB(WA_ID, summary.dob)
def Setup(self): self.WA_API = WaApiClient() while (not self.WA_API.ConnectAPI(self.config.get('api', 'key'))): time.sleep(5) self.processed_filename = "followup_processed.txt"