def render_dynamic(self, context): # dynamic if context.main_section and ("<!-- render-jinja -->" in context.main_section) \ or ("{{" in context.main_section): try: context["main_section"] = render_template(context.main_section, context) context["no_cache"] = 1 except TemplateSyntaxError: pass
def render_dynamic(self, context): # dynamic is_jinja = "<!-- jinja -->" in context.main_section if is_jinja or ("{{" in context.main_section): try: context["main_section"] = render_template(context.main_section, context) if not "<!-- static -->" in context.main_section: context["no_cache"] = 1 except TemplateSyntaxError: if is_jinja: raise
def get_name_from_naming_series(self): """ Get a name generated for a Batch from the Batch's naming series. :return: The string that was generated. """ naming_series_prefix = _get_batch_prefix() # validate_template(naming_series_prefix) naming_series_prefix = render_template(str(naming_series_prefix), self.__dict__) key = _make_naming_series_key(naming_series_prefix) name = make_autoname(key) return name
def send_auto_reply(self, communication, email): """Send auto reply if set.""" if self.enable_auto_reply: set_incoming_outgoing_accounts(communication) frappe.sendmail(recipients = [email.from_email], sender = self.email_id, reply_to = communication.incoming_email_account, subject = _("Re: ") + communication.subject, content = render_template(self.auto_reply_message or "", communication.as_dict()) or \ frappe.get_template("templates/emails/auto_reply.html").render(communication.as_dict()), reference_doctype = communication.reference_doctype, reference_name = communication.reference_name, in_reply_to = email.mail.get("Message-Id"), # send back the Message-Id as In-Reply-To unsubscribe_message = _("Leave this conversation"))
def send_auto_reply(self, communication, email): """Send auto reply if set.""" if self.enable_auto_reply: communication.set_incoming_outgoing_accounts() frappe.sendmail( recipients=[email.from_email], sender=self.email_id, reply_to=communication.incoming_email_account, subject=_("Re: ") + communication.subject, content=render_template(self.auto_reply_message or "", communication.as_dict()) or frappe.get_template("templates/emails/auto_reply.html").render(communication.as_dict()), reference_doctype=communication.reference_doctype, reference_name=communication.reference_name, message_id=communication.name, bulk=True, )
def irs_1099_print(filters): if not filters: frappe._dict({ "company": frappe.db.get_default("Company"), "fiscal_year": frappe.db.get_default("Fiscal Year") }) else: filters = frappe._dict(json.loads(filters)) fiscal_year_doc = get_fiscal_year(fiscal_year=filters.fiscal_year, as_dict=True) fiscal_year = cstr(fiscal_year_doc.year_start_date.year) company_address = get_payer_address_html(filters.company) company_tin = frappe.db.get_value("Company", filters.company, "tax_id") columns, data = execute(filters) template = frappe.get_doc("Print Format", "IRS 1099 Form").html output = PdfFileWriter() for row in data: row["fiscal_year"] = fiscal_year row["company"] = filters.company row["company_tin"] = company_tin row["payer_street_address"] = company_address row["recipient_street_address"], row[ "recipient_city_state"] = get_street_address_html( "Supplier", row.supplier) row["payments"] = fmt_money(row["payments"], precision=0, currency="USD") pdf = get_pdf(render_template(template, row), output=output if output else None) frappe.local.response.filename = "{0} {1} IRS 1099 Forms{2}".format( filters.fiscal_year, filters.company, IRS_1099_FORMS_FILE_EXTENSION) frappe.local.response.filecontent = read_multi_pdf(output) frappe.local.response.type = "download"
def get_print_content(print_format, doctype, docname, is_escpos=False, is_raw=False): if is_escpos or is_raw: doc = frappe.get_doc(doctype, docname) template = frappe.db.get_value("Print Format", print_format, "html") content = render_template(template, {"doc": doc}) if is_escpos: content.replace("<br>", "<br/>") else: content = frappe.get_print(doctype, docname, print_format) if is_escpos: printer = IOPrinter() printer.receipt(content) raw = printer.get_content() elif is_raw: raw = content else: raw = get_pdf(content) #frappe.msgprint("<pre>%s</pre>" %raw) raw_encoded = raw.encode() return b64encode(raw_encoded)
def generate_contract_terms_display(contract, method): if contract.contract_terms: contract.contract_terms_display = render_template( contract.contract_terms, {"doc": contract.as_dict()})
def make_variant_description(variant, template=None): #Matière première en {{Wood Species}}, {{Wood Grad}},{{Wood Width}} #Raw material, {{Wood Species}}, {{Wood Grad}},{{Wood Width}} # {u'Wood Width': u'2-5/8"' #, u'Wood Grade': u'Colonial - (GRADE-CN)' #, u'Wood Species': u'Pine' #, u'Thickness': u'4/4'} if print_debug: frappe.logger().debug("variant : " + cstr(variant.name)) if variant.variant_of is not None: template = template or frappe.get_doc("Item", variant.variant_of) variant.set('language', []) for template in template.language: jinjaTemplate = template.description values = {} if print_debug: frappe.logger().debug("template.language : " + template.language) """ Passe chaque attribut du variant. Va chercher le document Item attribute de l'attribut Remplace les noms d'attributs de la desccription jinja par le field_name de l'attribut Atribut les paramètres de traduction """ for d in variant.attributes: attribute = frappe.get_doc("Item Attribute", d.attribute) jinjaTemplate = jinjaTemplate.replace( "{{" + d.attribute, "{{" + attribute.field_name) target_field = "target_name" source_field = "source_name" template_language = template.language if template.language == "en": target_field = "source_name" source_field = "target_name" template_language = "fr" filters = { 'language_code': template_language, source_field: d.attribute_value } target_name = frappe.db.get_value("Translation", filters, target_field, None, False, False, False) values[attribute.field_name] = target_name or d.attribute_value #values[d.attribute] = target_name or d.attribute_value if print_debug: frappe.logger().debug("jinjaTemplate : " + jinjaTemplate) if print_debug: frappe.logger().debug("values : " + cstr(values)) if print_debug: frappe.logger().debug("jinjaTemplate : " + jinjaTemplate) if print_debug: frappe.logger().debug("values : " + cstr(values)) description = render_template(jinjaTemplate, values) if print_debug: frappe.logger().debug("description : " + description) filters = { "parent": variant.name, "parentfield": "language", "parenttype": "Item", "language": template.language } #name = frappe.db.get_value("Item Language", filters,"name",None,False,False,False) #if print_debug and name: frappe.logger().debug("name : " + name) language_description = None # if print_debug and name: frappe.logger().debug("language_description : " ) # for d in self.language: # if d.language = template.language # d.db_set('description', description, update_modified = False) # if name: # if print_debug: frappe.logger().debug("if name" + name) # if print_debug: frappe.logger().debug("description : " + description) # #language_description = frappe.get_doc("Item Language", name) # frappe.db.set_value("Item Language", name, "description", description) # else: #if print_debug: frappe.logger().debug("Else : " ) values = filters values["doctype"] = "Item Language" language_description = frappe.get_doc(values) language_description.description = description variant.append("language", language_description)
def generate_contract_terms_display(self): if self.contract_terms: self.contract_terms_display = render_template( self.contract_terms, {"doc": self.as_dict()})
def render_dynamic(self, context): # dynamic if context.main_section and "<!-- render-jinja -->" in context.main_section: context["main_section"] = render_template(context.main_section, {"doc": self, "frappe": frappe}) context["no_cache"] = 1
def run_testcase(self, testcase, test_suite, testcase_srno, total_testcases, suite_srno, total_suites, run_name): try: start_time = time.time() function_result = None # Populate generic test result fields test_result_doc = frappe.new_doc("Test Result") test_result_doc.test_run_name = run_name test_result_doc.test_suite = test_suite test_result_doc.action = "Test Case" testcase_doc = frappe.get_doc("Test Case", testcase) testcase_doc.testcase_type = testcase_doc.testcase_type.upper() test_result_doc.test_case = testcase_doc.name test_result_doc.test_data_id = testcase_doc.test_data test_result_doc.test_case_status = "Passed" test_result_doc.test_case_execution = "Executed" # test result fields ended print("Update function execution") print("Update function:" + test_result_doc.test_case) print( "\033[0;36;96m>> ({suite_srno}/{total_suites}) {testcase}:{testcase_type} [{testcase_srno}/{total_testcases}] :" .format(suite_srno=str(suite_srno), total_suites=str(total_suites), testcase=str(testcase), testcase_type=testcase_doc.testcase_type, testcase_srno=str(testcase_srno), total_testcases=str(total_testcases))) testdata_generator = TestDataGenerator() # Test Data record doc if testcase_doc.test_data: testdata_doc = frappe.get_doc("Test Data", testcase_doc.test_data) # cannot use insert scripts in test case data generation as doctype.name will not be recorded if (testdata_doc.use_script == 1): test_result_doc.test_case_execution = "Execution Failed" test_result_doc.execution_result = "The test data - " + testdata_doc.name + \ " selected is genereted using script for which record name cannot be recorded" test_result_doc.test_case_status = "Failed" # check if test case is create and test data already created then recreate the data testdata_doc_test_record_name = frappe.db.get_value( 'Test Run Log', { 'test_run_name': run_name, 'test_data': testcase_doc.test_data }, 'test_record') if (testdata_doc_test_record_name and testcase_doc.testcase_type == "CREATE"): testdata_doc_test_record_name = None create_test_run_log(run_name, testcase_doc.test_data, None) # get record document new_record_doc = testdata_generator.create_testdata( testcase_doc.test_data, run_name) error_message = None if (testcase_doc.testcase_type == "CREATE"): try: if new_record_doc: try: new_record_doc.save() testdata_doc_test_record_name = new_record_doc.name create_test_run_log(run_name, testcase_doc.test_data, new_record_doc.name) testdata_generator.set_record_name_child_table( new_record_doc, testdata_doc, True, run_name) print("\033[0;33;93m >>> Test Data created") except frappe.DuplicateEntryError as e: new_record_doc = resolve_duplicate_entry_error( e, testdata_doc, run_name) testdata_doc_test_record_name = new_record_doc.name create_test_run_log(run_name, testcase_doc.test_data, new_record_doc.name) testdata_generator.set_record_name_child_table( new_record_doc, testdata_doc, True, run_name) print("\033[0;33;93m >>> Test Data created") else: frappe.throw( 'Test Data {test_data} generated None doc. Please check Test Data {test_data}' .format(test_data=testcase_doc.test_data)) except Exception as e: frappe.log_error(frappe.get_traceback(), ('barista-CREATE-' + testcase_doc.name + '-' + str(e))[:error_log_title_len]) error_message = str(e) print('\033[0;31;91m Error occurred ---', str(e)) elif (testcase_doc.testcase_type == "UPDATE"): try: print("Update function execution") create_new = False if testcase_doc.testcase_doctype != testdata_doc.doctype_name: value_from_test_record_doc = frappe.db.get_value( testdata_doc.doctype_name, testdata_doc_test_record_name, testcase_doc.test_data_docfield) all_existing_docs = frappe.get_all( testcase_doc.testcase_doctype, filters={ testcase_doc.test_case_docfield: value_from_test_record_doc }) if len(all_existing_docs) == 1: existing_doc_name = all_existing_docs[0]['name'] new_record_doc = frappe.get_doc( testcase_doc.testcase_doctype, existing_doc_name) else: test_result_doc.test_case_execution = "Execution Failed" test_result_doc.execution_result = "The Test Case DocType - {testcase_doctype} with reference field {test_case_docfield} value {testdata_doc_test_record_name} records found {all_existing_docs}".format( testcase_doctype=testcase_doc.testcase_doctype, test_case_docfield=testcase_doc. test_case_docfield, testdata_doc_test_record_name= testdata_doc_test_record_name, all_existing_docs=str(len(all_existing_docs))) test_result_doc.test_case_status = "Failed" frappe.throw(test_result_doc.execution_result) # create the record if already not created if (new_record_doc and new_record_doc.name == None): try: new_record_doc.save() except frappe.UniqueValidationError as e: new_record_doc = resolve_unique_validation_error( e, testdata_doc, run_name) testdata_doc_test_record_name = new_record_doc.name create_test_run_log(run_name, testdata_doc.name, new_record_doc.name) # now take the fields to be updated update_fields = frappe.get_list( "Testdatafield", filters={"parent": testcase_doc.name}) fields = frappe.get_meta( testcase_doc.testcase_doctype).fields for update_field in update_fields: update_field_doc = frappe.get_doc( "Testdatafield", update_field['name']) for field in fields: if field.fieldname == update_field_doc.docfield_fieldname: field_doc = field break print("Field Name:" + update_field_doc.docfield_fieldname) if update_field_doc.docfield_fieldname == "name": new_name = update_field_doc.docfield_value print("Field Value:" + new_name) if update_field_doc.docfield_code_value == "Code": new_name = eval(update_field_doc.docfield_code) rd.rename_doc(update_field_doc.doctype_name, testdata_doc_test_record_name, new_name, force=True) testdata_doc_test_record_name = new_name new_record_doc = frappe.get_doc( update_field_doc.doctype_name, new_name) create_test_run_log(run_name, testdata_doc.name, new_record_doc.name) elif new_record_doc and update_field_doc.docfield_fieldname == "docstatus": new_record_doc.set( update_field_doc.docfield_fieldname, int(update_field_doc.docfield_value)) elif new_record_doc: if (field_doc.fieldtype == "Table"): # if it is table then user will have to add multiple rows for multiple records. # each test data field will link to one record. child_testdata_doc = frappe.get_doc( "Test Data", update_field_doc.linkfield_name) if (child_testdata_doc.doctype_type == "Transaction"): create_new = True child_doc = testdata_generator.create_testdata( update_field_doc.linkfield_name, run_name) child_doc.parentfield = field_doc.fieldname child_doc.parenttype = testcase_doc.testcase_doctype new_record_doc.append(field_doc.fieldname, child_doc) elif (field_doc.fieldtype in ["Link", "Dynamic Link"] and update_field_doc.docfield_code_value == "Fixed Value"): new_record_doc.set( field_doc.fieldname, update_field_doc.docfield_value) elif (field_doc.fieldtype in ["Link", "Dynamic Link"]): child_testdata_doc = frappe.get_doc( 'Test Data', update_field_doc.linkfield_name) if (child_testdata_doc.doctype_type == "Transaction"): create_test_run_log( run_name, child_testdata_doc.name, None) child_doc = testdata_generator.create_testdata( update_field_doc.linkfield_name, run_name) try: if child_doc: child_doc.save() else: frappe.throw( "Child Doc is None. Test Data of Child {linkfield_name}. Test Data of Parent {name}" .format( linkfield_name=update_field_doc .linkfield_name, name=testdata_doc.name)) except frappe.DuplicateEntryError as e: child_doc = resolve_duplicate_entry_error( e, child_testdata_doc, run_name) except frappe.UniqueValidationError as e: child_doc = resolve_unique_validation_error( e, child_testdata_doc, run_name) child_testdata_doc_test_record_name = child_doc.name create_test_run_log(run_name, child_testdata_doc.name, child_doc.name) new_record_doc.set(field_doc.fieldname, child_doc.name) # for rest of data type.. either it should be code or fixed value elif (update_field_doc.docfield_code_value == "Code"): if update_field_doc.docfield_code and not update_field_doc.linkfield_name: new_record_doc.set( field_doc.fieldname, eval(update_field_doc.docfield_code)) if not update_field_doc.docfield_code and update_field_doc.linkfield_name: value = frappe.db.get_value( 'Test Run Log', { 'test_run_name': run_name, 'test_data': update_field_doc.linkfield_name }, 'test_record') new_record_doc.set(field_doc.fieldname, value) elif new_record_doc: new_record_doc.set( update_field_doc.docfield_fieldname, update_field_doc.docfield_value) try: if new_record_doc: new_record_doc.save() print("\033[0;33;93m >>> Test Data updated") else: frappe.throw( "Test Data {name} generated None doc. Please check Test Data {test_data}" .format(name=testdata_doc.name, test_data=testcase_doc.test_data)) except frappe.UniqueValidationError as e: new_record_doc = resolve_unique_validation_error( e, testdata_doc, run_name) except Exception as e: frappe.log_error(frappe.get_traceback(), ('barista-UPDATE-' + testcase_doc.name + '-' + str(e))[:error_log_title_len]) error_message = str(e) print('\033[0;31;91m Error occurred ---', str(e)) testdata_generator.set_record_name_child_table( new_record_doc, testcase_doc, create_new, run_name) elif (testcase_doc.testcase_type == "READ"): pass elif (testcase_doc.testcase_type == "DELETE"): try: record_doc = frappe.get_doc(testdata_doc.doctype_name, testdata_doc_test_record_name) record_doc.delete() except Exception as e: frappe.log_error(frappe.get_traceback(), ('barista-' + testcase_doc.name + '-DELETE-' + str(e))[:error_log_title_len]) error_message = str(e) print("\033[0;31;91m >>> Error in deleting - " + str(e)) elif (testcase_doc.testcase_type == "WORKFLOW"): try: start_time = time.time() current_workflow_state = None if (new_record_doc and new_record_doc.name == None): current_workflow_state = new_record_doc.workflow_state try: new_record_doc = new_record_doc.save() except frappe.UniqueValidationError as e: new_record_doc = resolve_unique_validation_error( e, testdata_doc, run_name) testdata_doc_test_record_name = new_record_doc.name create_test_run_log(run_name, testdata_doc.name, new_record_doc.name) apply_workflow(new_record_doc, testcase_doc.workflow_state) print("\033[0;32;92m >>> Workflow Applied") except Exception as e: frappe.log_error( frappe.get_traceback(), ("""barista-WORKFLOW-{testcase_doc.name}-{str( e)}-DocType-[{doctype_name}]-WorkflowState-[{current_workflow_state}]-Action-[{workflow_state}]""" .format(name=testcase_doc.name, current_workflow_state=current_workflow_state, doctype_name=testdata_doc.doctype_name, workflow_state=testcase_doc.workflow_state) )[:error_log_title_len]) error_message = str(e) print( "\033[0;31;91m >>> Error in applying Workflow - " + str(e)) elif (testcase_doc.testcase_type == "FUNCTION"): kwargs = {} error_message = "" try: for param in testcase_doc.function_parameters: parameter = param.parameter print("------1-----") print(parameter) if param.value and param.value.strip()[0] in [ '{', '[' ]: value = eval(param.value) else: value = param.value kwargs[parameter] = value print("------2-----") print(kwargs) if param.test_data: test_record_name = frappe.db.get_value( 'Test Run Log', { 'test_run_name': run_name, 'test_data': param.test_data }, 'test_record') print("-----3------") print(test_record_name) test_record_doctype = frappe.db.get_value( 'Test Data', param.test_data, 'doctype_name') print("-----4------") print(test_record_doctype) test_record_doc = frappe.get_doc( test_record_doctype, test_record_name) print("-----5------") print(test_record_doc) if param.is_object == 1: kwargs[parameter] = test_record_doc.as_dict() else: kwargs[parameter] = test_record_doc.get( param.field) print("-----6------") print(kwargs) print("\033[0;33;93m >>> Executing Function --", testcase_doc.function_name) if testcase_doc.json_parameter and testcase_doc.json_parameter.strip( ) != '': context_dict = {} resolved_jinja = ' ' if testcase_doc.testcase_doctype and testcase_doc.test_data: test_record_name = frappe.db.get_value( 'Test Run Log', { 'test_run_name': run_name, 'test_data': testcase_doc.test_data }, 'test_record') context = frappe.get_doc( testcase_doc.testcase_doctype, test_record_name).as_dict() context_dict = {"doc": context} try: validate_template(testcase_doc.json_parameter) resolved_jinja = render_template( testcase_doc.json_parameter, context_dict) except Exception as e: print( "\033[0;31;91m >>>> Error in Json Parameter\n ", str(e)) kwargs.update(eval(str(resolved_jinja))) method = testcase_doc.function_name if method and '.' in method: print("------method------") args = [] function_result = frappe.get_attr(method)(*args, **kwargs) print("\033>>>>") print("\033" + str(function_result)) else: test_data_record_name = frappe.db.get_value( 'Test Run Log', { 'test_run_name': run_name, 'test_data': testcase_doc.test_data }, 'test_record') test_record_doc = frappe.get_doc( testcase_doc.testcase_doctype, test_data_record_name) function_result = test_record_doc.run_method( method, **kwargs) print("\033>>>>") print("\033" + str(function_result)) print("\033[0;32;92m >>> Function Executed") except Exception as e: frappe.log_error(frappe.get_traceback(), ('barista-FUNCTION-' + testcase_doc.name + '-' + str(e))[:error_log_title_len]) error_message = str(e) print( "\033[0;31;91m >>>> Execution of function failed\n Error occurred :", str(e)) test_result_doc.execution_time = get_execution_time(start_time) assertions = frappe.get_list("Assertion", filters={'parent': testcase}) if len(assertions) == 0: test_result_doc.execution_result = 'Assertions are not present in the TestCase. Please add atleast one assertion.' test_result_doc.test_case_status = "Failed" test_result_doc.save() for assertion in assertions: self.process_assertion(assertion, testcase_doc, run_name, error_message, function_result, test_result_doc) except Exception as e: frappe.log_error(frappe.get_traceback(), ('barista-Critical Error-' + testcase + '-' + str(e))[:error_log_title_len]) test_result_doc.test_case_execution = "Execution Failed" test_result_doc.execution_result = str(e) test_result_doc.test_case_status = "Failed" test_result_doc.save() finally: print("\033[0;36;96m>> " + "Execution Ended \n\n") test_result_doc.save()