def savedocs(doc, action): """save / submit / update doclist""" try: doc = frappe.get_doc(json.loads(doc)) set_local_name(doc) # action doc.docstatus = { "Save": 0, "Submit": 1, "Update": 1, "Cancel": 2 }[action] if doc.docstatus == 1: doc.submit() else: try: doc.save() except frappe.NameError as e: doctype, name, original_exception = e if isinstance( e, tuple) else (doc.doctype or "", doc.name or "", None) frappe.msgprint( frappe._("{0} {1} already exists").format(doctype, name)) raise # update recent documents run_onload(doc) frappe.get_user().update_recent(doc.doctype, doc.name) send_updated_docs(doc) except Exception: if not frappe.local.message_log: frappe.msgprint(frappe._('Did not save')) frappe.errprint(frappe.utils.get_traceback()) raise
def savedocs(): """save / submit / update doclist""" try: doc = frappe.get_doc(json.loads(frappe.form_dict.doc)) set_local_name(doc) # action doc.docstatus = { "Save": 0, "Submit": 1, "Update": 1, "Cancel": 2 }[frappe.form_dict.action] try: doc.save() except frappe.NameError, e: doctype, name, original_exception = e if isinstance( e, tuple) else (doc.doctype or "", doc.name or "", None) frappe.msgprint( frappe._("{0} {1} already exists").format(doctype, name)) raise # update recent documents run_onload(doc) frappe.get_user().update_recent(doc.doctype, doc.name) send_updated_docs(doc)
def getdoc(doctype, name, user=None): """ Loads a doclist for a given document. This method is called directly from the client. Requries "doctype", "name" as form variables. Will also call the "onload" method on the document. """ if not (doctype and name): raise Exception, 'doctype and name required!' if not name: name = doctype if not frappe.db.exists(doctype, name): return [] try: doc = frappe.get_doc(doctype, name) run_onload(doc) if not doc.has_permission("read"): raise frappe.PermissionError, ("read", doctype, name) # add file list get_docinfo(doc) except Exception: frappe.errprint(frappe.utils.get_traceback()) frappe.msgprint(_('Did not load')) raise if doc and not name.startswith('_'): frappe.get_user().update_recent(doctype, name) frappe.response.docs.append(doc)
def savedocs(doc, action): """save / submit / update doclist""" try: doc = frappe.get_doc(json.loads(doc)) set_local_name(doc) # action doc.docstatus = {"Save":0, "Submit": 1, "Update": 1, "Cancel": 2}[action] if doc.docstatus==1: doc.submit() else: try: doc.save() except frappe.NameError as e: doctype, name, original_exception = e if isinstance(e, tuple) else (doc.doctype or "", doc.name or "", None) frappe.msgprint(frappe._("{0} {1} already exists").format(doctype, name)) raise # update recent documents run_onload(doc) frappe.get_user().update_recent(doc.doctype, doc.name) send_updated_docs(doc) except Exception: if not frappe.local.message_log: frappe.msgprint(frappe._('Did not save')) frappe.errprint(frappe.utils.get_traceback()) raise
def is_logged_in(): session_user = frappe.get_user() if session_user.name == "Guest": return False return True
def get_notifications_for_doctypes(config, notification_count): can_read = frappe.get_user().get_can_read() open_count_doctype = {} for d in config.for_doctype: if d in can_read: condition = config.for_doctype[d] if d=='Appointment': pass #frappe.errprint(['condition in desk _notification',type(condition)]) if d in notification_count: open_count_doctype[d] = notification_count[d] else: try: result = frappe.get_list(d, fields=["count(*)"], filters=condition, as_list=True)[0][0] except frappe.PermissionError, e: frappe.msgprint("Permission Error in notifications for {0}".format(d)) except Exception, e: # OperationalError: (1412, 'Table definition has changed, please retry transaction') if e.args[0]!=1412: raise else: open_count_doctype[d] = result frappe.cache().hset("notification_count:" + d, frappe.session.user, result)
def x_render_page(path): log("-- on render_page(%s)" % path) try: filepath, ext = os.path.splitext(path) # we only care about pages if ext not in [".js", ".css"]: user = frappe.get_user() if user.name == "Guest": email = random_string(20) + "@guest.local" user = frappe.get_doc({ "doctype": "User", "email": email, "first_name": "Guest User", "enabled": 1, "new_password": random_string(10), "user_type": "Website User" }) user.flags.ignore_permissions = True user.insert() frappe.local.login_manager.login_as(user.name) frappe.set_user(user.name) log("USER: %s" % user.name) result = x_render_page.patched_method(path) except Exception as ex: log(traceback.format_exc()) raise ex #log(result[0:40] + "...") return result
def get_oauth_session(service, user=None): current = int(time()) if not user: user = frappe.get_user().name filters = [ ["APP Token User", "parent", "=", service], ["APP Token User", "user", "=", user] ] dl = frappe.get_all("APP Token User", fields=["auth_token", "app_user_id"], filters=filters) if not dl or not dl[0].auth_token: return request_oauth_code(service, user) elif dl[0].expires_in and dl.expires_in > -1 and (dl[0].expires_in - current) <= 0: auth_token = refresh_oauth_token(service, user) else: auth_token = dl[0].auth_token session_provider = frappe.db.get_value("APP Token", service, "session_given_by") flow = get_oauth_service(service) headers = get_headers_data(service, {'auth_token': auth_token, 'client_id': flow.client_id, 'client_secret': flow.client_secret}) if session_provider == "Simple Session": session = requests.Session() session.auth = requests.auth.HTTPBasicAuth(flow.client_id, flow.client_secret) session.headers.update(headers) return session
def get_permission_query_conditions(user): if not user: user = frappe.session.user if not frappe.permissions.apply_user_permissions("Feed", "read", user): return "" user_permissions = frappe.defaults.get_user_permissions(user) can_read = frappe.get_user().get_can_read() can_read_doctypes = ['"{}"'.format(doctype) for doctype in list(set(can_read) - set(user_permissions.keys()))] if not can_read_doctypes: return "" conditions = ["tabFeed.doc_type in ({})".format(", ".join(can_read_doctypes))] if user_permissions: can_read_docs = [] for doctype, names in user_permissions.items(): for n in names: can_read_docs.append('"{}|{}"'.format(doctype, n)) if can_read_docs: conditions.append("concat_ws('|', tabFeed.doc_type, tabFeed.doc_name) in ({})".format( ", ".join(can_read_docs))) return "(" + " or ".join(conditions) + ")"
def get_feed_match_conditions(user=None, doctype='Comment'): if not user: user = frappe.session.user conditions = ['`tab{doctype}`.owner={user} or `tab{doctype}`.reference_owner={user}'.format( user = frappe.db.escape(user), doctype = doctype )] user_permissions = frappe.permissions.get_user_permissions(user) can_read = frappe.get_user().get_can_read() can_read_doctypes = ["'{}'".format(dt) for dt in list(set(can_read) - set(list(user_permissions)))] if can_read_doctypes: conditions += ["""(`tab{doctype}`.reference_doctype is null or `tab{doctype}`.reference_doctype = '' or `tab{doctype}`.reference_doctype in ({values}))""".format( doctype = doctype, values =", ".join(can_read_doctypes) )] if user_permissions: can_read_docs = [] for dt, obj in user_permissions.items(): for n in obj: can_read_docs.append('{}|{}'.format(frappe.db.escape(dt), frappe.db.escape(n.get('doc', '')))) if can_read_docs: conditions.append("concat_ws('|', `tab{doctype}`.reference_doctype, `tab{doctype}`.reference_name) in ({values})".format( doctype = doctype, values = ", ".join(can_read_docs))) return "(" + " or ".join(conditions) + ")"
def get_feed_match_conditions(user=None, force=True): if not user: user = frappe.session.user conditions = ['`tabCommunication`.owner="{user}" or `tabCommunication`.reference_owner="{user}"'.format(user=frappe.db.escape(user))] user_permissions = frappe.permissions.get_user_permissions(user) can_read = frappe.get_user().get_can_read() can_read_doctypes = ['"{}"'.format(doctype) for doctype in list(set(can_read) - set(list(user_permissions)))] if can_read_doctypes: conditions += ["""(`tabCommunication`.reference_doctype is null or `tabCommunication`.reference_doctype = '' or `tabCommunication`.reference_doctype in ({}))""".format(", ".join(can_read_doctypes))] if user_permissions: can_read_docs = [] for doctype, names in user_permissions.items(): for n in names: can_read_docs.append('"{}|{}"'.format(doctype, frappe.db.escape(n))) if can_read_docs: conditions.append("concat_ws('|', `tabCommunication`.reference_doctype, `tabCommunication`.reference_name) in ({})".format( ", ".join(can_read_docs))) return "(" + " or ".join(conditions) + ")"
def get_permission_query_conditions(user): if not user: user = frappe.session.user if not frappe.permissions.apply_user_permissions("Feed", "read", user): return "" user_permissions = frappe.defaults.get_user_permissions(user) can_read = frappe.get_user().get_can_read() can_read_doctypes = [ '"{}"'.format(doctype) for doctype in list(set(can_read) - set(user_permissions.keys())) ] if not can_read_doctypes: return "" conditions = [ "tabFeed.doc_type in ({})".format(", ".join(can_read_doctypes)) ] if user_permissions: can_read_docs = [] for doctype, names in user_permissions.items(): for n in names: can_read_docs.append('"{}|{}"'.format(doctype, n)) if can_read_docs: conditions.append( "concat_ws('|', tabFeed.doc_type, tabFeed.doc_name) in ({})". format(", ".join(can_read_docs))) return "(" + " or ".join(conditions) + ")"
def apply_permissions(data): default_country = frappe.db.get_default("country") user = frappe.get_user() user.build_permissions() allowed_pages = get_allowed_pages() allowed_reports = get_allowed_reports() new_data = [] for section in data: new_items = [] for item in (section.get("items") or []): item = frappe._dict(item) if item.country and item.country != default_country: continue if ((item.type == "doctype" and item.name in user.can_read) or (item.type == "page" and item.name in allowed_pages) or (item.type == "report" and item.name in allowed_reports) or item.type == "help"): new_items.append(item) if new_items: new_section = section.copy() new_section["items"] = new_items new_data.append(new_section) return new_data
def get_feed_match_conditions(user=None, force=True): if not user: user = frappe.session.user conditions = ['`tabCommunication`.owner="{user}" or `tabCommunication`.reference_owner="{user}"'.format(user=frappe.db.escape(user))] user_permissions = frappe.permissions.get_user_permissions(user) can_read = frappe.get_user().get_can_read() can_read_doctypes = ['"{}"'.format(doctype) for doctype in list(set(can_read) - set(user_permissions.keys()))] if can_read_doctypes: conditions += ["""(`tabCommunication`.reference_doctype is null or `tabCommunication`.reference_doctype = '' or `tabCommunication`.reference_doctype in ({}))""".format(", ".join(can_read_doctypes))] if user_permissions: can_read_docs = [] for doctype, names in user_permissions.items(): for n in names: can_read_docs.append('"{}|{}"'.format(doctype, frappe.db.escape(n))) if can_read_docs: conditions.append("concat_ws('|', `tabCommunication`.reference_doctype, `tabCommunication`.reference_name) in ({})".format( ", ".join(can_read_docs))) return "(" + " or ".join(conditions) + ")"
def __init__(self, page_name): self.page_name = page_name self.extended_cards = [] self.extended_charts = [] self.extended_shortcuts = [] self.user = frappe.get_user() self.allowed_modules = self.get_cached_value('user_allowed_modules', self.get_allowed_modules) self.doc = self.get_page_for_user() if self.doc.module not in self.allowed_modules: raise frappe.PermissionError self.can_read = self.get_cached_value('user_perm_can_read', self.get_can_read_items) self.allowed_pages = get_allowed_pages(cache=True) self.allowed_reports = get_allowed_reports(cache=True) self.onboarding_doc = self.get_onboarding_doc() self.onboarding = None self.table_counts = get_table_with_counts() self.restricted_doctypes = frappe.cache().get_value( "domain_restricted_doctypes" ) or build_domain_restriced_doctype_cache() self.restricted_pages = frappe.cache().get_value( "domain_restricted_pages") or build_domain_restriced_page_cache()
def get_notifications_for_doctypes(config, notification_count): """Notifications for DocTypes""" can_read = frappe.get_user().get_can_read() open_count_doctype = {} for d in config.for_doctype: if d in can_read: condition = config.for_doctype[d] if d in notification_count: open_count_doctype[d] = notification_count[d] else: try: if isinstance(condition, dict): result = len(frappe.get_list(d, fields=["name"], filters=condition, limit_page_length = 100, as_list=True, ignore_ifnull=True)) else: result = frappe.get_attr(condition)() except frappe.PermissionError: frappe.clear_messages() pass # frappe.msgprint("Permission Error in notifications for {0}".format(d)) except Exception as e: # OperationalError: (1412, 'Table definition has changed, please retry transaction') # InternalError: (1684, 'Table definition is being modified by concurrent DDL statement') if e.args[0] not in (1412, 1684): raise else: open_count_doctype[d] = result frappe.cache().hset("notification_count:" + d, frappe.session.user, result) return open_count_doctype
def get_notifications_for_doctypes(config, notification_count): """Notifications for DocTypes""" can_read = frappe.get_user().get_can_read() open_count_doctype = {} for d in config.for_doctype: if d in can_read: condition = config.for_doctype[d] if d in notification_count: open_count_doctype[d] = notification_count[d] else: try: if isinstance(condition, dict): result = len(frappe.get_list(d, fields=["name"], filters=condition, limit_page_length = 21, as_list=True, ignore_ifnull=True)) else: result = frappe.get_attr(condition)() except frappe.PermissionError: frappe.msgprint("Permission Error in notifications for {0}".format(d)) except Exception, e: # OperationalError: (1412, 'Table definition has changed, please retry transaction') if e.args[0]!=1412: raise else: open_count_doctype[d] = result frappe.cache().hset("notification_count:" + d, frappe.session.user, result)
def apply_permissions(data): default_country = frappe.db.get_default("country") user = frappe.get_user() user.build_permissions() allowed_pages = get_allowed_pages() new_data = [] for section in data: new_items = [] for item in (section.get("items") or []): item = frappe._dict(item) if item.country and item.country!=default_country: continue if ((item.type=="doctype" and item.name in user.can_read) or (item.type=="page" and item.name in allowed_pages) or (item.type=="report" and item.doctype in user.can_get_report) or item.type=="help"): new_items.append(item) if new_items: new_section = section.copy() new_section["items"] = new_items new_data.append(new_section) return new_data
def get_notifications_for_doctypes(config, notification_count): """Notifications for DocTypes""" can_read = frappe.get_user().get_can_read() open_count_doctype = {} for d in config.for_doctype: if d in can_read: condition = config.for_doctype[d] if d in notification_count: open_count_doctype[d] = notification_count[d] else: try: if isinstance(condition, dict): result = frappe.get_list(d, fields=["count(*)"], filters=condition, as_list=True)[0][0] else: result = frappe.get_attr(condition)() except frappe.PermissionError: pass # frappe.msgprint("Permission Error in notifications for {0}".format(d)) except Exception, e: # OperationalError: (1412, 'Table definition has changed, please retry transaction') if e.args[0]!=1412: raise else: open_count_doctype[d] = result frappe.cache().hset("notification_count:" + d, frappe.session.user, result)
def is_logged_in(): log("Are we still using this method?\n{0}".format(get_trace())) session_user = frappe.get_user() if session_user.name == "Guest": return False return True
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.get_user()._get("can_import")
def savedocs(): """save / submit / update doclist""" try: doc = frappe.get_doc(json.loads(frappe.form_dict.doc)) set_local_name(doc) # action doc.docstatus = {"Save":0, "Submit": 1, "Update": 1, "Cancel": 2}[frappe.form_dict.action] try: doc.save() except frappe.NameError, e: doctype, name, original_exception = e if isinstance(e, tuple) else (doc.doctype or "", doc.name or "", None) frappe.msgprint(frappe._("{0} {1} already exists").format(doctype, name)) raise # update recent documents run_onload(doc) frappe.get_user().update_recent(doc.doctype, doc.name) send_updated_docs(doc)
def get_current_user_permissions(): info = frappe.get_user().load_user() ret = frappe._dict() for k in [ 'can_print', 'can_set_user_permissions', 'can_create', 'can_search', 'can_export', 'can_get_report', 'can_write', 'can_import', 'can_email', 'can_cancel', 'can_delete', 'can_read' ]: ret[k] = info.get(k) return ret
def getdoc(doctype, name, user=None): """ Loads a doclist for a given document. This method is called directly from the client. Requries "doctype", "name" as form variables. Will also call the "onload" method on the document. """ if not (doctype and name): raise Exception('doctype and name required!') if not name: name = doctype if not frappe.db.exists(doctype, name): return [] try: doc = frappe.get_doc(doctype, name) run_onload(doc) if not doc.has_permission("read"): frappe.flags.error_message = _( 'Insufficient Permission for {0}').format( frappe.bold(doctype + ' ' + name)) raise frappe.PermissionError(("read", doctype, name)) doc.apply_fieldlevel_read_permissions() # add file list doc.add_viewed() get_docinfo(doc) except Exception: frappe.errprint(frappe.utils.get_traceback()) raise if doc and not name.startswith('_'): frappe.get_user().update_recent(doctype, name) doc.add_seen() frappe.response.docs.append(doc)
def getdoc(doctype, name, user=None): """ Loads a doclist for a given document. This method is called directly from the client. Requries "doctype", "name" as form variables. Will also call the "onload" method on the document. """ if not (doctype and name): raise Exception('doctype and name required!') if not name: name = doctype if not frappe.db.exists(doctype, name): return [] try: doc = frappe.get_doc(doctype, name) run_onload(doc) if not doc.has_permission("read"): frappe.flags.error_message = _('Insufficient Permission for {0}').format(frappe.bold(doctype + ' ' + name)) raise frappe.PermissionError(("read", doctype, name)) doc.apply_fieldlevel_read_permissions() # add file list doc.add_viewed() get_docinfo(doc) except Exception: frappe.errprint(frappe.utils.get_traceback()) raise if doc and not name.startswith('_'): frappe.get_user().update_recent(doctype, name) doc.add_seen() frappe.response.docs.append(doc)
def get_current_customer(): session_user = frappe.get_user() if session_user.name == "Guest": return None awc_session = session.get_awc_session() party = None if awc_session.get("selected_customer"): party = frappe.get_doc("Customer", awc_session["selected_customer"]) quotation = get_cart_quotation(party=party)["doc"] customer = frappe.get_doc("Customer", quotation.customer) return customer
def get_notifications_for_targets(config, notification_percent): """Notifications for doc targets""" can_read = frappe.get_user().get_can_read() doc_target_percents = {} # doc_target_percents = { # "Company": { # "Acme": 87, # "RobotsRUs": 50, # }, {}... # } for doctype in config.targets: if doctype in can_read: if doctype in notification_percent: doc_target_percents[doctype] = notification_percent[doctype] else: doc_target_percents[doctype] = {} d = config.targets[doctype] condition = d["filters"] target_field = d["target_field"] value_field = d["value_field"] try: if isinstance(condition, dict): doc_list = frappe.get_list( doctype, fields=["name", target_field, value_field], filters=condition, limit_page_length=100, ignore_ifnull=True, ) except frappe.PermissionError: frappe.clear_messages() pass except Exception as e: if e.args[0] not in (1412, 1684): raise else: for doc in doc_list: value = doc[value_field] target = doc[target_field] doc_target_percents[doctype][doc.name] = ( value / target * 100) if value < target else 100 return doc_target_percents
def get_notification_info_for_boot(): out = get_notifications() config = get_notification_config() can_read = frappe.get_user().get_can_read() conditions = {} module_doctypes = {} doctype_info = dict(frappe.db.sql("""select name, module from tabDocType""")) for d in list(set(can_read + config.for_doctype.keys())): if d in config.for_doctype: conditions[d] = config.for_doctype[d] if d in doctype_info: module_doctypes.setdefault(doctype_info[d], []).append(d) out.update({"conditions": conditions, "module_doctypes": module_doctypes}) return out
def validate(self): ticket_number = self.name attached_job_cards = frappe.db.sql( "SELECT status FROM `tabJob Card` WHERE ticket_number = '{0}'". format(ticket_number)) if len(attached_job_cards): if not 'Helpdesk Admin' in frappe.get_roles(): frappe.throw( 'Only Helpdesk Admin can edit a ticket that has job cards') # if self.assigned_to: # if not 'Helpdesk Admin' in frappe.get_roles(): # frappe.throw('Only Helpdesk Admin can assign tickets.') if not self.raised_by_name: if self.raised_by: self.raised_by_name = get_full_name(self.raised_by) if self.status == 'Draft': self.status = 'Open' # if self.assigned_to and self.status != 'On-Hold' and self.status !='Close': # if not 'Helpdesk Admin' in frappe.get_roles(): # frappe.throw('Only Helpdesk Admin can assign tickets.') # else: # self.status = 'Assigned' if self.status == 'On-Hold': if not 'Helpdesk Admin' in frappe.get_roles(): frappe.throw( 'Only Helpdesk Admin can change the status to On-Hold.') if self.status == 'Close': if frappe.get_user() is not self.created_by: frappe.throw('Only the creator can close the ticket.') for attached_job_card in attached_job_cards: if attached_job_card[0] != 'Completed': frappe.throw( 'Cannot save while attached Job Card is not complete.') if self.status == 'Assigned': if not self.assigned_to: frappe.throw('The assigned to field is empty.')
def get_notifications_for_targets(config, notification_percent): """Notifications for doc targets""" can_read = frappe.get_user().get_can_read() doc_target_percents = {} # doc_target_percents = { # "Company": { # "Acme": 87, # "RobotsRUs": 50, # }, {}... # } for doctype in config.targets: if doctype in can_read: if doctype in notification_percent: doc_target_percents[doctype] = notification_percent[doctype] else: doc_target_percents[doctype] = {} d = config.targets[doctype] condition = d["filters"] target_field = d["target_field"] value_field = d["value_field"] try: if isinstance(condition, dict): doc_list = frappe.get_list(doctype, fields=["name", target_field, value_field], filters=condition, limit_page_length = 100, ignore_ifnull=True) except frappe.PermissionError: frappe.clear_messages() pass except Exception as e: if e.args[0] not in (1412, 1684): raise else: for doc in doc_list: value = doc[value_field] target = doc[target_field] doc_target_percents[doctype][doc.name] = (value/target * 100) if value < target else 100 return doc_target_percents
def get_notification_info_for_boot(): out = get_notifications() config = get_notification_config() can_read = frappe.get_user().get_can_read() conditions = {} module_doctypes = {} doctype_info = dict(frappe.db.sql("""select name, module from tabDocType""")) for d in list(set(can_read + list(config.for_doctype))): if d in config.for_doctype: conditions[d] = config.for_doctype[d] if d in doctype_info: module_doctypes.setdefault(doctype_info[d], []).append(d) out.update({ "conditions": conditions, "module_doctypes": module_doctypes, }) return out
def __init__(self, page, minimal=False): self.page_name = page.get('name') self.page_title = page.get('title') self.public_page = page.get('public') self.extended_links = [] self.extended_charts = [] self.extended_shortcuts = [] self.workspace_manager = "Workspace Manager" in frappe.get_roles() self.user = frappe.get_user() self.allowed_modules = self.get_cached('user_allowed_modules', self.get_allowed_modules) self.doc = frappe.get_cached_doc("Workspace", self.page_name) if self.doc and self.doc.module and self.doc.module not in self.allowed_modules and not self.workspace_manager: raise frappe.PermissionError self.can_read = self.get_cached('user_perm_can_read', self.get_can_read_items) self.allowed_pages = get_allowed_pages(cache=True) self.allowed_reports = get_allowed_reports(cache=True) if not minimal: if self.doc.content: self.onboarding_list = [ x['data']['onboarding_name'] for x in loads(self.doc.content) if x['type'] == 'onboarding' ] self.onboardings = [] self.table_counts = get_table_with_counts() self.restricted_doctypes = frappe.cache().get_value( "domain_restricted_doctypes" ) or build_domain_restriced_doctype_cache() self.restricted_pages = frappe.cache().get_value( "domain_restricted_pages") or build_domain_restriced_page_cache()
def get_doctypes(): return frappe.get_user()._get("can_import")
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.get_user()._get("can_import")
def get_user(user=None): return user or frappe.get_user().name
def contact_validate_for_sms(doc, method=None, *args, **kwargs): if cint(doc.sms_optin) == 1: if "Quality Manager" not in frappe.get_user( frappe.session.user).get_roles(): frappe.throw("Quality Manager can update sms opted in contacts")
def get_user(bootinfo): """get user info""" bootinfo.user = frappe.get_user().load_user()
def checkout(form): log("Are we still using this method?\n{0}".format(get_trace())) result = { "success": False, "msg": "Not Implemented", "errors": {} } try: form = json.loads(form) except: result["msg"] = "Invalid data" return result billing = form.get("billing", {}) shipping = form.get("shipping", {}) session_user = frappe.get_user() customer = None user = frappe.get_doc("User", session_user.name) form["user"] = { "email": user.email } result['form'] = form # set form back to browser to update any ids as neccessary gateway = None try: quotation = cart.get_cart_quotation() quote = quotation["doc"] gateway = embed.get_gateway_module(billing.get("gateway", None)) customer = frappe.get_doc("Customer", quote.customer) except: result["success"] = False result["msg"] = "Internal Error" result["exception"] = traceback.format_exc() try: if gateway: bill_address = None bill_address_insert = False ship_address = None ship_address_insert = False # lets extract billing address if one was entered if not billing['fields'].get('bill_address_id', False): bill_address = { k: billing['fields'].get(k, None) \ for k in ["bill_%s" % j for j in ADDRESS_FIELDS] } bill_address = _create_customer_address(bill_address, customer, 'bill_') bill_address.flags.ignore_permissions = True bill_address_insert = True else: bill_address = frappe.get_doc('Address', billing['fields']['bill_address_id']) if not shipping['fields'].get('ship_address_id', False): ship_address = { k: shipping['fields'].get(k, None) \ for k in ["ship_%s" % j for j in ADDRESS_FIELDS] } ship_address = _create_customer_address(ship_address, customer, 'ship_') ship_address.flags.ignore_permissions = True ship_address_insert = True else: ship_address = frappe.get_doc('Address', shipping['fields']['ship_address_id']) # setup transaction transaction = create_transaction(quote.grand_total, quote.currency) transaction.email = user.email stored_payment = None if form.get("stored_payment", False): stored_payment = None # update with new doctype try: success, msg = gateway.process(transaction, form, stored_payment, bill_address, ship_address) if success: result["success"] = True # on success insert new addresses if bill_address_insert: bill_address.insert() billing['fields']['bill_address_id'] = bill_address.name if ship_address_insert: # regenerate title since erpnext uses # title to generate id(name) in case # billing address uses same title ship_address.address_title = get_doctype_next_series('Address', "%s-%s" % (shipping['fields']['ship_address_title'], 'Shipping')) ship_address.insert() shipping['fields']['ship_address_id'] = ship_address.name # apply addresses to quotation quote.shipping_address_name = ship_address.name quote.shipping_address = get_address_display(ship_address.as_dict()) quote.customer_address = bill_address.name quote.address_display = get_address_display(bill_address.as_dict()) quote.flags.ignore_permissions = True quote.save() # now we'll submit quotation, create sales order, # create payment request and fullfill it so_name = cart.place_order() # submit quotation and create so result["so_name"] = so_name # lets now create a payment request and fullfill it immediately preq = payment_request.make_payment_request(dt="Sales Order", dn=so_name, submit_doc=1, return_doc=1) if preq: gdoc = gateway.get_gateway() adoc = gateway.get_bank_account() gadoc = gateway.get_account() preq.payment_gateway = gdoc.name preq.payment_account = adoc.name preq.payment_gateway_account = gadoc.name preq.flags.ignore_validate_update_after_submit = 1 preq.flags.ignore_permissions = True preq.save() payment_entry = preq.run_method("set_as_paid") transaction.log(json.dumps(sanitize_checkout_form(form), indent=4)) transaction.reference_doctype = "Payment Request" transaction.reference_docname = preq.name transaction.gateway = gdoc.name transaction.save() # find invoice inv_item = frappe.get_list("Sales Invoice Item", fields=["parent"], filters={"sales_order": so_name})[0] result["inv_name"] = inv_item.get("parent") frappe.session['awc_success_inv_name'] = inv_item.get("parent") frappe.session['awc_success_so_name'] = so_name frappe.session['awc_success_email'] = user.email else: result["success"] = False result["msg"] = msg except: transaction.log(json.dumps(sanitize_checkout_form(form), indent=4)) transaction.status = "Failed" transaction.log(traceback.format_exc() + "\n---\n") transaction.save() result["success"] = False result["msg"] = 'Internal Error' result["exception"] = traceback.format_exc() raise except: result["success"] = False if not result.get('msg'): result['msg'] = 'Internal Error' if not result.get('exception'): result['exception'] = traceback.format_exc() return result
def register(email, password, password_check, first_name, last_name): log("Are we still using this method?\n{0}".format(get_trace())) result = dict( success=False, msg="Unhandled Error" ) guest_user = frappe.get_user() user = frappe.get_doc("User", guest_user.name) quotation = cart.get_cart_quotation()["doc"] if user: if user.email[-12:] == "@guest.local": user.email = email user.first_name = first_name user.last_name = last_name user.new_password = password user.flags.ignore_permissions = True user.save() old_name = user.name frappe.rename_doc("User", old_name, email, ignore_permissions=True) user.name = email user.owner = user.name user.save() frappe.local.login_manager.login_as(email) frappe.set_user(email) customer = None contact = frappe.get_doc("Contact", { "user": email }) if contact: contact.first_name = first_name contact.last_name = last_name contact.email_id = email contact.flags.ignore_permissions = True contact.save() frappe.rename_doc("Contact", contact.name, email, ignore_permissions=True) contact.name = email customer = frappe.get_doc("Customer", contact.customer) if customer and customer.name.startswith("Guest"): customer.full_name = "%s %s" % (first_name, last_name) customer.flags.ignore_permissions = True customer.save() customer_next = get_doctype_next_series("Customer", customer.full_name) frappe.rename_doc("Customer", customer.name, customer_next, ignore_permissions=True) customer.name = customer_next # move quotation to logged in user transfer_quotation_to_user(quotation, user, customer=customer, contact=contact) result["success"] = True result["msg"] = "" result["user"] = { "full_name": user.full_name, "name": user.name } else: result["msg"] = "User is not a guest: %s" % user.email else: result["msg"] = "Internal Error, could not fetch user: %s" % guest_user.name return result
def get_user_info(): return frappe.get_user().load_user()
def is_website_user(): return frappe.get_user().doc.user_type == "Website User"