def get_document_to_index(self, item): try: item = frappe.get_doc("Item", item) title = item.item_name keywords = [item.item_group] if item.brand: keywords.append(item.brand) if item.website_image_alt: keywords.append(item.website_image_alt) if item.has_variants and item.variant_based_on == "Item Attribute": keywords = keywords + [ attr.attribute for attr in item.attributes ] if item.web_long_description: content = strip_html_tags(item.web_long_description) elif item.description: content = strip_html_tags(item.description) return frappe._dict( title=title, name=item.name, path=item.route, content=content, keywords=", ".join(keywords), ) except Exception: pass
def execute_gql_query(): query, variables, operation_name = get_query() validation_errors = validate( schema=get_schema(), document_ast=parse(query), rules=( depth_limit_validator( max_depth=cint(frappe.local.conf.get("frappe_graphql_depth_limit")) or 10 ), ) ) if validation_errors: output = frappe._dict(errors=validation_errors) else: output = execute( query=query, variables=variables, operation_name=operation_name ) frappe.clear_messages() frappe.local.response = output if len(output.get("errors", [])): frappe.db.rollback() log_error(query, variables, operation_name, output) frappe.local.response["http_status_code"] = get_max_http_status_code(output.get("errors")) errors = [] for err in output.errors: if isinstance(err, GraphQLError): err = err.formatted err['message'] = strip_html_tags(err.get("message")) errors.append(err) output.errors = errors
def get_context(context): message_context = frappe._dict() if hasattr(frappe.local, "message"): message_context["header"] = frappe.local.message_title message_context["title"] = strip_html_tags(frappe.local.message_title) message_context["message"] = frappe.local.message if hasattr(frappe.local, "message_success"): message_context["success"] = frappe.local.message_success elif frappe.local.form_dict.id: message_id = frappe.local.form_dict.id key = "message_id:{0}".format(message_id) message = frappe.cache().get_value(key, expires=True) if message: message_context.update(message.get('context', {})) if message.get('http_status_code'): frappe.local.response['http_status_code'] = message[ 'http_status_code'] if not message_context.title: message_context.title = frappe.form_dict.title if not message_context.message: message_context.message = frappe.form_dict.message return message_context
def set_read_time(self): content = self.content or self.content_html or '' if self.content_type == "Markdown": content = markdown(self.content_md) total_words = len(strip_html_tags(content).split()) self.read_time = ceil(total_words / 250)
def get_read_time(blog): content = blog.content or blog.content_html if blog.content_type == "Markdown": content = markdown(blog.content_md) total_words = len(strip_html_tags(content or "").split()) return ceil(total_words / 250)
def get_context(self, context): # this is for double precaution. usually it wont reach this code if not published if not cint(self.published): raise Exception("This blog has not been published yet!") # temp fields context.full_name = get_fullname(self.owner) context.updated = global_date_format(self.published_on) if self.blogger: context.blogger_info = frappe.get_doc("Blogger", self.blogger).as_dict() context.author = self.blogger context.content = get_html_content_based_on_type(self, 'content', self.content_type) context.description = self.blog_intro or strip_html_tags(context.content[:140]) context.metatags = { "name": self.title, "description": context.description, } image = find_first_image(context.content) if image: context.metatags["image"] = image self.load_comments(context) context.category = frappe.db.get_value("Blog Category", context.doc.blog_category, ["title", "route"], as_dict=1) context.parents = [{"name": _("Home"), "route":"/"}, {"name": "Blog", "route": "/blog"}, {"label": context.category.title, "route":context.category.route}]
def update_translations_for_source(source=None, translation_dict=None): if not (source and translation_dict): return translation_dict = json.loads(translation_dict) if is_html(source): source = strip_html_tags(source) # for existing records translation_records = frappe.db.get_values('Translation', { 'source_text': source }, ['name', 'language'], as_dict=1) for d in translation_records: if translation_dict.get(d.language, None): doc = frappe.get_doc('Translation', d.name) doc.translated_text = translation_dict.get(d.language) doc.save() # done with this lang value translation_dict.pop(d.language) else: frappe.delete_doc('Translation', d.name) # remaining values are to be inserted for lang, translated_text in translation_dict.items(): doc = frappe.new_doc('Translation') doc.language = lang doc.source_text = source doc.translated_text = translated_text doc.save() return translation_records
def validate(self): super(BlogPost, self).validate() if not self.blog_intro: content = get_html_content_based_on_type(self, 'content', self.content_type) self.blog_intro = content[:200] self.blog_intro = strip_html_tags(self.blog_intro) if self.blog_intro: self.blog_intro = self.blog_intro[:200] if not self.meta_title: self.meta_title = self.title[:60] else: self.meta_title = self.meta_title[:60] if not self.meta_description: self.meta_description = self.blog_intro[:140] else: self.meta_description = self.meta_description[:140] if self.published and not self.published_on: self.published_on = today() if self.featured: if not self.meta_image: frappe.throw(_("A featured post must have a cover image")) self.reset_featured_for_other_blogs() self.set_read_time()
def get_blog_list(doctype, txt=None, filters=None, limit_start=0, limit_page_length=20): conditions = [] if filters: if filters.by: conditions.append('t1.blogger="%s"' % frappe.db.escape(filters.by)) if filters.category: conditions.append( 't1.blog_category="%s"' % frappe.db.escape(get_blog_category(filters.category))) if txt: conditions.append('t1.content like "%{0}%"'.format( frappe.db.escape(txt))) if conditions: frappe.local.no_cache = 1 query = """\ select t1.title, t1.name, t1.blog_category, t1.parent_website_route, t1.published_on, concat(t1.parent_website_route, "/", t1.page_name) as page_name, t1.published_on as creation, ifnull(t1.blog_intro, t1.content) as content, t2.full_name, t2.avatar, t1.blogger, (select count(name) from `tabComment` where comment_doctype='Blog Post' and comment_docname=t1.name and comment_type="Comment") as comments from `tabBlog Post` t1, `tabBlogger` t2 where ifnull(t1.published,0)=1 and t1.blogger = t2.name %(condition)s order by published_on desc, name asc limit %(start)s, %(page_len)s""" % { "start": limit_start, "page_len": limit_page_length, "condition": (" and " + " and ".join(conditions)) if conditions else "" } posts = frappe.db.sql(query, as_dict=1) for post in posts: post.published = global_date_format(post.creation) post.content = strip_html_tags(post.content[:140]) if not post.comments: post.comment_text = _('No comments yet') elif post.comments == 1: post.comment_text = _('1 comment') else: post.comment_text = _('{0} comments').format(str(post.comments)) post.avatar = post.avatar or "" if (not "http:" in post.avatar or "https:" in post.avatar) and not post.avatar.startswith("/"): post.avatar = "/" + post.avatar return posts
def get_translations(source_name): if is_html(source_name): source_name = strip_html_tags(source_name) return frappe.db.get_list( 'Translation', fields=['name', 'language', 'target_name as translation'], filters={'source_name': source_name})
def get_translations(source_text): if is_html(source_text): source_text = strip_html_tags(source_text) return frappe.db.get_list( 'Translation', fields=['name', 'language', 'translated_text as translation'], filters={'source_text': source_text})
def get_blog_list(doctype, txt=None, filters=None, limit_start=0, limit_page_length=20, order_by=None): conditions = [] if filters: if filters.blogger: conditions.append('t1.blogger="%s"' % frappe.db.escape(filters.blogger)) if filters.blog_category: conditions.append('t1.blog_category="%s"' % frappe.db.escape(filters.blog_category)) if txt: conditions.append('(t1.content like "%{0}%" or t1.title like "%{0}%")'.format(frappe.db.escape(txt))) if conditions: frappe.local.no_cache = 1 query = """\ select t1.title, t1.name, t1.blog_category, t1.route, t1.published_on, t1.published_on as creation, t1.content as content, ifnull(t1.blog_intro, t1.content) as intro, t2.full_name, t2.avatar, t1.blogger, (select count(name) from `tabCommunication` where communication_type='Comment' and comment_type='Comment' and reference_doctype='Blog Post' and reference_name=t1.name) as comments from `tabBlog Post` t1, `tabBlogger` t2 where ifnull(t1.published,0)=1 and t1.blogger = t2.name %(condition)s order by published_on desc, name asc limit %(start)s, %(page_len)s""" % { "start": limit_start, "page_len": limit_page_length, "condition": (" and " + " and ".join(conditions)) if conditions else "" } posts = frappe.db.sql(query, as_dict=1) for post in posts: post.cover_image = find_first_image(post.content) post.published = global_date_format(post.creation) post.content = strip_html_tags(post.content[:340]) if not post.comments: post.comment_text = _('No comments yet') elif post.comments==1: post.comment_text = _('1 comment') else: post.comment_text = _('{0} comments').format(str(post.comments)) post.avatar = post.avatar or "" post.category = frappe.db.get_value('Blog Category', post.blog_category, ['route', 'title'], as_dict=True) if post.avatar and (not "http:" in post.avatar and not "https:" in post.avatar) and not post.avatar.startswith("/"): post.avatar = "/" + post.avatar return posts
def get_blog_list(doctype, txt=None, filters=None, limit_start=0, limit_page_length=20, order_by=None): conditions = [] if filters: if filters.blogger: conditions.append('t1.blogger=%s' % frappe.db.escape(filters.blogger)) if filters.blog_category: conditions.append('t1.blog_category=%s' % frappe.db.escape(filters.blog_category)) if txt: conditions.append('(t1.content like {0} or t1.title like {0}")'.format(frappe.db.escape('%' + txt + '%'))) if conditions: frappe.local.no_cache = 1 query = """\ select t1.title, t1.name, t1.blog_category, t1.route, t1.published_on, t1.published_on as creation, t1.content as content, ifnull(t1.blog_intro, t1.content) as intro, t2.full_name, t2.avatar, t1.blogger, (select count(name) from `tabComment` where and comment_type='Comment' and reference_doctype='Blog Post' and reference_name=t1.name) as comments from `tabBlog Post` t1, `tabBlogger` t2 where ifnull(t1.published,0)=1 and t1.blogger = t2.name %(condition)s order by published_on desc, name asc limit %(start)s, %(page_len)s""" % { "start": limit_start, "page_len": limit_page_length, "condition": (" and " + " and ".join(conditions)) if conditions else "" } posts = frappe.db.sql(query, as_dict=1) for post in posts: post.cover_image = find_first_image(post.content) post.published = global_date_format(post.creation) post.content = strip_html_tags(post.content[:340]) if not post.comments: post.comment_text = _('No comments yet') elif post.comments==1: post.comment_text = _('1 comment') else: post.comment_text = _('{0} comments').format(str(post.comments)) post.avatar = post.avatar or "" post.category = frappe.db.get_value('Blog Category', post.blog_category, ['route', 'title'], as_dict=True) if post.avatar and (not "http:" in post.avatar and not "https:" in post.avatar) and not post.avatar.startswith("/"): post.avatar = "/" + post.avatar return posts
def get_translations(source_text): if is_html(source_text): source_text = strip_html_tags(source_text) return frappe.db.get_list( "Translation", fields=["name", "language", "translated_text as translation"], filters={"source_text": source_text}, )
def get_items_to_index(self): all_docs = [] marks = frappe.get_all("Bookmark", fields=["name", "readable"]) for mark in marks: all_docs.append({ 'name': mark.name, 'title': mark.meta_title, 'content': strip_html_tags(mark.readable) }) return all_docs
def get_translations(source_name): if is_html(source_name): source_name = strip_html_tags(source_name) return frappe.db.get_list('Translation', fields = ['name', 'language', 'target_name as translation'], filters = { 'source_name': source_name } )
def get_context(context): message_context = {} if hasattr(frappe.local, "message"): message_context["header"] = frappe.local.message_title message_context["title"] = strip_html_tags(frappe.local.message_title) message_context["message"] = frappe.local.message if hasattr(frappe.local, "message_success"): message_context["success"] = frappe.local.message_success return message_context
def get_context(self, context): # this is for double precaution. usually it wont reach this code if not published if not cint(self.published): raise Exception("This blog has not been published yet!") context.no_breadcrumbs = True # temp fields context.full_name = get_fullname(self.owner) context.updated = global_date_format(self.published_on) context.social_links = self.fetch_social_links_info() context.cta = self.fetch_cta() context.enable_cta = not self.hide_cta and frappe.db.get_single_value( "Blog Settings", "show_cta_in_blog", cache=True) if self.blogger: context.blogger_info = frappe.get_doc("Blogger", self.blogger).as_dict() context.author = self.blogger context.content = get_html_content_based_on_type( self, 'content', self.content_type) #if meta description is not present, then blog intro or first 140 characters of the blog will be set as description context.description = self.meta_description or self.blog_intro or strip_html_tags( context.content[:140]) context.metatags = { "name": self.meta_title, "description": context.description, } #if meta image is not present, then first image inside the blog will be set as the meta image image = find_first_image(context.content) context.metatags["image"] = self.meta_image or image or None self.load_comments(context) self.load_feedback(context) context.category = frappe.db.get_value("Blog Category", context.doc.blog_category, ["title", "route"], as_dict=1) context.parents = [{ "name": _("Home"), "route": "/" }, { "name": "Blog", "route": "/blog" }, { "label": context.category.title, "route": context.category.route }] context.guest_allowed = True
def get_formatted_value(value, field): '''Prepare field from raw data''' from six.moves.html_parser import HTMLParser if(getattr(field, 'fieldtype', None) in ["Text", "Text Editor"]): h = HTMLParser() value = h.unescape(value) value = (re.subn(r'<[\s]*(script|style).*?</\1>(?s)', '', text_type(value))[0]) value = ' '.join(value.split()) return field.label + " : " + strip_html_tags(text_type(value))
def get_formatted_value(value, field): '''Prepare field from raw data''' from HTMLParser import HTMLParser if(getattr(field, 'fieldtype', None) in ["Text", "Text Editor"]): h = HTMLParser() value = h.unescape(value) value = (re.subn(r'<[\s]*(script|style).*?</\1>(?s)', '', unicode(value))[0]) value = ' '.join(value.split()) return field.label + " : " + strip_html_tags(unicode(value))
def get_formatted_value(value, field): """ Prepare field from raw data :param value: :param field: :return: """ if getattr(field, 'fieldtype', None) in ["Text", "Text Editor"]: value = unescape_html(frappe.safe_decode(value)) value = (re.subn(r'<[\s]*(script|style).*?</\1>(?s)', '', text_type(value))[0]) value = ' '.join(value.split()) return field.label + " : " + strip_html_tags(text_type(value))
def get_blog_list(doctype, txt=None, filters=None, limit_start=0, limit_page_length=20): conditions = [] if filters: if filters.by: conditions.append('t1.blogger="%s"' % frappe.db.escape(filters.by)) if filters.category: conditions.append('t1.blog_category="%s"' % frappe.db.escape(get_blog_category(filters.category))) if txt: conditions.append('t1.content like "%{0}%"'.format(frappe.db.escape(txt))) if conditions: frappe.local.no_cache = 1 query = """\ select t1.title, t1.name, t1.blog_category, t1.parent_website_route, t1.published_on, concat(t1.parent_website_route, "/", t1.page_name) as page_name, t1.published_on as creation, ifnull(t1.blog_intro, t1.content) as content, t2.full_name, t2.avatar, t1.blogger, (select count(name) from `tabComment` where comment_doctype='Blog Post' and comment_docname=t1.name and comment_type="Comment") as comments from `tabBlog Post` t1, `tabBlogger` t2 where ifnull(t1.published,0)=1 and t1.blogger = t2.name %(condition)s order by published_on desc, name asc limit %(start)s, %(page_len)s""" % { "start": limit_start, "page_len": limit_page_length, "condition": (" and " + " and ".join(conditions)) if conditions else "" } posts = frappe.db.sql(query, as_dict=1) for post in posts: post.published = global_date_format(post.creation) post.content = strip_html_tags(post.content[:140]) if not post.comments: post.comment_text = _('No comments yet') elif post.comments==1: post.comment_text = _('1 comment') else: post.comment_text = _('{0} comments').format(str(post.comments)) post.avatar = post.avatar or "" if (not "http:" in post.avatar or "https:" in post.avatar) and not post.avatar.startswith("/"): post.avatar = "/" + post.avatar return posts
def update_global_search(doc): '''Add values marked with `in_global_search` to `frappe.flags.update_global_search` from given doc :param doc: Document to be added to global search''' if cint(doc.meta.istable) == 1 and frappe.db.exists("DocType", doc.parenttype): d = frappe.get_doc(doc.parenttype, doc.parent) update_global_search(d) return if doc.docstatus > 1: return if frappe.flags.update_global_search==None: frappe.flags.update_global_search = [] content = [] for field in doc.meta.get_global_search_fields(): if doc.get(field.fieldname): if getattr(field, 'fieldtype', None) == "Table": # Get children for d in doc.get(field.fieldname): if d.parent == doc.name: for field in d.meta.get_global_search_fields(): if d.get(field.fieldname): content.append(field.label + "&&& " + strip_html_tags(unicode(d.get(field.fieldname)))) else: content.append(field.label + "&&& " + strip_html_tags(unicode(doc.get(field.fieldname)))) if content: published = 0 if hasattr(doc, 'is_website_published') and doc.meta.allow_guest_to_view: published = 1 if doc.is_website_published() else 0 frappe.flags.update_global_search.append( dict(doctype=doc.doctype, name=doc.name, content='|||'.join(content or ''), published=published, title=doc.get_title(), route=doc.get('route')))
def get_data(category=None,user=None,page_no=0,limit=3): """Returns processed HTML page for a standard listing.""" conditions = [] if page_no: offset = (cint(page_no) * cint(limit)) else: offset = 0 #next_start = cint(limit_start) + cint(limit_page_length) if user: conditions.append('t1.post_by="%s"' % frappe.db.escape(user)) if category: conditions.append('t1.blog_category="%s"' % frappe.db.escape(category)) limit_query = " limit %(start)s offset %(page_len)s"%{"start": limit, "page_len":offset } query = """\ select t1.title, t1.name, t1.blog_category, t1.published_on, t1.published_on as creation, ifnull(t1.intro, t1.content) as content, t2.employee_name,t1.post_by, (select count(name) from `tabComment` where comment_doctype='Discussion Topic' and comment_docname=t1.name and comment_type="Comment") as comments from `tabDiscussion Topic` t1, `tabEmployee` t2 where ifnull(t1.published,0)=1 and t1.post_by = t2.name %(condition)s order by published_on desc, name asc""" % { "condition": (" and " + " and ".join(conditions)) if conditions else "" } posts = frappe.db.sql(query+ limit_query, as_dict=1) for post in posts: post.published = global_date_format(post.creation) post.content = strip_html_tags(post.content[:140]) post.assigned = check_if_assigned(post) if not post.comments: post.comment_text = _('No comments yet') elif post.comments==1: post.comment_text = _('1 comment') else: post.comment_text = _('{0} comments').format(str(post.comments)) total_records = get_total_topics(conditions) paginate = True if total_records > limit else False total_pages = math.ceil(total_records/flt(limit)) return posts,total_pages,int(page_no)+1,paginate if posts else {}
def get_formatted_value(value, field): """ Prepare field from raw data :param value: :param field: :return: """ from six.moves.html_parser import HTMLParser if getattr(field, 'fieldtype', None) in ["Text", "Text Editor"]: h = HTMLParser() value = h.unescape(value) value = (re.subn(r'<[\s]*(script|style).*?</\1>(?s)', '', text_type(value))[0]) value = ' '.join(value.split()) return field.label + " : " + strip_html_tags(text_type(value))
def validate(self): super(BlogPost, self).validate() if not self.blog_intro: self.blog_intro = self.content[:140] self.blog_intro = strip_html_tags(self.blog_intro) if self.blog_intro: self.blog_intro = self.blog_intro[:140] if self.published and not self.published_on: self.published_on = today() # update posts frappe.db.sql("""UPDATE `tabBlogger` SET `posts`=(SELECT COUNT(*) FROM `tabBlog Post` WHERE IFNULL(`blogger`,'')=`tabBlogger`.`name`) WHERE `name`=%s""", (self.blogger,))
def validate(self): super(BlogPost, self).validate() if not self.blog_intro: self.blog_intro = self.content[:140] self.blog_intro = strip_html_tags(self.blog_intro) if self.blog_intro: self.blog_intro = self.blog_intro[:140] if self.published and not self.published_on: self.published_on = today() # update posts frappe.db.sql("""update tabBlogger set posts=(select count(*) from `tabBlog Post` where ifnull(blogger,'')=tabBlogger.name) where name=%s""", (self.blogger,))
def get_context(context): message_context = {} if hasattr(frappe.local, "message"): message_context["header"] = frappe.local.message_title message_context["title"] = strip_html_tags(frappe.local.message_title) message_context["message"] = frappe.local.message if hasattr(frappe.local, "message_success"): message_context["success"] = frappe.local.message_success elif frappe.local.form_dict.id: message_id = frappe.local.form_dict.id key = "message_id:{0}".format(message_id) message = frappe.cache().get_value(key, expires=True) if message: message_context.update(message.get('context', {})) if message.get('http_status_code'): frappe.local.response['http_status_code'] = message['http_status_code'] return message_context
def _(msg, lang=None): """Returns translated string in current lang, if exists.""" from frappe.translate import get_full_dict from frappe.utils import strip_html_tags, is_html if not hasattr(local, 'lang'): local.lang = lang or 'en' if not lang: lang = local.lang non_translated_msg = msg if is_html(msg): msg = strip_html_tags(msg) # msg should always be unicode msg = as_unicode(msg).strip() # return lang_full_dict according to lang passed parameter return get_full_dict(lang).get(msg) or non_translated_msg
def execute(filters=None): if not filters: filters = {} conditions, filters = get_conditions(filters) columns = get_columns(filters) data = [] if not conditions: return columns, data item_list,quotation = get_quotation(conditions, filters) if quotation: letter_head = frappe.db.get_value("Company", quotation.company, "default_letter_head") or "" filters["letter_head"] = letter_head row_count = 0 section_count = 0 total = 0 first_item = item_list[0] has_header = 0 has_headers = 0 count = 0 if str(first_item.item_group).lower() in ["header1","header2","header3"]: has_header = 1 for item in item_list: if count > 0 and str(item.item_group).lower() in ["header1","header2","header3"]: has_headers = 1 count = count +1 from frappe.utils import strip_html_tags item.description = strip_html_tags(item.description) if item.manufacturer_part_no: item.brand = str(item.brand) + " " + str(item.manufacturer_part_no) item.stock_uom += ' '*10 item.qty = str(item.stock_uom) + str(int(item.qty)) if item.item_group.lower() in ["header1","header2","header3"]: # New Section if section_count: if filters.get("format") == "Quotation": if filters.get("simplified"): row = ["","Total","", "","",total] else: row = ["","Total","","","","", "","",total] data.append(row) data.append([]) elif filters.get("format") == "BoqAmount": if filters.get("simplified"): row = ["","Total","", "",total] else: row = ["","Total","","","","", "",total] data.append(row) data.append([]) elif filters.get("format") == "Boq": data.append([]) row_count = 0 total = 0 section_count = section_count + 1 if not filters.get("format") == "Summary": row = ["",item.item_name, item.description,"","","", "","",""] else: row = [section_count,item.item_name, item.description,item.rate] data.append(row) else: if row_count == 0 and section_count == 0: section_count = section_count + 1 if not filters.get("format") == "Summary": row = ["","No Header for first section","","","","","","",""] data.append(row) else: row = [section_count,"No Header for first section","",""] data.append(row) total = total + item.amount if filters.get("format") == "BoqAmount": row_count = row_count + 1 if filters.get("simplified"): row = [row_count,item.item_name, item.description, item.qty,"",""] else: row = [row_count,item.item_name, item.description,item.brand,item.item_group,item.warranty_period, item.qty,"",""] data.append(row) elif not filters.get("format") == "Summary": row_count = row_count + 1 if filters.get("simplified"): row = [row_count,item.item_name, item.description, item.qty,item.rate,item.amount] else: row = [row_count,item.item_name, item.description,item.brand,item.item_group,item.warranty_period, item.qty,item.rate,item.amount] data.append(row) if filters.get("format") == "Quotation": if filters.get("simplified"): row = ["","Total","", "","",total] else: row = ["","Total","","","","", "","",total] data.append(row) data.append([]) if quotation.discount_amount: if filters.get("simplified"): row = ["","Discount Amount","", "","",quotation.discount_amount] else: row = ["","Discount Amount","","", "" ,"", "","",quotation.discount_amount] data.append(row) data.append([]) if filters.get("simplified"): row = ["","Grand Total",quotation.in_words, "","",quotation.grand_total] else: row = ["","Grand Total",quotation.in_words,"", "" ,"", "","",quotation.grand_total] data.append(row) elif filters.get("format") == "BoqAmount": if filters.get("simplified"): row = ["","Total","", "",total] else: row = ["","Total","","", "" ,"", "",total] data.append(row) data.append([]) if quotation.discount_amount: if filters.get("simplified"): row = ["","Discount Amount","", "",quotation.discount_amount] else: row = ["","Discount Amount","","", "" ,"", "",quotation.discount_amount] data.append(row) data.append([]) if filters.get("simplified"): row = ["","Grand Total",quotation.in_words, "",quotation.grand_total] else: row = ["","Grand Total",quotation.in_words,"", "" ,"", "",quotation.grand_total] data.append(row) elif filters.get("format") == "Summary": data.append([]) if quotation.discount_amount: row = ["","Discount Amount","",quotation.discount_amount] data.append(row) data.append([]) row = ["","Grand Total",quotation.in_words,quotation.grand_total] data.append(row) data.append([]) if not has_header and has_headers: msgprint(_("Your items have headers but the first item is not a header.")) return columns, data
def execute(filters=None): if not filters: filters = {} conditions, filters = get_conditions(filters) columns = get_columns(filters) data = [] if not conditions: return columns, data quotation_list = get_quotation(conditions, filters) if not quotation_list: return columns, data project = quotation_list[0]["project"] # title = quotation_list[0]["title"] # name = quotation_list[0]["name"] # row = [name,title,project,"",""] # data.append(row) quotation_names = "" for i, quotation in enumerate(quotation_list): quotation_names += str(quotation.name) if not i == len(quotation_list)-1: quotation_names += "," headers = ["header1","header2","header3"] if filters.get("format") == "Sales Order": item_list = frappe.db.sql("select item_code,item_name,description,item_group,stock_uom, SUM(qty) AS qty,brand,SUM(delivered_qty) AS delivered_qty from `tabSales Order Item` t2 where t2.parent in (%s) GROUP BY item_code", quotation_names, as_dict = 1) else: item_list = frappe.db.sql("select item_code,item_name,description,item_group,stock_uom,SUM(qty) AS qty,brand from `tabQuotation Item` t2 where t2.parent in (%s) GROUP BY item_code", quotation_names, as_dict = 1) newlist = [] for i,item in enumerate(item_list): if not item.item_group.lower() in headers: newlist.append(item) bomitems = {} for item in newlist: from frappe.utils import strip_html_tags item["description"] = strip_html_tags(item["description"]) item["description"] = item["description"][:55] + (item["description"][55:] and '..') if filters.get("bom_only") == "Without BOM": if filters.get("format") == "Sales Order": stock_details = frappe.db.sql("select actual_qty from `tabBin` where item_code = (%s)", item["item_code"], as_dict = 1) actual_qty = 0 if stock_details: actual_qty =flt(stock_details[0]) row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"], item.delivered_qty, actual_qty] else: row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"]] data.append(row) else: from erpnext.manufacturing.doctype.bom.bom import get_bom_items bom = frappe.db.get_value("BOM", filters={"item": item["item_code"], "project": project}) or frappe.db.get_value("BOM", filters={"item": item["item_code"], "is_default": 1}) frappe.errprint(bom) if bom: if filters.get("format") == "Sales Order": stock_details = frappe.db.sql("select actual_qty from `tabBin` where item_code = (%s)", item["item_code"], as_dict = 1) actual_qty = 0 if stock_details: actual_qty =flt(stock_details[0]) row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"], item.delivered_qty, actual_qty] bomitems = get_bom_items(bom, company="Al Maarifa Lab Supplies LLC",qty = item["qty"]) else: row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"]] bomitems = get_bom_items(bom, company="Al Maarifa Lab Supplies LLC",qty = item["qty"]) data.append(row) if bomitems: row = [item["item_code"] + " BOM","", "","",""] data.append(row) for b in bomitems: row = [b["item_code"],b["item_name"], b["description"],b["stock_uom"],b["qty"]] data.append(row) row = ["","", "","",""] data.append(row) return columns, data
def get_blog_context(context): context["blog_fields"] = [ "published_on", "blog_intro", "route", "title", "content", "name", "blog_category" ] context["blog_conditions"] = "" hooks = frappe.get_hooks("starter_theme_blog_context_before") for hook in hooks: frappe.call(hook, context) #posts = frappe.get_all("Blog Post", fields=context["blog_fields"], filters={"published": 1}, order_by="published_on desc, creation desc", limit=cint(context.get("theme_display_blog_length", 4))) query = """\ select %(fields)s, ifnull(t1.blog_intro, t1.content) as intro, t2.full_name, t2.avatar, t1.blogger, (select count(name) from `tabCommunication` where communication_type='Comment' and comment_type='Comment' and reference_doctype='Blog Post' and reference_name=t1.name) as comments from `tabBlog Post` t1, `tabBlogger` t2 where ifnull(t1.published,0)=1 and t1.blogger = t2.name %(condition)s order by published_on desc, t1.creation desc limit %(start)s, %(page_len)s""" % { "start": 0, "page_len": cint(context.get("theme_display_blog_length", 4)), "condition": (" and " + " and ".join(context["blog_conditions"])) if context.get("blog_conditions") else "", "fields": ",".join(["t1.%s" % field for field in context["blog_fields"]]) } posts = frappe.db.sql(query, as_dict=1) for post in posts: post.cover_image = find_first_image(post.content) post.published = global_date_format(post.creation) post.content = strip_html_tags(post.content[:340]) post.intro = post.blog_intro if post.blog_intro else post.content if not post.comments: post.comment_text = _('No comments yet') elif post.comments == 1: post.comment_text = _('1 comment') else: post.comment_text = _('{0} comments').format(str(post.comments)) post.avatar = post.avatar or "" post.category = frappe.db.get_value('Blog Category', post.blog_category, ['route', 'title'], as_dict=True) if (not "http:" in post.avatar or "https:" in post.avatar) and not post.avatar.startswith("/"): post.avatar = "/" + post.avatar context["blog_posts"] = posts hooks = frappe.get_hooks("starter_theme_blog_context_after") for hook in hooks: frappe.call(hook, context)
def execute(filters=None): if not filters: filters = {} conditions, filters = get_conditions(filters) columns = get_columns(filters) data = [] if not conditions: return columns, data item_list, quotation = get_quotation(conditions, filters) if quotation: letter_head = frappe.db.get_value("Company", quotation.company, "default_letter_head") or "" filters["letter_head"] = letter_head row_count = 0 for i, item in enumerate(item_list): from frappe.utils import strip_html_tags item.description = strip_html_tags(item.description) if item.manufacturer_part_no: item.brand = str(item.brand) + " " + str( item.manufacturer_part_no) text_uom = str(item.uom or item.stock_uom) + ' ' * 10 text_qty = str(text_uom) + str(int(item.qty)) row_count = i + 1 if filters.get("format") == "BoqAmount": if filters.get("simplified"): row = [ row_count, item.item_name, item.description, text_qty, "", item.warranty_period ] else: row = [ row_count, item.item_name, item.description, item.brand, item.item_group, text_qty, "", item.warranty_period ] data.append(row) elif filters.get("format") == "Boq": if filters.get("simplified"): row = [ row_count, item.item_name, item.description, text_qty, item.warranty_period ] else: row = [ row_count, item.item_name, item.description, item.brand, item.item_group, text_qty, item.warranty_period ] data.append(row) elif filters.get("format") == "Quotation": if filters.get("simplified"): row = [ row_count, item.item_name, item.description, text_qty, item.rate, item.amount, item.warranty_period ] else: row = [ row_count, item.item_name, item.description, item.brand, item.item_group, text_qty, item.rate, item.amount, item.warranty_period ] data.append(row) if filters.get("format") == "Quotation": if quotation.discount_amount: if filters.get("simplified"): row = [ "", "Discount", "", "", "", quotation.discount_amount ] else: row = [ "", "Discount", "", "", "", "", "", "", quotation.discount_amount ] data.append(row) if filters.get("simplified"): row = [ "", "Total", quotation.in_words, "", "", quotation.grand_total ] else: row = [ "", "Total", quotation.in_words, "", "", "", "", quotation.grand_total, "" ] data.append(row) elif filters.get("format") == "BoqAmount": if quotation.discount_amount: if filters.get("simplified"): row = ["", "Discount", "", "", quotation.discount_amount] else: row = [ "", "Discount", "", "", "", "", quotation.discount_amount, "" ] data.append(row) if filters.get("simplified"): row = [ "", "Total", quotation.in_words, quotation.grand_total, "" ] else: row = [ "", "Total", quotation.in_words, "", "", quotation.grand_total, "" ] data.append(row) data.append([]) return columns, data
def execute(filters=None): if not filters: filters = {} conditions, filters = get_conditions(filters) columns = get_columns(filters) data = [] if not conditions: return columns, data quotation_list = get_quotation(conditions, filters) project = filters["project"] row = ["","",project,"", "" ,"", "","",""] data.append(row) project_total = 0 for quotation in quotation_list: if quotation: letter_head = frappe.db.get_value("Company", quotation.company, "default_letter_head") or "" filters["letter_head"] = letter_head row = ["",quotation.title,"","", "" ,"", "","",""] data.append(row) item_list = frappe.db.sql("select item_name,description,item_group,qty,rate,amount,brand,manufacturer_part_no,warranty_period from `tabQuotation Item` t2 where t2.parent =%s order by idx", quotation.name, as_dict = 1) row_count = 0 section_count = 0 total = 0 first_item = item_list[0] has_header = 0 has_headers = 0 count = 0 if str(first_item.item_group).lower() in ["header1","header2"]: has_header = 1 for item in item_list: if count > 0 and str(item.item_group).lower() in ["header1","header2"]: has_headers = 1 count = count +1 from frappe.utils import strip_html_tags item.description = strip_html_tags(item.description) if item.manufacturer_part_no: item.brand = str(item.brand) + " " + str(item.manufacturer_part_no) if item.item_group.lower() in ["header1","header2","header3"]: # New Section if section_count: if filters.get("format") == "Quotation": row = ["","Total","","", "" ,"", "","",total] data.append(row) data.append([]) elif filters.get("format") == "Boq": data.append([]) row_count = 0 total = 0 section_count = section_count + 1 if not filters.get("format") == "Summary": row = ["",item.item_name, item.description,"","","", "","",""] else: row = [section_count,item.item_name, item.description,item.rate] data.append(row) else: if row_count == 0 and section_count == 0: section_count = section_count + 1 if not filters.get("format") == "Summary": row = ["","No Header for first section","","","","","","",""] data.append(row) else: row = [section_count,"No Header for first section","",""] data.append(row) total = total + item.amount if not filters.get("format") == "Summary": row_count = row_count + 1 row = [row_count,item.item_name, item.description,item.brand,item.item_group,item.warranty_period, item.qty,item.rate,item.amount] data.append(row) if filters.get("format") == "Quotation": row = ["","Total","","", "" ,"", "","",total] data.append(row) data.append([]) row = ["","Grand Total","","", "" ,"", "","",quotation.grand_total] data.append(row) elif filters.get("format") == "Summary": data.append([]) row = ["","Grand Total","",quotation.grand_total] data.append(row) data.append([]) project_total = project_total + quotation.grand_total if not has_header and has_headers: msgprint(_("Your items have headers but the first item is not a header.")) if filters.get("format") == "Quotation": data.append([]) row = ["","Project Total","","", "" ,"", "","",project_total] data.append(row) elif filters.get("format") == "Summary": data.append([]) row = ["","Project Total","",project_total] data.append(row) return columns, data
def get_data(filters,quotation_names): if filters.get("format") == "SO": query = 'select item_code,item_name,description,item_group,stock_uom,SUM(qty) AS qty, brand, SUM(delivered_qty) AS delivered_qty from `tabSales Order Item` where parent IN (%s) GROUP BY item_code' % quotation_names else: query = 'select item_code,item_name,description,item_group,stock_uom,SUM(qty) AS qty, brand from `tabQuotation Item` where parent IN (%s) GROUP BY item_code' % quotation_names item_list = frappe.db.sql(query, as_dict = 1) project = filters["project"] newlist = [] data = [] headers = ["header1","header2","header3"] for i,item in enumerate(item_list): if not item.item_group.lower() in headers: newlist.append(item) bomitems = {} for item in newlist: from frappe.utils import strip_html_tags item["description"] = strip_html_tags(item["description"]) item["description"] = item["description"][:55] + (item["description"][55:] and '..') if filters.get("bom_only") == "Without BOM": if filters.get("format") == "SO": stock_details = frappe.db.sql("select actual_qty from `tabBin` where item_code = (%s)", item["item_code"], as_dict = 1) actual_qty = 0 if stock_details: actual_qty =flt(stock_details[0]) row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"], item.delivered_qty, actual_qty] else: row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"]] data.append(row) else: from erpnext.manufacturing.doctype.bom.bom import get_bom_items bom = frappe.db.get_value("BOM", filters={"item": item["item_code"], "project": project}) or frappe.db.get_value("BOM", filters={"item": item["item_code"], "is_default": 1}) frappe.errprint(bom) if bom: if filters.get("format") == "SO": stock_details = frappe.db.sql("select actual_qty from `tabBin` where item_code = (%s)", item["item_code"], as_dict = 1) actual_qty = 0 if stock_details: actual_qty =flt(stock_details[0]) row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"], item.delivered_qty, actual_qty] bomitems = get_bom_items(bom, company="Al Maarifa Lab Supplies LLC",qty = item["qty"]) else: row = [item["item_code"],item["item_name"], item["description"],item["stock_uom"],item["qty"]] bomitems = get_bom_items(bom, company="Al Maarifa Lab Supplies LLC",qty = item["qty"]) data.append(row) if bomitems: row = [item["item_code"] + " BOM","", "","",""] data.append(row) for b in bomitems: row = [b["item_code"],b["item_name"], b["description"],b["stock_uom"],b["qty"]] data.append(row) row = ["","", "","",""] data.append(row) return data
def remove_html_from_source(self): self.source_text = strip_html_tags(self.source_text).strip()
def send_via_fcm(notification, doc, context): title = notification.subject if "{" in title: title = frappe.render_template(notification.subject, context) body = strip_html_tags( frappe.render_template(notification.message, context)) data = frappe.render_template(notification.fcm_data, context) # literal_eval supports dict parsing if data: try: data = ast.literal_eval(data) except Exception as e: frappe.log_error(message=frappe.get_traceback(), title=str(e)) frappe.msgprint( "Error while parsing FCM Data in Notification: {}".format( notification.name)) if not isinstance(data, dict): data = None recipients = get_fcm_recipients(notification, context) if recipients.users and len(recipients.users): for user in recipients.users: lang = frappe.get_cached_value('User', user, 'language') if isinstance(data, dict): data['lang'] = lang if isinstance(context, dict): context['lang'] = lang _body = body _title = title if notification and lang and frappe.get_cached_value( 'System Settings', 'System Settings', 'language') != lang: find_row = notification.get('language_wise_content', {'language': lang}) if find_row: if find_row[0].message: _body = strip_html_tags( frappe.render_template(find_row[0].message, context)) if find_row[0].subject: _title = frappe.render_template( find_row[0].subject, context) if '{' in find_row[ 0].subject else find_row[0].subject else: _title = _(title, lang) _body = _(body, lang) notify_via_fcm(title=_title, body=_body, data=data, users=[user]) if recipients.topics and len(recipients.topics): notify_via_fcm(title=title, body=body, data=data, topics=recipients.topics) if recipients.tokens and len(recipients.tokens): notify_via_fcm(title=title, body=body, data=data, tokens=recipients.tokens)
def execute(filters=None): if not filters: filters = {} conditions, filters = get_conditions(filters) columns = get_columns(filters) data = [] if not conditions: return columns, data quotation_list = get_quotation(conditions, filters) if not quotation_list: return columns, data project = quotation_list[0]["project"] company = quotation_list[0]["company"] # title = quotation_list[0]["title"] # name = quotation_list[0]["name"] # row = [name,title,project,"",""] # data.append(row) quotation_names = "" for i, quotation in enumerate(quotation_list): quotation_names += str(quotation.name) if not i == len(quotation_list) - 1: quotation_names += "," headers = ["header1", "header2", "header3"] doctype = filters.get("format") if doctype == "Sales Order": item_list = frappe.db.sql( "select item_code,item_name,description,item_group,stock_uom,warehouse, SUM(qty) AS qty,brand,actual_qty from `tabSales Order Item` t2 where t2.parent in (%s) GROUP BY item_code,warehouse", quotation_names, as_dict=1) elif doctype == "Quotation": item_list = frappe.db.sql( "select item_code,item_name,description,item_group,stock_uom,warehouse,SUM(qty) AS qty,brand,actual_qty from `tabQuotation Item` t2 where t2.parent in (%s) GROUP BY item_code,warehouse", quotation_names, as_dict=1) elif doctype == "Delivery Note": item_list = frappe.db.sql( "select item_code,item_name,description,item_group,stock_uom,warehouse,SUM(qty) AS qty,brand,actual_qty from `tabDelivery Note Item` t2 where t2.parent in (%s) GROUP BY item_code,warehouse", quotation_names, as_dict=1) all_bom_items = [] newlist = [] for i, item in enumerate(item_list): if not item.item_group.lower() in headers: newlist.append(item) for item in newlist: from frappe.utils import strip_html_tags item["description"] = strip_html_tags(item["description"]) item["description"] = item["description"][:55] + ( item["description"][55:] and '..') if filters.get("bom_only") == "Without BOM": actual_qty = get_actual_qty(item["item_code"]) if doctype == "Sales Order": row = [ item["item_code"], item["item_name"], item["description"], item["stock_uom"], item["qty"], actual_qty ] else: row = [ item["item_code"], item["item_name"], item["description"], item["stock_uom"], item["qty"], actual_qty ] data.append(row) elif filters.get("bom_only") == "With BOM": bom = get_default_bom(item["item_code"], project) actual_qty = get_actual_qty(item["item_code"]) if doctype == "Sales Order": row = [ item["item_code"], item["item_name"], item["description"], item["stock_uom"], item["qty"], actual_qty ] else: row = [ item["item_code"], item["item_name"], item["description"], item["stock_uom"], item["qty"], actual_qty ] data.append(row) if bom: bomitems = get_bom_items(bom, company=company, qty=item["qty"]) if bomitems: row = ["", "---------", "", "", ""] data.append(row) for b in bomitems: actual_qty = get_actual_qty(b["item_code"]) row = [ b["item_code"], b["item_name"], b["description"], b["stock_uom"], b["qty"], actual_qty ] data.append(row) row = ["", "---------", "", "", ""] data.append(row) elif filters.get("bom_only") == "Consolidate BOM": bom = get_default_bom(item["item_code"], project) if bom: bomitems = get_bom_items(bom, company=company, qty=item["qty"]) for b in bomitems: actual_qty = get_actual_qty(b["item_code"]) new_bom_item = { 'item_code': b['item_code'], 'item_name': b["item_name"], 'description': b["description"], 'stock_uom': b["stock_uom"], 'qty': b["qty"], 'actual_qty': actual_qty } all_bom_items.append(new_bom_item) else: bom = get_default_bom(item["item_code"], project) if bom: actual_qty = get_actual_qty(item["item_code"]) if doctype == "Sales Order": row = [ item["item_code"], item["item_name"], item["description"], item["stock_uom"], item["qty"], actual_qty ] else: row = [ item["item_code"], item["item_name"], item["description"], item["stock_uom"], item["qty"], actual_qty ] data.append(row) bomitems = get_bom_items(bom, company=company, qty=item["qty"]) if bomitems: row = ["", "---------", "", "", ""] data.append(row) for b in bomitems: actual_qty = get_actual_qty(b["item_code"]) row = [ b["item_code"], b["item_name"], b["description"], b["stock_uom"], b["qty"], actual_qty ] data.append(row) row = ["", "---------", "", "", ""] data.append(row) if filters.get("bom_only") == "Consolidate BOM": merged_bom_items = merge(all_bom_items) for b in merged_bom_items: d = merged_bom_items[b] row = [ d["item_code"], d["item_name"], d["description"], d["stock_uom"], d["qty"], d["actual_qty"] ] data.append(row) return columns, data
def remove_html_from_source(self): self.source_name = strip_html_tags(self.source_name).strip()