def on_trash(self): if self.doc.attached_to_name: # check persmission try: if not webnotes.has_permission(self.doc.attached_to_doctype, "write", self.doc.attached_to_name): webnotes.msgprint( webnotes._("No permission to write / remove."), raise_exception=True) except webnotes.DoesNotExistError: pass # if file not attached to any other record, delete it if self.doc.file_name and not webnotes.conn.count( "File Data", { "file_name": self.doc.file_name, "name": ["!=", self.doc.name] }): if self.doc.file_name.startswith("files/"): path = webnotes.utils.get_site_path("public", self.doc.file_name) else: path = webnotes.utils.get_site_path(conf.files_path, self.doc.file_name) if os.path.exists(path): os.remove(path)
def get_dashboard_info(customer): if not webnotes.has_permission("Customer", "read", customer): webnotes.msgprint("No Permission", raise_exception=True) out = {} for doctype in [ "Opportunity", "Quotation", "Sales Order", "Delivery Note", "Sales Invoice" ]: out[doctype] = webnotes.conn.get_value(doctype, { "customer": customer, "docstatus": ["!=", 2] }, "count(*)") billing = webnotes.conn.sql( """select sum(grand_total), sum(outstanding_amount) from `tabSales Invoice` where customer=%s and docstatus = 1 and fiscal_year = %s""", (customer, webnotes.conn.get_default("fiscal_year"))) out["total_billing"] = billing[0][0] out["total_unpaid"] = billing[0][1] return out
def save(self, check_links=1): perm_to_check = "write" if self.doc.fields.get("__islocal"): perm_to_check = "create" if not self.doc.owner: self.doc.owner = webnotes.session.user if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, perm_to_check, self.doc): self.to_docstatus = 0 self.prepare_for_save("save") if self.doc.fields.get("__islocal"): # set name before validate self.doc.set_new_name() self.run_method('before_insert') if not self.ignore_validate: self.run_method('validate') if not self.ignore_mandatory: self.check_mandatory() self.save_main() self.save_children() self.run_method('on_update') else: self.no_permission_to(_(perm_to_check.title())) return self
def get_dashboard_info(supplier): if not webnotes.has_permission("Supplier", "read", supplier): webnotes.msgprint("No Permission", raise_exception=True) out = {} for doctype in [ "Supplier Quotation", "Purchase Order", "Purchase Receipt", "Purchase Invoice" ]: out[doctype] = webnotes.conn.get_value(doctype, { "supplier": supplier, "docstatus": ["!=", 2] }, "count(*)") billing = webnotes.conn.sql( """select sum(grand_total), sum(outstanding_amount) from `tabPurchase Invoice` where supplier=%s and docstatus = 1 and fiscal_year = %s""", (supplier, webnotes.conn.get_default("fiscal_year"))) out["total_billing"] = billing[0][0] out["total_unpaid"] = billing[0][1] return out
def get_value(doctype, fieldname, filters=None, as_dict=True, debug=False): if not webnotes.has_permission(doctype): webnotes.msgprint("No Permission", raise_exception=True) if fieldname and fieldname.startswith("["): fieldname = json.loads(fieldname) return webnotes.conn.get_value(doctype, json.loads(filters), fieldname, as_dict=as_dict, debug=debug)
def get_events(start, end): from webnotes.widgets.reportview import build_match_conditions if not webnotes.has_permission("Time Log"): webnotes.msgprint(_("No Permission"), raise_exception=1) match = build_match_conditions("Time Log") data = webnotes.conn.sql("""select name, from_time, to_time, activity_type, task, project from `tabTime Log` where from_time between '%(start)s' and '%(end)s' or to_time between '%(start)s' and '%(end)s' %(match)s""" % { "start": start, "end": end, "match": match and (" and " + match) or "" }, as_dict=True, update={"allDay": 0}) for d in data: d.title = d.name + ": " + (d.activity_type or "[Activity Type not set]") if d.task: d.title += " for Task: " + d.task if d.project: d.title += " for Project: " + d.project return data
def upload(select_doctype=None, rows=None): from webnotes.utils.datautils import read_csv_content_from_uploaded_file from webnotes.modules import scrub from webnotes.model.rename_doc import rename_doc if not select_doctype: select_doctype = webnotes.form_dict.select_doctype if not webnotes.has_permission(select_doctype, "write"): raise webnotes.PermissionError if not rows: rows = read_csv_content_from_uploaded_file() if not rows: webnotes.msgprint(_("Please select a valid csv file with data.")) raise Exception if len(rows) > 500: webnotes.msgprint(_("Max 500 rows only.")) raise Exception rename_log = [] for row in rows: # if row has some content if len(row) > 1 and row[0] and row[1]: try: if rename_doc(select_doctype, row[0], row[1]): rename_log.append(_("Successful: ") + row[0] + " -> " + row[1]) webnotes.conn.commit() else: rename_log.append(_("Ignored: ") + row[0] + " -> " + row[1]) except Exception, e: rename_log.append("<span style='color: RED'>" + \ _("Failed: ") + row[0] + " -> " + row[1] + "</span>") rename_log.append("<span style='margin-left: 20px;'>" + repr(e) + "</span>")
def get_events(start, end, filters=None): from webnotes.widgets.reportview import build_match_conditions if not webnotes.has_permission("Task"): webnotes.msgprint(_("No Permission"), raise_exception=1) conditions = build_match_conditions("Task") conditions and (" and " + conditions) or "" if filters: filters = json.loads(filters) for key in filters: if filters[key]: conditions += " and " + key + ' = "' + filters[key].replace( '"', '\"') + '"' data = webnotes.conn.sql("""select name, exp_start_date, exp_end_date, subject, status, project from `tabTask` where ((exp_start_date between '%(start)s' and '%(end)s') \ or (exp_end_date between '%(start)s' and '%(end)s')) %(conditions)s""" % { "start": start, "end": end, "conditions": conditions }, as_dict=True, update={"allDay": 0}) return data
def get_events(start, end, filters=None): from webnotes.widgets.reportview import build_match_conditions if not webnotes.has_permission("Task"): webnotes.msgprint(_("No Permission"), raise_exception=1) conditions = build_match_conditions("Task") conditions and (" and " + conditions) or "" if filters: filters = json.loads(filters) for key in filters: if filters[key]: conditions += " and " + key + ' = "' + filters[key].replace('"', '\"') + '"' data = webnotes.conn.sql("""select name, exp_start_date, exp_end_date, subject, status, project from `tabTask` where ((exp_start_date between '%(start)s' and '%(end)s') \ or (exp_end_date between '%(start)s' and '%(end)s')) %(conditions)s""" % { "start": start, "end": end, "conditions": conditions }, as_dict=True, update={"allDay": 0}) return data
def run(report_name): report = webnotes.doc("Report", report_name) if not webnotes.has_permission(report.ref_doctype, "report"): webnotes.msgprint(_("Must have report permission to access this report."), raise_exception=True) if report.report_type=="Query Report": if not report.query: webnotes.msgprint(_("Must specify a Query to run"), raise_exception=True) if not report.query.lower().startswith("select"): webnotes.msgprint(_("Query must be a SELECT"), raise_exception=True) result = [list(t) for t in webnotes.conn.sql(report.query)] columns = [c[0] for c in webnotes.conn.get_description()] else: from webnotes.modules import scrub method_name = scrub(webnotes.conn.get_value("DocType", report.ref_doctype, "module")) \ + ".report." + scrub(report.name) + "." + scrub(report.name) + ".execute" columns, result = webnotes.get_method(method_name)() return { "result": result, "columns": columns }
def get_args(): if not webnotes.form_dict.format: webnotes.form_dict.format = standard_format if not webnotes.form_dict.doctype or not webnotes.form_dict.name: return { "body": """<h1>Error</h1> <p>Parameters doctype, name and format required</p> <pre>%s</pre>""" % repr(webnotes.form_dict) } bean = webnotes.bean(webnotes.form_dict.doctype, webnotes.form_dict.name) for ptype in ("read", "print"): if not webnotes.has_permission(bean.doc.doctype, ptype, bean.doc): return { "body": """<h1>Error</h1> <p>No {ptype} permission</p>""".format( ptype=ptype ) } return { "body": get_html(bean.doc, bean.doclist), "css": get_print_style(webnotes.form_dict.style), "comment": webnotes.session.user, }
def run(report_name, filters=None): report = webnotes.doc("Report", report_name) if filters and isinstance(filters, basestring): filters = json.loads(filters) if not webnotes.has_permission(report.ref_doctype, "report"): webnotes.msgprint(_("Must have report permission to access this report."), raise_exception=True) if report.report_type=="Query Report": if not report.query: webnotes.msgprint(_("Must specify a Query to run"), raise_exception=True) if not report.query.lower().startswith("select"): webnotes.msgprint(_("Query must be a SELECT"), raise_exception=True) result = [list(t) for t in webnotes.conn.sql(report.query, filters)] columns = [c[0] for c in webnotes.conn.get_description()] else: method_name = scrub(webnotes.conn.get_value("DocType", report.ref_doctype, "module")) \ + ".report." + scrub(report.name) + "." + scrub(report.name) + ".execute" columns, result = webnotes.get_method(method_name)(filters or {}) 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 validate_rename(doctype, new, doclist, merge, force): exists = webnotes.conn.exists(doctype, new) if merge and not exists: webnotes.msgprint( "%s: %s does not exist, select a new target to merge." % (doctype, new), raise_exception=1) if (not merge) and exists: webnotes.msgprint("%s: %s exists, select a new, new name." % (doctype, new), raise_exception=1) if not webnotes.has_permission(doctype, "write"): webnotes.msgprint("You need write permission to rename", raise_exception=1) if not force and not doclist[0].allow_rename: webnotes.msgprint("%s cannot be renamed" % doctype, raise_exception=1) # validate naming like it's done in doc.py new = validate_name(doctype, new, merge=merge) return new
def get_mapped_doclist(from_doctype, from_docname, table_maps, target_doclist=[], postprocess=None, ignore_permissions=False): if isinstance(target_doclist, basestring): target_doclist = json.loads(target_doclist) source = webnotes.bean(from_doctype, from_docname) if not ignore_permissions and not webnotes.has_permission(from_doctype, "read", source.doc): webnotes.msgprint("No Permission", raise_exception=webnotes.PermissionError) source_meta = webnotes.get_doctype(from_doctype) target_meta = webnotes.get_doctype(table_maps[from_doctype]["doctype"]) # main if target_doclist: if isinstance(target_doclist[0], dict): target_doc = webnotes.doc(fielddata=target_doclist[0]) else: target_doc = target_doclist[0] else: target_doc = webnotes.new_doc(table_maps[from_doctype]["doctype"]) map_doc(source.doc, target_doc, table_maps[source.doc.doctype], source_meta, target_meta) if target_doclist: target_doclist[0] = target_doc else: target_doclist = [target_doc] # children for source_d in source.doclist[1:]: table_map = table_maps.get(source_d.doctype) if table_map: if "condition" in table_map: if not table_map["condition"](source_d): continue target_doctype = table_map["doctype"] parentfield = target_meta.get({ "parent": target_doc.doctype, "doctype": "DocField", "fieldtype": "Table", "options": target_doctype })[0].fieldname if table_map.get("add_if_empty") and row_exists_in_target(parentfield, target_doclist): continue target_d = webnotes.new_doc(target_doctype, target_doc, parentfield) map_doc(source_d, target_d, table_map, source_meta, target_meta, source.doclist[0]) target_doclist.append(target_d) target_doclist = webnotes.doclist(target_doclist) if postprocess: new_target_doclist = postprocess(source, target_doclist) if new_target_doclist: target_doclist = new_target_doclist return target_doclist
def submit(self): if webnotes.has_permission(self.doc.doctype, "submit"): if self.doc.docstatus != 0: webnotes.msgprint("Only draft can be submitted", raise_exception=1) self.to_docstatus = 1 self.save() self.run_method('on_submit') else: webnotes.msgprint("No Permission to Submit", raise_exception=True)
def save(self, check_links=1): if webnotes.has_permission(self.doc.doctype, "write"): self.prepare_for_save(check_links) self.run_method('validate') self.save_main() self.save_children() self.run_method('on_update') else: webnotes.msgprint("No Permission to Write", raise_exception=True)
def check_permission_and_not_submitted(doctype, name): # permission if webnotes.session.user!="Administrator" and not webnotes.has_permission(doctype, "cancel"): webnotes.msgprint(_("User not allowed to delete."), raise_exception=True) # check if submitted if webnotes.conn.get_value(doctype, name, "docstatus") == 1: webnotes.msgprint(_("Submitted Record cannot be deleted")+": "+name+"("+doctype+")", raise_exception=True)
def check_permission_and_not_submitted(doctype, name, ignore_permissions=False): # permission if not ignore_permissions and webnotes.session.user!="Administrator" and not webnotes.has_permission(doctype, "cancel"): webnotes.msgprint(_("User not allowed to delete."), raise_exception=True) # check if submitted if webnotes.conn.get_value(doctype, name, "docstatus") == 1: webnotes.msgprint(_("Submitted Record cannot be deleted")+": "+name+"("+doctype+")", raise_exception=True)
def get_report_doc(report_name): bean = webnotes.bean("Report", report_name) if not bean.has_read_perm(): raise webnotes.PermissionError("You don't have access to: {report}".format(report=report_name)) if not webnotes.has_permission(bean.doc.ref_doctype, "report"): raise webnotes.PermissionError("You don't have access to get a report on: {doctype}".format( doctype=bean.doc.ref_doctype)) return bean.doc
def submit(self): if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc): if self.doc.docstatus != 0: webnotes.msgprint("Only draft can be submitted", raise_exception=1) self.to_docstatus = 1 self.save() self.run_method('on_submit') else: self.no_permission_to(_("Submit")) return self
def cancel(self): if webnotes.has_permission(self.doc.doctype, "submit"): if self.doc.docstatus != 1: webnotes.msgprint("Only submitted can be cancelled", raise_exception=1) self.to_docstatus = 2 self.prepare_for_save(1) self.save_main() self.save_children() self.run_method('on_cancel') else: webnotes.msgprint("No Permission to Cancel", raise_exception=True)
def save(self, check_links=1): if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc): self.prepare_for_save(check_links) self.run_method('validate') self.save_main() self.save_children() self.run_method('on_update') else: self.no_permission_to(_("Write")) return self
def save(doclist): """insert or update from form query""" if isinstance(doclist, basestring): doclist = json.loads(doclist) if not webnotes.has_permission(doclist[0]["doctype"], "write"): webnotes.msgprint("No Write Permission", raise_exception=True) doclistobj = webnotes.model_wrapper(doclist) doclistobj.save() return [d.fields for d in doclist]
def make(doctype=None, name=None, content=None, subject=None, sent_or_received = "Sent", sender=None, recipients=None, communication_medium="Email", send_email=False, print_html=None, attachments='[]', send_me_a_copy=False, set_lead=True, date=None): if doctype and name and not webnotes.has_permission(doctype, "email", name): raise webnotes.PermissionError("You are not allowed to send emails related to: {doctype} {name}".format( doctype=doctype, name=name)) _send(doctype=doctype, name=name, content=content, subject=subject, sent_or_received=sent_or_received, sender=sender, recipients=recipients, communication_medium=communication_medium, send_email=send_email, print_html=print_html, attachments=attachments, send_me_a_copy=send_me_a_copy, set_lead=set_lead, date=date)
def save(): """insert or update from form query""" doclist = json.loads(webnotes.form_dict.doclist) from webnotes.model.wrapper import ModelWrapper if not webnotes.has_permission(doclist[0]["doctype"], "write"): webnotes.msgprint("No Write Permission", raise_exception=True) doclistobj = ModelWrapper(doclist) doclistobj.save() return [d.fields for d in doclist]
def submit(self): if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "submit", self.doc): self.to_docstatus = 1 self.prepare_for_save("submit") self.run_method('validate') self.save_main() self.save_children() self.run_method('on_update') self.run_method('on_submit') else: self.no_permission_to(_("Submit")) return self
def load_doctypes(): """load all doctypes and roles""" global doctypes, roles import webnotes.model.doctype roles = webnotes.get_roles() for t in tables: if t.startswith('`'): doctype = t[4:-1] if not webnotes.has_permission(doctype): raise webnotes.PermissionError, doctype doctypes[doctype] = webnotes.model.doctype.get(doctype)
def save(self, check_links=1): if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc): self.to_docstatus = 0 self.prepare_for_save("save") if not self.ignore_validate: self.run_method("validate") self.save_main() self.save_children() self.run_method("on_update") else: self.no_permission_to(_("Write")) return self
def validate_rename(doctype, new, doclist, merge, force): exists = webnotes.conn.exists(doctype, new) if merge and not exists: webnotes.msgprint("%s: %s does not exist, select a new target to merge." % (doctype, new), raise_exception=1) if not merge and exists: webnotes.msgprint("%s: %s exists, select a new, new name." % (doctype, new), raise_exception=1) if not webnotes.has_permission(doctype, "write"): webnotes.msgprint("You need write permission to rename", raise_exception=1) if not force and not doclist[0].allow_rename: webnotes.msgprint("%s cannot be renamed" % doctype, raise_exception=1)
def cancel(self): if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc): if self.doc.docstatus != 1: webnotes.msgprint("Only submitted can be cancelled", raise_exception=1) self.to_docstatus = 2 self.prepare_for_save(1) self.save_main() self.save_children() self.run_method('on_cancel') else: self.no_permission_to(_("Cancel")) return self
def cancel(self): if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "cancel", self.doc): self.to_docstatus = 2 self.prepare_for_save("cancel") self.run_method('before_cancel') self.save_main() self.save_children() self.run_method('on_cancel') self.check_no_back_links_exist() else: self.no_permission_to(_("Cancel")) return self
def update_after_submit(self): if self.doc.docstatus != 1: webnotes.msgprint("Only to called after submit", raise_exception=1) if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc): self.to_docstatus = 1 self.prepare_for_save(1) self.save_main() self.save_children() self.run_method('on_update_after_submit') else: self.no_permission_to(_("Update")) return self
def save(self, check_links=1): if self.ignore_permissions or webnotes.has_permission( self.doc.doctype, "write", self.doc): self.to_docstatus = 0 self.prepare_for_save("save") if not self.ignore_validate: self.run_method('validate') self.save_main() self.save_children() self.run_method('on_update') else: self.no_permission_to(_("Write")) return self
def submit(self): if self.ignore_permissions or webnotes.has_permission( self.doc.doctype, "submit", self.doc): self.to_docstatus = 1 self.prepare_for_save("submit") self.run_method('validate') self.save_main() self.save_children() self.run_method('on_update') self.run_method('on_submit') else: self.no_permission_to(_("Submit")) return self
def update_after_submit(self): if self.doc.docstatus != 1: webnotes.msgprint("Only to called after submit", raise_exception=1) if self.ignore_permissions or webnotes.has_permission(self.doc.doctype, "write", self.doc): self.to_docstatus = 1 self.prepare_for_save("update_after_submit") self.run_method('before_update_after_submit') self.save_main() self.save_children() self.run_method('on_update_after_submit') else: self.no_permission_to(_("Update")) return self
def on_trash(self): if self.doc.file_name and webnotes.conn.sql("""select count(*) from `tabFile Data` where file_name=%s""", self.doc.file_name)[0][0]==1: path = webnotes.utils.get_path("public", "files", self.doc.file_name) if os.path.exists(path): os.remove(path) if self.doc.attached_to_name: # check persmission if not webnotes.has_permission(self.doc.attached_to_doctype, "write", self.doc.attached_to_name): webnotes.msgprint(webnotes._("No permission to write / remove."), raise_exception=True)
def load_doctypes(): """load all doctypes and roles""" import webnotes.model.doctype webnotes.local.reportview_roles = webnotes.get_roles() if not getattr(webnotes.local, "reportview_doctypes", None): webnotes.local.reportview_doctypes = {} for t in webnotes.local.reportview_tables: if t.startswith('`'): doctype = t[4:-1] if not webnotes.has_permission(doctype): raise webnotes.PermissionError, doctype webnotes.local.reportview_doctypes[doctype] = webnotes.model.doctype.get(doctype)
def on_trash(self): if self.doc.file_name and webnotes.conn.sql( """select count(*) from `tabFile Data` where file_name=%s""", self.doc.file_name)[0][0] == 1: path = webnotes.utils.get_path("public", "files", self.doc.file_name) if os.path.exists(path): os.remove(path) if self.doc.attached_to_name: # check persmission if not webnotes.has_permission(self.doc.attached_to_doctype, "write", self.doc.attached_to_name): webnotes.msgprint( webnotes._("No permission to write / remove."), raise_exception=True)
def get_template(): if not webnotes.has_permission("Attendance", "create"): raise webnotes.PermissionError args = webnotes.local.form_dict webnotes.local.uploadattendance_doclist = webnotes.model.doctype.get("Attendance") w = UnicodeWriter() w = add_header(w) w = add_data(w, args) # write out response as a type csv webnotes.response['result'] = cstr(w.getvalue()) webnotes.response['type'] = 'csv' webnotes.response['doctype'] = "Attendance"
def get_template(): if not webnotes.has_permission("Attendance", "create"): raise webnotes.PermissionError args = webnotes.local.form_dict webnotes.local.uploadattendance_doclist = webnotes.model.doctype.get( "Attendance") w = UnicodeWriter() w = add_header(w) w = add_data(w, args) # write out response as a type csv webnotes.response['result'] = cstr(w.getvalue()) webnotes.response['type'] = 'csv' webnotes.response['doctype'] = "Attendance"
def on_trash(self): if self.doc.attached_to_name: # check persmission try: if not webnotes.has_permission(self.doc.attached_to_doctype, "write", self.doc.attached_to_name): webnotes.msgprint(webnotes._("No permission to write / remove."), raise_exception=True) except webnotes.DoesNotExistError: pass # if file not attached to any other record, delete it if self.doc.file_name and webnotes.conn.sql("""select count(*) from `tabFile Data` where file_name=%s and name!=%s""", (self.doc.file_name, self.doc.name)): path = webnotes.utils.get_site_path(conf.files_path, self.doc.file_name) if os.path.exists(path): os.remove(path)
def has_permission(page_doclist): if webnotes.user.name == "Administrator" or "System Manager" in webnotes.user.get_roles(): return True page_roles = [d.role for d in page_doclist if d.fields.get("doctype")=="Page Role"] if page_roles: if webnotes.session.user == "Guest" and "Guest" not in page_roles: return False elif not set(page_roles).intersection(set(webnotes.get_roles())): # check if roles match return False if not webnotes.has_permission("Page", ptype="read", refdoc=page_doclist[0].name): # check if there are any restrictions return False else: # hack for home pages! if no page roles, allow everyone to see! return True
def run(): globals().update(webnotes.form_dict) if not query: webnotes.msgprint("Must specify a Query to run", raise_exception=1) if not doctype: webnotes.msgprint("Must specify DocType for permissions.", raise_exception=1) if not webnotes.has_permission(doctype, "read"): webnotes.msgprint("Must have read permission to access this report.", raise_exception=1) if not query.lower().startswith("select"): webnotes.msgprint("Query must be a SELECT", raise_exception=True) result = [list(t) for t in webnotes.conn.sql(query)] columns = webnotes.conn.get_description() return {"result": result, "columns": [c[0] for c in columns]}
def on_trash(self): if self.doc.attached_to_name: # check persmission try: if not webnotes.has_permission(self.doc.attached_to_doctype, "write", self.doc.attached_to_name): webnotes.msgprint( webnotes._("No permission to write / remove."), raise_exception=True) except webnotes.DoesNotExistError: pass # if file not attached to any other record, delete it if self.doc.file_name and webnotes.conn.sql( """select count(*) from `tabFile Data` where file_name=%s and name!=%s""", (self.doc.file_name, self.doc.name)): path = webnotes.utils.get_site_path(conf.files_path, self.doc.file_name) if os.path.exists(path): os.remove(path)
def upload(select_doctype=None, rows=None): from webnotes.utils.datautils import read_csv_content_from_uploaded_file from webnotes.modules import scrub from webnotes.model.rename_doc import rename_doc if not select_doctype: select_doctype = webnotes.form_dict.select_doctype if not webnotes.has_permission(select_doctype, "write"): raise webnotes.PermissionError if not rows: rows = read_csv_content_from_uploaded_file() if not rows: webnotes.msgprint(_("Please select a valid csv file with data.")) raise Exception if len(rows) > 500: webnotes.msgprint(_("Max 500 rows only.")) raise Exception rename_log = [] for row in rows: # if row has some content if len(row) > 1 and row[0] and row[1]: try: if rename_doc(select_doctype, row[0], row[1]): rename_log.append( _("Successful: ") + row[0] + " -> " + row[1]) webnotes.conn.commit() else: rename_log.append( _("Ignored: ") + row[0] + " -> " + row[1]) except Exception, e: rename_log.append("<span style='color: RED'>" + \ _("Failed: ") + row[0] + " -> " + row[1] + "</span>") rename_log.append("<span style='margin-left: 20px;'>" + repr(e) + "</span>")
def upload(): if not webnotes.has_permission("Attendance", "create"): raise webnotes.PermissionError from webnotes.utils.datautils import read_csv_content_from_uploaded_file from webnotes.modules import scrub rows = read_csv_content_from_uploaded_file() 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 webnotes.utils.datautils import check_record, import_doc doctype_dl = webnotes.get_doctype("Attendance") for i, row in enumerate(rows[5:]): if not row: continue row_idx = i + 5 d = webnotes._dict(zip(columns, row)) d["doctype"] = "Attendance" if d.name: d["docstatus"] = webnotes.conn.get_value("Attendance", d.name, "docstatus") try: check_record(d, doctype_dl=doctype_dl) 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))) webnotes.errprint(webnotes.getTraceback())
def get_mapped_doclist(from_doctype, from_docname, table_maps, target_doclist=None, postprocess=None, ignore_permissions=False): if target_doclist is None: target_doclist = [] if isinstance(target_doclist, basestring): target_doclist = json.loads(target_doclist) source = webnotes.bean(from_doctype, from_docname) if not ignore_permissions and not webnotes.has_permission(from_doctype, "read", source.doc): webnotes.msgprint("No Permission", raise_exception=webnotes.PermissionError) source_meta = webnotes.get_doctype(from_doctype) target_meta = webnotes.get_doctype(table_maps[from_doctype]["doctype"]) # main if target_doclist: if isinstance(target_doclist[0], dict): target_doc = webnotes.doc(fielddata=target_doclist[0]) else: target_doc = target_doclist[0] else: target_doc = webnotes.new_doc(table_maps[from_doctype]["doctype"]) map_doc(source.doc, target_doc, table_maps[source.doc.doctype], source_meta, target_meta) if target_doclist: target_doclist[0] = target_doc else: target_doclist = [target_doc] target_doclist = webnotes.doclist(target_doclist) # children for source_d in source.doclist[1:]: table_map = table_maps.get(source_d.doctype) if table_map: if "condition" in table_map: if not table_map["condition"](source_d): continue target_doctype = table_map["doctype"] parentfield = target_meta.get({ "parent": target_doc.doctype, "doctype": "DocField", "fieldtype": "Table", "options": target_doctype })[0].fieldname if table_map.get("add_if_empty") and row_exists_in_target(parentfield, target_doclist): continue target_d = webnotes.new_doc(target_doctype, target_doc, parentfield) map_doc(source_d, target_d, table_map, source_meta, target_meta, source.doclist[0]) target_d.idx = None target_doclist.append(target_d) target_doclist = webnotes.doclist(target_doclist) if postprocess: new_target_doclist = postprocess(source, target_doclist) if new_target_doclist: target_doclist = new_target_doclist return target_doclist
def has_read_perm(self): return webnotes.has_permission(self.doc.doctype, "read", self.doc)
def has_permission(doctype, docname, perm_type="read"): # perm_type can be one of read, write, create, submit, cancel, report return { "has_permission": webnotes.has_permission(doctype, perm_type.lower(), docname) }