def andes_daily_load(): print("Cargando en " + str(datetime.now())) ex_api = expaApi.ExpaApi(account='*****@*****.**', fail_attempts=10) bd_api = expaApi.ExpaApi(account='*****@*****.**', fail_attempts=10) for function, kwargs in load_dict.items(): try: print( "Attempting to load all {interaction} people of the {program} program from {days} days ago in LC {officeID}" .format(**kwargs)) function(ex_api.get_past_interactions(**kwargs)) print("Success") except (expaApi.APIUnavailableException) as e: print("Failure: EXPA is not working, the API is unavailable") print(e) except api.api.transport.TransportException as e: print("Failure: PODIO transport exception") print(e) except Exception as e: print("Failure: Unknown error") print(kwargs) print(e) print("Todas las cargas han sido exitosas")
def refresh_rankings_v2(): print "Refreshing the EXPA rankings" api = expaApi.ExpaApi(account='*****@*****.**', fail_attempts=5) mcs = Office.objects.filter(office_type="MC").order_by('expaID') programs = Program.objects.all() for mc in mcs: print "Cargando datos del MC %s" % mc.name for program in programs: #Loads the performance in the given program for the given MC try: performance = api.getCountryCurrentYearStats(program.name, mc.expaID) for officeID, values in performance.iteritems(): #Recorre todas las oficinas y sus logros para el programa dado #print "Office ID: %s" % officeID #print values #Si los logros de este programa ya existen, se actualizan en la base de datos. Si no existen (sucede cuando algún comité del mundo acaba de abrir un nuevo programa) se crean unos nuevos suboffices_loaded = False # This keeps track on whether suboffices have already been loaded at least once. If that's the case, then empty LCs will be ignored. try: logros, created = LogrosPrograma.objects.update_or_create(program=program, office_id=officeID, defaults=values) except IntegrityError as e: #Esto quiere decir que probablemente intentó cargar un LC que todavía no existe. Esto pasa cuando se crean nuevos LCs desde la última vez que se actualizó en ranking. print "Integrity error loading data of LC %s" % officeID print e if not suboffices_loaded: try: load_suboffices(mc.expaID, "LC", api) logros, created = LogrosPrograma.objects.update_or_create(program=program, office_id=officeID, defaults=values) except IntegrityError as e2: print "Error al intentar cargar los logros después de cargar las suboficinas. Probablemente el LC ya no existe. Ignorando..." print e2 except expaApi.APIUnavailableException as e: print "Error de EXPA cargando el país actual, continuando..." break
def loadWorldPerformance(): """ Loads the performance of all LCs of the world. """ api = expaApi.ExpaApi() for region in Region.objects.all(): loadRegionPerformance(region.expaID, api)
def update_country_applications(): p_api = api.PodioApi(19156174) bd_api = expaApi.ExpaApi(account='*****@*****.**', fail_attempts=10) apps = bd_api.get_interactions(interaction='applied', start_date='01-03-2018', end_date='17-03-2018', officeID=2010, program='ogx') update_dict = {} print(len(apps)) for app in apps['items']: # add app expa_id to update_dict person_id = app['person']['id'] try: models.Office.objects.get( expa_id=app['opportunity']['office']['parent_id']) if person_id in update_dict: update_dict[person_id] += 1 else: update_dict[person_id] = 1 except models.Office.DoesNotExist: continue #now it updates the PODIO field for country partner applications in all items for expa_id, applications in update_dict.iteritems(): # Search for the person by using the PODIO search function search = p_api.search_in_application_v2(app_id=19156174, ref_type='item', query=expa_id) item_id = search['results'][0]['id'] p_api.updateItem(item_id, {167580470: applications})
def load_monthly_stats(): print "Refreshing the monthly goals" api = expaApi.ExpaApi() mcs = Office.objects.filter(office_type="MC", expaID=1551) programs = Program.objects.all() current_year, end_month = datetime.today().strftime('%Y-%m').split('-') for mes in range(1, int(end_month)): for mc in mcs: print "Cargando datos del MC %s" % mc.name for program in programs: start_date = '%s-%s-01' % (current_year, mes) end_date = '%s-%s-%s' % (current_year, mes, calendar.monthrange(int(current_year), mes)[1]) print "Cargando %s, entre %s y %s" % (program.name, start_date, end_date) #Loads the performance in the given program for the given MC performance = api.getCountryStats(program.name, mc.expaID, start_date, end_date) for officeID, values in performance.iteritems(): #Recorre todas las oficinas y sus logros para el programa dado #print "Office ID: %s" % officeID #print values #Si los logros de este programa ya existen, se actualizan en la base de datos. Si no existen (sucede cuando algún comité del mundo acaba de abrir un nuevo programa) se crean unos nuevos try: logros, created = MonthlyAchievement.objects.update_or_create(program=program, office_id=officeID, month=mes, defaults=values) except IntegrityError as e: #Esto quiere decir que probablemente intentó cargar un LC que todavía no existe. Esto pasa cuando se crean nuevos LCs desde la última vez que se actualizó en ranking. print "Un nuevo LC ha sido agregado. Cargando..." try: load_suboffices(mc.expaID, "LC", api) logros, created = MonthlyAchievement.objects.update_or_create(program=program, office_id=officeID, month=mes, defaults=values) except IntegrityError as e: print "Double integrity error, aborting current cycle"
def count_ge_gt(days, office_id): api = expaApi.ExpaApi('*****@*****.**') ans = {} for application in applications: lc_name = application['person']['home_lc']['name'] try: lc = ans[lc_name] except KeyError as e: ans[lc_name] = {'GT': 0, 'GE': 0} lc = ans[lc_name]
def loadLCs(mc): api = expaApi.ExpaApi() lcs = api.getSuboffices(mc) for lc in lcs: item = LC(nombre=lc['name'], expaID=lc['id'], mc=MC.objects.get(expaID=mc)) try: item.save() except IntegrityError as e: print e item.nombre += '_' + item.mc.nombre print item.nombre
def super_sync_ogx_finished(start_date): kwargs = { 'interaction': 'finished', 'start_date': start_date, 'officeID': 2010, 'program': 'ogx' } bd_api = expaApi.ExpaApi(account='*****@*****.**', fail_attempts=10) sync_bangladesh_ogx_finished(bd_api.get_interactions(**kwargs), ex_api=bd_api)
def malaysia_daily_load(): print("Cargando en " + str(datetime.now())) ex_api = expaApi.ExpaApi(fail_attempts=10) try: malaysia_opens = ex_api.get_past_interactions('registered', 1, 1611, today=False, filters={'filters[has_managers]':False}) send_malaysia_opens_emails(malaysia_opens) print("Los correos a los LCs han sido enviados exitosamente") except (expaApi.APIUnavailableException) as e: print("Error de EXPA cargando a los EPs aprobados de OGX") print(e) # except Exception as e: # print("Unknown error") # print(e) print("Todas las cargas han sido exitosas")
def get_context_data(self, **kwargs): api = expaApi.ExpaApi() context = super(GetMatchableEPs, self).get_context_data(**kwargs) try: office_name = self.kwargs['office_name'] except KeyError: office_name = 'ANDES' office = Office.objects.get(name=office_name.replace('_', ' ')) officeID = office.expaID context['office_name'] = office_name eps = api.get_matchable_EPs(officeID)['eps'] print eps print "TEST" eps = tools.set_program(eps) context['personas'] = eps context['header'] = 'AIESEC %s EP Search Tool' % office_name return context
def get_context_data(self, **kwargs): api = expaApi.ExpaApi() context = super(GetUncontactedEPs, self).get_context_data(**kwargs) try: office_name = self.kwargs['office_name'] except KeyError: office_name = 'ANDES' context['office_name'] = office_name office = Office.objects.select_related( 'superoffice', 'superoffice__superoffice').get(name=office_name.replace('_', ' ')) officeID = office.expaID eps = api.getUncontactedEPs(officeID)['eps'] eps = tools.set_program(eps) context['personas'] = eps context['header'] = 'Uncontacted EPs' return context
def send_partners_email(): ex_api = expaApi.ExpaApi(account='*****@*****.**') email = mailApi.MailApi("partners_analytics_mail") country_partners = [ {'id':1609, 'name': 'Egypt'}, {'id':1539, 'name': 'Indonesia'}, {'id':1585, 'name': 'India'}, {'id':1623, 'name': 'Sri Lanka'}, {'id':112, 'name': 'Nepal'}, {'id':1607, 'name': 'Thailand'}, {'id':1622, 'name': 'Turkey'}, {'id':1611, 'name': 'Malaysia'}, ] results = {} for partner in country_partners: #results[partner['name']] = ex_api.e3e_analytics(2010, partner['id'], 'ogv', '2018-04-01') #results[partner['name']] = ex_api.e2e_analytics(2010, partner['id'], 'ogv', '2017-08-01') results[partner['name']] = ex_api.e2e_analytics(2010, partner['id'], 'ogv', '2016-08-01', '2017-07-31') email.send_mail('*****@*****.**', ['*****@*****.**'], {'results': results})
def get_context_data(self, **kwargs): api = expaApi.ExpaApi() context = super(ContactedRanking, self).get_context_data(**kwargs) try: office_name = self.kwargs['office_name'] except KeyError: office_name = 'ANDES' context['office_name'] = office_name office = Office.objects.select_related( 'superoffice', 'superoffice__superoffice').get(name=office_name.replace('_', ' ')) officeID = office.expaID cnt_eps = api.get_past_interactions('contacted', 0, officeID, today=True) eps = tools.count_contacted(cnt_eps) context['personas'] = eps context['header'] = 'Conteo de contactados por persona en AIESEC Andes' return context
def get_context_data(self, **kwargs): api = expaApi.ExpaApi() context = super(CountApplications, self).get_context_data(**kwargs) try: office_name = self.kwargs['office_name'] except KeyError: office_name = 'ANDES' context['office_name'] = office_name office = Office.objects.select_related( 'superoffice', 'superoffice__superoffice').get(name=office_name.replace('_', ' ')) officeID = office.expaID applications = api.get_past_interactions('applied', 7, officeID, today=True) eps = tools.count_applications(applications) context['personas'] = eps context[ 'header'] = 'Aplicaciones a oportunidades en AIESEC %s' % office_name return context
def load_country_EBs(expaID): api = expaApi.ExpaApi() eb_data = api.getCountryEBs(expaID) mc_object = Office.objects.get(expaID) print "Cargando MC %s " % mc_object.name for lc in eb_data: lc_object = Office.objects.get(expaID=lc['expaID']) print "Cargando EBs de %s " % lc_object.name for cargo in lc['cargos']: try: member = Member(office_id=lc['expaID'], expaID=cargo['expaID'], name=cargo['name'], role=cargo['cargo'], phone=cargo['contactData'].get('phone'), email=cargo['contactData'].get('email'), alt_email=cargo['contactData'].get('altMail'), facebook=cargo['contactData'].get('facebook')) member.save() except Exception as e: print cargo print e
def fix_skipped_day(date): kwargs = { 'interaction': 'registered', 'start_date': date, 'officeID': 2010, 'program': 'ogx', 'end_date': date } bd_api = expaApi.ExpaApi(account='*****@*****.**', fail_attempts=10) kwargs['interaction'] = 'applied' load_bangladesh_ogx_applied(bd_api.get_interactions(**kwargs), ex_api=bd_api) kwargs['interaction'] = 'accepted' load_bangladesh_ogx_accepted(bd_api.get_interactions(**kwargs), ex_api=bd_api) kwargs['interaction'] = 'approved' load_bangladesh_ogx_approved(bd_api.get_interactions(**kwargs), ex_api=bd_api) kwargs['interaction'] = 'realized' load_bangladesh_ogx_realized(bd_api.get_interactions(**kwargs), ex_api=bd_api)
def get_context_data(self, **kwargs): api = expaApi.ExpaApi() context = super(GetEPs, self).get_context_data(**kwargs) try: office_name = self.kwargs['office_name'] except KeyError: office_name = 'ANDES' context['office_name'] = office_name office = Office.objects.select_related( 'superoffice', 'superoffice__superoffice').get(name=office_name.replace('_', ' ')) officeID = office.expaID start_date = '%s-%s-01' % (self.kwargs['year'], self.kwargs['month']) end_date = '%s-%s-%s' % (self.kwargs['year'], self.kwargs['month'], calendar.monthrange( int(self.kwargs['year']), int(self.kwargs['month']))[1]) context['applications'] = api.get_interactions( self.kwargs['interaction'], officeID, self.kwargs['program'], start_date, end_date)['items'] context['header'] = '%s EPs' % self.kwargs['interaction'] return context
def load_companies(): api = expaApi.ExpaApi(user="******", pwd="cr2rx6tS") api.token = "6036e590449213a850e9a5ac6e71e64524847d547de530fc1fe1f90ddf7cc05a" companies = api.get_companies(officeID=1589, program=None, start_date="2017-03-05", end_date="2017-03-13") for company in companies["items"]: print(company) data = json.dumps({ "type": "", "industry": "", "assignedUserId": "58c5d30f838d2e363", "assignedUserName": "******", "name": company["name"], "emailAddressData": [{ "emailAddress": "", "primary": True, "optOut": False, "invalid": False, "lower": "" }], "emailAddress": "", "phoneNumberData": [{ "phoneNumber": "", "primary": True, "type": "Office" }], "phoneNumber": "", "website": company["url"], "billingAddressPostalCode": "", "billingAddressStreet": "", "billingAddressState": "", "billingAddressCity": "", "billingAddressCountry": "", "shippingAddressPostalCode": "", "shippingAddressStreet": "", "shippingAddressState": "", "shippingAddressCity": "", "shippingAddressCountry": "", "sicCode": "", "description": "", "teamsIds": [], "teamsNames": {} }) print(data) r = requests.post( "http://104.197.179.91/espocrm/api/v1/Account", data=data, verify=False, headers={ "Authorization": "Basic Y2FtaWxvLmZvcmVyb0BhaWVzZWMubmV0OjUyYjMyNDE5OTAwY2U4MTk1MGEyNzIwZDdjNDM5NTQy", "Content-Type": "application/json" })
def load_regions_v2(): AI = Office.objects.update_or_create(name='AIESEC INTERNATIONAL', expaID=1626, office_type='AI', superoffice_id=None) api = expaApi.ExpaApi() load_suboffices(1626, 'Region', api)
def loadMCs(regionID): api = expaApi.ExpaApi() mcs = api.getMCs(regionID) for mc in mcs: item = MC(nombre=mc['name'], expaID=mc['id'], region=Region.objects.get(expaID=regionID)) item.save()
def lda_score_updater(): p_api = api.PodioApi(19600457) bd_api = expaApi.ExpaApi(account='*****@*****.**', fail_attempts=10) items = p_api.get_filtered_items({}, no_html=True) podio_dict = { 'Self Aware': { 'score': 161812900, 'subqualities': 161818453 }, 'Solution Oriented': { 'score': 161812901, 'subqualities': 161818454 }, 'World Citizen': { 'score': 161812902, 'subqualities': 161818455 }, 'Empowering Others': { 'score': 161812903, 'subqualities': 161818456 }, } for item in items: ldm_data = bd_api.lda_report(item['values'][157141794]['value'], 'person_id') for result_set in ldm_data: if result_set['opportunity_application_id'] == int( item['values'][157141793]['value']): #print(result['results']) for result in result_set['results']: if result[ 'ldm_response_type'] == 'initial': # Checks that it gets the initial LDM result, instead of the final or the AIESEC impact one print('success') params = {} for key in result.keys(): if key in podio_dict: params[podio_dict[key] ['score']] = result[key]['score'] description = "" for subresult in result[key]['sub_scores']: description2 = "" score = 0 for measurement in subresult[ 'measurements']: description2 += ( measurement['result'] + ' - ') score += int(measurement['score']) element_total = subresult[ 'sub_quality'] + ': Total score: ' + str( score ) + ". Description: " + description2 + "<br/>" description += element_total print(description) params[podio_dict[key] ['subqualities']] = description print(params) p_api.updateItem(item['item'], params) break break else: print(result['opportunity_application_id']) print(item['values'][157141793]['value'])
def loadRegions(): api = expaApi.ExpaApi() regions = api.getRegions() for region in regions: rgn = Region(nombre=region['name'], expaID=region['id']) rgn.save()