def get_script(report_name): report = get_report_doc(report_name) module = report.module or frappe.db.get_value("DocType", report.ref_doctype, "module") module_path = get_module_path(module) report_folder = os.path.join(module_path, "report", scrub(report.name)) script_path = os.path.join(report_folder, scrub(report.name) + ".js") print_path = os.path.join(report_folder, scrub(report.name) + ".html") script = None if os.path.exists(script_path): with open(script_path, "r") as f: script = f.read() html_format = get_html_format(print_path) if not script and report.javascript: script = report.javascript if not script: script = "frappe.query_reports['%s']={}" % report_name # load translations if frappe.lang != "en": send_translations(frappe.get_lang_dict("report", report_name)) return { "script": script, "html_format": html_format }
def get_script(report_name): report = get_report_doc(report_name) module = frappe.db.get_value("DocType", report.ref_doctype, "module") module_path = get_module_path(module) report_folder = os.path.join(module_path, "report", scrub(report.name)) script_path = os.path.join(report_folder, scrub(report.name) + ".js") script = None if os.path.exists(script_path): with open(script_path, "r") as script: script = script.read() if not script and report.javascript: script = report.javascript if not script: script = "frappe.query_reports['%s']={}" % report_name # load translations if frappe.lang != "en": frappe.response["__messages"] = frappe.get_lang_dict( "report", report_name) return script
def load_assets(self): from frappe.modules import get_module_path, scrub import os path = os.path.join(get_module_path(self.module), 'page', scrub(self.name)) # script fpath = os.path.join(path, scrub(self.name) + '.js') if os.path.exists(fpath): with open(fpath, 'r') as f: self.script = unicode(f.read(), "utf-8") # css fpath = os.path.join(path, scrub(self.name) + '.css') if os.path.exists(fpath): with open(fpath, 'r') as f: self.style = unicode(f.read(), "utf-8") # html as js template for fname in os.listdir(path): if fname.endswith(".html"): with open(os.path.join(path, fname), 'r') as f: template = unicode(f.read(), "utf-8") self.script = html_to_js_template(fname, template) + self.script if frappe.lang != 'en': from frappe.translate import get_lang_js self.script += get_lang_js("page", self.name)
def run(report_name, filters=()): report = get_report_doc(report_name) if filters and isinstance(filters, basestring): filters = json.loads(filters) if not frappe.has_permission(report.ref_doctype, "report"): frappe.msgprint( _("Must have report permission to access this report."), raise_exception=True) if report.report_type == "Query Report": if not report.query: frappe.msgprint(_("Must specify a Query to run"), raise_exception=True) if not report.query.lower().startswith("select"): frappe.msgprint(_("Query must be a SELECT"), raise_exception=True) result = [list(t) for t in frappe.db.sql(report.query, filters)] columns = [c[0] for c in frappe.db.get_description()] else: module = frappe.db.get_value("DocType", report.ref_doctype, "module") if report.is_standard == "Yes": method_name = frappe.local.module_app[scrub(module)] + "." + scrub(module) \ + ".report." + scrub(report.name) + "." + scrub(report.name) + ".execute" columns, result = frappe.get_attr(method_name)( frappe._dict(filters)) result = get_filtered_data(report.ref_doctype, columns, result) if cint(report.add_total_row) and result: result = add_total_row(result, columns) return {"result": result, "columns": columns}
def scrub_dt_dn(dt, dn): """Returns in lowercase and code friendly names of doctype and name for certain types""" ndt, ndn = dt, dn if dt in lower_case_files_for: ndt, ndn = scrub(dt), scrub(dn) return ndt, ndn
def load_assets(self): from frappe.modules import get_module_path, scrub import os path = os.path.join(get_module_path(self.module), 'page', scrub(self.name)) # script fpath = os.path.join(path, scrub(self.name) + '.js') if os.path.exists(fpath): with open(fpath, 'r') as f: self.script = f.read() # css fpath = os.path.join(path, scrub(self.name) + '.css') if os.path.exists(fpath): with open(fpath, 'r') as f: self.style = f.read() # html fpath = os.path.join(path, scrub(self.name) + '.html') if os.path.exists(fpath): with open(fpath, 'r') as f: self.content = f.read() if frappe.lang != 'en': from frappe.translate import get_lang_js self.script += get_lang_js("page", self.name)
def on_update(self): """ Writes the .txt for this page and if write_content is checked, it will write out a .html file """ from frappe import conf from frappe.core.doctype.doctype.doctype import make_module_and_roles make_module_and_roles(self, "roles") if not frappe.flags.in_import and getattr(conf,'developer_mode', 0) and self.standard=='Yes': from frappe.modules.export_file import export_to_files from frappe.modules import get_module_path, scrub import os export_to_files(record_list=[['Page', self.name]]) # write files path = os.path.join(get_module_path(self.module), 'page', scrub(self.name), scrub(self.name)) # js if not os.path.exists(path + '.js'): with open(path + '.js', 'w') as f: f.write("""frappe.pages['%s'].on_page_load = function(wrapper) { var page = frappe.ui.make_app_page({ parent: wrapper, title: '%s', single_column: true }); }""" % (self.name, self.title))
def reset_doc(doctype): ''' doctype = name of the DocType that you want to reset ''' # fetch module name module = frappe.db.get_value('DocType', doctype, 'module') app = utils.get_module_app(module) # get path for doctype's json and its equivalent git url doc_path = os.path.join(get_module_path(module), 'doctype', scrub(doctype), scrub(doctype)+'.json') try: git_link = '/'.join(['https://raw.githubusercontent.com/frappe',\ app, branch, doc_path.split('apps/'+app)[1]]) original_file = urlopen(git_link).read() except: print('Did not find {0} in {1}'.format(doctype, app)) return # load local and original json objects local_doc = json.loads(open(doc_path, 'r').read()) original_doc = json.loads(original_file) remove_duplicate_fields(doctype) set_property_setter(doctype, local_doc, original_doc) make_custom_fields(doctype, local_doc, original_doc) with open(doc_path, 'w+') as f: f.write(original_file) f.close() setup_perms_for(doctype) frappe.db.commit()
def load_assets(self): from frappe.modules import get_module_path, scrub import os path = os.path.join(get_module_path(self.module), "page", scrub(self.name)) # script fpath = os.path.join(path, scrub(self.name) + ".js") if os.path.exists(fpath): with open(fpath, "r") as f: self.script = unicode(f.read(), "utf-8") # css fpath = os.path.join(path, scrub(self.name) + ".css") if os.path.exists(fpath): with open(fpath, "r") as f: self.style = unicode(f.read(), "utf-8") # html fpath = os.path.join(path, scrub(self.name) + ".html") if os.path.exists(fpath): with open(fpath, "r") as f: self.content = unicode(f.read(), "utf-8") if frappe.lang != "en": from frappe.translate import get_lang_js self.script += get_lang_js("page", self.name)
def get_report_module_dotted_path(module, report_name): return ( frappe.local.module_app[scrub(module)] + "." + scrub(module) + ".report." + scrub(report_name) + "." + scrub(report_name) )
def load_assets(self): from frappe.modules import get_module_path, scrub import os self.script = '' page_name = scrub(self.name) path = os.path.join(get_module_path(self.module), 'page', page_name) # script fpath = os.path.join(path, page_name + '.js') if os.path.exists(fpath): with open(fpath, 'r') as f: self.script = render_include(f.read()) # css fpath = os.path.join(path, page_name + '.css') if os.path.exists(fpath): with open(fpath, 'r') as f: self.style = safe_decode(f.read()) # html as js template for fname in os.listdir(path): if fname.endswith(".html"): with open(os.path.join(path, fname), 'r') as f: template = f.read() if "<!-- jinja -->" in template: context = frappe._dict({}) try: out = frappe.get_attr("{app}.{module}.page.{page}.{page}.get_context".format( app = frappe.local.module_app[scrub(self.module)], module = scrub(self.module), page = page_name ))(context) if out: context = out except (AttributeError, ImportError): pass template = frappe.render_template(template, context) self.script = html_to_js_template(fname, template) + self.script # flag for not caching this page self._dynamic_page = True if frappe.lang != 'en': from frappe.translate import get_lang_js self.script += get_lang_js("page", self.name) for path in get_code_files_via_hooks("page_js", self.name): js = get_js(path) if js: self.script += "\n\n" + js
def make_controller_template(self): from frappe.modules import get_doc_path, get_module_path, scrub target_path = get_doc_path(self.module, self.doctype, self.name) app = frappe.local.module_app[scrub(self.module)] if not app: frappe.throw(_("App not found")) app_publisher = frappe.get_hooks(hook="app_publisher", app_name=app)[0] def _make_boilerplate(template): template_name = template.replace("controller", scrub(self.name)) target_file_path = os.path.join(target_path, template_name) if not os.path.exists(target_file_path): with open(target_file_path, 'w') as target: with open( os.path.join(get_module_path("core"), "doctype", "doctype", "boilerplate", template), 'r') as source: target.write(source.read().format( app_publisher=app_publisher, classname=self.name.replace(" ", ""), doctype=self.name)) _make_boilerplate("controller.py") if not (self.istable or self.issingle): _make_boilerplate("test_controller.py") _make_boilerplate("test_records.json")
def write_document_file(doc, record_module=None, create_init=None): newdoc = doc.as_dict(no_nulls=True) # strip out default fields from children for df in doc.meta.get_table_fields(): for d in newdoc.get(df.fieldname): for fieldname in frappe.model.default_fields: if fieldname in d: del d[fieldname] for fieldname in d.keys(): if d[fieldname] == 0 or d[fieldname] == "": del d[fieldname] module = record_module or get_module_name(doc) if create_init is None: create_init = doc.doctype in lower_case_files_for # create folder folder = create_folder(module, doc.doctype, doc.name, create_init) # write the data file fname = (doc.doctype in lower_case_files_for and scrub(doc.name)) or doc.name with open(os.path.join(folder, fname + ".json"), 'w+') as txtfile: txtfile.write(frappe.as_json(newdoc))
def execute(): for dn in rename_map: frappe.reload_doc(get_doctype_module(dn), "doctype", scrub(dn)) for dt, field_list in rename_map.items(): for field in field_list: rename_field(dt, field[0], field[1])
def upload(): if not frappe.has_permission("Quotation", "create"): raise frappe.PermissionError from frappe.utils.csvutils import read_csv_content_from_uploaded_file from frappe.modules import scrub rows = read_csv_content_from_uploaded_file() rows = filter(lambda x: x and any(x), rows) if not rows: msg = [_("Please select a csv file")] return {"messages": msg, "error": msg} columns = [scrub(f) for f in rows[0]] columns[0] = "item_code" ret = [] error = [] start_row = 1 total = len(rows)-1 for i, row in enumerate(rows[start_row:]): row_idx = i + start_row d = frappe._dict(zip(columns, row)) item = frappe.db.sql("""select name from `tabItem` where name = %s and docstatus < 2""",d.item_code, as_dict=1) if item: newitem = {} newitem["item_code"] = item[0].name newitem["qty"] = d.quantity ret.append(newitem) else: error.append('Error for row (#%d) %s : Invalid Item Code' % (row_idx,row[0])) return {"messages": ret, "error": error}
def upload(): if not frappe.has_permission("BRS Entries", "create"): raise frappe.PermissionError from frappe.utils.csvutils import read_csv_content_from_uploaded_file from frappe.modules import scrub rows = read_csv_content_from_uploaded_file() rows = filter(lambda x: x and any(x), rows) if not rows: msg = [_("Please select a csv file")] return {"messages": msg, "error": msg} #Columns located at 4th row columns = [scrub(f) for f in rows[2]] ret = [] error = False from frappe.utils.csvutils import check_record, import_doc for i, row in enumerate(rows[3:]): if not row: continue row_idx = i + 3 d = frappe._dict(zip(columns, row)) d["doctype"] = "BRS Entries" try: check_record(d) ret.append(import_doc(d, "BRS Entries", 1, row_idx, submit=True)) except Exception, e: error = True ret.append('Error for row (#%d) %s : %s' % (row_idx, len(row)>1 and row[1] or "", cstr(e))) frappe.errprint(frappe.get_traceback())
def add_code(self): path = os.path.join(get_module_path(self.module), 'doctype', scrub(self.name)) def _get_path(fname): return os.path.join(path, scrub(fname)) system_country = frappe.get_system_settings("country") self._add_code(_get_path(self.name + '.js'), '__js') if system_country: self._add_code(_get_path(os.path.join('regional', system_country + '.js')), '__js') self._add_code(_get_path(self.name + '.css'), "__css") self._add_code(_get_path(self.name + '_list.js'), '__list_js') self._add_code(_get_path(self.name + '_calendar.js'), '__calendar_js') self._add_code(_get_path(self.name + '_tree.js'), '__tree_js') listview_template = _get_path(self.name + '_list.html') if os.path.exists(listview_template): self.set("__listview_template", get_html_format(listview_template)) self.add_code_via_hook("doctype_js", "__js") self.add_code_via_hook("doctype_list_js", "__list_js") self.add_code_via_hook("doctype_tree_js", "__tree_js") self.add_code_via_hook("doctype_calendar_js", "__calendar_js") self.add_custom_script() self.add_html_templates(path)
def upload(): if not frappe.has_permission("Attendance", "create"): raise frappe.PermissionError from frappe.utils.csvutils import read_csv_content_from_uploaded_file from frappe.modules import scrub rows = read_csv_content_from_uploaded_file() rows = filter(lambda x: x and any(x), rows) if not rows: msg = [_("Please select a csv file")] return {"messages": msg, "error": msg} columns = [scrub(f) for f in rows[4]] columns[0] = "name" columns[3] = "att_date" ret = [] error = False from frappe.utils.csvutils import check_record, import_doc for i, row in enumerate(rows[5:]): if not row: continue row_idx = i + 5 d = frappe._dict(zip(columns, row)) d["doctype"] = "Attendance" if d.name: d["docstatus"] = frappe.db.get_value("Attendance", d.name, "docstatus") try: check_record(d) ret.append(import_doc(d, "Attendance", 1, row_idx, submit=True)) except Exception, e: error = True ret.append('Error for row (#%d) %s : %s' % (row_idx, len(row)>1 and row[1] or "", cstr(e)))
def execute(): # rename doctypes tables = frappe.db.sql_list("show tables") for old_dt, new_dt in [["Journal Voucher Detail", "Journal Entry Account"], ["Journal Voucher", "Journal Entry"], ["Budget Distribution Detail", "Monthly Distribution Percentage"], ["Budget Distribution", "Monthly Distribution"]]: if "tab"+new_dt not in tables: frappe.rename_doc("DocType", old_dt, new_dt, force=True) # reload new child doctypes frappe.reload_doc("manufacturing", "doctype", "work_order_operation") frappe.reload_doc("manufacturing", "doctype", "workstation_working_hour") frappe.reload_doc("stock", "doctype", "item_variant") frappe.reload_doc("hr", "doctype", "salary_detail") frappe.reload_doc("accounts", "doctype", "party_account") frappe.reload_doc("accounts", "doctype", "fiscal_year_company") #rename table fieldnames for dn in rename_map: if not frappe.db.exists("DocType", dn): continue frappe.reload_doc(get_doctype_module(dn), "doctype", scrub(dn)) for dt, field_list in rename_map.items(): if not frappe.db.exists("DocType", dt): continue for field in field_list: rename_field(dt, field[0], field[1]) # update voucher type for old, new in [["Bank Voucher", "Bank Entry"], ["Cash Voucher", "Cash Entry"], ["Credit Card Voucher", "Credit Card Entry"], ["Contra Voucher", "Contra Entry"], ["Write Off Voucher", "Write Off Entry"], ["Excise Voucher", "Excise Entry"]]: frappe.db.sql("update `tabJournal Entry` set voucher_type=%s where voucher_type=%s", (new, old))
def execute(): frappe.reload_doc("accounts", "doctype", "loyalty_program") frappe.reload_doc("accounts", "doctype", "sales_invoice_item") if "Healthcare" not in frappe.get_active_domains(): return healthcare_custom_field_in_sales_invoice() for si_ref_doc in sales_invoice_referenced_doc: if frappe.db.exists("DocType", si_ref_doc): frappe.reload_doc(get_doctype_module(si_ref_doc), "doctype", scrub(si_ref_doc)) if frappe.db.has_column( si_ref_doc, sales_invoice_referenced_doc[si_ref_doc] ) and frappe.db.has_column(si_ref_doc, "invoiced"): # Set Reference DocType and Reference Docname doc_list = frappe.db.sql(""" select name from `tab{0}` where {1} is not null """.format(si_ref_doc, sales_invoice_referenced_doc[si_ref_doc])) if doc_list: frappe.reload_doc(get_doctype_module("Sales Invoice"), "doctype", "sales_invoice") for doc_id in doc_list: invoice_id = frappe.db.get_value( si_ref_doc, doc_id[0], sales_invoice_referenced_doc[si_ref_doc]) if frappe.db.exists("Sales Invoice", invoice_id): if si_ref_doc == "Lab Test": template = frappe.db.get_value( "Lab Test", doc_id[0], "template") if template: item = frappe.db.get_value( "Lab Test Template", template, "item") if item: frappe.db.sql( """update `tabSales Invoice Item` set reference_dt = '{0}', reference_dn = '{1}' where parent = '{2}' and item_code='{3}'""". format(si_ref_doc, doc_id[0], invoice_id, item)) else: invoice = frappe.get_doc( "Sales Invoice", invoice_id) for item_line in invoice.items: if not item_line.reference_dn: item_line.db_set({ "reference_dt": si_ref_doc, "reference_dn": doc_id[0] }) break # Documents mark invoiced for submitted sales invoice frappe.db.sql("""update `tab{0}` doc, `tabSales Invoice` si set doc.invoiced = 1 where si.docstatus = 1 and doc.{1} = si.name """.format(si_ref_doc, sales_invoice_referenced_doc[si_ref_doc]))
def get_items_from_csv(): if not frappe.has_permission("Quotation", "create"): raise frappe.PermissionError from frappe.utils.csvutils import read_csv_content_from_uploaded_file from frappe.modules import scrub rows = read_csv_content_from_uploaded_file() rows = filter(lambda x: x and any(x), rows) if not rows: msg = [_("Please select a csv file")] return {"messages": msg, "error": msg} columns = [scrub(f) for f in rows[0]] columns[0] = "item_code" ret = [] error = False messages = [] start_row = 1 for i, row in enumerate(rows[start_row:]): row_idx = i + start_row d = frappe._dict(zip(columns, row)) itemdict = frappe.db.sql("""select name,item_group, is_sales_item from `tabItem` where name = %s and docstatus < 2""",d.item_code, as_dict=1) if itemdict: item = itemdict[0] newitem = {} newitem["item_code"] = item.name newitem["qty"] = d.quantity newitem["item_group"] = item.item_group if d.page_break: newitem["page_break"] = True else: newitem["page_break"] = False if item.is_sales_item: if str(item.item_group).lower() == "raw material": messages.append('Ignored Row (#%d) %s : Item is a raw material' % (row_idx,row[0])) elif str(item.item_group).lower() == "assemblypart": messages.append('Ignored Row (#%d) %s : Item is an assembly part' % (row_idx,row[0])) else: ret.append(newitem) if d.page_break: messages.append('Row (#%d) %s : Item added with Page Break' % (row_idx,row[0])) else: messages.append('Row (#%d) %s : Item added' % (row_idx,row[0])) else: error = True messages.append('Error for row (#%d) %s : Item is not a sales item' % (row_idx,row[0])) else: error = True messages.append('Error for row (#%d) %s : Invalid Item Code' % (row_idx,row[0])) return {"items":ret,"messages": messages, "error": error}
def import_attendances(rows): def remove_holidays(rows): rows = [row for row in rows if row[4] != "Holiday"] return rows from frappe.modules import scrub rows = list(filter(lambda x: x and any(x), rows)) columns = [scrub(f) for f in rows[4]] columns[0] = "name" columns[3] = "attendance_date" rows = rows[5:] ret = [] error = False rows = remove_holidays(rows) from frappe.utils.csvutils import check_record, import_doc for i, row in enumerate(rows): if not row: continue row_idx = i + 5 d = frappe._dict(zip(columns, row)) d["doctype"] = "Attendance" if d.name: d["docstatus"] = frappe.db.get_value( "Attendance", d.name, "docstatus") try: check_record(d) ret.append(import_doc(d, "Attendance", 1, row_idx, submit=True)) frappe.publish_realtime('import_attendance', dict( progress=i, total=len(rows) )) except AttributeError: pass except Exception as e: error = True ret.append('Error for row (#%d) %s : %s' % (row_idx, len(row) > 1 and row[1] or "", cstr(e))) frappe.errprint(frappe.get_traceback()) if error: frappe.db.rollback() else: frappe.db.commit() frappe.publish_realtime('import_attendance', dict( messages=ret, error=error ))
def get_custom_module_path(module): package = frappe.db.get_value('Module Def', module, 'package') if not package: frappe.throw( 'Package must be set for custom Module <b>{module}</b>'.format( module=module)) path = os.path.join(get_package_path(package), scrub(module)) if not os.path.exists(path): os.makedirs(path) return path
def add_code(self): path = os.path.join(get_module_path(self.module), 'doctype', scrub(self.name)) def _get_path(fname): return os.path.join(path, scrub(fname)) self._add_code(_get_path(self.name + '.js'), '__js') self._add_code(_get_path(self.name + '.css'), "__css") self._add_code(_get_path(self.name + '_list.js'), '__list_js') self._add_code(_get_path(self.name + '_calendar.js'), '__calendar_js') self._add_code(_get_path(self.name + '_map.js'), '__map_js') self.add_custom_script() self.add_code_via_hook("doctype_js", "__js")
def reload_docs(docs): for dn in docs: frappe.reload_doc(get_doctype_module(dn), "doctype", scrub(dn)) # reload all standard print formats for pf in frappe.db.sql( """select name, module from `tabPrint Format` where ifnull(standard, 'No') = 'Yes'""", as_dict=1, ): try: frappe.reload_doc(pf.module, "Print Format", pf.name) except Exception, e: print e pass
def get_script(report_name): report = get_report_doc(report_name) module = frappe.db.get_value("DocType", report.ref_doctype, "module") module_path = get_module_path(module) report_folder = os.path.join(module_path, "report", scrub(report.name)) script_path = os.path.join(report_folder, scrub(report.name) + ".js") script = None if os.path.exists(script_path): with open(script_path, "r") as script: script = script.read() if not script and report.javascript: script = report.javascript if not script: script = "frappe.query_reports['%s']={}" % report_name # load translations if frappe.lang != "en": frappe.response["__messages"] = frappe.get_lang_dict("report", report_name) return script
def execute(): for doctypes, fields in [[selling_doctypes, selling_renamed_fields], [buying_doctypes, buying_renamed_fields]]: for dt in doctypes: frappe.reload_doc(get_doctype_module(dt), "doctype", scrub(dt)) table_columns = frappe.db.get_table_columns(dt) base_net_total = frappe.db.sql("select sum(ifnull({0}, 0)) from `tab{1}`".format(fields[0][1], dt))[0][0] if not base_net_total: for f in fields: if f[0] in table_columns: rename_field(dt, f[0], f[1]) # Added new field "total_taxes_and_charges" in buying cycle, updating value if dt in ("Supplier Quotation", "Purchase Order", "Purchase Receipt", "Purchase Invoice"): frappe.db.sql("""update `tab{0}` set total_taxes_and_charges = round(base_total_taxes_and_charges/conversion_rate, 2)""".format(dt))
def get_test_doclist(doctype, name=None): """get test doclist, collection of doclists""" import os, frappe from frappe import conf from frappe.modules.utils import peval_doclist from frappe.modules import scrub doctype = scrub(doctype) doctype_path = os.path.join(os.path.dirname(os.path.abspath(conf.__file__)), conf.test_data_path, doctype) if name: with open(os.path.join(doctype_path, scrub(name) + ".json"), 'r') as txtfile: doclist = peval_doclist(txtfile.read()) return doclist else: all_doclists = [] for fname in filter(lambda n: n.endswith(".json"), os.listdir(doctype_path)): with open(os.path.join(doctype_path, scrub(fname)), 'r') as txtfile: all_doclists.append(peval_doclist(txtfile.read())) return all_doclists
def run(report_name, filters=()): report = get_report_doc(report_name) if filters and isinstance(filters, basestring): filters = json.loads(filters) if not frappe.has_permission(report.ref_doctype, "report"): frappe.msgprint(_("Must have report permission to access this report."), raise_exception=True) if report.report_type=="Query Report": if not report.query: frappe.msgprint(_("Must specify a Query to run"), raise_exception=True) if not report.query.lower().startswith("select"): frappe.msgprint(_("Query must be a SELECT"), raise_exception=True) result = [list(t) for t in frappe.db.sql(report.query, filters)] columns = [c[0] for c in frappe.db.get_description()] else: module = frappe.db.get_value("DocType", report.ref_doctype, "module") if report.is_standard=="Yes": method_name = frappe.local.module_app[scrub(module)] + "." + scrub(module) \ + ".report." + scrub(report.name) + "." + scrub(report.name) + ".execute" columns, result = frappe.get_attr(method_name)(frappe._dict(filters)) result = get_filtered_data(report.ref_doctype, columns, result) if cint(report.add_total_row) and result: result = add_total_row(result, columns) return { "result": result, "columns": columns }
def add_code(self): path = os.path.join(get_module_path(self.module), 'doctype', scrub(self.name)) def _get_path(fname): return os.path.join(path, scrub(fname)) self._add_code(_get_path(self.name + '.js'), '__js') self._add_code(_get_path(self.name + '.css'), "__css") self._add_code(_get_path(self.name + '_list.js'), '__list_js') self._add_code(_get_path(self.name + '_calendar.js'), '__calendar_js') listview_template = _get_path(self.name + '_list.html') if os.path.exists(listview_template): self.set("__listview_template", get_html_format(listview_template)) self.add_code_via_hook("doctype_js", "__js") self.add_custom_script()
def make_records(records, debug=False): from frappe import _dict from frappe.modules import scrub if debug: print("make_records: in DEBUG mode") # LOG every success and failure for record in records: doctype = record.get("doctype") condition = record.get('__condition') if condition and not condition(): continue doc = frappe.new_doc(doctype) doc.update(record) # ignore mandatory for root parent_link_field = ("parent_" + scrub(doc.doctype)) if doc.meta.get_field(parent_link_field) and not doc.get(parent_link_field): doc.flags.ignore_mandatory = True try: doc.insert(ignore_permissions=True) except frappe.DuplicateEntryError as e: # print("Failed to insert duplicate {0} {1}".format(doctype, doc.name)) # pass DuplicateEntryError and continue if e.args and e.args[0]==doc.doctype and e.args[1]==doc.name: # make sure DuplicateEntryError is for the exact same doc and not a related doc pass else: raise except Exception as e: exception = record.get('__exception') if exception: config = _dict(exception) if isinstance(e, config.exception): config.handler() else: show_document_insert_error() else: show_document_insert_error()
def make_controller_template(self): from frappe.modules import get_doc_path, get_module_path, scrub pypath = os.path.join(get_doc_path(self.module, self.doctype, self.name), scrub(self.name) + '.py') if not os.path.exists(pypath): # get app publisher for copyright app = frappe.local.module_app[frappe.scrub(self.module)] if not app: frappe.throw(_("App not found")) app_publisher = frappe.get_hooks(hook="app_publisher", app_name=app)[0] with open(pypath, 'w') as pyfile: with open(os.path.join(get_module_path("core"), "doctype", "doctype", "doctype_template.py"), 'r') as srcfile: pyfile.write(srcfile.read().format(app_publisher=app_publisher, classname=self.name.replace(" ", "")))
def switch_module(dt, dn, to, frm=None, export=None): """ Change the module of the given doctype, if export is true, then also export txt and copy code files from src """ frappe.db.sql("update `tab"+dt+"` set module=%s where name=%s", (to, dn)) if export: export_doc(dt, dn) # copy code files if dt in ('DocType', 'Page', 'Report'): from_path = os.path.join(get_module_path(frm), scrub(dt), scrub(dn), scrub(dn)) to_path = os.path.join(get_module_path(to), scrub(dt), scrub(dn), scrub(dn)) # make dire if exists os.system('mkdir -p %s' % os.path.join(get_module_path(to), scrub(dt), scrub(dn))) for ext in ('py','js','html','css'): os.system('cp %s %s')
def write_document_file(doc, record_module=None, create_init=True): newdoc = doc.as_dict(no_nulls=True) # strip out default fields from children for df in doc.meta.get_table_fields(): for d in newdoc.get(df.fieldname): for fieldname in frappe.model.default_fields: if fieldname in d: del d[fieldname] module = record_module or get_module_name(doc) # create folder folder = create_folder(module, doc.doctype, doc.name, create_init) # write the data file fname = scrub(doc.name) with open(os.path.join(folder, fname +".json"),'w+') as txtfile: txtfile.write(frappe.as_json(newdoc))
def execute(): frappe.reload_doc('accounts', 'doctype', 'loyalty_program') frappe.reload_doc('accounts', 'doctype', 'sales_invoice_item') if "Healthcare" not in frappe.get_active_domains(): return healthcare_custom_field_in_sales_invoice() for si_ref_doc in sales_invoice_referenced_doc: if frappe.db.exists('DocType', si_ref_doc): frappe.reload_doc(get_doctype_module(si_ref_doc), 'doctype', scrub(si_ref_doc)) if frappe.db.has_column(si_ref_doc, sales_invoice_referenced_doc[si_ref_doc]) \ and frappe.db.has_column(si_ref_doc, 'invoiced'): # Set Reference DocType and Reference Docname doc_list = frappe.db.sql(""" select name from `tab{0}` where {1} is not null """.format(si_ref_doc, sales_invoice_referenced_doc[si_ref_doc])) if doc_list: frappe.reload_doc(get_doctype_module("Sales Invoice"), 'doctype', 'sales_invoice') for doc_id in doc_list: invoice_id = frappe.db.get_value(si_ref_doc, doc_id[0], sales_invoice_referenced_doc[si_ref_doc]) if frappe.db.exists("Sales Invoice", invoice_id): if si_ref_doc == "Lab Test": template = frappe.db.get_value("Lab Test", doc_id[0], "template") if template: item = frappe.db.get_value("Lab Test Template", template, "item") if item: frappe.db.sql("""update `tabSales Invoice Item` set reference_dt = '{0}', reference_dn = '{1}' where parent = '{2}' and item_code='{3}'""".format\ (si_ref_doc, doc_id[0], invoice_id, item)) else: invoice = frappe.get_doc("Sales Invoice", invoice_id) for item_line in invoice.items: if not item_line.reference_dn: item_line.db_set({"reference_dt":si_ref_doc, "reference_dn": doc_id[0]}) break # Documents mark invoiced for submitted sales invoice frappe.db.sql("""update `tab{0}` doc, `tabSales Invoice` si set doc.invoiced = 1 where si.docstatus = 1 and doc.{1} = si.name """.format(si_ref_doc, sales_invoice_referenced_doc[si_ref_doc]))
def make_fixture_records(records): from frappe.modules import scrub for r in records: doc = frappe.new_doc(r.get("doctype")) doc.update(r) # ignore mandatory for root parent_link_field = ("parent_" + scrub(doc.doctype)) if doc.meta.get_field(parent_link_field) and not doc.get(parent_link_field): doc.flags.ignore_mandatory = True try: doc.insert(ignore_permissions=True) except frappe.DuplicateEntryError as e: # pass DuplicateEntryError and continue if e.args and e.args[0]==doc.doctype and e.args[1]==doc.name: # make sure DuplicateEntryError is for the exact same doc and not a related doc pass else: raise
def execute(): for dt, field_list in field_rename_map.items(): if frappe.db.exists('DocType', dt): frappe.reload_doc(get_doctype_module(dt), "doctype", scrub(dt)) for field in field_list: if frappe.db.has_column(dt, field[0]): rename_field(dt, field[0], field[1]) if frappe.db.exists('DocType', 'Lab Prescription'): if frappe.db.has_column('Lab Prescription', 'parentfield'): frappe.db.sql(""" update `tabLab Prescription` set parentfield = 'lab_test_prescription' where parentfield = 'test_prescription' """) if frappe.db.exists('DocType', 'Lab Test Groups'): if frappe.db.has_column('Lab Test Groups', 'parentfield'): frappe.db.sql(""" update `tabLab Test Groups` set parentfield = 'lab_test_groups' where parentfield = 'test_groups' """)
def write_document_file(doc, record_module=None, create_init=None): newdoc = doc.as_dict(no_nulls=True) # strip out default fields from children for df in doc.meta.get_table_fields(): for d in newdoc.get(df.fieldname): for fieldname in frappe.model.default_fields: if fieldname in d: del d[fieldname] module = record_module or get_module_name(doc) if create_init is None: create_init = doc.doctype in lower_case_files_for # create folder folder = create_folder(module, doc.doctype, doc.name, create_init) # write the data file fname = (doc.doctype in lower_case_files_for and scrub(doc.name)) or doc.name with open(os.path.join(folder, fname +".json"),'w+') as txtfile: txtfile.write(json.dumps(newdoc, indent=1, sort_keys=True))