def get_transitions(doc, workflow = None): '''Return list of possible transitions for the given doc''' doc = frappe.get_doc(frappe.parse_json(doc)) if doc.is_new(): return [] frappe.has_permission(doc, 'read', throw=True) roles = frappe.get_roles() if not workflow: workflow = get_workflow(doc.doctype) current_state = doc.get(workflow.workflow_state_field) if not current_state: frappe.throw(_('Workflow State not set'), WorkflowStateError) transitions = [] for transition in workflow.transitions: if transition.state == current_state and transition.allowed in roles: if transition.condition: # if condition, evaluate # access to frappe.db.get_value and frappe.db.get_list success = frappe.safe_eval(transition.condition, dict(frappe = frappe._dict( db = frappe._dict(get_value = frappe.db.get_value, get_list=frappe.db.get_list), session = frappe.session )), dict(doc = doc)) if not success: continue transitions.append(transition.as_dict()) return transitions
def get_permission_query_conditions(user): if not user: user = frappe.session.user if "System Manager" in frappe.get_roles(user): return None else: abc=""" `tabFirst Timer`.cell=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='Cells') or `tabFirst Timer`.senior_cell=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='Senior Cells') or `tabFirst Timer`.pcf=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='PCFs') or `tabFirst Timer`.church=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='Churches') or `tabFirst Timer`.church_group=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='Group Churches') or `tabFirst Timer`.zone=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='Zones') or `tabFirst Timer`.region=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='Regions') or `tabFirst Timer`.ftv_owner=(select distinct defvalue from `tabDefaultValue` where parent='%(user)s' and defkey='Member') """ % { "user": frappe.db.escape(user), "roles": "', '".join([frappe.db.escape(r) for r in frappe.get_roles(user)]) } return abc
def get_permission_query_conditions(user): if user in ("Administrator", "System Manager"): return "" elif "Client User" in frappe.get_roles() or "Client Support User" in frappe.get_roles() or "Client Support Manager": return "" # print user,"\n\n\n\n\n\n\n\n" # projects = frappe.db.sql("""select name from `tabProject` where client_user ='******'""".format(user)) # print("hiiiiiiiiiiiiiii",projects) # return frappe.db.sql("select name from `tabClient Support Ticket` where project in '{0}'".format(",".join(["'%s'"%project for project in projects]))) # print ("hellllllllllllllllllllllll",format(join(["'%s'" %project for project in projects])))
def build_conditions(filters): condition = "" status = "" department = "" date_type = "i.opening_date" # status if filters.get("status") != "All": if filters.get("status") == ("Pending"): status = "AND i.status NOT IN ('Open', 'Closed')" else: status = "AND i.status='%s'"%(filters.get("status")) date_type = "i.resolution_date" if filters.get("status") == "Closed" else "i.opening_date" # order by order_by = "ORDER BY {field} ASC".format(field=date_type) # department if filters.get("dept"): department = "AND i.department='%s'"%(filters.get("dept")) # TODO system manager, Administrator, Department Head ticket filters names = "" if "System Manager" in frappe.get_roles(filters.get("user")): names = "" elif "Department Head" in frappe.get_roles(filters.get("user")): names = "AND i.department='{dept}' AND i.name IN (SELECT t.reference_name FROM tabToDo AS t WHERE \ (t.owner='{user}' AND t.status='Open') OR t.assigned_by='{user}' AND t.reference_type='Issue' \ AND t.reference_name=i.name) OR i.owner='{user}'".format( user=filters.get("user"), dept=frappe.db.get_value("User", filters.get("user"), "department") ) else: names = "AND i.name IN (SELECT t.reference_name FROM tabToDo AS t WHERE (t.owner='{user}' AND t.status='Open') \ OR t.assigned_by='{user}' AND t.reference_type='Issue' AND t.reference_name=i.name) OR i.owner='{user}'".format( user=filters.get("user") ) condition = "WHERE {field} BETWEEN '{start}' AND '{end}' {names} {dept} {status} {order_by}".format( field=date_type, start=filters.get("start"), end=filters.get("end"), dept=department, status=status, order_by=order_by, names=names ) return condition
def category_sync(force_override_categories=False, force_override_features=False): """Load a new set of eBay categories. By default, this checks the current versions of the eBay categories cache and does not update it if the category version has not changed (i.e. the eBay categories have not changed). If force_override_categories is set, then the eBay categories will be redownloaded and new Item Group eBay entries set. If force_override_features is set, then the eBay features will be redownloaded. Setting force_override_features to True implies force_override_categories. """ # Check permissions, as this is a whitelisted function if 'System Manager' not in frappe.get_roles(frappe.session.user): return frappe.PermissionError( 'Only System Managers can update the eBay categories.') if force_override_features: force_override_categories = True categories_ok, features_ok = check_cache_versions() # Do we need to update the cache? update_categories = force_override_categories or not categories_ok update_features = force_override_features or not features_ok # Update the cache if required ensure_updated_cache(update_categories, update_features) # Update the Item Group eBay categories if required. if update_categories: # We only wipe the tables if we are forcing an override # otherwise we just update the existing entries. create_item_group_ebay(force_override_categories)
def get_permission_query_conditions(user): if not user: user = frappe.session.user if "System Manager" in frappe.get_roles(user): return None else: return """(tabToDo.owner = '{user}' or tabToDo.assigned_by = '{user}')""".format(user=user)
def validate_employee_leave_approver(self): for l in self.get("leave_approvers")[:]: #if l.leave_approver: # frappe.permissions.add_user_permission("User", self.user_id, l.leave_approver) if "Leave Approver" not in frappe.get_roles(l.leave_approver): frappe.get_doc("User", l.leave_approver).add_roles("Leave Approver")
def get_events(start, end): events = [] employee = frappe.db.get_value("Employee", {"user_id": frappe.session.user}, ["name", "company"], as_dict=True) #if not employee: # return events if employee: employee, company = employee.name, employee.company else: employee='' company=frappe.db.get_value("Global Defaults", None, "default_company") from frappe.desk.reportview import build_match_conditions match_conditions = build_match_conditions("Leave Application") # show department leaves for employee if "Employee" in frappe.get_roles(): add_department_leaves(events, start, end, employee, company) add_leaves(events, start, end, match_conditions) add_block_dates(events, start, end, employee, company) add_holidays(events, start, end, employee, company) return events
def set_user_info(self, resume=False): # set sid again frappe.local.cookie_manager.init_cookies() self.info = frappe.db.get_value("User", self.user, ["user_type", "first_name", "last_name", "user_image"], as_dict=1) self.full_name = " ".join(filter(None, [self.info.first_name, self.info.last_name])) self.user_type = self.info.user_type if self.info.user_type=="Website User": frappe.local.cookie_manager.set_cookie("system_user", "no") if not resume: frappe.local.response["message"] = "No App" frappe.local.response["home_page"] = get_website_user_home_page(self.user) else: frappe.local.cookie_manager.set_cookie("system_user", "yes") if not resume: frappe.local.response['message'] = 'Logged In' if "Hospital User" in frappe.get_roles(frappe.session.user) : frappe.local.response["home_page"] = "/desk#modules/Hospital Bed Management" else: frappe.local.response["home_page"] = "/desk" if not resume: frappe.response["full_name"] = self.full_name frappe.local.cookie_manager.set_cookie("full_name", self.full_name) frappe.local.cookie_manager.set_cookie("user_id", self.user) frappe.local.cookie_manager.set_cookie("user_image", self.info.user_image or "")
def apply_user_permissions_to_all_roles(self): # add apply user permissions for all roles that # for this doctype def show_progress(i, l): if l > 2: frappe.publish_realtime("progress", dict(progress=[i, l], title=_('Updating...')), user=frappe.session.user) roles = frappe.get_roles(self.user) linked = frappe.db.sql('''select distinct parent from tabDocField where fieldtype="Link" and options=%s''', self.allow) for i, link in enumerate(linked): doctype = link[0] for perm in get_valid_perms(doctype, self.user): # if the role is applicable to the user show_progress(i+1, len(linked)) if perm.role in roles: if not perm.apply_user_permissions: update_permission_property(doctype, perm.role, 0, 'apply_user_permissions', '1') try: user_permission_doctypes = json.loads(perm.user_permission_doctypes or '[]') except ValueError: user_permission_doctypes = [] if self.allow not in user_permission_doctypes: user_permission_doctypes.append(self.allow) update_permission_property(doctype, perm.role, 0, 'user_permission_doctypes', json.dumps(user_permission_doctypes), validate=False) show_progress(len(linked), len(linked))
def get_appr_user_role(self, det, doctype_name, total, based_on, condition, item, company): amt_list, appr_users, appr_roles = [], [], [] users, roles = '','' if det: for x in det: amt_list.append(flt(x[0])) max_amount = max(amt_list) app_dtl = frappe.db.sql("""select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and company = %s %s""" % ('%s', '%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on, company)) if not app_dtl: app_dtl = frappe.db.sql("""select approving_user, approving_role from `tabAuthorization Rule` where transaction = %s and (value = %s or value > %s) and docstatus != 2 and based_on = %s and ifnull(company,'') = '' %s""" % ('%s', '%s', '%s', '%s', condition), (doctype_name, flt(max_amount), total, based_on)) for d in app_dtl: if(d[0]): appr_users.append(d[0]) if(d[1]): appr_roles.append(d[1]) if not has_common(appr_roles, frappe.get_roles()) and not has_common(appr_users, [session['user']]): frappe.msgprint(_("Not authroized since {0} exceeds limits").format(_(based_on))) frappe.throw(_("Can be approved by {0}").format(comma_or(appr_roles + appr_users)))
def add_sidebar_data(context): from frappe.utils.user import get_fullname_and_avatar import frappe.www.list if not context.sidebar_items: sidebar_items = frappe.cache().hget('portal_menu_items', frappe.session.user) if sidebar_items == None: sidebar_items = [] roles = frappe.get_roles() portal_settings = frappe.get_doc('Portal Settings', 'Portal Settings') def add_items(sidebar_items, menu_field): for d in portal_settings.get(menu_field): if d.enabled and ((not d.role) or d.role in roles): sidebar_items.append(d.as_dict()) if not portal_settings.hide_standard_menu: add_items(sidebar_items, 'menu') if portal_settings.custom_menu: add_items(sidebar_items, 'custom_menu') frappe.cache().hset('portal_menu_items', frappe.session.user, sidebar_items) context.sidebar_items = sidebar_items info = get_fullname_and_avatar(frappe.session.user) context["fullname"] = info.fullname context["user_image"] = info.avatar context["user"] = info.name
def check_jasper_perm(perms, ptypes=("read",), user=None): found = False if isinstance(ptypes, basestring): ptypes = (ptypes, ) if user == None: user = frappe.local.session['user'] def check_perm(perms, user_roles, ptype): found = False for perm in perms: jasper_perm_type = perm.get('jasper_can_' + ptype, None) jasper_role = perm.get('jasper_role', None) if jasper_role in user_roles and jasper_perm_type: found = True break return found if user == "Administrator": return True user_roles = frappe.get_roles(user) for ptype in ptypes: found = check_perm(perms, user_roles, ptype) if found == False: break return found
def get_ftv_member(): roles=frappe.get_roles(frappe.user.name) val=frappe.db.sql("select defkey,defvalue from `tabDefaultValue` where defkey in ('Cells','Senior Cells','PCFs','Churches','Group Churches','Zones','Regions') and parent='%s' limit 1"%(frappe.user.name),as_list=1) # frappe.errprint(val) if val: if val[0][0]=='Cells': key='cell' value=val[0][1] elif val[0][0]=='Senior Cells': key='senior_cell' value=val[0][1] elif val[0][0]=='PCFs': key='pcf' value=val[0][1] elif val[0][0]=='Churches': key='Church' value=val[0][1] elif val[0][0]=='Group Churches': key='church_group' value=val[0][1] elif val[0][0]=='Zones': key='zone' value=val[0][1] elif val[0][0]=='Regions': key='region' value=val[0][1] return{ "key" : key, "value" : value } else: return{ "key" : 1, "value" : 1 }
def get_role_permissions(meta, user=None): if not user: user = frappe.session.user cache_key = (meta.name, user) if not frappe.local.role_permissions.get(cache_key): perms = frappe._dict({ "apply_user_permissions": {}, "user_permission_doctypes": {} }) user_roles = frappe.get_roles(user) for p in meta.permissions: if cint(p.permlevel)==0 and (p.role in user_roles): for ptype in rights: perms[ptype] = perms.get(ptype, 0) or cint(p.get(ptype)) if ptype != "set_user_permissions" and p.get(ptype): perms["apply_user_permissions"][ptype] = (perms["apply_user_permissions"].get(ptype, 1) and p.get("apply_user_permissions")) if p.apply_user_permissions and p.user_permission_doctypes: # set user_permission_doctypes in perms user_permission_doctypes = json.loads(p.user_permission_doctypes) if user_permission_doctypes: # perms["user_permission_doctypes"][ptype] would be a list of list like [["User", "Blog Post"], ["User"]] for ptype in rights: if p.get(ptype): perms["user_permission_doctypes"].setdefault(ptype, []).append(user_permission_doctypes) for key, value in perms.get("apply_user_permissions").items(): if not value: del perms["apply_user_permissions"][key] frappe.local.role_permissions[cache_key] = perms return frappe.local.role_permissions[cache_key]
def get_allowed_pages(): roles = frappe.get_roles() page_info = {} for p in frappe.db.sql( """select distinct tabPage.name, tabPage.modified, tabPage.title from `tabPage Role`, `tabPage` where `tabPage Role`.role in (%s) and `tabPage Role`.parent = `tabPage`.name""" % ", ".join(["%s"] * len(roles)), roles, as_dict=True, ): page_info[p.name] = {"modified": p.modified, "title": p.title} # pages where role is not set are also allowed for p in frappe.db.sql( """select name, modified, title from `tabPage` where (select count(*) from `tabPage Role` where `tabPage Role`.parent=tabPage.name) = 0""", as_dict=1, ): page_info[p.name] = {"modified": p.modified, "title": p.title} return page_info
def recommended_patients(user): conditions = [] roles = frappe.get_roles(user) for role in roles: if role == "Hospital User": conditions.append("ifnull(`tabPatient Allotment`.`status`, '')!='Not Verified' or ifnull(`tabPatient Allotment`.`owner`, '')='"+user+"' ") return " and ".join(conditions) if conditions else None
def validate_employee_leave_approver(self): from erpnext.hr.doctype.leave_application.leave_application import InvalidLeaveApproverError for l in self.get("employee_leave_approvers")[:]: if "Leave Approver" not in frappe.get_roles(l.leave_approver): self.get("employee_leave_approvers").remove(l) msgprint(_("{0} is not a valid Leave Approver. Removing row #{1}.").format(l.leave_approver, l.idx))
def get_context(context): context.icons = get_user_icons(frappe.session.user) context.user = frappe.session.user if 'System Manager' in frappe.get_roles(): context.users = frappe.db.get_all('User', filters={'user_type': 'System User', 'enabled': 1}, fields = ['name', 'first_name', 'last_name'])
def can_export(doctype, raise_exception=False): if not ("System Manager" in frappe.get_roles() or has_permission(doctype, "export")): if raise_exception: raise frappe.PermissionError("You are not allowed to export: {doctype}".format(doctype=doctype)) else: return False return True
def validate_frozen_accounts_modifier(self): old_value = frappe.db.get_value("Account", self.name, "freeze_account") if old_value and old_value != self.freeze_account: frozen_accounts_modifier = frappe.db.get_value('Accounts Settings', None, 'frozen_accounts_modifier') if not frozen_accounts_modifier or \ frozen_accounts_modifier not in frappe.get_roles(): throw(_("You are not authorized to set Frozen value"))
def _get_home_page(): home_page = None get_website_user_home_page = frappe.get_hooks('get_website_user_home_page') if get_website_user_home_page: home_page = frappe.get_attr(get_website_user_home_page[-1])(frappe.session.user) if not home_page: role_home_page = frappe.get_hooks("role_home_page") if role_home_page: for role in frappe.get_roles(): if role in role_home_page: home_page = role_home_page[role][-1] break if not home_page: home_page = frappe.get_hooks("home_page") if home_page: home_page = home_page[-1] if not home_page: home_page = frappe.db.get_value("Website Settings", None, "home_page") or "login" home_page = home_page.strip('/') return home_page
def get_expiry_message(): if "System Manager" not in frappe.get_roles(): return "" limits = get_limits() if not limits.expiry: return "" expires_on = getdate(get_limits().get("expiry")) today = now_datetime().date() message = "" if today > expires_on: message = _("Your subscription has expired.") else: days_to_expiry = (expires_on - today).days if days_to_expiry == 0: message = _("Your subscription will expire today.") elif days_to_expiry == 1: message = _("Your subscription will expire tomorrow.") elif days_to_expiry <= EXPIRY_WARNING_DAYS: message = _("Your subscription will expire on {0}.").format(formatdate(expires_on)) if message and limits.upgrade_url: upgrade_link = get_upgrade_link(limits.upgrade_url) message += " " + _("To renew, {0}.").format(upgrade_link) return message
def validate_party(self): if self.party_type and self.party: frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None,'frozen_accounts_modifier') if not frozen_accounts_modifier in frappe.get_roles(): if frappe.db.get_value(self.party_type, self.party, "is_frozen"): frappe.throw("{0} {1} is frozen".format(self.party_type, self.party), CustomerFrozen) validate_party_frozen_disabled(self.party_type, self.party)
def get_permission_query_conditions(user): roles = frappe.get_roles() if "Central Delivery" not in roles and frappe.session.user != "Administrator": emp_name = frappe.db.get_value("Employee",{"user_id":frappe.session.user}, "name") ip_files = frappe.db.sql(""" select name from `tabIP File` where owner = '{0}' or file_approver = '{1}' """.format(frappe.session.user, emp_name),as_dict=1) ip_files = "', '".join([ipf.get("name") for ipf in ip_files if ipf]) return """(`tabIP File`.name in ('{files}') )""".format(files = ip_files)
def validate_expense_approver(self): if self.exp_approver and "Expense Approver" not in frappe.get_roles(self.exp_approver): frappe.throw( _("{0} ({1}) must have role 'Expense Approver'").format( get_fullname(self.exp_approver), self.exp_approver ), InvalidExpenseApproverError, )
def add_message_to_redis(update_json): # "update-message" will store the update message string # "update-user-set" will be a set of users cache = frappe.cache() cache.set_value("update-info", json.dumps(update_json)) user_list = [x.name for x in frappe.get_all("User", filters={"enabled": True})] system_managers = [user for user in user_list if 'System Manager' in frappe.get_roles(user)] cache.sadd("update-user-set", *system_managers)
def get_permission_query_conditions(user): if not user: user = frappe.session.user if "System Manager" in frappe.get_roles(user): return None else: return """(tabTask.owner = '{user}' or tabTask._assign like '%{user}%' )"""\ .format(user=frappe.db.escape(user))
def has_permission(doc, user): if doc.event_type=="Public" or doc.owner==user: return True if doc.get("roles", {"role":("in", frappe.get_roles(user))}): return True return False
def get_permlevel_access(self): user_roles = frappe.get_roles() has_access_to = [] for perm in self.meta.permissions: if perm.role in user_roles and perm.permlevel > 0 and perm.write: if perm.permlevel not in has_access_to: has_access_to.append(perm.permlevel) return has_access_to
def get_roles(arg=None): """get roles for a user""" return frappe.get_roles(frappe.form_dict['uid'])
def has_permission(doc, user): if "System Manager" in frappe.get_roles(user): return True else: return doc.owner == user or doc.assigned_by == user
def get_user_pages_or_reports(parent, cache=False): _cache = frappe.cache() if cache: has_role = _cache.get_value('has_role:' + parent, user=frappe.session.user) if has_role: return has_role roles = frappe.get_roles() has_role = {} column = get_column(parent) # get pages or reports set on custom role pages_with_custom_roles = frappe.db.sql(""" select `tabCustom Role`.{field} as name, `tabCustom Role`.modified, `tabCustom Role`.ref_doctype, {column} from `tabCustom Role`, `tabHas Role`, `tab{parent}` where `tabHas Role`.parent = `tabCustom Role`.name and `tab{parent}`.name = `tabCustom Role`.{field} and `tabCustom Role`.{field} is not null and `tabHas Role`.role in ({roles}) """.format(field=parent.lower(), parent=parent, column=column, roles=', '.join(['%s'] * len(roles))), roles, as_dict=1) for p in pages_with_custom_roles: has_role[p.name] = { "modified": p.modified, "title": p.title, "ref_doctype": p.ref_doctype } pages_with_standard_roles = frappe.db.sql(""" select distinct `tab{parent}`.name as name, `tab{parent}`.modified, {column} from `tabHas Role`, `tab{parent}` where `tabHas Role`.role in ({roles}) and `tabHas Role`.parent = `tab{parent}`.name and `tab{parent}`.`name` not in ( select `tabCustom Role`.{field} from `tabCustom Role` where `tabCustom Role`.{field} is not null) {condition} """.format( parent=parent, column=column, roles=', '.join(['%s'] * len(roles)), field=parent.lower(), condition="and `tabReport`.disabled=0" if parent == "Report" else ""), roles, as_dict=True) for p in pages_with_standard_roles: if p.name not in has_role: has_role[p.name] = {"modified": p.modified, "title": p.title} if parent == "Report": has_role[p.name].update({'ref_doctype': p.ref_doctype}) # pages with no role are allowed if parent == "Page": pages_with_no_roles = frappe.db.sql(""" select `tab{parent}`.name, `tab{parent}`.modified, {column} from `tab{parent}` where (select count(*) from `tabHas Role` where `tabHas Role`.parent=`tab{parent}`.`name`) = 0 """.format(parent=parent, column=column), as_dict=1) for p in pages_with_no_roles: if p.name not in has_role: has_role[p.name] = {"modified": p.modified, "title": p.title} elif parent == "Report": reports = frappe.get_all("Report", fields=["name", "report_type"], filters={"name": ("in", has_role.keys())}, ignore_ifnull=True) for report in reports: has_role[report.name]["report_type"] = report.report_type # Expire every six hours _cache.set_value('has_role:' + parent, has_role, frappe.session.user, 21600) return has_role
def validate_employee_leave_approver(self): for l in self.get("leave_approvers")[:]: if "Leave Approver" not in frappe.get_roles(l.leave_approver): frappe.get_doc("User", l.leave_approver).add_roles("Leave Approver")
def get_role_permissions(doctype_meta, user=None, is_owner=None): """ Returns dict of evaluated role permissions like { "read": 1, "write": 0, // if "if_owner" is enabled "if_owner": { "read": 1, "write": 0 } } """ if isinstance(doctype_meta, string_types): doctype_meta = frappe.get_meta( doctype_meta) # assuming doctype name was passed if not user: user = frappe.session.user cache_key = (doctype_meta.name, user) if user == 'Administrator': return allow_everything() if not frappe.local.role_permissions.get(cache_key): perms = frappe._dict(if_owner={}) roles = frappe.get_roles(user) def is_perm_applicable(perm): return perm.role in roles and cint(perm.permlevel) == 0 def has_permission_without_if_owner_enabled(ptype): return any( p.get(ptype, 0) and not p.get('if_owner', 0) for p in applicable_permissions) applicable_permissions = list( filter(is_perm_applicable, getattr(doctype_meta, 'permissions', []))) has_if_owner_enabled = any( p.get('if_owner', 0) for p in applicable_permissions) perms['has_if_owner_enabled'] = has_if_owner_enabled for ptype in rights: pvalue = any(p.get(ptype, 0) for p in applicable_permissions) # check if any perm object allows perm type perms[ptype] = cint(pvalue) if (pvalue and has_if_owner_enabled and not has_permission_without_if_owner_enabled(ptype) and ptype != 'create'): perms['if_owner'][ptype] = cint(pvalue and is_owner) # has no access if not owner # only provide select or read access so that user is able to at-least access list # (and the documents will be filtered based on owner sin further checks) perms[ptype] = 1 if ptype in ('select', 'read') else 0 frappe.local.role_permissions[cache_key] = perms return frappe.local.role_permissions[cache_key]
def get_role_permissions(meta, user=None, verbose=False): """Returns dict of evaluated role permissions like `{"read": True, "write":False}` If user permissions are applicable, it adds a dict of user permissions like { // user permissions will apply on these rights "apply_user_permissions": {"read": 1, "write": 1}, // doctypes that will be applicable for each right "user_permission_doctypes": { "read": [ // AND between "DocType 1" and "DocType 2" ["DocType 1", "DocType 2"], // OR ["DocType 3"] ] } "if_owner": {"read": 1, "write": 1} } """ if not user: user = frappe.session.user cache_key = (meta.name, user) if not frappe.local.role_permissions.get(cache_key): perms = frappe._dict( apply_user_permissions={}, user_permission_doctypes={}, if_owner={} ) roles = frappe.get_roles(user) dont_match = [] has_a_role_with_apply_user_permissions = False for p in meta.permissions: if cint(p.permlevel)==0 and (p.role in roles): # apply only for level 0 for ptype in rights: # build if_owner dict if applicable for this right perms[ptype] = perms.get(ptype, 0) or cint(p.get(ptype)) if ptype != "set_user_permissions" and p.get(ptype): perms["apply_user_permissions"][ptype] = (perms["apply_user_permissions"].get(ptype, 1) and p.get("apply_user_permissions")) if p.if_owner and p.get(ptype): perms["if_owner"][ptype] = 1 if p.get(ptype) and not p.if_owner and not p.get("apply_user_permissions"): dont_match.append(ptype) if p.apply_user_permissions: has_a_role_with_apply_user_permissions = True if p.user_permission_doctypes: # set user_permission_doctypes in perms try: user_permission_doctypes = json.loads(p.user_permission_doctypes) except ValueError: user_permission_doctypes = [] else: user_permission_doctypes = get_linked_doctypes(meta.name) if user_permission_doctypes: # perms["user_permission_doctypes"][ptype] would be a list of list like [["User", "Blog Post"], ["User"]] for ptype in rights: if p.get(ptype): perms["user_permission_doctypes"].setdefault(ptype, []).append(user_permission_doctypes) # if atleast one record having both Apply User Permission and If Owner unchecked is found, # don't match for those rights for ptype in rights: if ptype in dont_match: if perms["apply_user_permissions"].get(ptype): del perms["apply_user_permissions"][ptype] if perms["if_owner"].get(ptype): del perms["if_owner"][ptype] # if one row has only "Apply User Permissions" checked and another has only "If Owner" checked, # set Apply User Permissions as checked # i.e. the case when there is a role with apply_user_permissions as 1, but resultant apply_user_permissions is 0 if has_a_role_with_apply_user_permissions: for ptype in rights: if perms["if_owner"].get(ptype) and perms["apply_user_permissions"].get(ptype)==0: perms["apply_user_permissions"][ptype] = 1
def _is_sys_mgr(): return "System Manager" in frappe.get_roles(frappe.session.user)
def get_data(filters, leave_types): user = frappe.session.user allocation_records_based_on_to_date = get_leave_allocation_records( filters.to_date) allocation_records_based_on_from_date = get_leave_allocation_records( filters.from_date) active_employees = frappe.get_all( "Employee", filters={ "status": "Active", "company": filters.company }, fields=["name", "employee_name", "department", "user_id"]) data = [] for employee in active_employees: leave_approvers = get_approvers(employee.department) if (len(leave_approvers) and user in leave_approvers) or (user in [ "Administrator", employee.user_id ]) or ("HR Manager" in frappe.get_roles(user)): row = [employee.name, employee.employee_name, employee.department] for leave_type in leave_types: # leaves taken leaves_taken = get_approved_leaves_for_period( employee.name, leave_type, filters.from_date, filters.to_date) # opening balance opening = 0 closing = 0 conditions = ( " and leave_type= '" + str(leave_type) + "' and employee='%s' " % employee.name) if employee else "" leave_allocation_records = frappe.db.sql( """select employee, leave_type, total_leaves_allocated, total_leaves_encashed, from_date, to_date from `tabLeave Allocation` where from_date >= %s and to_date <= %s and docstatus=1 {0}""" .format(conditions), (filters.from_date, filters.to_date), as_dict=1) allocated_leaves = frappe._dict() for d in leave_allocation_records: opening = d.total_leaves_allocated # allocated_leaves.setdefault(d.employee, frappe._dict()).setdefault(d.leave_type, frappe._dict({ # "from_date": d.from_date, # "to_date": d.to_date, # "total_leaves_allocated": d.total_leaves_allocated, # "total_leaves_encashed":d.total_leaves_encashed # })) # opening = get_leave_balance_on(employee.name, leave_type, filters.from_date,allocation_records_based_on_from_date.get(employee.name, frappe._dict())) # closing balance closing = float(opening) - float(leaves_taken) # closing = get_leave_balance_on(employee.name, leave_type, filters.to_date, # allocation_records_based_on_to_date.get(employee.name, frappe._dict())) row += [opening, leaves_taken, closing] data.append(row) return data
def validate_due_date(posting_date, due_date, party_type, party, company): if getdate(due_date) < getdate(posting_date): frappe.throw(_("Due Date cannot be before Posting Date")) else: default_due_date = get_due_date(posting_date, party_type, party, company) if not default_due_date: return if default_due_date != posting_date and getdate(due_date) > getdate(default_due_date): is_credit_controller = frappe.db.get_single_value("Accounts Settings", "credit_controller") in frappe.get_roles() if is_credit_controller: msgprint(_("Note: Due / Reference Date exceeds allowed customer credit days by {0} day(s)") .format(date_diff(due_date, default_due_date))) else: frappe.throw(_("Due / Reference Date cannot be after {0}").format(formatdate(default_due_date)))
def list_company_member(company): if 'Company Admin' not in frappe.get_roles(frappe.session.user): return False if frappe.db.get_value("Cloud Company", company, "enabled") != 1: return False return [{"member_id": d[0], "member_name": get_user_fullname(d[0])} for d in frappe.db.get_values("Cloud Employee", {"company": company})]
def list_company_user(company): if 'Company Admin' not in frappe.get_roles(frappe.session.user): return False if frappe.db.get_value("Cloud Company", company, "enabled") != 1: return False return [d[0] for d in frappe.db.get_values("Cloud Employee", {"company": company})]
def get_data(filters): conditions = get_item_conditions(filters, for_item_dt=False) item_conditions = get_item_conditions(filters, for_item_dt=True) show_amounts_role = frappe.db.get_single_value( "Stock Settings", "restrict_amounts_in_report_to_role") price_lists, selected_price_list = get_price_lists(filters) price_lists_cond = " and p.price_list in ('{0}')".format("', '".join( [frappe.db.escape(d) for d in price_lists])) item_data = frappe.db.sql(""" select item.name as item_code, item.item_name, item.item_group, item.stock_uom, item.sales_uom, item.alt_uom, item.alt_uom_size, item.hide_in_price_list from tabItem item where disabled != 1 {0} """.format(item_conditions), filters, as_dict=1) po_data = frappe.db.sql( """ select item.item_code, sum(if(item.qty - item.received_qty < 0, 0, item.qty - item.received_qty) * item.conversion_factor) as po_qty, sum(if(item.qty - item.received_qty < 0, 0, item.qty - item.received_qty) * item.conversion_factor * item.base_net_rate) as po_lc_amount from `tabPurchase Order Item` item inner join `tabPurchase Order` po on po.name = item.parent where item.docstatus = 1 and po.status != 'Closed' {0} group by item.item_code """.format(conditions), filters, as_dict=1) # TODO add valuation rate in PO and use that bin_data = frappe.db.sql(""" select bin.item_code, sum(bin.actual_qty) as actual_qty, sum(bin.stock_value) as stock_value from tabBin bin, tabItem item where item.name = bin.item_code {0} group by bin.item_code """.format(item_conditions), filters, as_dict=1) item_price_data = frappe.db.sql(""" select p.name, p.price_list, p.item_code, p.price_list_rate, p.currency, p.uom, ifnull(p.valid_from, '2000-01-01') as valid_from from `tabItem Price` p inner join `tabItem` item on item.name = p.item_code where %(date)s between ifnull(p.valid_from, '2000-01-01') and ifnull(p.valid_upto, '2500-12-31') and ifnull(p.customer, '') = '' and ifnull(p.supplier, '') = '' {0} {1} order by p.uom """.format(item_conditions, price_lists_cond), filters, as_dict=1) previous_item_prices = frappe.db.sql(""" select p.price_list, p.item_code, p.price_list_rate, ifnull(p.valid_from, '2000-01-01') as valid_from, p.uom from `tabItem Price` as p inner join `tabItem` item on item.name = p.item_code where ifnull(p.valid_upto, '0000-00-00') != '0000-00-00' and p.valid_upto < %(date)s {0} {1} order by p.valid_upto desc """.format(item_conditions, price_lists_cond), filters, as_dict=1) items_map = {} for d in item_data: default_uom = d.purchase_uom if filters.buying_selling == "Buying" else d.sales_uom if filters.uom: d['uom'] = filters.uom elif filters.default_uom == "Stock UOM": d['uom'] = d.stock_uom elif filters.default_uom == "Contents UOM": d['uom'] = d.alt_uom or default_uom else: d['uom'] = default_uom if not d.get('uom'): d['uom'] = d.stock_uom d['print_in_price_list'] = cint(not d['hide_in_price_list']) del d['hide_in_price_list'] d['alt_uom_size'] = convert_item_uom_for(d.alt_uom_size, d.item_code, d.stock_uom, d.uom) items_map[d.item_code] = d for d in po_data: if d.item_code in items_map: items_map[d.item_code].update(d) for d in bin_data: if d.item_code in items_map: items_map[d.item_code].update(d) for item_prices in [item_price_data, previous_item_prices]: for d in item_prices: if d.item_code in items_map: d.price_list_rate = convert_item_uom_for( d.price_list_rate, d.item_code, d.uom, items_map[d.item_code]['uom'], null_if_not_convertible=True) item_price_map = {} for d in item_price_data: if d.item_code in items_map and d.price_list_rate is not None: current_item = items_map[d.item_code] price = item_price_map.setdefault(d.item_code, {}).setdefault( d.price_list, frappe._dict()) pick_price = (cstr(d.uom) == cstr(current_item.uom) or (cstr(price.reference_uom) != cstr(current_item.uom) and cstr(d.uom) != current_item.stock_uom) or not price) if pick_price: price.current_price = d.price_list_rate price.valid_from = d.valid_from price.reference_uom = d.uom price.currency = d.currency if d.price_list == filters.standard_price_list: items_map[d.item_code].standard_rate = d.price_list_rate show_amounts = not show_amounts_role or show_amounts_role in frappe.get_roles( ) if show_amounts: price.item_price = d.name for d in previous_item_prices: if d.item_code in item_price_map and d.price_list in item_price_map[ d.item_code] and d.price_list_rate is not None: price = item_price_map[d.item_code][d.price_list] if 'previous_price' not in price and d.valid_from < price.valid_from: price.previous_price = d.price_list_rate for item_code, d in iteritems(items_map): conversion_factor = convert_item_uom_for(1, d.item_code, d.stock_uom, d.uom) d.actual_qty = flt(d.actual_qty) / conversion_factor d.po_qty = flt(d.po_qty) / conversion_factor d.po_lc_rate = flt(d.po_lc_amount) / d.po_qty if d.po_qty else 0 d.valuation_rate = flt( d.stock_value) / d.actual_qty if d.actual_qty else 0 d.balance_qty = d.actual_qty + d.po_qty d.avg_lc_rate = (flt(d.stock_value) + flt(d.po_lc_amount) ) / d.balance_qty if d.balance_qty else 0 d.margin_rate = (d.standard_rate - d.avg_lc_rate ) * 100 / d.standard_rate if d.standard_rate else None for price_list, price in iteritems(item_price_map.get(item_code, {})): d["rate_" + scrub(price_list)] = price.current_price d["currency_" + scrub(price_list)] = price.currency if d.standard_rate is not None: d["rate_diff_" + scrub(price_list)] = flt( price.current_price) - flt(d.standard_rate) if price.previous_price is not None: d["rate_old_" + scrub(price_list)] = price.previous_price if price.item_price: d["item_price_" + scrub(price_list)] = price.item_price d['print_rate'] = d.get("rate_" + scrub(selected_price_list) ) if selected_price_list else d.standard_rate if filters.filter_items_without_price: to_remove = [] for item_code, d in iteritems(items_map): if not d.get('print_rate'): to_remove.append(item_code) for item_code in to_remove: del items_map[item_code] return items_map.values(), price_lists
def get_columns(filters, price_lists): columns = [ { "fieldname": "item_code", "label": _("Item"), "fieldtype": "Link", "options": "Item", "width": 200, "price_list_note": frappe.db.get_single_value("Price List Settings", "price_list_note") }, { "fieldname": "print_in_price_list", "label": _("Print"), "fieldtype": "Check", "width": 50, "editable": 1 }, { "fieldname": "uom", "label": _("UOM"), "fieldtype": "Data", "width": 50 }, { "fieldname": "alt_uom_size", "label": _("Per Unit"), "fieldtype": "Float", "width": 68 }, # {"fieldname": "item_group", "label": _("Item Group"), "fieldtype": "Link", "options": "Item Group", "width": 120}, { "fieldname": "po_qty", "label": _("PO Qty"), "fieldtype": "Float", "width": 80, "restricted": 1 }, { "fieldname": "po_lc_rate", "label": _("PO Rate"), "fieldtype": "Currency", "width": 90, "restricted": 1 }, { "fieldname": "actual_qty", "label": _("Stock Qty"), "fieldtype": "Float", "width": 80, "restricted": 1 }, { "fieldname": "valuation_rate", "label": _("Stock Rate"), "fieldtype": "Currency", "width": 90, "restricted": 1 }, { "fieldname": "avg_lc_rate", "label": _("Avg Rate"), "fieldtype": "Currency", "width": 90, "restricted": 1 }, ] if filters.standard_price_list: columns += [ { "fieldname": "standard_rate", "label": _("Standard Rate"), "fieldtype": "Currency", "width": 110, "editable": 1, "price_list": filters.standard_price_list, "force_currency_symbol": 1, "options": "currency_" + scrub(filters.standard_price_list) }, { "fieldname": "margin_rate", "label": _("Margin"), "fieldtype": "Percent", "width": 60, "restricted": 1 }, ] for price_list in sorted(price_lists): if price_list != filters.standard_price_list: columns.append({ "fieldname": "rate_" + scrub(price_list), "label": price_list, "fieldtype": "Currency", "width": 110, "editable": 1, "price_list": price_list, "options": "currency_" + scrub(price_list), "force_currency_symbol": 1 }) show_amounts_role = frappe.db.get_single_value( "Stock Settings", "restrict_amounts_in_report_to_role") show_amounts = not show_amounts_role or show_amounts_role in frappe.get_roles( ) if not show_amounts: columns = filter(lambda d: not d.get('restricted'), columns) '''for c in columns: if c.get('editable'): del c['editable']''' return columns
def onload(self): frozen_accounts_modifier = frappe.db.get_value("Accounts Settings", "Accounts Settings", "frozen_accounts_modifier") if not frozen_accounts_modifier or frozen_accounts_modifier in frappe.get_roles(): self.set_onload("can_freeze_account", True)
def validate_due_date(posting_date, due_date, party_type, party, company=None, bill_date=None, template_name=None): if getdate(due_date) < getdate(posting_date): frappe.throw(_("Due Date cannot be before Posting / Supplier Invoice Date")) else: if not template_name: return default_due_date = get_due_date_from_template(template_name, posting_date, bill_date).strftime("%Y-%m-%d") if not default_due_date: return if default_due_date != posting_date and getdate(due_date) > getdate(default_due_date): is_credit_controller = frappe.db.get_single_value("Accounts Settings", "credit_controller") in frappe.get_roles() if is_credit_controller: msgprint(_("Note: Due / Reference Date exceeds allowed customer credit days by {0} day(s)") .format(date_diff(due_date, default_due_date))) else: frappe.throw(_("Due / Reference Date cannot be after {0}") .format(formatdate(default_due_date)))
def get_data(filters): leave_types = frappe.db.sql_list( "SELECT `name` FROM `tabLeave Type` ORDER BY `name` ASC") conditions = get_conditions(filters) user = frappe.session.user department_approver_map = get_department_leave_approver_map( filters.get('department')) active_employees = frappe.get_list('Employee', filters=conditions, fields=[ 'name', 'employee_name', 'department', 'user_id', 'leave_approver' ]) data = [] for leave_type in leave_types: if len(active_employees) > 1: data.append({'leave_type': leave_type}) else: row = frappe._dict({'leave_type': leave_type}) for employee in active_employees: leave_approvers = department_approver_map.get( employee.department_name, []).append(employee.leave_approver) if (leave_approvers and len(leave_approvers) and user in leave_approvers) or (user in ["Administrator", employee.user_id]) \ or ("HR Manager" in frappe.get_roles(user)): if len(active_employees) > 1: row = frappe._dict() row.employee = employee.name, row.employee_name = employee.employee_name leaves_taken = get_leaves_for_period(employee.name, leave_type, filters.from_date, filters.to_date) * -1 new_allocation, expired_leaves = get_allocated_and_expired_leaves( filters.from_date, filters.to_date, employee.name, leave_type) opening = get_leave_balance_on( employee.name, leave_type, add_days(filters.from_date, -1)) # allocation boundary condition row.leaves_allocated = new_allocation row.leaves_expired = expired_leaves - \ leaves_taken if expired_leaves - leaves_taken > 0 else 0 row.opening_balance = opening row.leaves_taken = leaves_taken # not be shown on the basis of days left it create in user mind for carry_forward leave row.closing_balance = (new_allocation + opening - (row.leaves_expired + leaves_taken)) row.indent = 1 data.append(row) new_leaves_allocated = 0 return data
def _get_columns(filters): columns = concatv( [ make_column( "invoice_name", "Sales Invoice", type="Link", options="Sales Invoice", width=150, ), make_column("invoice_date", type="Date", width=90), make_column("invoice_time", type="Time", width=90), make_column("brand", type="Link", options="Brand"), make_column("item_code", type="Link", options="Item"), make_column("item_group", type="Link", options="Item Group"), make_column("description"), ], [make_column("valuation_rate", "Cost Price", type="Currency", width=90)] if "Accounts Manager" in frappe.get_roles() else [], [ make_column( "selling_rate", "Standard Selling Rate", type="Currency", width=90 ), make_column("rate", "Sale Unit Rate", type="Currency", width=90), make_column("qty", type="Float", width=90), ], [make_column("valuation_amount", "Cost Amount", type="Currency", width=90)] if "Accounts Manager" in frappe.get_roles() else [], [ make_column( "amount_before_discount", "Sale Amount Before Discount", type="Currency", width=90, ), make_column("discount_amount", type="Currency", width=90), make_column("discount_percentage", type="Percent", width=90), make_column( "amount_after_discount", "Sale Amount After Discount", type="Currency", width=90, ), make_column("ms1", "Minimum Selling Rate 1", type="Currency", width=90), make_column( "below_ms1", "Sold Below Mimimum Selling Rate 1", type="Select", options=["No", "Yes"], width=60, ), make_column("ms2", "Minimum Selling Rate 2", type="Currency", width=90), make_column( "below_ms2", "Sold Below Mimimum Selling Rate 2", type="Select", options=["No", "Yes"], width=60, ), make_column("total", "Invoice Total", type="Currency", width=90), make_column( "additional_discount_amount", "Invoice Additional Discount", type="Currency", width=90, ), make_column( "total_taxes_and_charges", "Invoice Taxes and Charges", type="Currency", width=90, ), make_column( "grand_total", "Invoice Grand Total", type="Currency", width=90, ), make_column("sales_person", type="Link", options="Employee"), make_column("sales_person_name", width="150"), make_column("commission_amount", type="Currency", width=90), make_column("remarks", type="Small Text", width=150), make_column("customer", type="Link", options="Customer"), make_column("customer_name", width="150"), make_column("notes", type="Small Text", width=150), make_column("dispensor", "Optometrist", type="Link", options="Employee"), make_column("branch", type="Link", options="Branch"), make_column( "sales_status", type="Select", options=["Achieved", "Collected"] ), make_column("collection_date", type="Date", width=90), ], ) return list(columns)
def get_data(filters, leave_types): user = frappe.session.user allocation_records_based_on_to_date = get_leave_allocation_records( filters.to_date) allocation_records_based_on_from_date = get_leave_allocation_records( filters.from_date) hr_manager = frappe.get_doc("User", frappe.session.user).get( "roles", {"role": "HR Manager"}) if hr_manager: emp_filters = { "status": "Active", "company": filters.company, "department": filters.department } else: emp_filters = { "status": "Active", "company": filters.company, "department": filters.department, "user_id": frappe.session.user } active_employees = frappe.get_all( "Employee", filters=emp_filters, fields=["name", "employee_name", "department", "user_id"], order_by="name desc") data = [] for employee in active_employees: leave_approvers = [ l.leave_approver for l in frappe.db.sql( """select leave_approver from `tabEmployee Leave Approver` where parent = %s""", (employee.name), as_dict=True) ] if (len(leave_approvers) and user in leave_approvers) or (user in [ "Administrator", employee.user_id ]) or ("HR Manager" in frappe.get_roles(user)): row = [employee.name, employee.employee_name, employee.department] for leave_type in leave_types: # leaves taken leaves_taken = get_approved_leaves_for_period( employee.name, leave_type, filters.from_date, filters.to_date) # opening balance opening = get_leave_balance_on( employee.name, leave_type, filters.from_date, allocation_records_based_on_from_date.get( employee.name, frappe._dict())) # closing balance closing = get_leave_balance_on( employee.name, leave_type, filters.to_date, allocation_records_based_on_to_date.get( employee.name, frappe._dict())) row += [opening, leaves_taken, closing] data.append(row) return data
def validate_approving_authority(self, doctype_name, company, total, doc_obj=''): if not frappe.db.count("Authorization Rule"): return av_dis = 0 if doc_obj: price_list_rate, base_rate = 0, 0 for d in doc_obj.get("items"): if d.base_rate: price_list_rate += flt(d.base_price_list_rate) or flt( d.base_rate) base_rate += flt(d.base_rate) if doc_obj.get("discount_amount"): base_rate -= flt(doc_obj.discount_amount) if price_list_rate: av_dis = 100 - flt(base_rate * 100 / price_list_rate) final_based_on = [ 'Grand Total', 'Average Discount', 'Customerwise Discount', 'Itemwise Discount' ] # Check for authorization set for individual user based_on = [ x[0] for x in frappe.db.sql( """select distinct based_on from `tabAuthorization Rule` where transaction = %s and system_user = %s and (company = %s or ifnull(company,'')='') and docstatus != 2""", ( doctype_name, session['user'], company)) ] for d in based_on: self.bifurcate_based_on_type(doctype_name, total, av_dis, d, doc_obj, 1, company) # Remove user specific rules from global authorization rules for r in based_on: if r in final_based_on and r != 'Itemwise Discount': final_based_on.remove(r) # Check for authorization set on particular roles based_on = [ x[0] for x in frappe.db.sql( """select based_on from `tabAuthorization Rule` where transaction = %s and system_role IN (%s) and based_on IN (%s) and (company = %s or ifnull(company,'')='') and docstatus != 2 """ % ('%s', "'" + "','".join(frappe.get_roles()) + "'", "'" + "','".join(final_based_on) + "'", '%s'), (doctype_name, company)) ] for d in based_on: self.bifurcate_based_on_type(doctype_name, total, av_dis, d, doc_obj, 2, company) # Remove role specific rules from global authorization rules for r in based_on: if r in final_based_on and r != 'Itemwise Discount': final_based_on.remove(r) # Check for global authorization for g in final_based_on: self.bifurcate_based_on_type(doctype_name, total, av_dis, g, doc_obj, 0, company)
def get_user_pages_or_reports(parent): roles = frappe.get_roles() has_role = {} column = get_column(parent) # get pages or reports set on custom role custom_roles = frappe.db.sql(""" select `tabCustom Role`.{field} as name, `tabCustom Role`.modified, `tabCustom Role`.ref_doctype from `tabCustom Role`, `tabHas Role` where `tabHas Role`.parent = `tabCustom Role`.name and `tabCustom Role`.{field} is not null and `tabHas Role`.role in ({roles}) """.format(field=parent.lower(), roles=', '.join(['%s'] * len(roles))), roles, as_dict=1) for p in custom_roles: has_role[p.name] = { "modified": p.modified, "title": p.name, "ref_doctype": p.ref_doctype } standard_roles = frappe.db.sql(""" select distinct `tab{parent}`.name as name, `tab{parent}`.modified, {column} from `tabHas Role`, `tab{parent}` where `tabHas Role`.role in ({roles}) and `tabHas Role`.parent = `tab{parent}`.name and `tab{parent}`.`name` not in ( select `tabCustom Role`.{field} from `tabCustom Role` where `tabCustom Role`.{field} is not null) {condition} """.format( parent=parent, column=column, roles=', '.join(['%s'] * len(roles)), field=parent.lower(), condition="and `tabReport`.disabled=0" if parent == "Report" else ""), roles, as_dict=True) for p in standard_roles: if p.name not in has_role: has_role[p.name] = {"modified": p.modified, "title": p.title} if parent == "Report": has_role[p.name].update({'ref_doctype': p.ref_doctype}) # pages with no role are allowed if parent == "Page": pages_with_no_roles = frappe.db.sql(""" select `tab{parent}`.name, `tab{parent}`.modified, {column} from `tab{parent}` where (select count(*) from `tabHas Role` where `tabHas Role`.parent=`tab{parent}`.`name`) = 0 """.format(parent=parent, column=column), as_dict=1) for p in pages_with_no_roles: if p.name not in has_role: has_role[p.name] = {"modified": p.modified, "title": p.title} elif parent == "Report": for report_name in has_role: has_role[report_name]["report_type"] = frappe.db.get_value( "Report", report_name, "report_type") return has_role
def get_doctypes(): if "System Manager" in frappe.get_roles(): return [r[0] for r in frappe.db.sql("""select name from `tabDocType` where allow_import = 1""")] else: return frappe.user._get("can_import")
def get_permission_query_conditions(user): if not user: user = frappe.session.user roles = frappe.get_roles() if "Central Delivery" not in roles and frappe.session.user != "Administrator": return """(`tabTraining`.owner = '{user}' )""".format( user=frappe.session.user)
def can_edit(): if ("Administrador AGILEX" in frappe.get_roles()): return True else: return False
def validate_party(self): if self.party_type and self.party: frozen_accounts_modifier = frappe.db.get_value( 'Accounts Settings', None,'frozen_accounts_modifier') if not frozen_accounts_modifier in frappe.get_roles(): if frappe.db.get_value(self.party_type, self.party, "is_frozen"): frappe.throw("{0} {1} is frozen".format(self.party_type, self.party), CustomerFrozen)
def check_admin_or_system_manager(user=None): if not user: user = frappe.session.user if ("System Manager" not in frappe.get_roles(user)) and (user != "Administrator"): frappe.throw(_("Not permitted"), frappe.PermissionError)
def validate_expense_approver(self): if self.exp_approver and "Expense Approver" not in frappe.get_roles( self.exp_approver): frappe.throw(_("{0} ({1}) must have role 'Expense Approver'")\ .format(get_fullname(self.exp_approver), self.exp_approver), InvalidExpenseApproverError)
def test_fieldlevel_permissions_in_load(self): blog = frappe.get_doc({ "doctype": "Blog Post", "blog_category": "-test-blog-category-1", "blog_intro": "Test Blog Intro", "blogger": "_Test Blogger 1", "content": "Test Blog Content", "title": "_Test Blog Post {}".format(frappe.utils.now()), "published": 0 }) blog.insert() user = frappe.get_doc('User', '*****@*****.**') user_roles = frappe.get_roles() user.remove_roles(*user_roles) user.add_roles('Blogger') blog_post_property_setter = make_property_setter('Blog Post', 'published', 'permlevel', 1, 'Int') reset('Blog Post') # test field level permission before role level permissions are defined frappe.set_user(user.name) blog_doc = get_blog(blog.name) self.assertEqual(blog_doc.published, None) # this will be ignored because user does not # have write access on `published` field (or on permlevel 1 fields) blog_doc.published = 1 blog_doc.save() # since published field has higher permlevel self.assertEqual(blog_doc.published, 0) # test field level permission after role level permissions are defined frappe.set_user('Administrator') add('Blog Post', 'Website Manager', 1) update('Blog Post', 'Website Manager', 1, 'write', 1) frappe.set_user(user.name) blog_doc = get_blog(blog.name) self.assertEqual(blog_doc.name, blog.name) # since published field has higher permlevel self.assertEqual(blog_doc.published, None) # this will be ignored because user does not # have write access on `published` field (or on permlevel 1 fields) blog_doc.published = 1 blog_doc.save() # since published field has higher permlevel self.assertEqual(blog_doc.published, 0) frappe.set_user('Administrator') user.add_roles('Website Manager') frappe.set_user(user.name) doc = frappe.get_doc('Blog Post', blog.name) doc.published = 1 doc.save() blog_doc = get_blog(blog.name) # now user should be allowed to read field with higher permlevel # (after adding Website Manager role) self.assertEqual(blog_doc.published, 1) frappe.set_user('Administrator') # reset user roles user.remove_roles('Blogger', 'Website Manager') user.add_roles(*user_roles) blog_doc.delete() frappe.delete_doc(blog_post_property_setter.doctype, blog_post_property_setter.name)
def validate_expense_approver(exp_approver): if exp_approver and "Expense Approver" not in frappe.get_roles( exp_approver): return "{0} ({1}) must have role 'Expense Approver'".format( get_fullname(exp_approver), exp_approver) return ""
def check_credit_limit(customer, company, reference_doctype, reference_document, ignore_outstanding_sales_order=False, extra_amount=0): customer_outstanding = get_customer_outstanding( customer, company, ignore_outstanding_sales_order) if extra_amount > 0: customer_outstanding += flt(extra_amount) credit_limit = get_credit_limit(customer, company) if credit_limit > 0 and flt(customer_outstanding) > credit_limit: msgprint( _("Credit limit has been crossed for customer {0} ({1}/{2})"). format(customer, customer_outstanding, credit_limit)) # If not authorized person raise exception credit_controller_role = frappe.db.get_single_value( 'Accounts Settings', 'credit_controller') if not credit_controller_role or credit_controller_role not in frappe.get_roles( ): # form a list of emails for the credit controller users credit_controller_users = get_users_with_role( credit_controller_role or "Sales Master Manager") credit_controller_users = [ user[0] for user in credit_controller_users ] # form a list of emails and names to show to the user credit_controller_users_list = [ user for user in credit_controller_users if frappe.db.exists("Employee", {"prefered_email": user}) ] credit_controller_users = [ get_formatted_email(user).replace("<", "(").replace(">", ")") for user in credit_controller_users_list ] if not credit_controller_users: frappe.throw( _("Please contact your administrator to extend the credit limits for {0}." .format(customer))) message = """Please contact any of the following users to extend the credit limits for {0}: <br><br><ul><li>{1}</li></ul>""".format( customer, '<li>'.join(credit_controller_users)) # if the current user does not have permissions to override credit limit, # prompt them to send out an email to the controller users frappe.msgprint( message, title="Notify", raise_exception=1, primary_action={ 'label': 'Send Email', 'server_action': 'erpnext.selling.doctype.customer.customer.send_emails', 'hide_on_success': 1, 'args': { 'customer': customer, 'customer_outstanding': customer_outstanding, 'credit_limit': credit_limit, 'credit_controller_users_list': credit_controller_users_list, 'document_link': frappe.utils.get_link_to_form(reference_doctype, reference_document) } })
def get_attendance(limit_start=0, limit=10): default_date = datetime.date.today() user = frappe.session.user limit_start = cint(limit_start) row_template = 'for_attendance/doctype/attendance/templates/attendance_row.html' result = [] doctype = 'Attendance' meta = frappe.get_meta(doctype) all_fields = frappe.get_meta(doctype).fields list_view_fields = [df for df in all_fields if df.in_list_view][:4] time = frappe.form_dict.time if 'Employee' and not 'Administrator' in frappe.get_roles(user): attendances = frappe.db.sql('''select name from `tabAttendance` where attendance_date = %s and employee IN (select name from `tabEmployee` where user_id = %s) order by attendance_date desc limit %s, %s''', (default_date, user, limit_start, limit+1), as_dict=1) if time and time == 'weekly': attendances = frappe.db.sql('''select name from `tabAttendance` where WEEK(attendance_date, 1) = %s and employee IN (select name from `tabEmployee` where user_id = %s) order by attendance_date desc limit %s, %s''', (default_date.isocalendar()[1], user, limit_start, limit+1), as_dict=1) if time and time == 'monthly': attendances = frappe.db.sql('''select name from `tabAttendance` where MONTH(attendance_date) = %s and employee IN (select name from `tabEmployee` where user_id = %s) order by attendance_date desc limit %s, %s''', (default_date.month, user, limit_start, limit+1), as_dict=1) else: attendances = frappe.db.sql('''select name from `tabAttendance` where attendance_date = %s order by attendance_date desc limit %s, %s ''', (default_date, limit_start, limit+1), as_dict=1) if time and time == 'weekly': attendances = frappe.db.sql('''select name from `tabAttendance` where WEEK(attendance_date, 1) = %s order by attendance_date desc limit %s, %s''', (default_date.isocalendar()[1], limit_start, limit+1), as_dict=1) if time and time == 'monthly': attendances = frappe.db.sql('''select name from `tabAttendance` where MONTH(attendance_date) = %s order by attendance_date desc limit %s, %s''', (default_date.month, limit_start, limit+1), as_dict=1) show_more = len(attendances) > limit t_doc = frappe.get_doc('Attendance', attendances[0]) if show_more: attendances = attendances[:-1] for a in attendances: doc = frappe.get_doc(doctype, a) new_context = frappe._dict(doc=doc, meta=meta, list_view_fields=list_view_fields) rendered_row = frappe.render_template(row_template, new_context) result.append(rendered_row) return { "list_view_fields":list_view_fields, "result":result, "show_more": show_more, "next_start": limit_start + limit, "time": time, "week": t_doc.total_in_week, "month": t_doc.total_in_month } # Not removing follwoing for syntax purpose # but the above function is better approach I think # @frappe.whitelist() # def get_attendance(limit_start=0, limit=5): # limit_start = cint(limit_start) # row_template = 'for_attendance/doctype/attendance/templates/attendance_row.html' # result = [] # doctype = 'Attendance' # meta = frappe.get_meta(doctype) # all_fields = frappe.get_meta(doctype).fields # list_view_fields = [df for df in all_fields if df.in_list_view][:4] # time = frappe.form_dict.time # attendances = frappe.get_all(doctype, filters={'attendance_date': datetime.date.today()}, start=limit_start, page_length=limit+1) # if time and time != 'today': # attendances = frappe.get_all(doctype, start=limit_start, page_length=limit+1) # show_more = len(attendances) > limit # if show_more: # attendances = attendances[:-1] # for a in attendances: # doc = frappe.get_doc(doctype, a.name) # if time: # if time == 'today': # checker = True # elif time == 'monthly': # checker = bool((doc.attendance_date).month == datetime.date.today().month) # elif time == 'weekly': # checker = bool((doc.attendance_date).strftime("%V") == datetime.date.today().strftime("%V")) # if checker: # new_context = frappe._dict(doc=doc, meta=meta, list_view_fields=list_view_fields) # rendered_row = frappe.render_template(row_template, new_context) # result.append(rendered_row) # else: # new_context = frappe._dict(doc=doc, meta=meta, list_view_fields=list_view_fields) # rendered_row = frappe.render_template(row_template, new_context) # result.append(rendered_row) # return { # "attendances": attendances, # "list_view_fields":list_view_fields, # "result":result, # "show_more": show_more, # "next_start": limit_start + limit, # }