def get_linked_docs(doctype, name, metadata_loaded=None): if not metadata_loaded: metadata_loaded = [] meta = webnotes.get_doctype(doctype, True) linkinfo = meta[0].get("__linked_with") results = {} for dt, link in linkinfo.items(): link["doctype"] = dt linkmeta = webnotes.get_doctype(dt, True) if not linkmeta[0].get("issingle"): fields = [d.fieldname for d in linkmeta.get({"parent":dt, "in_list_view":1})] \ + ["name", "modified"] fields = ["`tab{dt}`.`{fn}`".format(dt=dt, fn=sf.strip()) for sf in fields if sf] if link.get("child_doctype"): ret = webnotes.get_list(doctype=dt, fields=fields, filters=[[link.get('child_doctype'), link.get("fieldname"), '=', name]]) else: ret = webnotes.get_list(doctype=dt, fields=fields, filters=[[dt, link.get("fieldname"), '=', name]]) if ret: results[dt] = ret if not dt in metadata_loaded: if not "docs" in webnotes.local.response: webnotes.local.response.docs = [] webnotes.local.response.docs += linkmeta return results
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 update_completed_qty(controller, caller_method): if controller.doc.doctype == "Stock Entry": material_request_map = {} for d in controller.doclist.get({"parentfield": "mtn_details"}): if d.material_request: if d.material_request not in material_request_map: material_request_map[d.material_request] = [] material_request_map[d.material_request].append( d.material_request_item) for mr_name, mr_items in material_request_map.items(): mr_obj = webnotes.get_obj("Material Request", mr_name, with_children=1) mr_doctype = webnotes.get_doctype("Material Request") if mr_obj.doc.status in ["Stopped", "Cancelled"]: msgprint(_("Material Request") + ": %s, " % mr_obj.doc.name + _(mr_doctype.get_label("status")) + " = %s. " % _(mr_obj.doc.status) + _("Cannot continue."), raise_exception=webnotes.InvalidStatusError) _update_requested_qty(controller, mr_obj, mr_items) # update ordered percentage and qty mr_obj.update_completed_qty(mr_items)
def has_permission(doctype, ptype="read", refdoc=None, verbose=True): """check if user has permission""" if webnotes.conn.get_value("DocType", doctype, "istable")==1: return True meta = webnotes.get_doctype(doctype) if ptype=="submit" and not cint(meta[0].is_submittable): return False if ptype=="import" and not cint(meta[0].allow_import): return False if webnotes.session.user=="Administrator": return True # get user permissions if not get_user_perms(meta).get(ptype): return False if refdoc: if isinstance(refdoc, basestring): refdoc = webnotes.doc(meta[0].name, refdoc) if not has_unrestricted_access(meta, refdoc, verbose=verbose): return False if not has_additional_permission(refdoc): return False return True
def export_doc(doctype, docname): import json doclist = [] ignore_list = [ "name", "owner", "creation", "modified", "modified_by", "idx", "naming_series", "parenttype", "parent", "docstatus" ] make_test_records(doctype) meta = webnotes.get_doctype(doctype) for d in webnotes.bean(doctype, docname): new_doc = {} for key, val in d.fields.iteritems(): if val and key not in ignore_list: df = meta.get_field(key, d.parent or None, d.parentfield or None) if df and df.fieldtype == "Link": val = (webnotes.test_objects.get(df.options) or [val])[0] elif df and df.fieldtype == "Select" and df.options and df.options.startswith( "link:"): val = (webnotes.test_objects.get(df.options[5:]) or [val])[0] if not df or df.reqd == 1: new_doc[key] = val doclist.append(new_doc) print json.dumps(doclist, indent=4, sort_keys=True).replace(" ", "\t")
def validate_currency(args, item, meta=None): from webnotes.model.meta import get_field_precision if not meta: meta = webnotes.get_doctype(args.doctype) # validate conversion rate if meta.get_field("currency"): validate_conversion_rate(args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company) # round it args.conversion_rate = flt(args.conversion_rate, get_field_precision(meta.get_field("conversion_rate"), webnotes._dict({"fields": args}))) # validate price list conversion rate if meta.get_field("price_list_currency") and (args.selling_price_list or args.buying_price_list) \ and args.price_list_currency: validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate, meta.get_label("plc_conversion_rate"), args.company) # round it args.plc_conversion_rate = flt(args.plc_conversion_rate, get_field_precision(meta.get_field("plc_conversion_rate"), webnotes._dict({"fields": args})))
def make_query(fields, dt, key, txt, start, length): doctype = webnotes.get_doctype(dt) enabled_condition = "" if doctype.get({ "parent": dt, "fieldname": "enabled", "fieldtype": "Check" }): enabled_condition = " AND ifnull(`tab%s`.`enabled`,0)=1" % dt if doctype.get({ "parent": dt, "fieldname": "disabled", "fieldtype": "Check" }): enabled_condition = " AND ifnull(`tab%s`.`disabled`,0)!=1" % dt query = """select %(fields)s FROM `tab%(dt)s` WHERE `tab%(dt)s`.`%(key)s` LIKE '%(txt)s' AND `tab%(dt)s`.docstatus != 2 %(enabled_condition)s ORDER BY `tab%(dt)s`.`%(key)s` ASC LIMIT %(start)s, %(len)s """ % { 'fields': fields, 'dt': dt, 'key': key, 'txt': txt + '%', 'start': start, 'len': length, 'enabled_condition': enabled_condition, } return query
def get_defaults(self, arg): if isinstance(arg, basestring): import json arg = json.loads(arg) match_key = arg["match"] with_profiles = arg["profiles"] pl = ol = [] # defaults dl = [ a for a in sql( "select parent, ifnull(parenttype,'') as parenttype, ifnull(defvalue,'') as defvalue from tabDefaultValue where defkey=%s order by parenttype desc, parent asc", match_key, as_dict=1, ) ] # options tn = webnotes.get_doctype(arg["doctype"]).get_options(match_key) # tn = sql("select options from tabDocField where fieldname=%s and fieldtype='Link' and docstatus=0 limit 1", match_key)[0][0] ol = [""] + [a[0] for a in sql("select name from `tab%s` where ifnull(docstatus,0)=0" % tn)] # roles if with_profiles == "Yes": # profiles pl = [""] + [a[0] for a in sql("select name from tabProfile where ifnull(enabled,0)=1")] return {"dl": dl, "pl": pl, "ol": ol}
def update_completed_qty(controller, caller_method): if controller.doc.doctype == "Stock Entry": material_request_map = {} for d in controller.doclist.get({"parentfield": "mtn_details"}): if d.material_request: if d.material_request not in material_request_map: material_request_map[d.material_request] = [] material_request_map[d.material_request].append(d.material_request_item) for mr_name, mr_items in material_request_map.items(): mr_obj = webnotes.get_obj("Material Request", mr_name, with_children=1) mr_doctype = webnotes.get_doctype("Material Request") if mr_obj.doc.status in ["Stopped", "Cancelled"]: msgprint( _("Material Request") + ": %s, " % mr_obj.doc.name + _(mr_doctype.get_label("status")) + " = %s. " % _(mr_obj.doc.status) + _("Cannot continue."), raise_exception=webnotes.InvalidStatusError, ) _update_requested_qty(controller, mr_obj, mr_items) # update ordered percentage and qty mr_obj.update_completed_qty(mr_items)
def execute(): webnotes.reload_doc("hr", "doctype", "leave_application") if not webnotes.get_doctype("Leave Application").get({"doctype": "DocField", "parent": "Leave Application", "permlevel": 2}): webnotes.conn.sql("""update `tabDocPerm` set permlevel=1 where parent="Leave Application" and permlevel=2""")
def create_custom_field_for_workflow_state(self): webnotes.clear_cache(doctype=self.doc.document_type) doctypeobj = webnotes.get_doctype(self.doc.document_type) if not len(doctypeobj.get({"doctype": "DocField", "fieldname": self.doc.workflow_state_field})): # create custom field webnotes.bean( [ { "doctype": "Custom Field", "dt": self.doc.document_type, "__islocal": 1, "fieldname": self.doc.workflow_state_field, "label": self.doc.workflow_state_field.replace("_", " ").title(), "hidden": 1, "fieldtype": "Link", "options": "Workflow State", # "insert_after": doctypeobj.get({"doctype":"DocField"})[-1].fieldname } ] ).save() webnotes.msgprint( "Created Custom Field '%s' in '%s'" % (self.doc.workflow_state_field, self.doc.document_type) )
def test_doclist(self): p_meta = webnotes.get_doctype("Profile") self.assertEquals( len( p_meta.get({ "doctype": "DocField", "parent": "Profile", "fieldname": "first_name" })), 1) self.assertEquals( len( p_meta.get({ "doctype": "DocField", "parent": "Profile", "fieldname": "^first" })), 1) self.assertEquals(len(p_meta.get({"fieldname": ["!=", "first_name"]})), len(p_meta) - 1) self.assertEquals( len(p_meta.get({"fieldname": ["in", ["first_name", "last_name"]]})), 2) self.assertEquals( len( p_meta.get( {"fieldname": ["not in", ["first_name", "last_name"]]})), len(p_meta) - 2)
def upload(): 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 upload(): 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_query_result(fields, dt, txt, searchfield, start, page_len, filters): doctype = webnotes.get_doctype(dt) enabled_condition = "" if doctype.get({"parent":dt, "fieldname":"enabled", "fieldtype":"Check"}): enabled_condition = " AND ifnull(`enabled`,0)=1 " if doctype.get({"parent":dt, "fieldname":"disabled", "fieldtype":"Check"}): enabled_condition = " AND ifnull(`disabled`,0)!=1" filter_condition, filter_values = build_filter_conditions(filters) args = { 'fields': fields, 'dt': dt, 'key': searchfield, 'txt': '%s', 'start': start, 'len': page_len, 'enabled_condition': enabled_condition, 'filter_condition': filter_condition } return webnotes.conn.sql("""select %(fields)s FROM `tab%(dt)s` WHERE `%(key)s` LIKE %(txt)s AND docstatus != 2 %(enabled_condition)s %(filter_condition)s ORDER BY `%(key)s` ASC LIMIT %(start)s, %(len)s""" % args, tuple(["%%%s%%" % txt] + filter_values))
def create_custom_field_for_workflow_state(self): webnotes.clear_cache(doctype=self.doc.document_type) doctypeobj = webnotes.get_doctype(self.doc.document_type) if not len( doctypeobj.get({ "doctype": "DocField", "fieldname": self.doc.workflow_state_field })): # create custom field webnotes.bean([{ "doctype": "Custom Field", "dt": self.doc.document_type, "__islocal": 1, "fieldname": self.doc.workflow_state_field, "label": self.doc.workflow_state_field.replace("_", " ").title(), "hidden": 1, "fieldtype": "Link", "options": "Workflow State", #"insert_after": doctypeobj.get({"doctype":"DocField"})[-1].fieldname }]).save() webnotes.msgprint( "Created Custom Field '%s' in '%s'" % (self.doc.workflow_state_field, self.doc.document_type))
def validate_currency(args, item, meta=None): from webnotes.model.meta import get_field_precision if not meta: meta = webnotes.get_doctype(args.doctype) # validate conversion rate if meta.get_field("currency"): validate_conversion_rate(args.currency, args.conversion_rate, meta.get_label("conversion_rate"), args.company) # round it args.conversion_rate = flt( args.conversion_rate, get_field_precision(meta.get_field("conversion_rate"), webnotes._dict({"fields": args}))) # validate price list conversion rate if meta.get_field("price_list_currency") and (args.selling_price_list or args.buying_price_list) \ and args.price_list_currency: validate_conversion_rate(args.price_list_currency, args.plc_conversion_rate, meta.get_label("plc_conversion_rate"), args.company) # round it args.plc_conversion_rate = flt( args.plc_conversion_rate, get_field_precision(meta.get_field("plc_conversion_rate"), webnotes._dict({"fields": args})))
def get_item_details(args): """ args = { "item_code": "", "warehouse": None, "customer": "", "conversion_rate": 1.0, "selling_price_list": None, "price_list_currency": None, "plc_conversion_rate": 1.0 } """ if isinstance(args, basestring): args = json.loads(args) args = webnotes._dict(args) if args.barcode: args.item_code = _get_item_code(barcode=args.barcode) elif not args.item_code and args.serial_no: args.item_code = _get_item_code(serial_no=args.serial_no) item_bean = webnotes.bean("Item", args.item_code) _validate_item_details(args, item_bean.doc) meta = webnotes.get_doctype(args.doctype) # hack! for Sales Order Item warehouse_fieldname = "warehouse" if meta.get_field("reserved_warehouse", parentfield=args.parentfield): warehouse_fieldname = "reserved_warehouse" out = _get_basic_details(args, item_bean, warehouse_fieldname) if meta.get_field("currency"): out.base_ref_rate = out.basic_rate = out.ref_rate = out.export_rate = 0.0 if args.selling_price_list and args.price_list_currency: out.update(_get_price_list_rate(args, item_bean, meta)) out.update(_get_item_discount(out.item_group, args.customer)) if out.get(warehouse_fieldname): out.update( get_available_qty(args.item_code, out.get(warehouse_fieldname))) out.customer_item_code = _get_customer_item_code(args, item_bean) if cint(args.is_pos): pos_settings = get_pos_settings(args.company) if pos_settings: out.update(apply_pos_settings(pos_settings, out)) if args.doctype in ("Sales Invoice", "Delivery Note"): if item_bean.doc.has_serial_no == "Yes" and not args.serial_no: out.serial_no = _get_serial_nos_by_fifo(args, item_bean) return out
def get_default_account(self, account_for): account = webnotes.conn.get_value("Company", self.doc.company, account_for) if not account: msgprint(_("Please mention default account for '") + _(webnotes.get_doctype("company").get_label(account_for) + _("' in Company: ") + self.doc.company), raise_exception=True) return account
def _get_fields(fieldnames): return [ webnotes._dict( zip(["label", "fieldname", "fieldtype", "options"], [df.label, df.fieldname, df.fieldtype, df.options])) for df in webnotes.get_doctype("Address", processed=True).get( {"fieldname": ["in", fieldnames]}) ]
def test_doclist(self): p_meta = webnotes.get_doctype("Profile") self.assertEquals(len(p_meta.get({"doctype": "DocField", "parent": "Profile", "fieldname": "first_name"})), 1) self.assertEquals(len(p_meta.get({"doctype": "DocField", "parent": "Profile", "fieldname": "^first"})), 1) self.assertEquals(len(p_meta.get({"fieldname": ["!=", "first_name"]})), len(p_meta) - 1) self.assertEquals(len(p_meta.get({"fieldname": ["in", ["first_name", "last_name"]]})), 2) self.assertEquals(len(p_meta.get({"fieldname": ["not in", ["first_name", "last_name"]]})), len(p_meta) - 2)
def get_item_details(args): """ args = { "item_code": "", "warehouse": None, "customer": "", "conversion_rate": 1.0, "selling_price_list": None, "price_list_currency": None, "plc_conversion_rate": 1.0 } """ if isinstance(args, basestring): args = json.loads(args) args = webnotes._dict(args) if args.barcode: args.item_code = _get_item_code(barcode=args.barcode) elif not args.item_code and args.serial_no: args.item_code = _get_item_code(serial_no=args.serial_no) item_bean = webnotes.bean("Item", args.item_code) _validate_item_details(args, item_bean.doc) meta = webnotes.get_doctype(args.doctype) # hack! for Sales Order Item warehouse_fieldname = "warehouse" if meta.get_field("reserved_warehouse", parentfield=args.parentfield): warehouse_fieldname = "reserved_warehouse" out = _get_basic_details(args, item_bean, warehouse_fieldname) if meta.get_field("currency"): out.base_ref_rate = out.basic_rate = out.ref_rate = out.export_rate = 0.0 if args.selling_price_list and args.price_list_currency: out.update(_get_price_list_rate(args, item_bean, meta)) out.update(_get_item_discount(out.item_group, args.customer)) if out.get(warehouse_fieldname): out.update(get_available_qty(args.item_code, out.get(warehouse_fieldname))) out.customer_item_code = _get_customer_item_code(args, item_bean) if cint(args.is_pos): pos_settings = get_pos_settings(args.company) if pos_settings: out.update(apply_pos_settings(pos_settings, out)) if args.doctype in ("Sales Invoice", "Delivery Note"): if item_bean.doc.has_serial_no == "Yes" and not args.serial_no: out.serial_no = _get_serial_nos_by_fifo(args, item_bean) return out
def get_stock_in_hand_account(self): stock_in_hand_account = webnotes.conn.get_value("Company", self.doc.company, "stock_in_hand_account") if not stock_in_hand_account: msgprint(_("Missing") + ": " + _(webnotes.get_doctype("company").get_label("stock_in_hand_account") + " " + _("for Company") + " " + self.doc.company), raise_exception=True) return stock_in_hand_account
def print_mandatory_fields(doctype): print "Please setup make_test_records for: " + doctype print "-" * 60 doctype_obj = webnotes.get_doctype(doctype) print "Autoname: " + (doctype_obj[0].autoname or "") print "Mandatory Fields: " for d in doctype_obj.get({"reqd":1}): print d.parent + ":" + d.fieldname + " | " + d.fieldtype + " | " + (d.options or "") print
def get_company_default(company, fieldname): value = webnotes.conn.get_value("Company", company, fieldname) if not value: msgprint(_("Please mention default value for '") + _(webnotes.get_doctype("company").get_label(fieldname) + _("' in Company: ") + company), raise_exception=True) return value
def copy_common_fields(from_doc, to_doc): from webnotes.model import default_fields doctype_list = webnotes.get_doctype(to_doc.doctype) for fieldname, value in from_doc.fields.items(): if fieldname in default_fields: continue if doctype_list.get_field(fieldname) and to_doc.fields[fieldname] != value: to_doc.fields[fieldname] = value
def get_new_doc(doctype, parent_doc = None, parentfield = None): doc = webnotes.doc({ "doctype": doctype, "__islocal": 1, "owner": webnotes.session.user, "docstatus": 0 }) meta = webnotes.get_doctype(doctype) restrictions = webnotes.defaults.get_restrictions() if parent_doc: doc.parent = parent_doc.name doc.parenttype = parent_doc.doctype if parentfield: doc.parentfield = parentfield for d in meta.get({"doctype":"DocField", "parent": doctype}): default = webnotes.defaults.get_user_default(d.fieldname) if (d.fieldtype=="Link") and d.ignore_restrictions != 1 and (d.options in restrictions)\ and len(restrictions[d.options])==1: doc.fields[d.fieldname] = restrictions[d.options][0] elif default: doc.fields[d.fieldname] = default elif d.fields.get("default"): if d.default == "__user": doc.fields[d.fieldname] = webnotes.session.user elif d.default == "Today": doc.fields[d.fieldname] = nowdate() elif d.default.startswith(":"): ref_fieldname = d.default[1:].lower().replace(" ", "_") if parent_doc: ref_docname = parent_doc.fields[ref_fieldname] else: ref_docname = webnotes.conn.get_default(ref_fieldname) doc.fields[d.fieldname] = webnotes.conn.get_value(d.default[1:], ref_docname, d.fieldname) else: doc.fields[d.fieldname] = d.default # convert type of default if d.fieldtype in ("Int", "Check"): doc.fields[d.fieldname] = cint(doc.fields[d.fieldname]) elif d.fieldtype in ("Float", "Currency"): doc.fields[d.fieldname] = flt(doc.fields[d.fieldname]) elif d.fieldtype == "Time": doc.fields[d.fieldname] = nowtime() return doc
def validate_restrictions(self): if self.ignore_restrictions: return has_restricted_data = False for d in self.doclist: if not webnotes.permissions.has_unrestricted_access(webnotes.get_doctype(d.doctype), d): has_restricted_data = True if has_restricted_data: raise BeanPermissionError
def copy_common_fields(from_doc, to_doc): from webnotes.model import default_fields doctype_list = webnotes.get_doctype(to_doc.doctype) for fieldname, value in from_doc.fields.items(): if fieldname in default_fields: continue if doctype_list.get_field( fieldname) and to_doc.fields[fieldname] != value: to_doc.fields[fieldname] = value
def can_restrict_user(user, doctype, docname=None): if not can_restrict(doctype, docname): return False meta = webnotes.get_doctype(doctype) # check if target user does not have restrict permission if has_only_non_restrict_role(meta, user): return True return False
def get_linked_docs(doctype, name, metadata_loaded=None): if not metadata_loaded: metadata_loaded = [] meta = webnotes.get_doctype(doctype, True) linkinfo = meta[0].get("__linked_with") results = {} for dt, link in linkinfo.items(): link["doctype"] = dt linkmeta = webnotes.get_doctype(dt, True) if not linkmeta[0].get("issingle"): fields = [d.fieldname for d in linkmeta.get({"parent":dt, "in_list_view":1, "fieldtype": ["not in", ["Image", "HTML", "Button", "Table"]]})] \ + ["name", "modified", "docstatus"] fields = [ "`tab{dt}`.`{fn}`".format(dt=dt, fn=sf.strip()) for sf in fields if sf ] if link.get("child_doctype"): ret = webnotes.get_list(doctype=dt, fields=fields, filters=[[ link.get('child_doctype'), link.get("fieldname"), '=', name ]]) else: ret = webnotes.get_list( doctype=dt, fields=fields, filters=[[dt, link.get("fieldname"), '=', name]]) if ret: results[dt] = ret if not dt in metadata_loaded: if not "docs" in webnotes.local.response: webnotes.local.response.docs = [] webnotes.local.response.docs += linkmeta return results
def get_match_cond(doctype, searchfield = 'name'): meta = webnotes.get_doctype(doctype) from webnotes.widgets.search import get_std_fields_list fields = get_std_fields_list(meta, searchfield) from webnotes.widgets.reportview import build_match_conditions cond = build_match_conditions(doctype, fields) if cond: cond = ' and ' + cond else: cond = '' return cond
def get_item_details(args): """ args = { "doctype": "", "docname": "", "item_code": "", "warehouse": None, "supplier": None, "transaction_date": None, "conversion_rate": 1.0, "buying_price_list": None, "price_list_currency": None, "plc_conversion_rate": 1.0, "is_subcontracted": "Yes" / "No" } """ if isinstance(args, basestring): args = json.loads(args) args = webnotes._dict(args) item_bean = webnotes.bean("Item", args.item_code) item = item_bean.doc _validate_item_details(args, item) out = _get_basic_details(args, item_bean) out.supplier_part_no = _get_supplier_part_no(args, item_bean) if not out.warehouse: out.warehouse = item_bean.doc.default_warehouse if out.warehouse: out.projected_qty = get_projected_qty(item.name, out.warehouse) if args.transaction_date and item.lead_time_days: out.schedule_date = out.lead_time_date = add_days(args.transaction_date, item.lead_time_days) meta = webnotes.get_doctype(args.doctype) if meta.get_field("currency"): out.purchase_ref_rate = out.discount_rate = out.purchase_rate = \ out.import_ref_rate = out.import_rate = 0.0 out.update(_get_price_list_rate(args, item_bean, meta)) if args.doctype == "Material Request": out.min_order_qty = flt(item.min_order_qty) return out
def get_plugin_name(doctype=None, docname=None): import os from webnotes.utils import get_site_base_path plugin = None if doctype: meta = webnotes.get_doctype(doctype) if meta.get_field("plugin"): plugin = webnotes.conn.get_value(doctype, docname, "plugin") if not plugin: plugin = os.path.basename(get_site_base_path()) return plugin
def get_html(doc, doclist, print_format=None): from jinja2 import Environment if isinstance(doc, basestring) and isinstance(doclist, basestring): bean = webnotes.bean(doc, doclist) doc = bean.doc doclist = bean.doclist template = Environment().from_string(get_print_format_name(doc.doctype, print_format or webnotes.form_dict.format)) doctype = webnotes.get_doctype(doc.doctype) args = {"doc": doc, "doclist": doclist, "doctype": doctype, "webnotes": webnotes, "utils": webnotes.utils} html = template.render(args) return html
def get_new_doc(doctype, parent_doc = None, parentfield = None): doc = webnotes.doc({ "doctype": doctype, "__islocal": 1, "owner": webnotes.session.user, "docstatus": 0 }) meta = webnotes.get_doctype(doctype) if parent_doc: doc.parent = parent_doc.name doc.parenttype = parent_doc.doctype if parentfield: doc.parentfield = parentfield for d in meta.get({"doctype":"DocField", "parent": doctype}): default = webnotes.defaults.get_user_default(d.fieldname) if default: doc.fields[d.fieldname] = default elif d.fields.get("default"): if d.default == "__user": doc.fields[d.fieldname] = webnotes.session.user elif d.default == "Today": doc.fields[d.fieldname] = nowdate() elif d.default.startswith(":"): ref_fieldname = d.default[1:].lower().replace(" ", "_") if parent_doc: ref_docname = parent_doc.fields[ref_fieldname] else: ref_docname = webnotes.conn.get_default(ref_fieldname) doc.fields[d.fieldname] = webnotes.conn.get_value(d.default[1:], ref_docname, d.fieldname) else: doc.fields[d.fieldname] = d.default # convert type of default if d.fieldtype in ("Int", "Check"): doc.fields[d.fieldname] = cint(doc.fields[d.fieldname]) elif d.fieldtype in ("Float", "Currency"): doc.fields[d.fieldname] = flt(doc.fields[d.fieldname]) elif d.fieldtype == "Time": doc.fields[d.fieldname] = nowtime() return doc
def search_widget(doctype, txt, query=None, searchfield="name", start=0, page_len=50, filters=None): if isinstance(filters, basestring): import json filters = json.loads(filters) meta = webnotes.get_doctype(doctype) standard_queries = webnotes.get_hooks().standard_queries or [] if standard_queries: standard_queries = dict([v.split(":") for v in standard_queries]) if query and query.split()[0].lower()!="select": # by method webnotes.response["values"] = webnotes.get_attr(query)(doctype, txt, searchfield, start, page_len, filters) elif not query and doctype in standard_queries: # from standard queries search_widget(doctype, txt, standard_queries[doctype], searchfield, start, page_len, filters) else: if query: # custom query webnotes.response["values"] = webnotes.conn.sql(scrub_custom_query(query, searchfield, txt)) else: if isinstance(filters, dict): filters_items = filters.items() filters = [] for f in filters_items: if isinstance(f[1], (list, tuple)): filters.append([doctype, f[0], f[1][0], f[1][1]]) else: filters.append([doctype, f[0], "=", f[1]]) if filters==None: filters = [] # build from doctype if txt: filters.append([doctype, searchfield or "name", "like", txt + "%"]) if meta.get({"parent":doctype, "fieldname":"enabled", "fieldtype":"Check"}): filters.append([doctype, "enabled", "=", 1]) if meta.get({"parent":doctype, "fieldname":"disabled", "fieldtype":"Check"}): filters.append([doctype, "disabled", "!=", 1]) webnotes.response["values"] = webnotes.widgets.reportview.execute(doctype, filters=filters, fields = get_std_fields_list(meta, searchfield or "name"), limit_start = start, limit_page_length=page_len, as_list=True)
def validate_end_of_life(item_code, end_of_life=None, verbose=1): if not end_of_life: end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life") from webnotes.utils import getdate, now_datetime, formatdate if end_of_life and getdate(end_of_life) > now_datetime().date(): msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \ " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \ "in Item master") % { "item_code": item_code, "date": formatdate(end_of_life), "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life") } _msgprint(msg, verbose)
def get_lead_naming_series(): """gets lead's default naming series""" global lead_naming_series naming_series_field = webnotes.get_doctype("Lead").get_field("naming_series") if naming_series_field.default: lead_naming_series = naming_series_field.default else: latest_naming_series = webnotes.conn.sql("""select naming_series from `tabLead` order by creation desc limit 1""") if latest_naming_series: lead_naming_series = latest_naming_series[0][0] else: lead_naming_series = filter(None, naming_series_field.options.split("\n"))[0] return lead_naming_series
def can_restrict(doctype, docname=None): # System Manager can always restrict if "System Manager" in webnotes.get_roles(): return True meta = webnotes.get_doctype(doctype) # check if current user has read permission for docname if docname and not has_permission(doctype, "read", docname): return False # check if current user has a role with restrict permission if not has_restrict_permission(meta): return False return True
def get_address_display(address_dict): if not isinstance(address_dict, dict): address_dict = webnotes.conn.get_value("Address", address_dict, "*", as_dict=True) or {} meta = webnotes.get_doctype("Address") sequence = (("", "address_line1"), ("\n", "address_line2"), ("\n", "city"), ("\n", "state"), ("\n" + meta.get_label("pincode") + ": ", "pincode"), ("\n", "country"), ("\n" + meta.get_label("phone") + ": ", "phone"), ("\n" + meta.get_label("fax") + ": ", "fax")) display = "" for separator, fieldname in sequence: if address_dict.get(fieldname): display += separator + address_dict.get(fieldname) return display.strip()
def validate_end_of_life(item_code, end_of_life=None, verbose=1): if not end_of_life: end_of_life = webnotes.conn.get_value("Item", item_code, "end_of_life") from webnotes.utils import getdate, now_datetime, formatdate if end_of_life and getdate(end_of_life) <= now_datetime().date(): msg = (_("Item") + " %(item_code)s: " + _("reached its end of life on") + \ " %(date)s. " + _("Please check") + ": %(end_of_life_label)s " + \ "in Item master") % { "item_code": item_code, "date": formatdate(end_of_life), "end_of_life_label": webnotes.get_doctype("Item").get_label("end_of_life") } _msgprint(msg, verbose)
def get_html(doc, doclist): from jinja2 import Environment from core.doctype.print_format.print_format import get_print_format template = Environment().from_string(get_print_format(doc.doctype, webnotes.form_dict.format)) doctype = webnotes.get_doctype(doc.doctype) args = { "doc": doc, "doclist": doclist, "doctype": doctype, "webnotes": webnotes, "utils": webnotes.utils } html = template.render(args) return html
def execute(): from webnotes.utils import cint webnotes.reload_doc("setup", "doctype", "global_defaults") doctype_list = webnotes.get_doctype("Sales Invoice") update_stock_df = doctype_list.get_field("update_stock") global_defaults = webnotes.bean("Global Defaults", "Global Defaults") global_defaults.doc.update_stock = cint(update_stock_df.default) global_defaults.save() webnotes.conn.sql("""delete from `tabProperty Setter` where doc_type='Sales Invoice' and doctype_or_field='DocField' and field_name='update_stock' and property='default'""") webnotes.reload_doc("accounts", "doctype", "sales_invoice")
def search_widget(doctype, txt, query=None, searchfield="name", start=0, page_len=50, filters=None): if isinstance(filters, basestring): import json filters = json.loads(filters) meta = webnotes.get_doctype(doctype) if query and query.split()[0].lower()!="select": # by method webnotes.response["values"] = webnotes.get_method(query)(doctype, txt, searchfield, start, page_len, filters) elif startup_standard_queries and not query and doctype in standard_queries: # from standard queries search_widget(doctype, txt, standard_queries[doctype], searchfield, start, page_len, filters) else: if query: # custom query webnotes.response["values"] = webnotes.conn.sql(scrub_custom_query(query, searchfield, txt)) else: if isinstance(filters, dict): filters_items = filters.items() filters = [] for f in filters_items: if isinstance(f[1], (list, tuple)): filters.append([doctype, f[0], f[1][0], f[1][1]]) else: filters.append([doctype, f[0], "=", f[1]]) if filters==None: filters = [] # build from doctype if txt: filters.append([doctype, searchfield or "name", "like", txt + "%"]) if meta.get({"parent":doctype, "fieldname":"enabled", "fieldtype":"Check"}): filters.append([doctype, "enabled", "=", 1]) if meta.get({"parent":doctype, "fieldname":"disabled", "fieldtype":"Check"}): filters.append([doctype, "disabled", "!=", 1]) webnotes.response["values"] = webnotes.widgets.reportview.execute(doctype, filters=filters, fields = get_std_fields_list(meta, searchfield or "name"), limit_start = start, limit_page_length=page_len, as_list=True)
def execute(): webnotes.reload_doc("core", "doctype", "custom_field") cf_doclist = webnotes.get_doctype("Custom Field") delete_list = [] for d in webnotes.conn.sql("""select cf.name as cf_name, ps.property, ps.value, ps.name as ps_name from `tabProperty Setter` ps, `tabCustom Field` cf where ps.doctype_or_field = 'DocField' and ps.property != 'previous_field' and ps.doc_type=cf.dt and ps.field_name=cf.fieldname""", as_dict=1): if cf_doclist.get_field(d.property): webnotes.conn.sql("""update `tabCustom Field` set `%s`=%s where name=%s""" % (d.property, '%s', '%s'), (d.value, d.cf_name)) delete_list.append(d.ps_name) if delete_list: webnotes.conn.sql("""delete from `tabProperty Setter` where name in (%s)""" % ', '.join(['%s']*len(delete_list)), tuple(delete_list))
def get_template(): """download template""" template_type = webnotes.form_dict.get('type') doctypelist = webnotes.get_doctype("Journal Voucher") naming_options = doctypelist.get_options("naming_series") voucher_type = doctypelist.get_options("voucher_type") if template_type == "Two Accounts": extra_note = "" columns = '''"Naming Series","Voucher Type","Posting Date","Amount","Debit Account","Credit Account","Cost Center","Against Sales Invoice","Against Purchase Invoice","Against Journal Voucher","Remarks","Due Date","Ref Number","Ref Date"''' else: extra_note = ''' "5. Put the account head as Data label each in a new column" "6. Put the Debit amount as +ve and Credit amount as -ve"''' columns = '''"Naming Series","Voucher Type","Posting Date","Cost Center","Against Sales Invoice","Against Purchase Invoice","Against Journal Voucher","Remarks","Due Date","Ref Number","Ref Date"''' webnotes.response['result'] = '''"Voucher Import: %(template_type)s" "Each entry below will be a separate Journal Voucher." "Note:" "1. Dates in format: %(user_fmt)s" "2. Cost Center is required for Income or Expense accounts" "3. Naming Series Options: %(naming_options)s" "4. Voucher Type Options: %(voucher_type)s"%(extra_note)s "-------Common Values-----------" "Company:","%(default_company)s" "--------Data----------" %(columns)s ''' % { "template_type": template_type, "user_fmt": webnotes.conn.get_value('Control Panel', None, 'date_format'), "default_company": webnotes.conn.get_default("company"), "naming_options": naming_options.replace("\n", ", "), "voucher_type": voucher_type.replace("\n", ", "), "extra_note": extra_note, "columns": columns } webnotes.response['type'] = 'csv' webnotes.response['doctype'] = "Voucher-Import-%s" % template_type
def get_down(self, ur): doctypelist = webnotes.get_doctype("Journal Voucher") naming_options = doctypelist.get_options("naming_series") voucher_type = doctypelist.get_options("voucher_type") #if template_type=="Two Accounts": # extra_note = "" re = sql("select name from `tabCustomer`") columns = '''"name"''' for (name) in re: #columns+="\n\""+cstr(name)+"\",\""+cstr(customer)+"\",\""+cstr(status1)+"\"" columns += "\n\"" + cstr(name) + "\"" webnotes.response['result'] = '''%(columns)s ''' % { "user_fmt": webnotes.defaults.get_global_default('date_format'), "default_company": webnotes.conn.get_default("company"), "naming_options": naming_options.replace("", " "), "voucher_type": voucher_type.replace("", ""), "columns": columns } webnotes.response['type'] = 'csv' webnotes.response['doctype'] = "Voucher-Import-%s" % template_type
def get_query_result(fields, dt, txt, searchfield, start, page_len, filters): doctype = webnotes.get_doctype(dt) enabled_condition = "" if doctype.get({ "parent": dt, "fieldname": "enabled", "fieldtype": "Check" }): enabled_condition = " AND ifnull(`enabled`,0)=1 " if doctype.get({ "parent": dt, "fieldname": "disabled", "fieldtype": "Check" }): enabled_condition = " AND ifnull(`disabled`,0)!=1" filter_condition, filter_values = build_filter_conditions(filters) args = { 'fields': fields, 'dt': dt, 'key': searchfield, 'txt': '%s', 'start': start, 'len': page_len, 'enabled_condition': enabled_condition, 'filter_condition': filter_condition } return webnotes.conn.sql( """select %(fields)s FROM `tab%(dt)s` WHERE `%(key)s` LIKE %(txt)s AND docstatus != 2 %(enabled_condition)s %(filter_condition)s ORDER BY `%(key)s` ASC LIMIT %(start)s, %(len)s""" % args, tuple(["%%%s%%" % txt] + filter_values))
def meta(self): if not hasattr(self, "_meta"): self._meta = webnotes.get_doctype(self.doc.doctype) return self._meta
def get_field(doctype, fieldname, parent=None, parentfield=None): doclist = webnotes.get_doctype(doctype) return doclist.get_field(fieldname, parent, parentfield)
def onload(self): self.doc.fields["__quotation_series"] = webnotes.get_doctype("Quotation").get_options("naming_series")