def get_context(context): project_user = frappe.db.get_value("Project User", {"parent": frappe.form_dict.project, "user": frappe.session.user} , ["user", "view_attachments"], as_dict= True) if frappe.session.user != 'Administrator' and (not project_user or frappe.session.user == 'Guest'): raise frappe.PermissionError context.no_cache = 1 context.show_sidebar = True project = frappe.get_doc('Project', frappe.form_dict.project) project.has_permission('read') project.tasks = get_tasks(project.name, start=0, item_status='open', search=frappe.form_dict.get("search")) project.timesheets = get_timesheets(project.name, start=0, search=frappe.form_dict.get("search")) if project_user and project_user.view_attachments: project.attachments = get_attachments(project.name) user=frappe.local.session_obj.user roles=frappe.get_roles(user) if has_common(["Supplier"], roles): context.is_supplier=True elif has_common(["Customer"], roles): context.is_customer=True frappe.local.cookie_manager.set_cookie("is_customer", cstr(context.is_customer)) if hasattr(frappe.local, "cookie_manager"): frappe.local.cookie_manager.set_cookie("is_supplier", cstr(context.is_supplier)) context.doc = project
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 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.user.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 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.user.get_roles()) and not has_common( appr_users, [session['user']]): msg, add_msg = '', '' if max_amount: dcc = get_company_currency(self.doc.company) if based_on == 'Grand Total': msg = "since Grand Total exceeds %s. %s" % ( dcc, flt(max_amount)) elif based_on == 'Itemwise Discount': msg = "since Discount exceeds %s for Item Code : %s" % ( cstr(max_amount) + '%', item) elif based_on == 'Average Discount' or based_on == 'Customerwise Discount': msg = "since Discount exceeds %s" % (cstr(max_amount) + '%') if appr_users: add_msg = "Users : " + cstr(appr_users) if appr_roles: add_msg = "Roles : " + cstr(appr_roles) if appr_users and appr_roles: add_msg = "Users : " + cstr( appr_users) + " or " + "Roles : " + cstr(appr_roles) msgprint( "You are not authorize to submit this %s %s. Please send for approval to %s" % (doctype_name, msg, add_msg)) raise Exception
def get_tasks(project, start=0, search=None, item_status=None): from project_management.api import get_customers_suppliers customers, suppliers = get_customers_suppliers('Task', frappe.session.user,'supplier_cf') user=frappe.session.user roles=frappe.get_roles(user) is_supplier=False if has_common(["Supplier"], roles): is_supplier=True if suppliers and is_supplier==True: filters = {"project": project,"supplier_cf":suppliers[0]} else: filters = {"project": project} if search: filters["subject"] = ("like", "%{0}%".format(search)) # if item_status: # filters["status"] = item_status tasks = frappe.get_all("Task", filters=filters, fields=["name", "subject", "status", "_seen", "_comments", "modified", "description","supplier_cf"], limit_start=start, limit_page_length=10) for task in tasks: task.todo = frappe.get_all('ToDo',filters={'reference_name':task.name, 'reference_type':'Task'}, fields=["assigned_by", "owner", "modified", "modified_by"]) if task.todo: task.todo=task.todo[0] task.todo.user_image = frappe.db.get_value('User', task.todo.owner, 'user_image') task.comment_count = len(json.loads(task._comments or "[]")) task.css_seen = '' if task._seen: if frappe.session.user in json.loads(task._seen): task.css_seen = 'seen' return tasks
def update_loan_charges(self, cancel=False): from frappe.utils import has_common for row in self.income_receipt_items: loan_charge = frappe.get_doc(row.voucher_type, row.voucher_name) base_allocated_amount = flt(row.allocated_amount) * flt(self.exchange_rate or 1.000) exchange_rate = get_exchange_rate(self.loan_currency, self.currency) or 1.000 amount = flt(base_allocated_amount / exchange_rate, 2) if not cancel: loan_charge.paid_amount += amount loan_charge.outstanding_amount -= amount else: loan_charge.paid_amount -= amount loan_charge.outstanding_amount += amount loan_charge.update_references(cancel=cancel) loan_charge.update_status() loan_charge.submit() loan_charges_type_list = [d.loan_charges_type for d in self.income_receipt_items] if has_common(["Repayment Amount", "Interest", "Capital"], loan_charges_type_list): frappe.get_doc(self.meta.get_field("loan").options, self.loan)\ .sync_this_with_loan_charges()
def get_customers_suppliers(doctype, user): customers = [] suppliers = [] meta = frappe.get_meta(doctype) customer_field_name = get_customer_field_name(doctype) has_customer_field = meta.has_field(customer_field_name) has_supplier_field = meta.has_field('supplier') if has_common(["Supplier", "Customer"], frappe.get_roles(user)): contacts = frappe.db.sql(""" select `tabContact`.email_id, `tabDynamic Link`.link_doctype, `tabDynamic Link`.link_name from `tabContact`, `tabDynamic Link` where `tabContact`.name=`tabDynamic Link`.parent and `tabContact`.email_id =%s """, user, as_dict=1) customers = [ c.link_name for c in contacts if c.link_doctype == 'Customer' ] suppliers = [ c.link_name for c in contacts if c.link_doctype == 'Supplier' ] elif frappe.has_permission(doctype, 'read', user=user): customer_list = frappe.get_list("Customer") customers = suppliers = [customer.name for customer in customer_list] return customers if has_customer_field else None, \ suppliers if has_supplier_field else None
def get(): if has_common(["Scanner"], frappe.get_roles()): return {"key": "Please contact with your Administrator"} args = get_form_params() data = compress(execute(**args), args=args) return data
def get_comp(self): ret = {} type = [] ret['period'] = ['Annual', 'Half Yearly', 'Quarterly', 'Monthly'] from erpnext.accounts.page.accounts_browser.accounts_browser import get_companies ret['company'] = get_companies() #--- to get fiscal year and start_date of that fiscal year ----- res = frappe.db.sql( "select name, year_start_date from `tabFiscal Year`") ret['fiscal_year'] = [r[0] for r in res] ret['start_dates'] = {} for r in res: ret['start_dates'][r[0]] = str(r[1]) #--- from month and to month (for MIS - Comparison Report) ------- month_list = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] fiscal_start_month = frappe.db.sql( "select MONTH(year_start_date) from `tabFiscal Year` where name = %s", (frappe.defaults.get_global_default("fiscal_year"))) fiscal_start_month = fiscal_start_month and fiscal_start_month[0][ 0] or 1 mon = [''] for i in range(fiscal_start_month, 13): mon.append(month_list[i - 1]) for i in range(0, fiscal_start_month - 1): mon.append(month_list[i]) ret['month'] = mon # get MIS Type on basis of roles of session user self.roles = frappe.user.get_roles() if has_common(self.roles, ['Sales Manager']): type.append('Sales') if has_common(self.roles, ['Purchase Manager']): type.append('Purchase') ret['type'] = type return ret
def get_appr_user_role(self, det, doctype_name, total, based_on, condition, item, company, doc_obj, item_obj): 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']]): self.custom_throw = True if item_obj and (appr_roles or appr_users): if appr_roles: self.custom_auth_details[item_obj.item_code][ appr_roles[0]] = flt(max_amount) elif appr_users: self.custom_auth_details[item_obj.item_code][ appr_users[0]] = flt(max_amount) if doc_obj: self.custom_doc_name = doc_obj.name
def update_task_document(self, method): from frappe.utils import flt, has_common import json user = frappe.local.session_obj.user roles = frappe.get_roles(user) if has_common(["Supplier"], roles): for d in self.get("task_document_pm_cf"): if d.is_new(): d.status = 'Under Review' d.can_client_view = 0 else: d.submit_attachment = d.submit_attachment print(d.name, d.is_new())
def is_permitted(self): """Returns true if Page Role is not set or the user is allowed.""" from frappe.utils import has_common allowed = [d.role for d in frappe.get_all("Page Role", fields=["role"], filters={"parent": self.name})] if not allowed: return True roles = frappe.get_roles() if has_common(roles, allowed): return True
def is_permitted(self): """Returns true if Has Role is not set or the user is allowed.""" from frappe.utils import has_common allowed = [d.role for d in frappe.get_all("Has Role", fields=["role"], filters={"parent": self.name})] custom_roles = get_custom_allowed_roles('report', self.name) allowed.extend(custom_roles) if not allowed: return True if has_common(frappe.get_roles(), allowed): return True
def is_permitted(self): """Returns true if Has Role is not set or the user is allowed.""" from frappe.utils import has_common allowed = [d.role for d in frappe.get_all("Has Role", fields=["role"], filters={"parent": self.name})] custom_roles = get_custom_allowed_roles('report', self.name) allowed.extend(custom_roles) if not allowed: return True roles = frappe.get_roles() if has_common(roles, allowed): return True
def get_dashboard(): from frappe.utils import has_common user_roles = frappe.get_roles() list_dashboard = frappe.get_list("Redash Dashboards", fields=["name", "title", "url_dashboard"], order_by="dborder", ignore_permissions=True) out = [] for dashboard in list_dashboard: dashboard_roles = [ d.role for d in frappe.get_all("RedashPerm", filters={"parent": dashboard.name}, fields=["role"], ignore_permissions=True) ] if has_common(user_roles, dashboard_roles): out.append([dashboard.title, dashboard.url_dashboard]) return out
def validate_rule(self): if self.doc.transaction != 'Appraisal': if not self.doc.approving_role and not self.doc.approving_user: msgprint("Please enter Approving Role or Approving User", raise_exception=1) elif self.doc.system_user and self.doc.system_user == self.doc.approving_user: msgprint( "Approving User cannot be same as user the rule is Applicable To (User)", raise_exception=1) elif self.doc.system_role and self.doc.system_role == self.doc.approving_role: msgprint("Approving Role cannot be same as user the rule is \ Applicable To (Role).", raise_exception=1) elif self.doc.system_user and self.doc.approving_role and \ has_common([self.doc.approving_role], [x[0] for x in \ frappe.db.sql("select role from `tabUserRole` where parent = '%s'" % \ (self.doc.system_user))]): msgprint( "System User : %s is assigned role : %s. So rule does not make sense" % (self.doc.system_user, self.doc.approving_role), raise_exception=1) elif self.doc.transaction in ['Purchase Order', 'Purchase Receipt', \ 'Purchase Invoice', 'Stock Entry'] and self.doc.based_on \ in ['Average Discount', 'Customerwise Discount', 'Itemwise Discount']: msgprint( "You cannot set authorization on basis of Discount for %s" % self.doc.transaction, raise_exception=1) elif self.doc.based_on == 'Average Discount' and flt( self.doc.value) > 100.00: msgprint("Discount cannot given for more than 100%", raise_exception=1) elif self.doc.based_on == 'Customerwise Discount' and not self.doc.master_name: msgprint( "Please enter Customer Name for 'Customerwise Discount'", raise_exception=1) else: if self.doc.transaction == 'Appraisal' and self.doc.based_on != 'Not Applicable': msgprint( "Based on should be 'Not Applicable' while setting authorization rule\ for 'Appraisal'", raise_exception=1)
def get_customers_suppliers(doctype, user, supplier_field_name): from erpnext.controllers.website_list_for_contact import get_customer_field_name from frappe.utils import flt, has_common customers = [] suppliers = [] meta = frappe.get_meta(doctype) print(meta, 'meta') customer_field_name = get_customer_field_name(doctype) has_customer_field = meta.has_field(customer_field_name) has_supplier_field = meta.has_field('supplier_cf') print(has_supplier_field, 'has_supplier_field') if has_common(["Supplier", "Customer"], frappe.get_roles(user)): contacts = frappe.db.sql(""" select `tabContact`.email_id, `tabDynamic Link`.link_doctype, `tabDynamic Link`.link_name from `tabContact`, `tabDynamic Link` where `tabContact`.name=`tabDynamic Link`.parent and `tabContact`.email_id =%s """, user, as_dict=1) customers = [ c.link_name for c in contacts if c.link_doctype == 'Customer' ] suppliers = [ c.link_name for c in contacts if c.link_doctype == 'Supplier' ] print(suppliers, 'suppliers') elif frappe.has_permission(doctype, 'read', user=user): customer_list = frappe.get_list("Customer") customers = suppliers = [customer.name for customer in customer_list] return customers if has_customer_field else None, \ suppliers if has_supplier_field else None
def save(doctype, user_settings): if has_common(["Scanner"], frappe.get_roles()): return {"key": "Please contact with your Administrator"} user_settings = json.loads(user_settings or '{}') update_user_settings(doctype, user_settings) return user_settings