def get_formatted( self, fieldname, doc=None, currency=None, absolute_value=False, translated=False, format=None ): from frappe.utils.formatters import format_value df = self.meta.get_field(fieldname) if not df and fieldname in default_fields: from frappe.model.meta import get_default_df df = get_default_df(fieldname) if df and not currency: currency = self.get(df.get("options")) if not frappe.db.exists("Currency", currency, cache=True): currency = None val = self.get(fieldname) if translated: val = _(val) if not doc: doc = getattr(self, "parent_doc", None) or self if (absolute_value or doc.get("absolute_value")) and isinstance(val, (int, float)): val = abs(self.get(fieldname)) return format_value(val, df=df, doc=doc, currency=currency, format=format)
def frappe_format_value(value, df=None, doc=None, currency=None, translated=False): from frappe.utils.formatters import format_value return format_value(value, df, doc, currency, translated)
def get_formatted(self, fieldname, doc=None, currency=None, absolute_value=False, translated=False): from frappe.utils.formatters import format_value df = self.meta.get_field(fieldname) if not df and fieldname in default_fields: from frappe.model.meta import get_default_df df = get_default_df(fieldname) val = self.get(fieldname) if translated: val = _(val) if absolute_value and isinstance(val, (int, float)): val = abs(self.get(fieldname)) if not doc: doc = getattr(self, "parent_doc", None) or self return format_value(val, df=df, doc=doc, currency=currency)
def get_formatted(self, fieldname, doc=None, currency=None): from frappe.utils.formatters import format_value df = self.meta.get_field(fieldname) if not df and fieldname in default_fields: from frappe.model.meta import get_default_df df = get_default_df(fieldname) return format_value(self.get(fieldname), df=df, doc=doc or self, currency=currency)
def get_formatted(self, fieldname, doc=None, currency=None, absolute_value=False): from frappe.utils.formatters import format_value df = self.meta.get_field(fieldname) if not df and fieldname in default_fields: from frappe.model.meta import get_default_df df = get_default_df(fieldname) val = self.get(fieldname) if absolute_value and isinstance(val, (int, float)): val = abs(self.get(fieldname)) return format_value(val, df=df, doc=doc or self, currency=currency)
def set_subject_field(doc): from frappe.utils.formatters import format_value meta = frappe.get_meta(doc.doctype) subject = '' patient_history_fields = get_patient_history_fields(doc) for entry in patient_history_fields: fieldname = entry.get('fieldname') if entry.get('fieldtype') == 'Table' and doc.get(fieldname): formatted_value = get_formatted_value_for_table_field( doc.get(fieldname), meta.get_field(fieldname)) subject += frappe.bold(_(entry.get('label')) + ': ' ) + '<br>' + cstr(formatted_value) + '<br>' else: if doc.get(fieldname): formatted_value = format_value(doc.get(fieldname), meta.get_field(fieldname), doc) subject += frappe.bold(_(entry.get('label')) + ': ') + cstr(formatted_value) + '<br>' return subject
def set_subject_field(doc): from frappe.utils.formatters import format_value meta = frappe.get_meta(doc.doctype) subject = "" patient_history_fields = get_patient_history_fields(doc) for entry in patient_history_fields: fieldname = entry.get("fieldname") if entry.get("fieldtype") == "Table" and doc.get(fieldname): formatted_value = get_formatted_value_for_table_field( doc.get(fieldname), meta.get_field(fieldname)) subject += frappe.bold(_(entry.get("label")) + ":" ) + "<br>" + cstr(formatted_value) + "<br>" else: if doc.get(fieldname): formatted_value = format_value(doc.get(fieldname), meta.get_field(fieldname), doc) subject += frappe.bold(_(entry.get("label")) + ":") + cstr(formatted_value) + "<br>" return subject
def raise_bill_to_ship_to_invoice(self, name=None, amended_from=None): if self.billing_type == 'Self Purchase': return # if name: # doc = frappe.get_doc("Sales Invoice", name) # doc.submit() # return doc customer_object = frappe.get_doc("Customer", self.customer) company_object = frappe.get_doc("Company", self.company) if customer_object.customer_group in ['Baddi']: return rate = float(self.actual_amount) / self.qty tax = frappe.get_doc("Indent Invoice Tax", self.sales_tax) net_tax = get_net_tax_percentage(tax.tax_percentage, tax.surcharge_percentage) rate_before_tax = get_basic_value_before_tax(rate, net_tax) frappe.msgprint([self.actual_amount, self.qty, rate, net_tax, rate_before_tax]) qty_in_kg = get_conversion_factor(self.item) * float(self.qty) d_m = collections.OrderedDict() d_m['Dt.'] = format_value(self.transaction_date, {"fieldtype": "Date"}) d_m['Bill No.'] = self.invoice_number d_m['Amt.'] = '<strong>\u20b9{}</strong>'.format(format_value(self.actual_amount, {"fieldtype": "Currency"})) d_m['Qty in KG'] = '<strong>{} x {}: <em>{}</em></strong>'.format(self.item, self.qty, qty_in_kg) description = """({})""".format(', '.join(['{}: {}'.format(k, v) for k, v in d_m.items()])) naming_series = get_gst_invoice_naming_series(self.company, self.posting_date, '') consignment_note_json_doc = { "doctype": "Sales Invoice", "customer": self.customer, "customer_name": self.customer.strip(), "posting_date": get_posting_date(naming_series, self.transaction_date), # "posting_time": self.posting_time, "fiscal_year": self.fiscal_year, "entries": [ { "qty": self.qty, "rate": rate_before_tax, "item_code": self.item, "item_name": self.item, "description": description, "stock_uom": "Kg", "doctype": "Sales Invoice Item", "idx": 1, "income_account": company_object.default_income_account, "cost_center": company_object.cost_center, "parenttype": "Sales Invoice", "parentfield": "entries" } ], "against_income_account": company_object.default_income_account, "select_print_heading": "Tax Invoice", "company": self.company, "debit_to": self._get_account_(self.company, self.customer), # BA "letter_head": self.company, "is_opening": "No", "naming_series": naming_series, "price_list_currency": "INR", "currency": "INR", "plc_conversion_rate": 1, # "tc_name": sales_invoice_conf.tc_name, # "consignor": self.supplier, "territory": customer_object.territory if customer_object.territory else 'NA', "remarks": "Bill To Ship To Against Bill No. {}""".format(self.invoice_number), "tax_paid_by_supplier": 1, } if amended_from: consignment_note_json_doc['amended_from'] = amended_from if name: consignment_note_json_doc['name'] = name c_addr = get_address(self.customer) if c_addr: consignment_note_json_doc["customer_address"] = c_addr if self.posting_date >= '2017-07-01': consignment_note_json_doc['taxes_and_charges'] = get_gst_sales_tax( consignment_note_json_doc["customer_address"]) + ' - MO' transportation_invoice = frappe.get_doc(consignment_note_json_doc) transportation_invoice.save() transportation_invoice.terms = get_terms_for_bill_to_ship_to_invoice(transportation_invoice) round_off = round(self.actual_amount - transportation_invoice.grand_total_export, 2) if round_off: transportation_invoice.append('other_charges', { "charge_type": "Actual", "description": "Round Off", "account_head": "writeoff - MO", "rate": round_off }) return transportation_invoice
def raise_consignment_note( self, qty_in_kg, transportation_rate_per_kg, indent_invoice_settings, discount_per_kg=0 ): registration = frappe.get_doc("OMC Customer Registration", self.omc_customer_registration) fiscal_year = account_utils.get_fiscal_year(self.get("posting_date"))[0] sales_invoice_conf = get_sales_invoice_config(registration.sales_invoice_company, fiscal_year) if not sales_invoice_conf: frappe.throw("Sales Invoice Config Not Found For Year {}, Company {}".format(sales_invoice_conf, registration.sales_invoice_company)) customer_object = frappe.get_doc("Customer", self.customer) description = '' if discount_per_kg > 0: description += "Rate: {} - {} (Paid By Consignor) per KG\n".\ format(transportation_rate_per_kg, discount_per_kg) d_m = collections.OrderedDict() d_m['Dt.'] = format_value(self.transaction_date, {"fieldtype": "Date"}) d_m['Bill No.'] = self.invoice_number d_m['Amt.'] = '<strong>\u20b9{}</strong>'.format(format_value(self.actual_amount, {"fieldtype": "Currency"})) d_m['Qty in KG'] = '<strong>{} x {}: <em>{}</em></strong>'.format(self.item, self.qty, qty_in_kg) description += """({})""".format(', '.join(['{}: {}'.format(k, v) for k, v in d_m.items()])) consignment_note_json_doc = { "doctype": "Sales Invoice", "customer": self.customer, "customer_name": self.customer.strip(), "posting_date": get_posting_date(sales_invoice_conf.naming_series, self.transaction_date), # "posting_time": , "fiscal_year": self.fiscal_year, "entries": [ { "qty": qty_in_kg, "rate": transportation_rate_per_kg - discount_per_kg, "item_code": "LPG Transport", "item_name": "LPG Transport", "description": description, "stock_uom": "Kg", "doctype": "Sales Invoice Item", "idx": 1, "income_account": sales_invoice_conf.credit_account, "cost_center": sales_invoice_conf.cost_center, "parenttype": "Sales Invoice", "parentfield": "entries", } ], "against_income_account": sales_invoice_conf.credit_account, "select_print_heading": "Transportation Invoice / Consignment Note", "company": registration.sales_invoice_company, "debit_to": registration.sales_invoice_account, "letter_head": registration.sales_invoice_company, "is_opening": "No", "naming_series": sales_invoice_conf.naming_series, "price_list_currency": "INR", "currency": "INR", "plc_conversion_rate": 1, "tc_name": sales_invoice_conf.tc_name, "consignor": self.supplier, "territory": customer_object.territory if customer_object.territory else indent_invoice_settings.default_territory, "remarks": "Against Bill No. {}""".format(self.invoice_number) } c_addr = get_address(self.customer) if c_addr: consignment_note_json_doc["customer_address"] = c_addr # if getdate(consignment_note_json_doc['posting_date']) < getdate('2015-06-01'): # consignment_note_json_doc["taxes_and_charges"] = "Road Transport" # elif getdate(consignment_note_json_doc['posting_date']) < getdate('2015-11-15'): # consignment_note_json_doc["taxes_and_charges"] = "Road Transport_June_1_15" # elif getdate(consignment_note_json_doc['posting_date']) < getdate('2016-06-01'): # consignment_note_json_doc["taxes_and_charges"] = "Road Transport_Nov_15_15" # else: consignment_note_json_doc["taxes_and_charges"] = "Road Transport_June_1_16" if getdate(consignment_note_json_doc['posting_date']) < getdate('2016-06-01'): frappe.throw("Tax Changed! Cant cancel/submit invoice") consignment_note_json_doc[ "tax_paid_by_supplier" ] = 1 if self.service_tax_liability == "Transporter" else 0 data_bank = self.get_data_bank() if 'transportation_invoice' in data_bank and data_bank['transportation_invoice']: consignment_note_json_doc["amended_from"] = data_bank.transportation_invoice consignment_note_json_doc["posting_date"] = frappe.db.get_value( "Sales Invoice", data_bank.transportation_invoice, 'posting_date' ) frappe.msgprint("Posting Date Of Amended Invoice {}".format(consignment_note_json_doc["posting_date"])) transportation_invoice = frappe.get_doc(consignment_note_json_doc) transportation_invoice.save() return transportation_invoice
def raise_aux_service_sales_invoice( self, qty_in_kg, transportation_rate_per_kg, indent_invoice_settings, discount_per_kg=0 ): registration = frappe.get_doc("OMC Customer Registration", self.omc_customer_registration) fiscal_year = account_utils.get_fiscal_year(self.get("posting_date"))[0] sales_invoice_conf = get_sales_invoice_config(registration.sales_invoice_company, fiscal_year) if not sales_invoice_conf: frappe.throw("Sales Invoice Config Not Found For Year {}, Company {}".format(sales_invoice_conf, registration.sales_invoice_company)) customer_object = frappe.get_doc("Customer", self.customer) description = '' if discount_per_kg > 0: description += "Rate: {} - {} (Discount) per KG\n". \ format(transportation_rate_per_kg, discount_per_kg) d_m = collections.OrderedDict() d_m['Dt.'] = format_value(self.transaction_date, {"fieldtype": "Date"}) d_m['Bill No.'] = self.invoice_number d_m['Amt.'] = '<strong>\u20b9{}</strong>'.format(format_value(self.actual_amount, {"fieldtype": "Currency"})) d_m['Qty in KG'] = '<strong>{} x {}: <em>{}</em></strong>'.format(self.item, self.qty, qty_in_kg) description += """({})""".format(', '.join(['{}: {}'.format(k, v) for k, v in d_m.items()])) naming_series = sales_invoice_conf.naming_series.replace('CN', 'SN') rc = False cr_acc = sales_invoice_conf.credit_account if self.gst_liability != 'Company': cr_acc = cr_acc.replace('Service', 'Reverse Service') rc=True consignment_note_json_doc = { "doctype": "Sales Invoice", "customer": self.customer, "customer_name": self.customer.strip(), "posting_date": get_posting_date(naming_series, self.transaction_date), # "posting_time": , "fiscal_year": self.fiscal_year, "entries": [ { "qty": qty_in_kg, "rate": transportation_rate_per_kg - discount_per_kg, "item_code": "LPG Transport" if rc else "AS", "description": description, "stock_uom": "Kg", "doctype": "Sales Invoice Item", "idx": 1, "income_account": cr_acc, "cost_center": sales_invoice_conf.cost_center, "parenttype": "Sales Invoice", "parentfield": "entries", } ], "against_income_account": cr_acc, "select_print_heading": "Tax Invoice", "company": registration.sales_invoice_company, "debit_to": registration.sales_invoice_account, "letter_head": registration.sales_invoice_company, "is_opening": "No", "naming_series": sales_invoice_conf.naming_series.replace('CN', 'SN'), "price_list_currency": "INR", "currency": "INR", "plc_conversion_rate": 1, "consignor": self.supplier, "territory": customer_object.territory if customer_object.territory else indent_invoice_settings.default_territory, "remarks": "Against Bill No. {}""".format(self.invoice_number), "tax_paid_by_supplier": 0 } c_addr = get_address(self.customer) if c_addr: consignment_note_json_doc["customer_address"] = c_addr if not rc: if self.posting_date >= '2017-07-01': consignment_note_json_doc['taxes_and_charges'] = get_gst_sales_tax(consignment_note_json_doc["customer_address"]) consignment_note_json_doc["tax_paid_by_supplier"] = 1 data_bank = self.get_data_bank() if 'transportation_invoice' in data_bank and data_bank['transportation_invoice']: consignment_note_json_doc["amended_from"] = data_bank.transportation_invoice consignment_note_json_doc["posting_date"] = frappe.db.get_value( "Sales Invoice", data_bank.transportation_invoice, 'posting_date' ) frappe.msgprint("Posting Date Of Amended Invoice {}".format(consignment_note_json_doc["posting_date"])) #consignment_note_json_doc['taxes_and_charges'] = get_gst_sales_tax(consignment_note_json_doc["customer_address"]) transportation_invoice = frappe.get_doc(consignment_note_json_doc) transportation_invoice.save() transportation_invoice.terms = self.get_terms_of_aux_invoice(transportation_invoice) return transportation_invoice
def render_doc_as_html(doctype, docname, exclude_fields=[]): #render document as html, three column layout will break doc = frappe.get_doc(doctype, docname) meta = frappe.get_meta(doctype) doc_html = "<div class='col-md-12 col-sm-12'>" section_html = '' section_label = '' html = '' sec_on = False col_on = 0 has_data = False for df in meta.fields: #on section break append append previous section and html to doc html if df.fieldtype == "Section Break": if has_data and col_on and sec_on: doc_html += section_html + html + "</div>" elif has_data and not col_on and sec_on: doc_html += "<div class='col-md-12 col-sm-12'\ ><div class='col-md-12 col-sm-12'>" \ + section_html + html +"</div></div>" while col_on: doc_html += "</div>" col_on -= 1 sec_on = True has_data = False col_on = 0 section_html = '' html = '' if df.label: section_label = df.label continue #on column break append html to section html or doc html if df.fieldtype == "Column Break": if sec_on and has_data: section_html += "<div class='col-md-12 col-sm-12'\ ><div class='col-md-6 col\ -sm-6'><b>" + section_label + "</b>" + html + "</div><div \ class='col-md-6 col-sm-6'>" elif has_data: doc_html += "<div class='col-md-12 col-sm-12'><div class='col-m\ d-6 col-sm-6'>" + html + "</div><div class='col-md-6 col-sm-6'>" elif sec_on and not col_on: section_html += "<div class='col-md-6 col-sm-6'>" html = '' col_on += 1 if df.label: html += '<br>' + df.label continue #on table iterate in items and create table based on in_list_view, append to section html or doc html if df.fieldtype == 'Table': items = doc.get(df.fieldname) if not items: continue child_meta = frappe.get_meta(df.options) if not has_data: has_data = True table_head = '' table_row = '' create_head = True for item in items: table_row += '<tr>' for cdf in child_meta.fields: if cdf.in_list_view: if create_head: table_head += '<th>' + cdf.label + '</th>' if item.get(cdf.fieldname): table_row += '<td>' + str(item.get(cdf.fieldname)) \ + '</td>' else: table_row += '<td></td>' create_head = False table_row += '</tr>' if sec_on: section_html += "<table class='table table-condensed \ bordered'>" + table_head + table_row + '</table>' else: html += "<table class='table table-condensed table-bordered'>" \ + table_head + table_row + "</table>" continue #on other field types add label and value to html if not df.hidden and not df.print_hide and doc.get( df.fieldname) and df.fieldname not in exclude_fields: if doc.get(df.fieldname): formatted_value = format_value(doc.get(df.fieldname), meta.get_field(df.fieldname), doc) html += '<br>{0} : {1}'.format(df.label or df.fieldname, formatted_value) if not has_data: has_data = True if sec_on and col_on and has_data: doc_html += section_html + html + '</div></div>' elif sec_on and not col_on and has_data: doc_html += "<div class='col-md-12 col-sm-12'\ ><div class='col-md-12 col-sm-12'>" \ + section_html + html +'</div></div>' if doc_html: doc_html = "<div class='small'><div class='col-md-12 text-right'><a class='btn btn-default btn-xs' href='/app/Form/%s/%s'></a></div>" % ( doctype, docname) + doc_html + '</div>' return {'html': doc_html}
def get_formatted(self, fieldname, doc=None, currency=None): from frappe.utils.formatters import format_value return format_value(self.get(fieldname), self.meta.get_field(fieldname), doc=doc or self, currency=currency)
def get_monthly_goal_graph_data(title, doctype, docname, goal_value_field, goal_total_field, goal_history_field, goal_doctype, goal_doctype_link, goal_field, date_field, filter_str, aggregation="sum"): ''' Get month-wise graph data for a doctype based on aggregation values of a field in the goal doctype :param title: Graph title :param doctype: doctype of graph doc :param docname: of the doc to set the graph in :param goal_value_field: goal field of doctype :param goal_total_field: current month value field of doctype :param goal_history_field: cached history field :param goal_doctype: doctype the goal is based on :param goal_doctype_link: doctype link field in goal_doctype :param goal_field: field from which the goal is calculated :param filter_str: where clause condition :param aggregation: a value like 'count', 'sum', 'avg' :return: dict of graph data ''' from frappe.utils.formatters import format_value import json meta = frappe.get_meta(doctype) doc = frappe.get_doc(doctype, docname) goal = doc.get(goal_value_field) formatted_goal = format_value(goal, meta.get_field(goal_value_field), doc) current_month_value = doc.get(goal_total_field) formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), doc) from frappe.utils import today, getdate, formatdate, add_months current_month_year = formatdate(today(), "MM-yyyy") history = doc.get(goal_history_field) try: month_to_value_dict = json.loads(history) if history and '{' in history else None except ValueError: month_to_value_dict = None if month_to_value_dict is None: doc_filter = (goal_doctype_link + ' = "' + docname + '"') if doctype != goal_doctype else '' if filter_str: doc_filter += ' and ' + filter_str if doc_filter else filter_str month_to_value_dict = get_monthly_results(goal_doctype, goal_field, date_field, doc_filter, aggregation) frappe.db.set_value(doctype, docname, goal_history_field, json.dumps(month_to_value_dict)) month_to_value_dict[current_month_year] = current_month_value months = [] months_formatted = [] values = [] values_formatted = [] for i in xrange(0, 12): month_value = formatdate(add_months(today(), -i), "MM-yyyy") month_word = getdate(month_value).strftime('%b') month_year = getdate(month_value).strftime('%B') + ', ' + getdate(month_value).strftime('%Y') months.insert(0, month_word) months_formatted.insert(0, month_year) if month_value in month_to_value_dict: val = month_to_value_dict[month_value] else: val = 0 values.insert(0, val) values_formatted.insert(0, format_value(val, meta.get_field(goal_total_field), doc)) specific_values = [] summary_values = [ { <<<<<<< HEAD 'name': "This month", ======= 'name': _("This month"), >>>>>>> 176d241496ede1357a309fa44a037b757a252581 'color': 'green', 'value': formatted_value } ]
def get_monthly_goal_graph_data(title, doctype, docname, goal_value_field, goal_total_field, goal_history_field, goal_doctype, goal_doctype_link, goal_field, date_field, filter_str, aggregation="sum"): ''' Get month-wise graph data for a doctype based on aggregation values of a field in the goal doctype :param title: Graph title :param doctype: doctype of graph doc :param docname: of the doc to set the graph in :param goal_value_field: goal field of doctype :param goal_total_field: current month value field of doctype :param goal_history_field: cached history field :param goal_doctype: doctype the goal is based on :param goal_doctype_link: doctype link field in goal_doctype :param goal_field: field from which the goal is calculated :param filter_str: where clause condition :param aggregation: a value like 'count', 'sum', 'avg' :return: dict of graph data ''' from frappe.utils.formatters import format_value import json meta = frappe.get_meta(doctype) doc = frappe.get_doc(doctype, docname) goal = doc.get(goal_value_field) formatted_goal = format_value(goal, meta.get_field(goal_value_field), doc) current_month_value = doc.get(goal_total_field) formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), doc) from frappe.utils import today, getdate, formatdate, add_months current_month_year = formatdate(today(), "MM-yyyy") history = doc.get(goal_history_field) try: month_to_value_dict = json.loads(history) if history and '{' in history else None except ValueError: month_to_value_dict = None if month_to_value_dict is None: doc_filter = (goal_doctype_link + ' = "' + docname + '"') if doctype != goal_doctype else '' if filter_str: doc_filter += ' and ' + filter_str if doc_filter else filter_str month_to_value_dict = get_monthly_results(goal_doctype, goal_field, date_field, doc_filter, aggregation) frappe.db.set_value(doctype, docname, goal_history_field, json.dumps(month_to_value_dict)) month_to_value_dict[current_month_year] = current_month_value months = [] months_formatted = [] values = [] values_formatted = [] for i in xrange(0, 12): month_value = formatdate(add_months(today(), -i), "MM-yyyy") month_word = getdate(month_value).strftime('%b') month_year = getdate(month_value).strftime('%B') + ', ' + getdate(month_value).strftime('%Y') months.insert(0, month_word) months_formatted.insert(0, month_year) if month_value in month_to_value_dict: val = month_to_value_dict[month_value] else: val = 0 values.insert(0, val) values_formatted.insert(0, format_value(val, meta.get_field(goal_total_field), doc)) specific_values = [] summary_values = [ { 'title': _("This month"), 'color': '#ffa00a', 'value': formatted_value } ] if float(goal) > 0: specific_values = [ { 'title': _("Goal"), 'line_type': "dashed", 'value': goal }, ] summary_values += [ { 'title': _("Goal"), 'color': '#5e64ff', 'value': formatted_goal }, { 'title': _("Completed"), 'color': '#28a745', 'value': str(int(round(float(current_month_value)/float(goal)*100))) + "%" } ] data = { 'title': title, # 'subtitle': 'data': { 'datasets': [ { 'values': values, 'formatted': values_formatted } ], 'labels': months, 'specific_values': specific_values, }, 'summary': summary_values } return data
def get_monthly_goal_graph_data( title, doctype, docname, goal_value_field, goal_total_field, goal_history_field, goal_doctype, goal_doctype_link, goal_field, date_field, filter_str, aggregation="sum", ): """ Get month-wise graph data for a doctype based on aggregation values of a field in the goal doctype :param title: Graph title :param doctype: doctype of graph doc :param docname: of the doc to set the graph in :param goal_value_field: goal field of doctype :param goal_total_field: current month value field of doctype :param goal_history_field: cached history field :param goal_doctype: doctype the goal is based on :param goal_doctype_link: doctype link field in goal_doctype :param goal_field: field from which the goal is calculated :param filter_str: where clause condition :param aggregation: a value like 'count', 'sum', 'avg' :return: dict of graph data """ import json from frappe.utils.formatters import format_value # should have atleast read perm if not frappe.has_permission(goal_doctype): return None meta = frappe.get_meta(doctype) doc = frappe.get_doc(doctype, docname) goal = doc.get(goal_value_field) formatted_goal = format_value(goal, meta.get_field(goal_value_field), doc) current_month_value = doc.get(goal_total_field) formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), doc) from frappe.utils import add_months, formatdate, getdate, today current_month_year = formatdate(today(), "MM-yyyy") history = doc.get(goal_history_field) try: month_to_value_dict = json.loads( history) if history and "{" in history else None except ValueError: month_to_value_dict = None if month_to_value_dict is None: doc_filter = ((goal_doctype_link + " = " + frappe.db.escape(docname)) if doctype != goal_doctype else "") if filter_str: doc_filter += " and " + filter_str if doc_filter else filter_str month_to_value_dict = get_monthly_results(goal_doctype, goal_field, date_field, doc_filter, aggregation) month_to_value_dict[current_month_year] = current_month_value months = [] months_formatted = [] values = [] values_formatted = [] for i in range(0, 12): date_value = add_months(today(), -i) month_value = formatdate(date_value, "MM-yyyy") month_word = getdate(date_value).strftime("%b %y") month_year = getdate(date_value).strftime("%B") + ", " + getdate( date_value).strftime("%Y") months.insert(0, month_word) months_formatted.insert(0, month_year) if month_value in month_to_value_dict: val = month_to_value_dict[month_value] else: val = 0 values.insert(0, val) values_formatted.insert( 0, format_value(val, meta.get_field(goal_total_field), doc)) y_markers = [] summary_values = [{ "title": _("This month"), "color": "#ffa00a", "value": formatted_value }] if float(goal) > 0: y_markers = [ { "label": _("Goal"), "lineType": "dashed", "value": goal }, ] summary_values += [ { "title": _("Goal"), "color": "#5e64ff", "value": formatted_goal }, { "title": _("Completed"), "color": "#28a745", "value": str(int(round(float(current_month_value) / float(goal) * 100))) + "%", }, ] data = { "title": title, # 'subtitle': "data": { "datasets": [{ "values": values, "formatted": values_formatted }], "labels": months, }, "summary": summary_values, } if y_markers: data["data"]["yMarkers"] = y_markers return data
def get_monthly_goal_graph_data(title, doctype, docname, goal_value_field, goal_total_field, goal_history_field, goal_doctype, goal_doctype_link, goal_field, date_field, filter_str, aggregation="sum"): ''' Get month-wise graph data for a doctype based on aggregation values of a field in the goal doctype :param title: Graph title :param doctype: doctype of graph doc :param docname: of the doc to set the graph in :param goal_value_field: goal field of doctype :param goal_total_field: current month value field of doctype :param goal_history_field: cached history field :param goal_doctype: doctype the goal is based on :param goal_doctype_link: doctype link field in goal_doctype :param goal_field: field from which the goal is calculated :param filter_str: where clause condition :param aggregation: a value like 'count', 'sum', 'avg' :return: dict of graph data ''' from frappe.utils.formatters import format_value import json meta = frappe.get_meta(doctype) doc = frappe.get_doc(doctype, docname) goal = doc.get(goal_value_field) formatted_goal = format_value(goal, meta.get_field(goal_value_field), doc) current_month_value = doc.get(goal_total_field) formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), doc) from frappe.utils import today, getdate, formatdate, add_months current_month_year = formatdate(today(), "MM-yyyy") history = doc.get(goal_history_field) try: month_to_value_dict = json.loads(history) if history and '{' in history else None except ValueError: month_to_value_dict = None if month_to_value_dict is None: doc_filter = (goal_doctype_link + " = '" + docname + "'") if doctype != goal_doctype else '' if filter_str: doc_filter += ' and ' + filter_str if doc_filter else filter_str month_to_value_dict = get_monthly_results(goal_doctype, goal_field, date_field, doc_filter, aggregation) frappe.db.set_value(doctype, docname, goal_history_field, json.dumps(month_to_value_dict)) month_to_value_dict[current_month_year] = current_month_value months = [] months_formatted = [] values = [] values_formatted = [] for i in range(0, 12): date_value = add_months(today(), -i) month_value = formatdate(date_value, "MM-yyyy") month_word = getdate(date_value).strftime('%b') month_year = getdate(date_value).strftime('%B') + ', ' + getdate(date_value).strftime('%Y') months.insert(0, month_word) months_formatted.insert(0, month_year) if month_value in month_to_value_dict: val = month_to_value_dict[month_value] else: val = 0 values.insert(0, val) values_formatted.insert(0, format_value(val, meta.get_field(goal_total_field), doc)) y_markers = [] summary_values = [ { 'title': _("This month"), 'color': '#ffa00a', 'value': formatted_value } ] if float(goal) > 0: y_markers = [ { 'label': _("Goal"), 'lineType': "dashed", 'value': goal }, ] summary_values += [ { 'title': _("Goal"), 'color': '#5e64ff', 'value': formatted_goal }, { 'title': _("Completed"), 'color': '#28a745', 'value': str(int(round(float(current_month_value)/float(goal)*100))) + "%" } ] data = { 'title': title, # 'subtitle': 'data': { 'datasets': [ { 'values': values, 'formatted': values_formatted } ], 'labels': months, }, 'summary': summary_values, } if y_markers: data["data"]["yMarkers"] = y_markers return data
def render_doc_as_html(doctype, docname, exclude_fields=None): """ Render document as HTML """ doc = frappe.get_doc(doctype, docname) meta = frappe.get_meta(doctype) doc_html = section_html = section_label = html = "" sec_on = has_data = False col_on = 0 if exclude_fields is None: exclude_fields = [] for df in meta.fields: # on section break append previous section and html to doc html if df.fieldtype == "Section Break": if has_data and col_on and sec_on: doc_html += section_html + html + "</div>" elif has_data and not col_on and sec_on: doc_html += """ <br> <div class='row'> <div class='col-md-12 col-sm-12'> <b>{0}</b> </div> </div> <div class='row'> <div class='col-md-12 col-sm-12'> {1} {2} </div> </div> """.format(section_label, section_html, html) # close divs for columns while col_on: doc_html += "</div>" col_on -= 1 sec_on = True has_data = False col_on = 0 section_html = html = "" if df.label: section_label = df.label continue # on column break append html to section html or doc html if df.fieldtype == "Column Break": if sec_on and not col_on and has_data: section_html += """ <br> <div class='row'> <div class='col-md-12 col-sm-12'> <b>{0}</b> </div> </div> <div class='row'> <div class='col-md-4 col-sm-4'> {1} </div> """.format(section_label, html) elif col_on == 1 and has_data: section_html += "<div class='col-md-4 col-sm-4'>" + html + "</div>" elif col_on > 1 and has_data: doc_html += "<div class='col-md-4 col-sm-4'>" + html + "</div>" else: doc_html += """ <div class='row'> <div class='col-md-12 col-sm-12'> {0} </div> </div> """.format(html) html = "" col_on += 1 if df.label: html += "<br>" + df.label continue # on table iterate through items and create table # based on the in_list_view property # append to section html or doc html if df.fieldtype == "Table": items = doc.get(df.fieldname) if not items: continue child_meta = frappe.get_meta(df.options) if not has_data: has_data = True table_head = table_row = "" create_head = True for item in items: table_row += "<tr>" for cdf in child_meta.fields: if cdf.in_list_view: if create_head: table_head += "<th class='text-muted'>" + cdf.label + "</th>" if item.get(cdf.fieldname): table_row += "<td>" + cstr(item.get( cdf.fieldname)) + "</td>" else: table_row += "<td></td>" create_head = False table_row += "</tr>" if sec_on: section_html += """ <table class='table table-condensed bordered'> {0} {1} </table> """.format(table_head, table_row) else: html += """ <table class='table table-condensed table-bordered'> {0} {1} </table> """.format(table_head, table_row) continue # on any other field type add label and value to html if (not df.hidden and not df.print_hide and doc.get(df.fieldname) and df.fieldname not in exclude_fields): formatted_value = format_value(doc.get(df.fieldname), meta.get_field(df.fieldname), doc) html += "<br>{0} : {1}".format(df.label or df.fieldname, formatted_value) if not has_data: has_data = True if sec_on and col_on and has_data: doc_html += section_html + html + "</div></div>" elif sec_on and not col_on and has_data: doc_html += """ <div class='col-md-12 col-sm-12'> <div class='col-md-12 col-sm-12'> {0} {1} </div> </div> """.format(section_html, html) return {"html": doc_html}
def get_monthly_goal_graph_data(title, doctype, docname, goal_value_field, goal_total_field, goal_history_field, goal_doctype, goal_doctype_link, goal_field, date_field, filter_str, aggregation="sum"): ''' Get month-wise graph data for a doctype based on aggregation values of a field in the goal doctype :param title: Graph title :param doctype: doctype of graph doc :param docname: of the doc to set the graph in :param goal_value_field: goal field of doctype :param goal_total_field: current month value field of doctype :param goal_history_field: cached history field :param goal_doctype: doctype the goal is based on :param goal_doctype_link: doctype link field in goal_doctype :param goal_field: field from which the goal is calculated :param filter_str: where clause condition :param aggregation: a value like 'count', 'sum', 'avg' :return: dict of graph data ''' from frappe.utils.formatters import format_value import json meta = frappe.get_meta(doctype) doc = frappe.get_doc(doctype, docname) goal = doc.get(goal_value_field) formatted_goal = format_value(goal, meta.get_field(goal_value_field), doc) current_month_value = doc.get(goal_total_field) formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), doc) from frappe.utils import today, getdate, formatdate, add_months current_month_year = formatdate(today(), "MM-yyyy") history = doc.get(goal_history_field) try: month_to_value_dict = json.loads( history) if history and '{' in history else None except ValueError: month_to_value_dict = None if month_to_value_dict is None: doc_filter = (goal_doctype_link + ' = "' + docname + '"') if doctype != goal_doctype else '' if filter_str: doc_filter += ' and ' + filter_str if doc_filter else filter_str month_to_value_dict = get_monthly_results(goal_doctype, goal_field, date_field, doc_filter, aggregation) frappe.db.set_value(doctype, docname, goal_history_field, json.dumps(month_to_value_dict)) month_to_value_dict[current_month_year] = current_month_value months = [] values = [] for i in xrange(0, 12): month_value = formatdate(add_months(today(), -i), "MM-yyyy") month_word = getdate(month_value).strftime('%b') months.insert(0, month_word) if month_value in month_to_value_dict: values.insert(0, month_to_value_dict[month_value]) else: values.insert(0, 0) specific_values = [] summary_values = [{ 'name': "This month", 'color': 'green', 'value': formatted_value }] if float(goal) > 0: specific_values = [ { 'name': "Goal", 'line_type': "dashed", 'value': goal }, ] summary_values += [{ 'name': "Goal", 'color': 'blue', 'value': formatted_goal }, { 'name': "Completed", 'color': 'green', 'value': str(int(round(float(current_month_value) / float(goal) * 100))) + "%" }] data = { 'title': title, # 'subtitle': 'y_values': values, 'x_points': months, 'specific_values': specific_values, 'summary_values': summary_values } return data