Exemple #1
0
def verify_export_allowed():
    """throw exception if user is not allowed to export"""
    global roles
    roles = webnotes.get_roles()
    if not ('Administrator' in roles or 'System Manager' in roles
            or 'Report Manager' in roles):
        raise webnotes.PermissionError
Exemple #2
0
def verify_export_allowed():
    """throw exception if user is not allowed to export"""
    webnotes.local.reportview_roles = webnotes.get_roles()
    if not ('Administrator' in webnotes.local.reportview_roles or \
     'System Manager' in webnotes.local.reportview_roles or \
     'Report Manager' in webnotes.local.reportview_roles):
        raise webnotes.PermissionError
Exemple #3
0
def verify_export_allowed():
	"""throw exception if user is not allowed to export"""
	webnotes.local.reportview_roles = webnotes.get_roles()
	if not ('Administrator' in webnotes.local.reportview_roles or \
		'System Manager' in webnotes.local.reportview_roles or \
		'Report Manager' in webnotes.local.reportview_roles):
		raise webnotes.PermissionError
def can_import(doctype, raise_exception=False):
	if not ("System Manager" in webnotes.get_roles() or has_permission(doctype, "import")):
		if raise_exception:
			raise webnotes.PermissionError("You are not allowed to import: {doctype}".format(doctype=doctype))
		else:
			return False
	return True
Exemple #5
0
def add_allowed_pages(bootinfo):
    bootinfo.page_info = dict(
        webnotes.conn.sql(
            """select distinct parent, modified from `tabPage Role`
		where role in ('%s')"""
            % "', '".join(webnotes.get_roles())
        )
    )
Exemple #6
0
def add_allowed_pages(bootinfo):
    bootinfo.allowed_pages = [
        p[0]
        for p in webnotes.conn.sql(
            """select distinct parent from `tabPage Role`
		where role in ('%s')"""
            % "', '".join(webnotes.get_roles())
        )
    ]
Exemple #7
0
def get_match_conditions():
	return """(tabEvent.event_type='Public' or tabEvent.owner='%(user)s'
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and `tabEvent User`.person='%(user)s')
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%(roles)s')))
		""" % {
			"user": webnotes.session.user,
			"roles": "', '".join(webnotes.get_roles(webnotes.session.user))
		}
Exemple #8
0
def get_match_conditions():
    return """(tabEvent.event_type='Public' or tabEvent.owner='%(user)s'
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and `tabEvent User`.person='%(user)s')
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%(roles)s')))
		""" % {
        "user": webnotes.session.user,
        "roles": "', '".join(webnotes.get_roles(webnotes.session.user))
    }
def get_restrictable_doctypes():
	user_roles = webnotes.get_roles()
	condition = ""
	values = []
	if "System Manager" not in user_roles:
		condition = """and exists(select `tabDocPerm`.name from `tabDocPerm` 
			where `tabDocPerm`.parent=`tabDocType`.name and restrict=1
			and `tabDocPerm`.name in ({roles}))""".format(roles=", ".join(["%s"]*len(user_roles)))
		values = user_roles
	
	return webnotes.conn.sql_list("""select name from tabDocType 
		where ifnull(issingle,0)=0 and ifnull(istable,0)=0 {condition}""".format(condition=condition),
		values)
Exemple #10
0
def load_doctypes():
	"""load all doctypes and roles"""
	global doctypes, roles
	import webnotes.model.doctype

	roles = webnotes.get_roles()
	
	for t in tables:
		if t.startswith('`'):
			doctype = t[4:-1]
			if not webnotes.has_permission(doctype):
				raise webnotes.PermissionError, doctype
			doctypes[doctype] = webnotes.model.doctype.get(doctype)
Exemple #11
0
def get_feed(arg=None):
	"""get feed"""	
	return webnotes.conn.sql("""select
		distinct t1.name, t1.feed_type, t1.doc_type, t1.doc_name, t1.subject, t1.owner,
		t1.modified
		from tabFeed t1, tabDocPerm t2
		where t1.doc_type = t2.parent
		and t2.role in ('%s')
		and ifnull(t2.`read`,0) = 1
		order by t1.modified desc
		limit %s, %s""" % ("','".join(webnotes.get_roles()), 
			webnotes.form_dict['limit_start'], webnotes.form_dict['limit_page_length']), 
			as_dict=1)
Exemple #12
0
def build_match_conditions(doctype, fields=None, as_condition=True):
	"""add match conditions if applicable"""
	
	match_filters = {}
	match_conditions = []
	match = True

	if not getattr(webnotes.local, "reportview_tables", None) \
		or not getattr(webnotes.local, "reportview_doctypes", None):
		webnotes.local.reportview_tables = get_tables(doctype, fields)
		load_doctypes()

	if not getattr(webnotes.local, "reportview_roles", None):
		webnotes.local.reportview_roles = webnotes.get_roles()

	for d in webnotes.local.reportview_doctypes[doctype]:
		if d.doctype == 'DocPerm' and d.parent == doctype:
			if d.role in webnotes.local.reportview_roles:
				if d.match: # role applicable
					if ':' in d.match:
						document_key, default_key = d.match.split(":")
					else:
						default_key = document_key = d.match
					for v in webnotes.defaults.get_user_default_as_list(default_key, \
						webnotes.session.user) or ["** No Match **"]:
						if as_condition:
							match_conditions.append('`tab%s`.%s="%s"' % (doctype,
								document_key, v))
						else:
							if v:
								match_filters.setdefault(document_key, [])
								if v not in match_filters[document_key]:
									match_filters[document_key].append(v)
							
				elif d.read == 1 and d.permlevel == 0:
					# don't restrict if another read permission at level 0 
					# exists without a match restriction
					match = False
					match_filters = {}
	
	if as_condition:
		conditions = ""
		if match_conditions and match:
			conditions =  '('+ ' or '.join(match_conditions) +')'
		
		doctype_conditions = get_doctype_conditions(doctype)
		if doctype_conditions:
				conditions += ' and ' + doctype_conditions if conditions else doctype_conditions
		return conditions
	else:
		return match_filters
Exemple #13
0
def build_match_conditions(doctype, fields=None, as_condition=True):
    """add match conditions if applicable"""

    match_filters = {}
    match_conditions = []
    match = True

    if not getattr(webnotes.local, "reportview_tables", None) \
     or not getattr(webnotes.local, "reportview_doctypes", None):
        webnotes.local.reportview_tables = get_tables(doctype, fields)
        load_doctypes()

    if not getattr(webnotes.local, "reportview_roles", None):
        webnotes.local.reportview_roles = webnotes.get_roles()

    for d in webnotes.local.reportview_doctypes[doctype]:
        if d.doctype == 'DocPerm' and d.parent == doctype:
            if d.role in webnotes.local.reportview_roles:
                if d.match:  # role applicable
                    if ':' in d.match:
                        document_key, default_key = d.match.split(":")
                    else:
                        default_key = document_key = d.match
                    for v in webnotes.defaults.get_user_default_as_list(default_key, \
                     webnotes.session.user) or ["** No Match **"]:
                        if as_condition:
                            match_conditions.append('`tab%s`.%s="%s"' %
                                                    (doctype, document_key, v))
                        else:
                            if v:
                                match_filters.setdefault(document_key, [])
                                if v not in match_filters[document_key]:
                                    match_filters[document_key].append(v)

                elif d.read == 1 and d.permlevel == 0:
                    # don't restrict if another read permission at level 0
                    # exists without a match restriction
                    match = False
                    match_filters = {}

    if as_condition:
        conditions = ""
        if match_conditions and match:
            conditions = '(' + ' or '.join(match_conditions) + ')'

        doctype_conditions = get_doctype_conditions(doctype)
        if doctype_conditions:
            conditions += ' and ' + doctype_conditions if conditions else doctype_conditions
        return conditions
    else:
        return match_filters if match else {}
Exemple #14
0
def get_feed(arg=None):
	"""get feed"""	
	return webnotes.conn.sql("""select
		distinct t1.name, t1.feed_type, t1.doc_type, t1.doc_name, t1.subject, t1.owner,
		t1.modified
		from tabFeed t1, tabDocPerm t2
		where t1.doc_type = t2.parent
		and t2.role in ('%s')
		and t2.permlevel = 0
		and ifnull(t2.`read`,0) = 1
		order by t1.modified desc
		limit %s, %s""" % ("','".join(webnotes.get_roles()), 
			webnotes.form_dict['limit_start'], webnotes.form_dict['limit_page_length']), 
			as_dict=1)
def get_defaults_for_match(userd):
    """	if a profile based match condition exists for a user's role 
		and no user property is specified for that match key,
		set default value as user's profile for that match key"""
    user_roles = webnotes.get_roles()
    out = {}

    for role, match in webnotes.conn.sql("""select distinct role, `match`
		from `tabDocPerm` where ifnull(permlevel, 0)=0 and `read`=1 
		and `match` like "%:user" """):
        if role in user_roles and match.split(":")[0] not in userd:
            out[match.split(":")[0]] = webnotes.session.user

    return out
Exemple #16
0
def load_doctypes():
    """load all doctypes and roles"""
    global doctypes, roles
    import webnotes.model.doctype

    roles = webnotes.get_roles()

    for t in tables:
        if t.startswith('`'):
            doctype = t[4:-1]
            if not doctype in webnotes.user.can_get_report:
                webnotes.response['403'] = 1
                raise webnotes.PermissionError
            doctypes[doctype] = webnotes.model.doctype.get(doctype)
Exemple #17
0
def get_defaults_for_match(userd):
	"""	if a profile based match condition exists for a user's role 
		and no user property is specified for that match key,
		set default value as user's profile for that match key"""
	user_roles = webnotes.get_roles()
	out = {}
	
	for role, match in webnotes.conn.sql("""select distinct role, `match`
		from `tabDocPerm` where ifnull(permlevel, 0)=0 and `read`=1 
		and `match` like "%:user" """):
			if role in user_roles and match.split(":")[0] not in userd:
				out[match.split(":")[0]] = webnotes.session.user

	return out
Exemple #18
0
def get_home_page(user=None):
	"""get home page for user"""
	if not user:
		user = '******'
	import webnotes
	hpl = webnotes.conn.sql("""select home_page 
		from `tabDefault Home Page` 
		where parent='Control Panel' 
		and role in ('%s') order by idx asc limit 1""" % "', '".join(webnotes.get_roles(user)))
		
	if hpl:
		return hpl[0][0]
	else:
		return webnotes.conn.get_value('Control Panel',None,'home_page') or 'Login Page'	
def load_doctypes():
	"""load all doctypes and roles"""
	global doctypes, roles
	import webnotes.model.doctype

	roles = webnotes.get_roles()
		
	for t in tables:
		if t.startswith('`'):
			doctype = t[4:-1]
			if not doctype in webnotes.user.can_get_report:
				webnotes.response['403'] = 1
				raise webnotes.PermissionError
			doctypes[doctype] = webnotes.model.doctype.get(doctype)
Exemple #20
0
def load_doctypes():
	"""load all doctypes and roles"""
	import webnotes.model.doctype

	webnotes.local.reportview_roles = webnotes.get_roles()
	
	if not getattr(webnotes.local, "reportview_doctypes", None):
		webnotes.local.reportview_doctypes = {}

	for t in webnotes.local.reportview_tables:
		if t.startswith('`'):
			doctype = t[4:-1]
			if not webnotes.has_permission(doctype):
				raise webnotes.PermissionError, doctype
			webnotes.local.reportview_doctypes[doctype] = webnotes.model.doctype.get(doctype)
def can_restrict(doctype, docname=None):
	# System Manager can always restrict
	if "System Manager" in webnotes.get_roles():
		return True
	meta = webnotes.get_doctype(doctype)
	
	# check if current user has read permission for docname
	if docname and not has_permission(doctype, "read", docname):
		return False

	# check if current user has a role with restrict permission
	if not has_restrict_permission(meta):
		return False
	
	return True
Exemple #22
0
def load_doctypes():
	"""load all doctypes and roles"""
	import webnotes.model.doctype

	webnotes.local.reportview_roles = webnotes.get_roles()
	
	if not getattr(webnotes.local, "reportview_doctypes", None):
		webnotes.local.reportview_doctypes = {}

	for t in webnotes.local.reportview_tables:
		if t.startswith('`'):
			doctype = t[4:-1]
			if not webnotes.has_permission(doctype):
				raise webnotes.PermissionError, doctype
			webnotes.local.reportview_doctypes[doctype] = webnotes.model.doctype.get(doctype)
Exemple #23
0
def get_home_page(user=None):
    """get home page for user"""
    if not user:
        user = '******'
    import webnotes
    hpl = webnotes.conn.sql("""select home_page 
		from `tabDefault Home Page` 
		where parent='Control Panel' 
		and role in ('%s') order by idx asc limit 1""" %
                            "', '".join(webnotes.get_roles(user)))

    if hpl:
        return hpl[0][0]
    else:
        return webnotes.conn.get_value('Control Panel', None,
                                       'home_page') or 'Login Page'
Exemple #24
0
def build_match_conditions(doctype, fields=None, as_condition=True):
	"""add match conditions if applicable"""
	global tables, roles
	
	match_filters = {}
	match_conditions = []
	match = True
	
	if not tables or not doctypes:
		tables = get_tables(doctype, fields)
		load_doctypes()

	if not roles:
		roles = webnotes.get_roles()

	for d in doctypes[doctype]:
		if d.doctype == 'DocPerm' and d.parent == doctype:
			if d.role in roles:
				if d.match: # role applicable
					if ':' in d.match:
						document_key, default_key = d.match.split(":")
					else:
						default_key = document_key = d.match
					for v in webnotes.defaults.get_user_default_as_list(default_key, \
						webnotes.session.user) or ["** No Match **"]:
						if as_condition:
							match_conditions.append('`tab%s`.%s="%s"' % (doctype,
								document_key, v))
						else:
							if v:
								match_filters.setdefault(document_key, [])
								if v not in match_filters[document_key]:
									match_filters[document_key].append(v)
							
				elif d.read == 1 and d.permlevel == 0:
					# don't restrict if another read permission at level 0 
					# exists without a match restriction
					match = False
					match_filters = {}
		
	if as_condition:
		if match_conditions and match:
			return '('+ ' or '.join(match_conditions) +')'
		else:
			return ""
	else:
		return match_filters
Exemple #25
0
def has_permission(doc):
	if doc.event_type=="Public" or doc.owner==webnotes.session.user:
		return True
		
	# need full doclist to check roles and users
	bean = webnotes.bean("Event", doc.name)
		
	if len(bean.doclist)==1:
		return False
	
	if bean.doclist.get({"doctype":"Event User", "person":webnotes.session.user}):
		return True
		
	if bean.doclist.get({"doctype":"Event Role", "role":("in", webnotes.get_roles())}):
		return True
		
	return False
Exemple #26
0
def build_match_conditions(doctype, fields=None, as_condition=True, match_filters=None):
	"""add match conditions if applicable"""
	global tables, roles
	
	if not match_filters: match_filters = {}
	match_conditions = []
	match = True
	
	if not tables or not doctypes:
		tables = get_tables(doctype, fields)
		load_doctypes()

	if not roles:
		roles = webnotes.get_roles()

	for d in doctypes[doctype]:
		if d.doctype == 'DocPerm' and d.parent == doctype:
			if d.role in roles:
				if d.match: # role applicable
					if ':' in d.match:
						document_key, default_key = d.match.split(":")
					else:
						default_key = document_key = d.match
					for v in webnotes.defaults.get_user_default_as_list(default_key, \
						webnotes.session.user) or ["** No Match **"]:
						if as_condition:
							match_conditions.append('`tab%s`.%s="%s"' % (doctype,
								document_key, v))
						else:
							if v:
								match_filters.setdefault(document_key, [])
								if v not in match_filters[document_key]:
									match_filters[document_key].append(v)
							
				elif d.read == 1 and d.permlevel == 0:
					# don't restrict if another read permission at level 0 
					# exists without a match restriction
					match = False
		
	if as_condition:
		if match_conditions and match:
			return '('+ ' or '.join(match_conditions) +')'
		else:
			return ""
	else:
		return match_filters
def get_user_perms(meta, user=None):
	cache_key = (meta[0].name, user)
	if not webnotes.local.user_perms.get(cache_key):
		perms = webnotes._dict()
		user_roles = webnotes.get_roles(user)
	
		for p in meta.get({"doctype": "DocPerm"}):
			if cint(p.permlevel)==0 and (p.role=="All" or p.role in user_roles):
				for ptype in rights:
					if ptype == "restricted":
						perms[ptype] = perms.get(ptype, 1) and cint(p.get(ptype))
					else:
						perms[ptype] = perms.get(ptype, 0) or cint(p.get(ptype))
					
		webnotes.local.user_perms[cache_key] = perms

	return webnotes.local.user_perms[cache_key]
Exemple #28
0
def has_permission(page_doclist):
	if webnotes.user.name == "Administrator" or "System Manager" in webnotes.user.get_roles():
		return True
		
	page_roles = [d.role for d in page_doclist if d.fields.get("doctype")=="Page Role"]
	if page_roles:
		if webnotes.session.user == "Guest" and "Guest" not in page_roles:
			return False
		elif not set(page_roles).intersection(set(webnotes.get_roles())):
			# check if roles match
			return False
		
	if not webnotes.has_permission("Page", ptype="read", refdoc=page_doclist[0].name):
		# check if there are any restrictions
		return False
	else:
		# hack for home pages! if no page roles, allow everyone to see!
		return True
Exemple #29
0
def get_events(start, end):
	events = []
	employee = webnotes.conn.get_default("employee", webnotes.session.user)
	company = webnotes.conn.get_default("company", webnotes.session.user)
	
	from webnotes.widgets.reportview import build_match_conditions
	match_conditions = build_match_conditions("Leave Application")
	
	# show department leaves for employee
	if "Employee" in webnotes.get_roles():
		add_department_leaves(events, start, end, employee, company)

	add_leaves(events, start, end, employee, company, match_conditions)
	
	add_block_dates(events, start, end, employee, company)
	add_holidays(events, start, end, employee, company)
	
	return events
def get_events(start, end):
	events = []
	employee = webnotes.conn.get_default("employee", webnotes.session.user)
	company = webnotes.conn.get_default("company", webnotes.session.user)
	
	from webnotes.widgets.reportview import build_match_conditions
	match_conditions = build_match_conditions("Leave Application")
	
	# show department leaves for employee
	if "Employee" in webnotes.get_roles():
		add_department_leaves(events, start, end, employee, company)

	add_leaves(events, start, end, employee, company, match_conditions)
	
	add_block_dates(events, start, end, employee, company)
	add_holidays(events, start, end, employee, company)
	
	return events
Exemple #31
0
def get_events(start, end):
	roles = webnotes.get_roles()
	events = webnotes.conn.sql("""select name, subject, 
		starts_on, ends_on, owner, all_day, event_type
		from tabEvent where (
			(starts_on between %s and %s)
			or (ends_on between %s and %s)
		)
		and (event_type='Public' or owner=%s
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and person=%s)
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%s')))
		order by starts_on""" % ('%s', '%s', '%s', '%s', '%s', '%s', 
			"', '".join(roles)), (start, end, start, end,
			webnotes.session.user, webnotes.session.user), as_dict=1)
			
	return events
Exemple #32
0
def get_events(start, end):
    roles = webnotes.get_roles()
    events = webnotes.conn.sql(
        """select name, subject, 
		starts_on, ends_on, owner, all_day, event_type
		from tabEvent where (
			(starts_on between %s and %s)
			or (ends_on between %s and %s)
		)
		and (event_type='Public' or owner=%s
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and person=%s)
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%s')))
		order by starts_on""" %
        ('%s', '%s', '%s', '%s', '%s', '%s', "', '".join(roles)),
        (start, end, start, end, webnotes.session.user, webnotes.session.user),
        as_dict=1)

    return events
Exemple #33
0
	def update_roles(self):
		"""update roles if set"""		

		if self.temp.get('roles'):
			from webnotes.model.doc import Document

			# remove roles
			webnotes.conn.sql("""delete from tabUserRole where parent='%s' 
				and role in ('%s')""" % (self.doc.name,
				"','".join(self.temp['roles']['unset_roles'])))

			if "System Manager" in self.temp['roles']['unset_roles']:
				self.check_one_system_manager()

			# add roles
			user_roles = webnotes.get_roles(self.doc.name)
			for role in self.temp['roles']['set_roles']:
				if not role in user_roles:
					d = Document('UserRole')
					d.role = role
					d.parenttype = 'Profile'
					d.parentfield = 'user_roles'
					d.parent = self.doc.name
					d.save()
Exemple #34
0
	def _load_roles(self):
		self.roles = webnotes.get_roles()
		return self.roles
Exemple #35
0
def get_user_roles(arg=None):
	"""get roles for a user"""
	return webnotes.get_roles(webnotes.form_dict['uid'])
def get_doctypes():
	if "System Manager" in webnotes.get_roles():
	    return [r[0] for r in webnotes.conn.sql("""select name from `tabDocType` 
			where allow_import = 1""")]
	else:
		return webnotes.user._get("can_import")
Exemple #37
0
	def _load_roles(self):
		self.roles = webnotes.get_roles()
		return self.roles
Exemple #38
0
	def get_permissions(self, user=None):
		user_roles = webnotes.get_roles(user)
		return [p for p in self.get({"doctype": "DocPerm"})
				if cint(p.permlevel)==0 and (p.role=="All" or p.role in user_roles)]
Exemple #39
0
def verify_export_allowed():
	"""throw exception if user is not allowed to export"""
	global roles
	roles = webnotes.get_roles()
	if not ('Administrator' in roles or 'System Manager' in roles or 'Report Manager' in roles):
		raise webnotes.PermissionError
Exemple #40
0
def get_permission_query_conditions():
	if "System Manager" in webnotes.get_roles():
		return None
	else:
		return """(tabToDo.owner = '{user}' or tabToDo.assigned_by = '{user}')""".format(user=webnotes.session.user)
Exemple #41
0
def has_permission(doc):
	if "System Manager" in webnotes.get_roles():
		return True
	else:
		return doc.owner==webnotes.session.user or doc.assigned_by==webnotes.session.user
		
Exemple #42
0
def add_allowed_pages(bootinfo):
    bootinfo.page_info = dict(
        webnotes.conn.sql(
            """select distinct parent, modified from `tabPage Role`
		where role in ('%s')""" % "', '".join(webnotes.get_roles())))
Exemple #43
0
def get_events(start, end, user=None, for_reminder=False):
	if not user:
		user = webnotes.session.user
	roles = webnotes.get_roles(user)
	events = webnotes.conn.sql("""select name, subject, description,
		starts_on, ends_on, owner, all_day, event_type, repeat_this_event, repeat_on,
		monday, tuesday, wednesday, thursday, friday, saturday, sunday
		from tabEvent where ((
			(date(starts_on) between date('%(start)s') and date('%(end)s'))
			or (date(ends_on) between date('%(start)s') and date('%(end)s'))
			or (date(starts_on) <= date('%(start)s') and date(ends_on) >= date('%(end)s'))
		) or (
			date(starts_on) <= date('%(start)s') and ifnull(repeat_this_event,0)=1 and
			ifnull(repeat_till, "3000-01-01") > date('%(start)s')
		))
		%(reminder_condition)s
		and (event_type='Public' or owner='%(user)s'
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and person='%(user)s')
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%(roles)s')))
		order by starts_on""" % {
			"start": start,
			"end": end,
			"reminder_condition": "and ifnull(send_reminder,0)=1" if for_reminder else "",
			"user": user,
			"roles": "', '".join(roles)
		}, as_dict=1)
			
	# process recurring events
	start = start.split(" ")[0]
	end = end.split(" ")[0]
	add_events = []
	remove_events = []
	
	def add_event(e, date):
		new_event = e.copy()
		new_event.starts_on = date + " " + e.starts_on.split(" ")[1]
		if e.ends_on:
			new_event.ends_on = date + " " + e.ends_on.split(" ")[1]
		add_events.append(new_event)
	
	for e in events:
		if e.repeat_this_event:
			event_start, time_str = e.starts_on.split(" ")
			if e.repeat_on=="Every Year":
				start_year = cint(start.split("-")[0])
				end_year = cint(end.split("-")[0])
				event_start = "-".join(event_start.split("-")[1:])
				
				# repeat for all years in period
				for year in range(start_year, end_year+1):
					date = str(year) + "-" + event_start
					if date >= start and date <= end:
						add_event(e, date)
						
				remove_events.append(e)

			if e.repeat_on=="Every Month":
				date = start.split("-")[0] + "-" + start.split("-")[1] + "-" + event_start.split("-")[2]
				
				# last day of month issue, start from prev month!
				try:
					getdate(date)
				except ValueError:
					date = date.split("-")
					date = date[0] + "-" + str(cint(date[1]) - 1) + "-" + date[2]
					
				start_from = date
				for i in xrange(int(date_diff(end, start) / 30) + 3):
					if date >= start and date <= end and date >= event_start:
						add_event(e, date)
					date = add_months(start_from, i+1)

				remove_events.append(e)

			if e.repeat_on=="Every Week":
				weekday = getdate(event_start).weekday()
				# monday is 0
				start_weekday = getdate(start).weekday()
				
				# start from nearest weeday after last monday
				date = add_days(start, weekday - start_weekday)
				
				for cnt in xrange(int(date_diff(end, start) / 7) + 3):
					if date >= start and date <= end and date >= event_start:
						add_event(e, date)

					date = add_days(date, 7)
				
				remove_events.append(e)

			if e.repeat_on=="Every Day":				
				for cnt in xrange(date_diff(end, start) + 1):
					date = add_days(start, cnt)
					if date >= event_start and date <= end \
						and e[weekdays[getdate(date).weekday()]]:
						add_event(e, date)
				remove_events.append(e)

	for e in remove_events:
		events.remove(e)
		
	events = events + add_events
	
	for e in events:
		# remove weekday properties (to reduce message size)
		for w in weekdays:
			del e[w]
			
	return events
Exemple #44
0
def get_events(start, end, user=None, for_reminder=False):
    if not user:
        user = webnotes.session.user
    roles = webnotes.get_roles(user)
    events = webnotes.conn.sql("""select name, subject, description,
		starts_on, ends_on, owner, all_day, event_type, repeat_this_event, repeat_on,
		monday, tuesday, wednesday, thursday, friday, saturday, sunday, patient, service
		from tabEvent where ((
			(date(starts_on) between date('%(start)s') and date('%(end)s'))
			or (date(ends_on) between date('%(start)s') and date('%(end)s'))
			or (date(starts_on) <= date('%(start)s') and date(ends_on) >= date('%(end)s'))
		) or (
			date(starts_on) <= date('%(start)s') and ifnull(repeat_this_event,0)=1 and
			ifnull(repeat_till, "3000-01-01") > date('%(start)s')
		))
		%(reminder_condition)s
		and (event_type='Public' or owner='%(user)s'
		or exists(select * from `tabEvent User` where 
			`tabEvent User`.parent=tabEvent.name and person='%(user)s')
		or exists(select * from `tabEvent Role` where 
			`tabEvent Role`.parent=tabEvent.name 
			and `tabEvent Role`.role in ('%(roles)s')))
		order by starts_on""" % {
        "start":
        start,
        "end":
        end,
        "reminder_condition":
        "and ifnull(send_reminder,0)=1" if for_reminder else "",
        "user":
        user,
        "roles":
        "', '".join(roles)
    },
                               as_dict=1)

    # process recurring events
    start = start.split(" ")[0]
    end = end.split(" ")[0]
    add_events = []
    remove_events = []

    def add_event(e, date):
        new_event = e.copy()
        new_event.starts_on = date + " " + e.starts_on.split(" ")[1]
        if e.ends_on:
            new_event.ends_on = date + " " + e.ends_on.split(" ")[1]
        add_events.append(new_event)

    for e in events:
        if e.repeat_this_event:
            event_start, time_str = e.starts_on.split(" ")
            if e.repeat_on == "Every Year":
                start_year = cint(start.split("-")[0])
                end_year = cint(end.split("-")[0])
                event_start = "-".join(event_start.split("-")[1:])

                # repeat for all years in period
                for year in range(start_year, end_year + 1):
                    date = str(year) + "-" + event_start
                    if date >= start and date <= end:
                        add_event(e, date)

                remove_events.append(e)

            if e.repeat_on == "Every Month":
                date = start.split("-")[0] + "-" + start.split(
                    "-")[1] + "-" + event_start.split("-")[2]

                # last day of month issue, start from prev month!
                try:
                    getdate(date)
                except ValueError:
                    date = date.split("-")
                    date = date[0] + "-" + str(cint(date[1]) -
                                               1) + "-" + date[2]

                start_from = date
                for i in xrange(int(date_diff(end, start) / 30) + 3):
                    if date >= start and date <= end and date >= event_start:
                        add_event(e, date)
                    date = add_months(start_from, i + 1)

                remove_events.append(e)

            if e.repeat_on == "Every Week":
                weekday = getdate(event_start).weekday()
                # monday is 0
                start_weekday = getdate(start).weekday()

                # start from nearest weeday after last monday
                date = add_days(start, weekday - start_weekday)

                for cnt in xrange(int(date_diff(end, start) / 7) + 3):
                    if date >= start and date <= end and date >= event_start:
                        add_event(e, date)

                    date = add_days(date, 7)

                remove_events.append(e)

            if e.repeat_on == "Every Day":
                for cnt in xrange(date_diff(end, start) + 1):
                    date = add_days(start, cnt)
                    if date >= event_start and date <= end \
                     and e[weekdays[getdate(date).weekday()]]:
                        add_event(e, date)
                remove_events.append(e)

    for e in remove_events:
        events.remove(e)

    events = events + add_events

    for e in events:
        # remove weekday properties (to reduce message size)
        for w in weekdays:
            del e[w]

    return events
	def get_roles(self):
		"""get list of roles"""
		if not self.roles:
			self.roles = webnotes.get_roles()
		return self.roles
Exemple #46
0
def get_user_roles(arg=None):
    """get roles for a user"""
    return webnotes.get_roles(webnotes.form_dict['uid'])
Exemple #47
0
 def get_roles(self):
     """get list of roles"""
     if not self.roles:
         self.roles = webnotes.get_roles(self.name)
     return self.roles