Exemplo n.º 1
0
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()
Exemplo n.º 2
0
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)