def add_trains(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.is_admin: return render_template('errors/error-500.html'), 500 form = TrainForm() # regions = get_regions(current_user) if 'create' in request.form: new_dict = request.form.to_dict(flat=True) train = TrainCode.query.filter_by(code=new_dict['code'][0]).filter_by( date=new_dict['date']).first() if train: return route_template('trains/add_train', error_msg=_('Поезд уже зарегистрирован'), form=form, change=None) train = TrainCode(**new_dict) db.session.add(train) db.session.commit() return route_template('trains/add_train', form=form, change=_("Поезд был успешно добавлен"), error_msg=None) else: return route_template('trains/add_train', form=form, change=None, error_msg=None)
def add_user_role(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_access_roles: return render_template('errors/error-500.html'), 500 form = CreateUserRoleForm() form.process() if 'create' in request.form: new_dict = request.form.to_dict(flat=True) del new_dict["csrf_token"] del new_dict["create"] for key in new_dict.keys(): if new_dict[key] == "y": new_dict[key] = True user_role = UserRole.query.filter_by(name=new_dict['name']).first() if user_role: return route_template( 'users/add_role_and_profile', error_msg=_('Роль с таким именем или кодом уже существует'), form=form, change=None) user = UserRole(**new_dict) db.session.add(user) db.session.commit() return redirect("{}?added_user_role".format(url_for('main_blueprint.users'))) else: return route_template( 'users/add_role_and_profile', form=form, change=None, error_msg=None, is_profile=False)
def add_user(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_edit_user: return render_template('errors/error-500.html'), 500 form = CreateUserForm() setup_user_form(form) form.process() if 'create' in request.form: new_dict = request.form.to_dict(flat=True) user = User.query.filter_by(username=new_dict['username']).first() if user: return route_template( 'users/add_user_and_profile', error_msg=_('Имя пользователя уже зарегистрировано'), form=form, change=None) # if "is_admin" in new_dict: # new_dict["is_admin"] = int(new_dict["is_admin"]) == 1 if 'region_id' in new_dict: if new_dict['region_id'] == '-1': new_dict['region_id'] = None user = User(**new_dict) db.session.add(user) db.session.commit() return redirect("{}?added_user".format(url_for('main_blueprint.users'))) else: return route_template( 'users/add_user_and_profile', form=form, change=None, error_msg=None, is_profile=False)
def add_hospital(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_edit_hospital: return render_template('errors/error-500.html'), 500 form = AddHospitalForm() prepare_hospital_form(form, current_user) form.process() if 'create' in request.form: new_dict = request.form.to_dict(flat=True) full_name = new_dict.get('full_name', '') hospital = Hospital.query.filter_by(full_name=full_name).first() if hospital: return route_template( 'hospitals/add_hospital_and_profile', error_msg=_('Стационар с таким именем уже добавлен'), form=form, change=None) if full_name: new_dict['name'] = get_hospital_short_name(full_name) new_dict['full_name'] = full_name hospital = Hospital(**new_dict) hospital.beds_amount = 0 hospital.meds_amount = 0 hospital.tests_amount = 0 hospital.tests_used = 0 db.session.add(hospital) db.session.commit() return redirect("{}?added_hospital".format( url_for('main_blueprint.hospitals'))) else: return render_template('errors/error-500.html'), 500 else: return route_template('hospitals/add_hospital_and_profile', form=form, change=None, error_msg=None, is_profile=False)
def user_roles(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_access_roles: return render_template('errors/error-500.html'), 500 change = None error_msg = None if "added_role" in request.args: change = _("Роль была успешно добавлена") elif "delete_role" in request.args: change = _("Роль была успешно удалена") elif "error" in request.args: error_msg = request.args["error"] q = UserRole.query user_roles_table = UserRolesTableModule(request, q, header_button=[(_("Добавить Роль"), "/users/roles/add") ]) return route_template('users/user_roles', user_roles_table=user_roles_table, constants=c, change=change, error_msg=error_msg)
def user_role_profile(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_access_roles: return render_template('errors/error-500.html'), 500 if "id" in request.args: # if request.args["id"] != str(current_user.id): # if not current_user.user_role.can_access_roles: # return render_template('errors/error-500.html'), 500 try: role_query = UserRole.query.filter_by(id=request.args["id"]) role = role_query.first() except exc.SQLAlchemyError: return render_template('errors/error-400.html'), 400 if not role: return render_template('errors/error-404.html'), 404 else: form = CreateUserRoleForm() change = None error_msg = None if 'update' in request.form: values = request.form.to_dict() values.pop('csrf_token') values.pop('update') for key in values.keys(): if values[key] == "y": values[key] = True role_keys = list(role.__dict__.keys()) role_keys.pop(role_keys.index('_sa_instance_state')) role_keys.pop(role_keys.index('id')) for key in role_keys: if key not in values.keys(): values[key] = False role_query.update(values) db.session.commit() change = _("Данные обновлены") form.name.default = role.name form.value.default = role.value populate_form(form, role.__dict__.copy()) form.process() return route_template('users/add_role_and_profile', form=form, change=change, error_msg=error_msg, role = role, is_profile=True) else: return render_template('errors/error-500.html'), 500
def downloads(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_access_users and not current_user.user_role.can_export_users: return render_template('errors/error-500.html'), 500 change = None error_msg = None if "added_user" in request.args: change = _("Пользователь был успешно добавлен") elif "delete_user" in request.args: change = _("Пользователь был успешно удален") elif "error" in request.args: error_msg = request.args["error"] downloads_search_form = DownloadSearchForm() q = Download.query # if not users_search_form.region_id.choices: # users_search_form.region_id.choices = [(-2, _("Неважно"))] # users_search_form.region_id.choices += get_regions_choices(current_user) # q_patient = db.session.query(Patient.created_by_id, # func.count('*').label('patient_count')) # q_patient = q_patient.group_by(Patient.created_by_id).subquery() # q = db.session.query(User, q_patient.c.patient_count).outerjoin(q_patient, User.id == q_patient.c.created_by_id) # header_buttons = [] # if current_user.user_role.can_access_roles: # header_buttons.append((_("Управление Ролями"), "users/roles")) # if current_user.user_role.can_add_edit_user: # header_buttons.append((_("Добавить Пользователя"), "add_user")) downloads_table = DownloadsTableModule(request, q, downloads_search_form) # user_allowed_exports = False if current_user.user_role.can_export_patients or \ current_user.user_role.can_export_contacted or \ current_user.user_role.can_export_contacted or \ current_user.user_role.can_export_users or \ current_user.user_role.can_access_various_exports: user_allowed_exports = True downloads_search_form.process() # form.process() return route_template('downloads/downloads', downloads_table=downloads_table, user_allowed_exports=user_allowed_exports, downloads_search_form=downloads_search_form, constants=c, change=change, error_msg=error_msg)
def add_train(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_train: return render_template('errors/error-400.html'), 400 form = TrainForm() populate_add_flight_train_form(form) if 'create' in request.form: new_dict = request.form.to_dict(flat=True) train_q = Train.query.filter_by( departure_date=new_dict['departure_date']) train_q = train_q.filter_by(arrival_date=new_dict['arrival_date']) train_q = train_q.filter_by(from_city=new_dict['from_city']) train_q = train_q.filter_by(to_city=new_dict['to_city']) train = train_q.first() if train: return route_template('flights_trains/add_flight_train', error_msg=_('ЖД Рейс уже зарегистрирован'), form=form, change=None, is_trains=True) train = Train(**new_dict) db.session.add(train) db.session.commit() message = _("Рейс успешно добавлен") return_url = "{}?success={}".format(url_for('main_blueprint.trains'), message) return redirect(return_url) else: return route_template('flights_trains/add_flight_train', form=form, change=None, error_msg=None, is_trains=True)
def add_flight(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_air: return render_template('errors/error-400.html'), 400 form = FlightForm() populate_add_flight_train_form(form) if 'create' in request.form: new_dict = request.form.to_dict(flat=True) flight = FlightCode.query.filter_by(code=new_dict['code']).filter_by( date=new_dict['date']).first() if flight: return route_template('flights_trains/add_flight_train', error_msg=_('Рейс уже зарегистрирован'), form=form, change=None, is_trains=False) flight = FlightCode(**new_dict) db.session.add(flight) db.session.commit() message = _("Рейс успешно добавлен") return_url = "{}?success={}".format(url_for('main_blueprint.flights'), message) return redirect(return_url) else: return route_template('flights_trains/add_flight_train', form=form, change=None, error_msg=None, is_trains=False)
def users(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_access_users and not current_user.user_role.can_export_users: return render_template('errors/error-500.html'), 500 form = UserActivityReportForm() regions = get_regions(current_user) if not form.region_id.choices: form.region_id.choices = [ (-1, c.all_regions) ] + [(r.id, r.name) for r in regions] change = None error_msg = None if "added_user" in request.args: change =_("Пользователь был успешно добавлен") elif "delete_user" in request.args: change =_("Пользователь был успешно удален") elif "error" in request.args: error_msg = request.args["error"] users_search_form = UserSearchForm() if not users_search_form.region_id.choices: users_search_form.region_id.choices = [(-2, _("Неважно"))] users_search_form.region_id.choices += get_regions_choices(current_user) q_patient = db.session.query(Patient.created_by_id, func.count('*').label('patient_count')) q_patient = q_patient.group_by(Patient.created_by_id).subquery() q = db.session.query(User, q_patient.c.patient_count).outerjoin(q_patient, User.id == q_patient.c.created_by_id) header_buttons = [] if current_user.user_role.can_access_roles: header_buttons.append((_("Управление Ролями"), "users/roles")) if current_user.user_role.can_add_edit_user: header_buttons.append((_("Добавить Пользователя"), "add_user")) users_table = UserTableModule(request, q, users_search_form, header_button=header_buttons) users_search_form.process() form.process() return route_template('users/users', users_table = users_table, form=form, users_search_form=users_search_form, constants=c, change=change, error_msg=error_msg)
def trains(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) form = TableSearchForm() regions = get_regions(current_user) if not form.region.choices: form.region.choices = [(-1, c.all_regions)] + [(r.id, r.name) for r in regions] trains = [] filt = dict() q = TrainCode.query page = 1 per_page = 5 if "page" in request.args: page = int(request.args["page"]) total_len = q.count() trains = q.offset((page - 1) * per_page).limit(per_page).all() max_page = math.ceil(total_len / per_page) trains_count = dict() for t in trains: trains_count[t.id] = TrainTravel.query.filter_by( train_code_id=t.id).count() form.process() return route_template('trains/trains', trains=trains, trains_count=trains_count, form=form, page=page, max_page=max_page, total=total_len, constants=c)
def various(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_access_various_exports: return render_template('errors/error-500.html'), 500 form = DownloadVariousData() form.hospital_type.choices = [c.all_types] + [ (t.id, t.name) for t in Hospital_Type.query.all() ] change = None error_msg = None return route_template('various/various', form=form, change=change, error_msg=error_msg)
def trains(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_train: return render_template('errors/error-400.html'), 400 change, error_msg = flights_trains(request) form = TrainSearchForm() populate_search_form(form, request) flights_table = TrainTableModule(request, form, [(_("Добавить ЖД Рейс"), "/add_train")]) form.process() return route_template('flights_trains/flights_trains', form=form, flights_table=flights_table, constants=c, change=change, error_msg=error_msg, is_trains=True)
def hospital_profile(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if "id" in request.args: try: hospital_query = Hospital.query.filter_by(id=request.args["id"]) hospital = hospital_query.first() except exc.SQLAlchemyError: return render_template('errors/error-400.html'), 400 if not hospital: return render_template('errors/error-404.html'), 404 else: form = AddHospitalForm() change = None error_msg = None if not current_user.user_role.can_add_edit_hospital: form_fields = ["full_name", "region_id", "hospital_type_id"] disable_form_fields(form, form_fields) if 'update' in request.form and current_user.user_role.can_add_edit_hospital: values = request.form.to_dict() values.pop("csrf_token", None) values.pop("update", None) values['name'] = get_hospital_short_name(values['full_name']) hospital_query.update(values) db.session.add(hospital) db.session.commit() change = _("Данные обновлены") prepare_hospital_form(form, current_user) hospital = hospital_query.first() hospital_parameters = hospital.__dict__.copy() populate_form(form, hospital_parameters) form.process() search_form = HospitalPatientsSearchForm() if not search_form.region_id.choices: search_form.region_id.choices = get_regions_choices( current_user, with_all_regions=True) patients_table = HospitalPatientsTableModule( request, Patient.query, search_form, hospital.id) return route_template('hospitals/add_hospital_and_profile', form=form, change=change, hospital=hospital, error_msg=error_msg, is_profile=True, patients_table=patients_table) else: return render_template('errors/error-500.html'), 500
def train_profile(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if "id" in request.args: train = TrainCode.query.filter_by(id=request.args["id"]).first() if not train: return render_template('errors/error-404.html'), 404 else: form = FlightForm() form.date.default = train.date form.from_country.default = train.from_country form.from_city.default = train.from_city form.to_country.default = train.to_country form.to_city.default = train.to_city change = None error_msg = None patients = [] train_type_id = TravelType.query.filter_by( value=c.train_type[0]).first().id q = db.session.query(Patient, TrainTravel) q = q.filter(Patient.travel_type_id == train_type_id) q = q.filter(Patient.travel_id == TrainTravel.id) q = q.filter(TrainTravel.train_code_id == train.id) letters = [] # plane_seats = [] # for result in q.all(): # if result[1].seat: # plane_seats.append((result[1].seat, result[0])) seatmap = [] patients_seat = {} # boardmap = [] # if len(plane_seats): # new_seats = {} # for p in plane_seats: # if p[0].lower() != c.board_team: # match = re.findall(r'[A-Za-zА-Яа-я]+|\d+', p[0]) # if len(match) == 2: # letter = c.cyrillic_to_ascii.get(match[1].upper(), match[1].upper()) # new_seats[int(match[0])] = new_seats.get(int(match[0]), {}) # new_seats[int(match[0])][letter] = p[1] # letters.append(letter) # else: # pass # new_seats = OrderedDict(sorted(new_seats.items(), key=lambda t: t[0])) # seat_num = list(new_seats.keys())[-1] # seat_letters = np.sort(np.unique(letters)) # for k in new_seats.keys(): # for s in new_seats[k].keys(): # seat = "{}{}".format(k, s) # patients_seat[seat] = new_seats[k][s] # for row in range(1, seat_num + 1): # row_string = "" # row_s = [] # row_seats = new_seats.get(row, {}).keys() # for letter in seat_letters: # row_letter = "" # if letter in row_seats: # row_letter = "i" if new_seats[row][letter].is_infected else "o" # else: # row_letter = "e" # row_letter = "{}[,{}]".format(row_letter, "{}{}".format(row, letter)) # row_s.append(row_letter) # if len(row_s) == 7: # row_string = "{}{}_{}{}{}_{}{}" # elif len(row_s) == 6: # row_string = "{}{}{}_{}{}{}" # else: # row_string = "{}"*len(row_s) # row_string = row_string.format(*row_s) # seatmap.append(row_string) page = 1 per_page = 5 if "page" in request.args: page = int(request.args["page"]) total_len = q.count() for p in q.offset((page - 1) * per_page).limit(per_page).all(): patients.append(p[0]) max_page = math.ceil(total_len / per_page) form.process() return route_template('trains/train_profile', form=form, train=train, change=change, seatmap=seatmap, patients_seat=patients_seat, error_msg=error_msg, patients=patients, total_patients=total_len, max_page=max_page, page=page) else: return render_template('errors/error-500.html'), 500 # @blueprint.route('/delete_user', methods=['POST']) # @login_required # def delete_user(): # if not current_user.is_authenticated: # return redirect(url_for('login_blueprint.login')) # if not current_user.is_admin: # return render_template('errors/error-500.html'), 500 # return_url = url_for('main_blueprint.users') # if len(request.form): # if "delete" in request.form: # user_id = request.form["delete"] # user = User.query.filter(User.id == user_id) # if user: # user.delete() # db.session.commit() # return redirect(return_url)
def user_profile(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) # if not current_user.user_role.can_add_edit_user: # return render_template('errors/error-500.html'), 500 if "id" in request.args: if request.args["id"] != str(current_user.id): if not current_user.user_role.can_add_edit_user: return render_template('errors/error-500.html'), 500 try: user_query = User.query.filter_by(id=request.args["id"]) user = user_query.first() except exc.SQLAlchemyError: return render_template('errors/error-400.html'), 400 if not user: return render_template('errors/error-404.html'), 404 else: form = UpdateUserForm() change = None error_msg = None if not current_user.user_role.can_add_edit_user: form_fields = [ "full_name", "username", "email", "region_id", "telephone", "organization", "is_admin", "user_role_id" ] disable_form_fields(form, form_fields) if 'update' in request.form: values = request.form.to_dict() if current_user.user_role.can_add_edit_user: if 'username' in values: new_username = values['username'] if not new_username == user.username: if not User.query.filter_by( username=new_username).count(): user.username = new_username else: error_msg = _( "Пользователь с таким логином уже существует" ) if 'region_id' in values: if values['region_id'] == '-1': values['region_id'] = None if 'is_admin' in values: values['is_admin'] = int(values['is_admin']) == 1 else: # Delete values that we don't update values.pop("is_admin", None) values.pop("username", None) values.pop("region_id", None) values.pop("user_role_id", None) if not error_msg: if values.get('password', ''): password = values['password'] user.password = hash_pass(password) values.pop("password", None) values.pop("csrf_token", None) values.pop("update", None) user_query.update(values) db.session.add(user) db.session.commit() change = _("Данные обновлены") user = user_query.first() user_parameters = user.__dict__.copy() user_parameters.pop("password", None) populate_form(form, user_parameters) form.region_id.choices = get_regions_choices(current_user) if not form.user_role_id.choices: roles = UserRole.query.all() form.user_role_id.choices = [(r.id, r.name) for r in roles] form.process() user_patients_search_form = UserPatientsSearchForm() user_patients_search_form.region_id.choices = get_regions_choices( current_user) patients_table = UserPatientsTableModule( request, Patient.query.filter_by(created_by_id=user.id), user_patients_search_form) return route_template('users/add_user_and_profile', form=form, change=change, user=user, patients_table=patients_table, error_msg=error_msg, is_profile=True) else: return render_template('errors/error-500.html'), 500
def train_profile(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_train: return render_template('errors/error-400.html'), 400 if "id" in request.args: train = None try: train = Train.query.filter_by(id=request.args["id"]).first() except exc.SQLAlchemyError: return render_template('errors/error-400.html'), 400 if not train: return render_template('errors/error-404.html'), 404 else: form = TrainForm() disable_form_fields(form) form.departure_date.default = train.departure_date form.arrival_date.default = train.arrival_date populate_profile_flight_train_form(form, train) change = None error_msg = None patients = [] train_type_id = TravelType.query.filter_by( value=c.train_type[0]).first().id q = db.session.query(Patient, TrainTravel) q = q.filter(Patient.travel_type_id == train_type_id) q = q.filter(Patient.id == TrainTravel.patient_id) q = q.filter(TrainTravel.train_id == train.id) patients_search_form = PatientsSearchForm() if not patients_search_form.region.choices: patients_search_form.region.choices = get_regions_choices( current_user) patients_table = PatientsTravelTableModule(request, q, patients_search_form, True) form.process() return route_template('flights_trains/flight_train_profile', form=form, travel=train, change=change, patients_search_form=patients_search_form, error_msg=error_msg, patients_table=patients_table, is_trains=True, seatmap=[], patients_seat={}) else: return render_template('errors/error-500.html'), 500
def flight_profile(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_air: return render_template('errors/error-400.html'), 400 if "id" in request.args: flight = None try: flight = FlightCode.query.filter_by(id=request.args["id"]).first() except exc.SQLAlchemyError: return render_template('errors/error-400.html'), 400 if not flight: return render_template('errors/error-404.html'), 404 else: form = FlightForm() disable_form_fields(form) form.code.default = flight.code form.date.default = flight.date populate_profile_flight_train_form(form, flight) form.from_country_id.default = flight.from_country_id form.from_city.default = flight.from_city form.to_country_id.default = flight.to_country_id form.to_city.default = flight.to_city change = None error_msg = None flight_type_id = TravelType.query.filter_by( value=c.flight_type[0]).first().id q = db.session.query(Patient, FlightTravel) q = q.filter(Patient.travel_type_id == flight_type_id) q = q.filter(Patient.id == FlightTravel.patient_id) q = q.filter(FlightTravel.flight_code_id == flight.id) patients_search_form = PatientsSearchForm() if not patients_search_form.region.choices: patients_search_form.region.choices = get_regions_choices( current_user) patients_table = PatientsTravelTableModule(request, q, patients_search_form) seatmap, patients_seat = generate_plane_seatmap(q) form.process() patients_search_form.process() return route_template('flights_trains/flight_train_profile', form=form, patients_search_form=patients_search_form, travel=flight, change=change, seatmap=seatmap, patients_seat=patients_seat, error_msg=error_msg, is_trains=False, patients_table=patients_table) else: return render_template('errors/error-500.html'), 500
def hospitals(): if not current_user.is_authenticated: return redirect(url_for('login_blueprint.login')) if not current_user.user_role.can_add_edit_hospital: return render_template('errors/error-500.html'), 500 form = HospitalSearchForm(request.form) if not form.region.choices: form.region.choices = get_regions_choices(current_user) filt = dict() q = Hospital.query region = request.args.get("region", '-1') if not current_user.user_role.can_add_edit_hospital: filt["region_id"] = current_user.region_id else: if region != str(-1): filt["region_id"] = region form.region.default = region q = Hospital.query.filter_by(region_id=filt["region_id"]) hospital_type = Hospital_Type.query.all() if not form.hospital_type.choices: form.hospital_type.choices = [(-1, c.all_hospital_types)] + [ (r.id, r.name) for r in hospital_type ] hospitals = [] hospital_type = request.args.get("hospital_type", '-1') if hospital_type != str(-1): filt["hospital_type_id"] = hospital_type form.hospital_type.default = hospital_type page = 1 per_page = 10 if "page" in request.args: page = int(request.args["page"]) q = q.filter_by(**filt) total_len = q.count() for h in q.offset((page - 1) * per_page).limit(per_page).all(): patients_num = Patient.query.filter_by(hospital_id=h.id).filter( PatientStatus.value == c.in_hospital[0]).count() hospitals.append((h, patients_num)) max_page = math.ceil(total_len / per_page) change = None error_msg = None if "added_hospital" in request.args: change = _("Стационар был успешно добавлен") elif "delete_hospital" in request.args: change = _("Стационар был успешно удален") elif "error" in request.args: error_msg = request.args["error"] form.process() return route_template('hospitals/hospitals', hospitals=hospitals, form=form, page=page, max_page=max_page, total=total_len, change=change, error_msg=error_msg)