def reject_registration(reg_id): """Route for a leader to reject a user participation to the event. :param int reg_id: Primary key of the registration. """ registration = Registration.query.filter_by(id=reg_id).first() if registration is None: flash("Inscription inexistante", "error") return redirect(url_for("event.index")) if not registration.event.has_edit_rights(current_user): flash("Non autorisé", "error") return redirect(url_for("event.index")) registration.status = RegistrationStatus.Rejected db.session.add(registration) db.session.commit() # Send notification e-mail to user send_reject_subscription_notification(current_user.full_name(), registration.event, registration.user.mail) return redirect(url_for("event.view_event", event_id=registration.event_id))
def process_record(self, message=None): """ Set processed field of the task record to True, so the task will be moved to the task ready to be executed. Based on action property set the accepted property and comment value and execute correspondent RequestLog method. Commit changes via self.commit() :return: Object. Pending object """ record = self.verify() record.processed = True record.processed_ts = dt.now() record.accepted_ts = dt.now() record.accepted = False record.author = current_user.full_name() debug("Action performed on project creation request: %s" % self.action) if self.action is "ignore": record.status = "ignore" self.result = RequestLog(record).ignore() elif self.action is "reject": record.status = "reject" self.result = RequestLog(record).reject(message) else: raise ValueError("Action %s is not supported" % self.action) if message: self.pending.comment = message return self.commit()
def delete_event(event_id): event = Event.query.get(event_id) if not (event and event.has_delete_rights(current_user)): flash("Non autorisé", "error") return redirect(url_for("event.index")) # Delete registrations, activities and leaders event.leaders.clear() event.activity_types.clear() for registration in event.registrations: if registration.status == RegistrationStatus.Active: user = User.query.filter_by(id=registration.user_id).first() # Send notification e-mail to each registered user send_deleted_event_notification(current_user.full_name(), event, user.mail) event.registrations.clear() db.session.commit() # Delete event itself db.session.delete(event) db.session.commit() # For now don't delete photo... there might # be other events using it flash("Événement supprimé", "success") return redirect(url_for("event.index"))
def handle_message(data): message = data['message'] room = data['room'] emit('text', { 'username': current_user.username, 'user_full_name': current_user.full_name(), 'message': message }, room=room)
def thesis_page(thesis_code): post = Thesis.query.get_or_404(thesis_code) new_log = UserLogs(id_number=current_user.id_number, thesis_code=thesis_code, name=current_user.full_name(), date_time=datetime.datetime.now(), user_level=current_user.user_level) db.session.add(new_log) db.session.commit() return render_template('thesis_page.html', title=post.title, post=post)
def profile_view(): form = MemberForm(obj=current_user) form.affiliation.data = current_user.affiliation.value form.email.description = "We do not allow you to change your email once you've created your account. If you really wish to change the email, please email [email protected]" try: if form.validate_on_submit(): filtered = { k: v for k, v in form.data.items() if v != "" and str(v) != "None" and k != "submit" and k != "csrf_token" and k != "affiliation" and current_user.__dict__[k] != v } filtered = {} invalid_items = ["submit", "csrf_token", "affiliation"] for k, v in form.data.items(): if k in invalid_items: continue # existing value e_v = current_user.__dict__[k] if type(e_v) is bool: if bool(v) != e_v: filtered[k] = v elif type(e_v) is int: if int(v) != e_v: filtered[k] = v elif type(e_v) is str: if v != e_v: filtered[k] = v else: # If we are here, then we're working with the arrays of majors/minors # which we currently are not allowing users to change continue for key, value in filtered.items(): setattr(current_user, key, value) db.session.commit() flash( message='User "{}" successfully updated'.format(current_user.full_name()), category='info', ) except Exception as e: raise e return render_template("profile.html", form=form)
def update_attendance(event_id): """Route to update attendance list. :param int event_id: Primary key of the event to update. """ event = Event.query.get(event_id) if event is None: raise Exception("Unknown Event") if not event.has_edit_rights(current_user): flash("Accès restreint, rôle insuffisant.", "error") return redirect(url_for("event.index")) for registration in event.registrations: field_name = f"reg_{registration.id}" if field_name in request.form: try: value = request.form.get(field_name, type=int) new_status = RegistrationStatus(value) except ValueError: continue if new_status == registration.status: continue if new_status not in registration.valid_transitions(): flash( f"Transition impossible de {registration.status.display_name()} vers {new_status.display_name} pour {registration.user.full_name()}.", "warning", ) continue if new_status == RegistrationStatus.ToBeDeleted: db.session.delete(registration) else: registration.status = new_status db.session.add(registration) if registration.status == RegistrationStatus.Rejected: # Send notification e-mail to user send_reject_subscription_notification( current_user.full_name(), registration.event, registration.user.mail, ) db.session.commit() return redirect( url_for("event.view_event", event_id=event_id) + "#attendancelistform" )
def pasien(id): if Pasien.query.filter_by(user=id).count() != 0: """data diagnosa.""" trainings = Training.query.all() pilihans = Pilihan.query.all() labels = Label.query.all() diagnosa = (Pasien.query.filter_by(user=id).join( User, Pasien.user == User.id).add_columns( Pasien.id, User.first_name.label("first_name"), User.last_name.label("last_name"), Pasien.k1, Pasien.k2, Pasien.k3, Pasien.k4, Pasien.k5, Pasien.k6, Pasien.k7, Pasien.user, ).first()) k1 = getAtribut("k1") k2 = getAtribut("k2") k3 = getAtribut("k3") k4 = getAtribut("k4") k5 = getAtribut("k5") k6 = getAtribut("k6") k7 = getAtribut("k7") c = getC() lh = likehood(diagnosa.id) hasildiagnosa = Diagnosa.query.filter_by(user=diagnosa.user).first() return render_template( "diagnosa/pasien.html", trainings=trainings, pilihans=pilihans, labels=labels, diagnosa=diagnosa, k1=k1, k2=k2, k3=k3, k4=k4, k5=k5, k6=k6, k7=k7, c=c, lh=lh, hasildiagnosa=hasildiagnosa, ) else: flash("Data pasien {} harus diisi".format(current_user.full_name()), "warning") return redirect(url_for("pasien.input"))
def reg_message(txt, selector): full_name = current_user.full_name() if selector == "accept": msg = "Project creation request accepted by %s" % full_name elif selector == "approve": msg = "Project software requirements approved by %s" % full_name elif selector == "reject": msg = "Project creation request rejected by %s\nReason:\n" % full_name elif selector == "ignore": msg = "Project creation request ignored by %s" % full_name else: raise ValueError("Selector %s does not supported" % selector) if txt: return "%s\n%s" % (txt, msg) return msg
def new_candidate(): """Create a new candiate.""" form = NewCandidateForm() if form.validate_on_submit(): demographic = Demographic( race=form.demographic.race.data, gender=form.demographic.gender.data, age=form.demographic.age.data, sexual_orientation=form.demographic.sexual_orientation.data, soc_class=form.demographic.soc_class.data ) candidate = Candidate( first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data, phone_number=form.phone_number.data, term=form.term.data, source=form.source.data, staff_contact=form.staff_contact.data, notes=form.notes.data, demographic=demographic, demographic_id=demographic.id, status=Status.PENDING, amount_donated=0 ) db.session.add(demographic) db.session.add(candidate) db.session.commit() admins = [] for u in User.query.all(): if u.is_admin(): admins.append(u) # Notify admins via email for a in admins: get_queue().enqueue( send_email, recipient=a.email, subject='New Giving Project Candidate', template='admin/email/new_candidate', user=a, candidate=candidate, add_method='Added by {}'.format(current_user.full_name())) flash('Candidate {} successfully created'.format(candidate.first_name), 'form-success') return render_template('admin/new_candidate.html', form=form)
def web_project_index(): def set_users_len(x): x.users_length = len(x.users) return x projects = Project.query.filter_by(responsible=current_user).all() if not projects: flash("No projects associated with %s found" % current_user.full_name()) return render_template("project.html", data={}) list(map(lambda x: clean_activity(x.get_name()), projects)) get_limbo_users(projects) list(map(lambda x: is_project_extendable(x), projects)) list(map(lambda x: is_project_renewable(x), projects)) list(map(lambda x: set_users_len(x), projects)) return render_template("project.html", data={"projects": projects})
def user_index(): start = dt.now(timezone.utc) for project in current_user.project: if project.resources.created < start: start = project.resources.created begin = start.strftime("%m/%d/%y-%H:%M") finish = dt.now().strftime("%m/%d/%y-%H:%M") user = { "full": current_user.full_name(), "name": current_user.name, "surname": current_user.surname, "email": current_user.email, "uid": current_user.uid, "login": current_user.login } try: jobs = get_jobs(begin, finish) except ValueError as err: jobs = None flash(str(err)) try: scratch = get_scratch() except ValueError as err: scratch = None flash(str(err)) if current_user.project: projects = projects_consumption(current_user.project) else: projects = None flash("No projects found for user '%s'" % current_user.full()) return render_template("user.html", data={ "user": user, "jobs": jobs, "scratch": scratch, "projects": projects })
def manage_event(event_id=None): """Event creation and modification page. If an ``event_id`` is given, it is a modification of an existing event. :param int event_id: Primary key of the event to manage. """ if not current_user.can_create_events(): flash("Accès restreint, rôle insuffisant.", "error") return redirect(url_for("event.index")) event = Event.query.get(event_id) if event_id is not None else Event() if event is not None and not event.has_edit_rights(current_user): flash("Accès restreint.", "error") return redirect(url_for("event.index")) current_status = event.status form = EventForm(CombinedMultiDict((request.files, request.form))) if not form.is_submitted(): if event_id is None: form = EventForm() form.set_default_values() else: form = EventForm(obj=event) form.setup_leader_actions() return render_template("editevent.html", event=event, form=form) # Get current activites from form tentative_activities = form.current_activities() requires_activity = form.current_event_type().requires_activity if requires_activity and len(tentative_activities) == 0: flash( f"Un événement de type {form.current_event_type().name} requiert au moins une activité", "error", ) return render_template("editevent.html", event=event, form=form) # Fetch existing readers leaders minus removed ones previous_leaders = [] tentative_leaders = [] has_removed_leaders = False for action in form.leader_actions: leader_id = int(action.data["leader_id"]) leader = User.query.get(leader_id) if leader is None or not leader.can_create_events(): flash("Encadrant invalide") continue previous_leaders.append(leader) if action.data["delete"]: has_removed_leaders = True else: tentative_leaders.append(leader) # Set current leaders from submitted form form.set_current_leaders(previous_leaders) form.update_choices() # Update activities only # Do not process the remainder of the form if int(form.update_activity.data): # Check that the set of leaders is valid for current activities validate_event_leaders( tentative_activities, previous_leaders, form.multi_activities_mode.data ) return render_template("editevent.html", event=event, form=form) # Add new leader new_leader_id = int(form.add_leader.data) if new_leader_id > 0: leader = User.query.get(new_leader_id) if leader is None or not leader.can_create_events(): flash("Encadrant invalide") else: tentative_leaders.append(leader) # Check that the main leader still exists try: main_leader_id = int(form.main_leader_id.data) except (TypeError, ValueError): main_leader_id = None if not any(l.id == main_leader_id for l in tentative_leaders): flash("Un encadrant responsable doit être défini") return render_template("editevent.html", event=event, form=form) # Update leaders only # Do not process the remainder of the form if has_removed_leaders or int(form.update_leaders.data): # Check that the set of leaders is valid for current activities if validate_event_leaders( tentative_activities, tentative_leaders, form.multi_activities_mode.data, ): form.set_current_leaders(tentative_leaders) form.update_choices() form.setup_leader_actions() return render_template("editevent.html", event=event, form=form) # The 'Update event' button has been clicked # Populate object, run custom validators if not form.validate(): return render_template("editevent.html", event=event, form=form) # Do not populate the real event as errors may still be raised and we do not want # SQLAlchemy to flush the temp data trial_event = Event() form.populate_obj(trial_event) if not validate_dates_and_slots(trial_event): return render_template("editevent.html", event=event, form=form) has_new_activity = any(a not in event.activity_types for a in tentative_activities) tentative_leaders_set = set(tentative_leaders) existing_leaders_set = set(event.leaders) has_changed_leaders = any(tentative_leaders_set ^ existing_leaders_set) # We have added a new activity or added/removed leaders # Check that the leaders are still valid if has_new_activity or has_changed_leaders: if not validate_event_leaders( tentative_activities, tentative_leaders, form.multi_activities_mode.data, ): return render_template("editevent.html", event=event, form=form) # If event has not been created yet use current activities to check rights if event_id is None: event.activity_types = tentative_activities # Check that we have not removed leaders that we don't have the right to removed_leaders = existing_leaders_set - tentative_leaders_set for removed_leader in removed_leaders: if not event.can_remove_leader(current_user, removed_leader): flash( f"Impossible de supprimer l'encadrant: {removed_leader.full_name()}", "error", ) return render_template("editevent.html", event=event, form=form) # All good! Apply changes form.populate_obj(event) event.activity_types = tentative_activities event.leaders = tentative_leaders # Remove registration associated to leaders (#327) if has_changed_leaders: for leader in event.leaders: leader_registrations = event.existing_registrations(leader) if any(leader_registrations): flash( f"{leader.full_name()} a été désinscrit(e) de l'événement car il/elle a été ajouté(e) comme encadrant(e)." ) for registration in leader_registrations: event.registrations.remove(registration) event.set_rendered_description(event.description) # Update tags (brute option: purge all and create new) event.tag_refs.clear() for tag in form.tag_list.data: event.tag_refs.append(EventTag(tag)) # We have to save new event before add the photo, or id is not defined db.session.add(event) db.session.commit() # If no photo is sent, we don't do anything, especially if a photo is # already existing if form.photo_file.data is not None: event.save_photo(form.photo_file.data) db.session.add(event) db.session.commit() elif form.duplicate_photo.data != "": duplicated_event = Event.query.get(form.duplicate_photo.data) if duplicated_event != None: event.photo = duplicated_event.photo db.session.add(event) db.session.commit() if event_id is None: # This is a new event, send notification to supervisor send_new_event_notification(event) else: # This is a modified event and the status has changed from Confirmed to Cancelled. # then, a notification is sent to supervisors if ( current_status == EventStatus.Confirmed and event.status == EventStatus.Cancelled ): send_cancelled_event_notification(current_user.full_name(), event) return redirect(url_for("event.view_event", event_id=event.id))
def on_join(data): room = data['room'] join_room(room) emit('status', '{} has joined the room.'.format(current_user.full_name()), room=room)
def on_leave(data): room = data['room'] leave_room(room) emit('status', '{} has left the room.'.format(current_user.full_name()), room=room)