def populate_list(self): self._list.value = AccessRequest.objects.filter( requested_by=PyFormsMiddleware.user() ) self._accesses.value = ResourceAccess.objects.filter( user=PyFormsMiddleware.user() )
def create_model_formfields(self): super().create_model_formfields() obj = self.model_object user = PyFormsMiddleware.user() person = user.person_user.first() self._costcenter = ControlAutoComplete( 'Cost center', queryset=CostCenter.objects.active().by_person(person), changed_event=self.load_finance_projects, default=obj.expensecode.project.costcenter.pk if obj and obj.expensecode else None) self._financeprj = ControlAutoComplete( 'Finance project', queryset=Project.objects.all(), enabled=False, changed_event=self.load_expense_codes, default=obj.expensecode.project.pk if obj and obj.expensecode else None) if obj and obj.expensecode: self.load_expense_codes() if person is None: self.warning('Sorry you require a person associated to your user.') return
def __revoke_evt(self, popup, button): if button == 'Confirm': access = self.model_object access.revoke(PyFormsMiddleware.user()) self.end_date.value = access.end_date self._revokebtn.hide() popup.close()
def TITLE(self): user = PyFormsMiddleware.user() n_msgs = Notification.objects.filter(user=user, read_on=None).count() if n_msgs == 0: return """<i class="bell icon"></i>""" else: return """<i class="bell red icon"></i> {0}""".format(n_msgs)
def __mark_as_favorite(self): user = PyFormsMiddleware.user() favorite = None try: favorite = Favorite.objects.get(user=user, funding=self.obj) if favorite.active: self._favoritebtn.label = self.ADD_FAVORITE_LABEL self._favoritebtn.css = 'blue' favorite.active = False favorite.save() else: self._favoritebtn.label = self.REMOVE_FAVORITE_LABEL self._favoritebtn.css = 'primary basic' favorite.active = True favorite.save() except Favorite.DoesNotExist: Favorite(user=user, funding=self.obj, active=True).save() self._favoritebtn.label = self.REMOVE_FAVORITE_LABEL self._favoritebtn.css = 'primary basic' sidemenu_app = PyFormsMiddleware.get_instance('sidemenu-app') sidemenu_app.reload()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.formset = [ "info:Group your notifications by the frequency you want to received them." ] PERIODS = [(n, c) for c, n in NotificationType.PERIODS] user = PyFormsMiddleware.user() for n in NotificationType.objects.filter( active=True, visible=True).order_by("code"): field_name = "period_{0}".format(n.pk) field = ControlCombo( n.label, items=PERIODS, changed_event=make_lambda_func(self.configure, notification_pk=n.pk), ) try: un = UserNotificationConf.objects.get(notification_type=n, user=user) field.value = un.period except UserNotificationConf.DoesNotExist: field.value = n.period traceback.print_exc() setattr(self, field_name, field) self.formset.append(field_name)
def __add_mytopics(self): user = PyFormsMiddleware.user() profile = Profile.objects.get(user=user) topics = list(self._topics.value) for topic in profile.topics.all(): topics.append(str(topic.pk)) self._topics.value = topics
def __init__(self, *args, **kwargs): self.user = PyFormsMiddleware.user() super().__init__(*args, **kwargs) self._list.columns_size = ["60%", "10%", "10%", "10%", "10%"] self._list.columns_align = ["left"] * len(self.LIST_DISPLAY) self._list.columns_align[-2] = "right" self._list.columns_align[-1] = "center"
def __has_permissions(self): """Custom method to check authorizations since PyForms ModelForm only inherits the permissions system for inlines. Once this is fixed, the following methods should be cleaned up. """ user = PyFormsMiddleware.user() return any([ user.is_superuser, settings.PROFILE_HUMAN_RESOURCES in user.groups.all(), ])
def get_readonly(self, default): res = super().get_readonly(default) obj = self.model_object if obj and obj.status in ['rejected', 'approved']: return res + ['status'] if obj and obj.has_approve_permissions(PyFormsMiddleware.user()): return res else: return res + ['status']
def update_object_fields(self, obj): """ Update the created by field. :param Reimbursement obj: :return: Return the updated reimbursement object. """ obj = super().update_object_fields(obj) if obj.pk is None: obj.created_by = PyFormsMiddleware.user() return obj
def __reject_evt(self): req = self.model_object req.comment = self.comment.value req.reject(PyFormsMiddleware.user(), comment=self.comment.value) self._acceptbtn.hide() self._rejectbtn.hide() self._until.hide() self.alert('The access request was rejected!') self.closed_by.show() self.closed_on.show() self.closed_by.value = str(req.closed_by) self.closed_on.value = req.closed_on self.comment.readonly = True
def __accept_evt(self): req = self.model_object req.comment = self.comment.value req.accept(PyFormsMiddleware.user(), until=self._until.value, comment=self.comment.value) self._acceptbtn.hide() self._rejectbtn.hide() self._until.hide() self.success('The access request was accepted successfully.') self.closed_by.show() self.closed_on.show() self.closed_by.value = str(req.closed_by) self.closed_on.value = req.closed_on self.comment.readonly = True
def __init__(self, *args, **kwargs): user = PyFormsMiddleware.user() try: person = Person.objects.get(auth_user=user) except Person.DoesNotExist: person = Person.objects.get(email=user.email) person.auth_user = user person.save() super().__init__(pk=person.pk, *args, **kwargs) membership = GroupMembership.objects.filter(person=person).first() membership_html = ( f'<h3><a>{membership.group}</a> - {membership.position}</h3>' if membership is not None else '') s = (f'<h1>{person.full_name}</h1>' '<address>' f'{membership_html}' '\n' f'<a href="mailto:{person.email}" target="_blank">' f'<i class="envelope icon"></i>{person.email}</a>' '</address>') self._summary = ControlSimpleLabel( default=s, label_visible=False, field_css='fourteen wide', ) if hr_module_installed: self._privateinfo = ControlEmptyWidget( parent=self, name='_privateinfo', default=ProfilePrivateInfoFormWidget( pk=person.get_privateinfo().pk, has_cancel_btn=False, ), ) try: img_url = self.model_object.thumbnail_url( geometry_string='300x300') except AttributeError: img_url = static('square-image.png') self._img = ControlImg('Image', default=img_url, label_visible=False, field_css='three wide')
def configure(self, notification_pk=None): if notification_pk is None: return try: n = NotificationType.objects.get(pk=notification_pk) except NotificationType.DoesNotExist: traceback.print_exc() user = PyFormsMiddleware.user() try: un = UserNotificationConf.objects.get(notification_type=n, user=user) except UserNotificationConf.DoesNotExist: un = UserNotificationConf(notification_type=n, user=user) field = getattr(self, "period_{0}".format(n.pk)) un.period = field.value un.save()
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user = PyFormsMiddleware.user() # Filter Auth Groups to the groups the user is a member of. self.group.queryset = self.group.queryset.order_by('name') if not user.is_superuser: self.group.queryset = self.group.queryset & user.groups.all() if self.group.queryset.count() == 1: self.group.value = self.group.queryset.first().pk if self.object_pk is not None: self._duplicate_btn = ControlButton( 'Duplicate', default=self.__duplicate_btn_evt, label_visible=False, css='basic brown')
def __init__(self, obj_pk): self.obj = FundingOpportunity.objects.get(pk=obj_pk) ModelViewFormWidget.__init__(self, title=self.obj.fundingopportunity_name, pk=obj_pk) if self.fundingopportunity_loideadline.value is None: self.fundingopportunity_loideadline.hide() if self.fundingopportunity_fullproposal.value is None: self.fundingopportunity_fullproposal.hide() user = PyFormsMiddleware.user() self._editbtn = ControlButton('<i class="icon edit" ></i> Edit', label_visible=False) self._editbtn.value = 'window.location = "/app/opportunities-app/#/funding.apps.fundingopportunities.EditFundingApp/?fund_pk={0}";'.format( obj_pk) if not user.groups.filter( name__in=[settings.PERMISSION_EDIT_FUNDING]).exists(): self._editbtn.hide() self._favoritebtn = ControlButton('Favorite') self._favoritebtn.label_visible = False self._favoritebtn.value = self.__mark_as_favorite if Favorite.objects.filter(user=user, funding=self.obj, active=True).exists(): self._favoritebtn.label = self.REMOVE_FAVORITE_LABEL self._favoritebtn.css = 'primary basic' else: self._favoritebtn.label = self.ADD_FAVORITE_LABEL self._favoritebtn.css = 'blue' self._urlbtn = ControlButton("<i class='ui icon external'></i> URL") self._urlbtn.label_visible = False self._urlbtn.css = 'basic blue' if self.obj and self.obj.fundingopportunity_link: self._urlbtn.value = "window.open('{0}', '_blank');".format( self.obj.fundingopportunity_link) else: self._urlbtn.hide()
def __init__(self, *args, **kwargs): self._previous = ControlButton( '<i class="ui icon paper plane outline"></i>Previous status', css="basic gray", visible = False, label_visible=False, default = self.__previous_status_evt ) self._submit = ControlButton( '<i class="ui icon paper plane outline"></i>Submit', css="blue", visible=False, label_visible=False, default = self.__submit_2_pending_evt ) self._print = ControlButton( '<i class="ui icon print"></i>Print', visible=False, css="basic blue", label_visible=False ) self._printed = ControlButton( '<i class="ui icon paper plane outline"></i>Set printed', visible=False, css="blue", label_visible=False, default=self.__set_printed_evt ) self._submit2approve = ControlButton( '<i class="ui icon paper plane outline"></i>Submit to approval', visible=False, css="blue", label_visible=False, default=self.__submit_2_approve_evt ) self._accept = ControlButton( '<i class="ui icon thumbs up"></i>Accept', visible=False, css="green", label_visible=False, default = self.__accept_evt ) self._reject = ControlButton( '<i class="ui icon thumbs down"></i>Reject', visible=False, css="red", label_visible=False, default=self.__reject_evt ) self._close = ControlButton( '<i class="ui icon thumbs up"></i>It was paid', visible=False, css="green basic", default=self.__set_closed_evt ) super().__init__(*args, **kwargs) self.person.enabled = False if self.model_object is None: user = PyFormsMiddleware.user() person = user.person_user.first() if person is not None: self.person.value = person.pk self.iban.value = person.privateinfo.iban else: self.warning( 'You need a Person profile associated to your account to be able to create reimbursements.' ) self.update_fields_visibility()
def has_remove_permissions(self, obj): user = PyFormsMiddleware.user() user_is_hr = settings.PROFILE_HUMAN_RESOURCES in user.groups.all() return user.is_superuser or user_is_hr
def save_event(self, obj, new_object): if new_object: user = PyFormsMiddleware.user() obj.responsible = user.person return super().save_event(obj, new_object)
def has_remove_permissions(self, obj): """Only superusers may delete these objects.""" user = PyFormsMiddleware.user() return user.is_superuser
def save_object(self, obj): obj = super().save_object(obj, user=PyFormsMiddleware.user()) return obj
def render_html(self, register_filter=True): subjects = OpportunitySubject.objects.all().order_by( 'opportunitysubject_name') topics = self._topics.value subjects = self._subjects.value today = timezone.now() if register_filter: reg = UserFilters(user=PyFormsMiddleware.user()) reg.save() reg.topics.add(*list(OpportunityTopic.objects.filter( pk__in=topics))) reg.subjects.add( *list(OpportunitySubject.objects.filter(pk__in=subjects))) funds = FundingOpportunity.objects.filter( Q(fundingopportunity_end__gte=today) | Q(fundingopportunity_loideadline__gte=today)) if len(topics) > 0: funds = funds.filter(topics__in=topics) if len(subjects) > 0: funds = funds.filter(subject__in=subjects) funds = funds.order_by('fundingopportunity_end') user = PyFormsMiddleware.user res = [] for fund in funds: classes = [] #if fund.groups.filter(group=groups).exists(): classes.append('mine') classes.append('subject' + str(fund.subject.pk)) two_weeks_ago = timezone.now() + timedelta(days=-14) if fund.fundingopportunity_createdon >= two_weeks_ago: classes.append('new') date, display_date, enddate = 0, None, None if fund.fundingopportunity_end: date = fund.fundingopportunity_end.isoformat() display_date = fund.fundingopportunity_end.strftime("%d. %B") enddate = fund.fundingopportunity_end.strftime("%d. %B %Y") elif fund.fundingopportunity_loideadline: date = fund.fundingopportunity_loideadline.isoformat() display_date = fund.fundingopportunity_loideadline.strftime( "%d. %B") enddate = fund.fundingopportunity_loideadline.strftime( "%d. %B %Y") obj = { 'classes': ' '.join(classes), "pk": fund.pk, "title": fund.fundingopportunity_name, "date": date, "display_date": display_date, "enddate": enddate, "grantor": fund.financingAgency.grantor_name, "subject": fund.subject.opportunitysubject_name, "body": fund.fundingopportunity_brifdesc, "read_more": fund.fundingopportunity_link, "topics": fund.topics.all(), } #if fund.financingAgency.grantor_icon: obj['photo_url'] = "/media/{0}".format( fund.financingAgency.grantor_icon ) res.append(obj) self._htmlcontrol.value = { 'subjects': subjects, 'nodes': sorted(res, key=lambda x: x['date']) }
def create_newobject(self): obj = super().create_newobject() obj.responsible = PyFormsMiddleware.user() return obj
def update_object_fields(self, obj): obj.createdby = PyFormsMiddleware.user() return super().update_object_fields(obj)
def __duplicate_btn_evt(self): user = PyFormsMiddleware.user() order = self.model_object.duplicate(user) OrderEditFormWidget(pk=order.pk, parent_win=self.parent)
def has_update_permissions(self, obj): user = PyFormsMiddleware.user() qs = self.parent_model.objects.filter(pk=self.parent_pk) return qs.has_update_permissions(user)
def create_newobject(self): obj = super().create_newobject() obj.created_by = PyFormsMiddleware.user() return obj
def validate_object(self, obj): obj.requested_by = PyFormsMiddleware.user() return obj
def reload(self): user = PyFormsMiddleware.user() favorites = Favorite.objects.filter( user=user, active=True).order_by('funding__fundingopportunity_name') self._htmlcontrol.value = {'favorites': favorites}