def run(appID, params, hook=None): """ Runs a hook. Parameters: appID: The ID of the application that called the hook params: The parameters coming from the POST data inside the hook """ template = { 'Ingles': 'englishAcceptedMail', 'Español': 'spanishAcceptedMail', } transformer = { 'title': 'name', } podioApi = api.PodioApi(appID) item = podioApi.getItem(params['item_id'], no_html=True) if item['values']['paso-entrevista'] == 'Si': data = tools.dictSwitch(item['values'], transformer) data['project_name'] = item['values']['project-you-are-applying']['values']['title'] data['tn_id'] = item['values']['project-you-are-applying']['values']['tn-id-2'] email = mailApi.MailApi(template[item['values']['project-you-are-applying']['values']['idioma-proyecto']]) status = email.send_mail('*****@*****.**', [item['values']['email'], ], data) podioApi.comment('item', params['item_id'], {'value': 'El correo ha sido enviado satisfactoriamente a ' + item['values']['email'] + ' con código ' + str(status)})
def run(appID, params, hook=None): """ Runs a hook. Parameters: appID: The ID of the application that called the hook params: The parameters coming from the POST data inside the hook """ template = { 'Ingles': 'englishMatchedMail', 'Español': 'spanishMatchedMail', } transformer = { 'nombre': 'name', } podioApi = api.PodioApi(appID) item = podioApi.getItem(params['item_id'], no_html=True) if item['values']['estado-en-expa'] == 'Match': data = tools.dictSwitch(item['values'], transformer) email = mailApi.MailApi(template[item['values']['proyecto']['values']['idioma-proyecto']]) status = email.send_mail('*****@*****.**', [item['values']['entrevista']['values']['email'], ], data) podioApi.comment('item', params['item_id'], {'value': 'El correo ha sido enviado satisfactoriamente: ' + str(status)})
def run(appID, params, hook=None): """ Runs a hook. Parameters: appID: The ID of the application that called the hook params: The parameters coming from the POST data inside the hook """ template = { 'Ingles': 'englishMatchedMail', 'Español': 'spanishMatchedMail', } transformer = { 'nombre': 'name', } podioApi = api.PodioApi(appID) item = podioApi.getItem(params['item_id'], no_html=True) if item['values']['estado-en-expa'] == 'Match': data = tools.dictSwitch(item['values'], transformer) email = mailApi.MailApi( template[item['values']['proyecto']['values']['idioma-proyecto']]) status = email.send_mail('*****@*****.**', [ item['values']['entrevista']['values']['email'], ], data) podioApi.comment( 'item', params['item_id'], { 'value': 'El correo ha sido enviado satisfactoriamente: ' + str(status) })
def run(appID, params, hook=None): transformer = { 'english-writing': 'writing', 'english-reading': 'reading', 'english-listening': 'listening', 'english-speaking': 'speaking', 'world-citizen-after': 'wc_a', 'solution-driven-before': 'sd_b', 'empowering-others-after': 'eo_a', 'horas-semanales': 'horas_semanales', 'title': 'cargo', 'world-citizen-before': 'wc_b', 'self-aware-before': 'sa_b', 'empowering-others-before': 'eo_b', 'self-aware-after': 'sa_a', 'lider': 'lider__nombre', 'main-functions': 'main_functions', 'software-knowledge': 'software_knowledge', 'specific-knowledge': 'specific_knowledge', 'kpis': 'critical_success_factors', 'job-description': 'job_description', 'solution-driven-after': 'sd_a', } podioApi = api.PodioApi(appID) item = podioApi.getItem(params['item_id'], no_html=True) data = tools.dictSwitch(item['values'], transformer) data['lider'] = item['values']['lider']['values']['title'] data['area'] = item['values']['lider']['values']['nombre-del-cargo'].replace('LCVP ', "") data['horas_semanales'] = data['horas_semanales'].split('.')[0] print data generator = documentsApi.ODTTemplate('jdTemplate.odt') if item['values']['formato-del-jd'] == 'Word': fileExtension = '.odt' jd = generator.renderODT(data) else: fileExtension = '.pdf' jd = generator.render(data) fileName = 'JD - %s' % data['cargo'] email = EmailMessage() email.subject = fileName email.body = 'Lo puedes encontrar como un archivo adjunto' email.from_email = '*****@*****.**' email.to = [item['values']['lider']['values']['correo-corporativo-aiesecandesorg'],] print email.to fileData = jd.read() #email.attach(fileName + fileExtension, fileData) #email.send() podioApi.appendFile(params['item_id'], fileName + fileExtension, fileData)
def run(appID, params, hook=None): podioApi = api.PodioApi(appID, client=True) item = podioApi.get_item(params['item_id'], external_id=False) print item transformer = { '118632836#124721552':'127894715',#Area '118632836#117701833':'119050124',#TMP, TLP o EB } new_dict = tools.dictSwitch(item['values'], {}, transformer, ignore_unknown = True) ans = podioApi.updateItem(params['item_id'], new_dict) return ans
def run(appID, params, hook=None): ans = "" podioApi = api.PodioApi(appID) item = podioApi.get_item(params['item_id'], external_id=False) hook = hook.email_document_hook conditions = hook.conditions.all() all_conditions = True for condition in conditions: ans += unicode(condition) if condition.condition_type == "=": all_conditions = all_conditions and condition.value == item['values'][condition.field_id]['value'] print item['values'][condition.field_id]['value'] print ans if all_conditions: transformer_dict = {} related_transformer_dict = {} transformers = hook.transformers.all() attachments = [] for transformer in transformers: if "#" in transformer.key: related_transformer_dict[transformer.key] = transformer.value else: transformer_dict[int(transformer.key)] = transformer.value data = tools.dictSwitch(item['values'], transformer_dict, related_transformer_dict, True) print data flat_data = tools.flatten_dict(data) if hook.document: generator = documentsApi.ODTTemplate(hook.document.name + '.odt')#TODO: esto solo sirve con odts, toca formalizarlo generated_document = generator.render(flat_data) file_name = hook.document.file_name + '.pdf' attachments.append({'filename':file_name, 'data': generated_document.read()}) generated_document.seek(0) podioApi.appendFile(params['item_id'], file_name, generated_document) if hook.email_template: print hook.email_template.pk email = mailApi.MailApi(hook.email_template.name) from_email = tools.retrieve_email(hook.from_email, item) to_email = tools.retrieve_email(hook.to_email, item) if hook.cc_email: cc_email = tools.retrieve_email(hook.cc_email, item) else: cc_email = [] print from_email print to_email status = email.send_mail(from_email, [to_email], flat_data, attachments=attachments) return status else: return ans
def run(appID, params, hook=None): """ Runs a hook. Parameters: appID: The ID of the application that called the hook params: The parameters coming from the POST data inside the hook """ template = { 'Ingles': 'englishAcceptedMail', 'Español': 'spanishAcceptedMail', } transformer = { 'title': 'name', } podioApi = api.PodioApi(appID) item = podioApi.getItem(params['item_id'], no_html=True) if item['values']['paso-entrevista'] == 'Si': data = tools.dictSwitch(item['values'], transformer) data['project_name'] = item['values']['project-you-are-applying'][ 'values']['title'] data['tn_id'] = item['values']['project-you-are-applying']['values'][ 'tn-id-2'] email = mailApi.MailApi( template[item['values']['project-you-are-applying']['values'] ['idioma-proyecto']]) status = email.send_mail('*****@*****.**', [ item['values']['email'], ], data) podioApi.comment( 'item', params['item_id'], { 'value': 'El correo ha sido enviado satisfactoriamente a ' + item['values']['email'] + ' con código ' + str(status) })
def load_lc_goals(): """ Este método carga todas las metas mensuales presentes en el espacio de PODIO asociado a esta funcionalidad """ #Un diccionario que asocia los field_ids de la aplicación con un mes month_dict = { 130505516:(1, 2016), 130505517:(2, 2016), 130505518:(3, 2016), 130505519:(4, 2016), 130505520:(5, 2016), 130505521:(6, 2016), 130505522:(7, 2016), 130505523:(8, 2016), 130505524:(9, 2016), 130505525:(10, 2016), 130505526:(11, 2016), 130505527:(12, 2016), 130652156:(1, 2017), } podioApi = api.PodioApi(16759334) items = podioApi.get_filtered_items({}) for item in items: #Se crea un diccionario que luego entra como parámetro a la creación de las metas. create_dict = { 'program_id':item['values'][130504336]['value'], #Para obtener el valor del programa del item de PODIO 'office_id':item['values'][130504335]['value']['values'][130513591]['value'], #Para obtener el ID del LC del related item "LC" } month_goals = tools.dictSwitch(item['values'], month_dict, ignore_unknown=True) #Recorre todos los meses en el diccionario y crea un objeto de tipo MonthlyGoal para cada uno de ellos for date, goals in month_goals.iteritems(): create_dict['month'] = date[0] create_dict['year'] = date[1] create_dict['defaults']= { item['values'][130507913]['value'].lower():goals['value'].split('.')[0]#Obtiene la meta, eliminando decimales, y la asigna al approved o al realized según sea el caso } print create_dict MonthlyGoal.objects.update_or_create(**create_dict)
def load_lc_goals(): """ Este método carga todas las metas mensuales presentes en el espacio de PODIO asociado a esta funcionalidad """ #Un diccionario que asocia los field_ids de la aplicación con un mes month_dict = { 139291307:(2, 2018), 139291308:(3, 2018), 139291309:(4, 2018), 139291310:(5, 2018), 139291311:(6, 2018), 139291312:(7, 2018), 139291313:(8, 2018), 139291314:(9, 2018), 139291315:(10, 2018), 139291316:(11, 2018), 139291317:(12, 2018), 139291318:(1, 2019), } podioApi = api.PodioApi(17770429) items = podioApi.get_filtered_items({}) for item in items: #Se crea un diccionario que luego entra como parámetro a la creación de las metas. create_dict = { 'program_id':item['values'][139291304]['value'], #Para obtener el valor del programa del item de PODIO 'office_id':item['values'][139291303]['value']['values'][130513591]['value'], #Para obtener el ID del LC del related item "LC" } month_goals = tools.dictSwitch(item['values'], month_dict, ignore_unknown=True) #Recorre todos los meses en el diccionario y crea un objeto de tipo MonthlyGoal para cada uno de ellos for date, goals in month_goals.iteritems(): create_dict['month'] = date[0] create_dict['year'] = date[1] create_dict['defaults']= { item['values'][139291305]['value'].lower():goals['value'].split('.')[0]#Obtiene la meta, eliminando decimales, y la asigna al approved o al realized según sea el caso } print create_dict MonthlyGoal.objects.update_or_create(**create_dict)
def email_document(item, email_document_hook, podioApi): """ This method takes a PODIO item, retrieves its data, and uses it to fill out fields inside an odt/pdf document template and/or an email. The document will be sent as an attachment of the email, if both exist. """ ans = "" hook = email_document_hook conditions = hook.conditions.all() all_conditions = True for condition in conditions: ans += unicode(condition) if condition.condition_type == "=": # Checks that the value exists. In PODIO, empty fields are not sent as part of the item, so trying to retrieve them will net an exception try: field = item['values'][condition.field_id]['value'] except KeyError: field = None # If the value is a "null" string, it is converted to a None value if condition.value == "null": value = None else: value = condition.value all_conditions = all_conditions and value == field print field print ans if all_conditions: transformer_dict = {} related_transformer_dict = {} transformers = hook.transformers.all() attachments = [] for transformer in transformers: if "#" in transformer.key: #Es un valor que está adentro de un Related Item related_transformer_dict[transformer.key] = transformer.value else: transformer_dict[int(transformer.key)] = transformer.value data = tools.dictSwitch(item['values'], transformer_dict, related_transformer_dict, True)#Crea el diccionario final, que será utilizado en los templates de los correos o de los pdfs, a partir de el item de PODIO y los distintos valores flat_data = tools.flatten_dict(data) #Para reemplazar las variables de tipo fecha for date in hook.dates.all(): #Primero se revisa si la fecha es un valor de PODIO o la fecha actual if date.field_id == "": raw_date = datetime.today() else: try: raw_date = datetime.strptime(item['values'][int(date.field_id)]['value']['start_date'], "%Y-%m-%d") except KeyError: # This happens when for some reason the date is not set, not found. Will just leave the field blank flat_data[date.variable] = "" break #TODO Debe atender dos casos: cuando es un campo normal y cuando es un campo dentro de un related item #Segundo, se corre la fecha la cantidad de días que especifica el date_manager raw_date = raw_date + timedelta(days=date.time_delta) #Tercero, se define el formato que va a tomar la fecha if date.formatting == date.INGLES: formatter = "%d of %B, %Y" elif date.formatting == date.ESPANHOL: mes = tools.MESES[int(raw_date.strftime("%m")) - 1] formatter = "%d de " + mes + ", %Y" elif date.formatting == date.DMA: formatter = "%d/%m/%Y" elif date.formatting == date.DIA: formatter = "%d" elif date.formatting == date.MES: mes = tools.MESES[int(raw_date.strftime("%m")) - 1] formatter = mes elif date.formatting == date.MONTH: formatter = "%B" elif date.formatting == date.NUM_MES: formatter = "%m" elif date.formatting == date.ANHO: formatter = "%Y" #Al final, se agrega el valor de la variable al diccionario print date.variable flat_data[date.variable] = raw_date.strftime(formatter) flat_data['fecha'] = datetime.today().strftime('%d de %%s, %Y') % tools.MESES[int(datetime.today().strftime('%m')) - 1] print flat_data status = "" final_message = "" if hook.document: print "generando documento" try: generator = documentsApi.ODTTemplate(hook.document.file_name + '.odt')#TODO: esto solo sirve con odts, toca formalizarlo generated_document = generator.render(flat_data, odt=hook.generate_odt) if hook.generate_odt: extension = '.odt' else: extension = '.pdf' file_name = Template(hook.document.generated_file_name).render(Context(flat_data)) + extension attachments.append({'filename':file_name, 'data': generated_document.read()}) generated_document.seek(0) #try: documentResponse = podioApi.appendFile(item['item'], file_name, generated_document) status += str(documentResponse) final_message += "Document created and uploaded successfully." print "documento subido exitosamente" except TemplateSyntaxError as e: print "Error con el documento, no tiene formato adecuado. Continuando con el script..." final_message += "Error when generating the document: %s. The script continued. Check it out @['Camilo Forero'](user:1707071)" % e podioApi.comment('item', item['item'], {"value":final_message}) print e return if hook.email_template: print "Iniciando el envio del correo" print hook.email_template.pk email = mailApi.MailApi(hook.email_template.name) from_email = tools.retrieve_email(hook.from_email, item) to_email = [tools.retrieve_email(hook.to_email, item)] if hook.cc_email: cc_email = tools.retrieve_email(hook.cc_email, item) else: cc_email = [] print "Enviando correo a %s desde %s" % (to_email, from_email) email_send_status = "Test mode" try: email_send_status = str(email.send_mail(from_email, to_email, flat_data, attachments=attachments)) final_message += "Email sent successfully from %s to %s" % (from_email, to_email) except Exception as e: final_message += "ERROR sending the email from %s to %s: %s. Check it out @['Camilo Forero'](user:1707071)" % (to_email, from_email, e) print e print "Status de envio: %s" % email_send_status status += email_send_status print final_message podioApi.comment('item', item['item'], {"value":final_message}) return status else: return ans