Exemple #1
0
def create(id):
    try:
        datos_turno = request.get_json()
        if id != datos_turno['centro_id']:
            raise ValueError("id url no coincide con centro_id.")
        center = Center.get_by_id(id)  # datos_turno['centro_id']
        Shifts.check_date(str_date_to_datetime(datos_turno['fecha']).date())
        Shifts.check_duration(str_time_to_datetime(datos_turno['hora_inicio']),
                              str_time_to_datetime(datos_turno['hora_fin']))
        datos_turno['hora_inicio'] = str_time_to_datetime(
            datos_turno['hora_inicio']).time()
        datos_turno['hora_fin'] = str_time_to_datetime(
            datos_turno['hora_fin']).time()
        datos_turno['fecha'] = str_date_to_datetime(
            datos_turno['fecha']).date()
        shift = Shifts.populate_from_api(datos_turno)
        created_shift = Shifts.create_shift(
            shift, center)  # errores posibles capturados
        return jsonify({"atributos": created_shift.serialize()}), 200

    except (BadRequestKeyError, ValueError, KeyError, AttributeError,
            NoResultFound) as err:
        app.logger.info(traceback.format_exc())
        return get_json_error_msg(error_msg=str(err),
                                  error_code=420,
                                  status="invalid request")

    except Exception as e:
        app.logger.info(traceback.format_exc())
        return get_json_error_msg(error_code=500,
                                  error_msg="Error inesperado",
                                  status="internal server error")
Exemple #2
0
def new_view(center_id):
    try:
        center = Center.get_by_id(center_id)
    except NoResultFound as err:
        flash(err, "danger")
        return redirect(url_for("turnos_index"))
    form = CreateShiftForm()
    return render_template("shifts/new.html", form=form, center=center)
Exemple #3
0
def update_center_form(object_id):
    """ renderiza el formulario para editar un centro """
    try:
        center = Center.get_by_id(object_id)
    except NoResultFound as e:
        flash(e, "danger")
        return redirect(url_for('center_index'))
    form = CreateCenterForm(obj=center)
    return render_template('center/update.html',
                           form=form,
                           center_id=object_id)
Exemple #4
0
def get_protocol(object_id):
    try:
        center = Center.get_by_id(object_id)
        return send_file(io.BytesIO(center.protocol),
                         mimetype='pdf',
                         as_attachment=True,
                         attachment_filename='{} protocol.pdf'.format(
                             center.name))
    except NoResultFound as e:
        flash(e, 'danger')
    return redirect(url_for("center_index"))
Exemple #5
0
def update_form():
    form_date = request.args['date']
    center_id = request.args['center_id']
    try:
        center = Center.get_by_id(center_id)
    except NoResultFound as err:
        flash(err, "danger")
        return redirect(url_for('turnos_new'))
    d = datetime.strptime(form_date, "%Y-%m-%d").date()
    return jsonify(
        list(
            map(lambda t: t.isoformat(),
                center.get_shifts_blocks_avalaible(d))))
Exemple #6
0
def delete_center():
    """Elimina un centro de manera definitiva"""
    try:
        center_id = request.args['object_id']
        center_name = Center.get_by_id(center_id).name
        if Center.delete_by_id(center_id):
            dbSession.commit()
            flash("el Centro {} ha sido borrado".format(center_name), "info")
    except BadRequestKeyError:
        flash("ERROR: id Centro no recibido", "danger")
    except NoResultFound as e:
        flash(e, 'danger')
    finally:
        return redirect(url_for('center_index'))
Exemple #7
0
def create_view(center_id):
    """Recibe el id del centro al que pertenece el turno. Crea un turno siempre
    y cuando haya disponibilidad en el día elegido."""
    form = CreateShiftForm()
    if form.validate():
        shift = Shifts()
        form.populate_obj(shift)
        shift.center_id = center_id
        try:
            center = Center.get_by_id(shift.center_id)
            Shifts.create_shift(shift, center)
            flash("Turno agregado exitosamente", "success")
        except (NoResultFound, ValueError) as err:
            flash(err, "danger")
    if form.errors:
        display_errors(form.errors)
        return redirect(url_for("turnos_new", center_id=center_id))
    return redirect(url_for("turnos_index", page=1))
Exemple #8
0
def update_center(object_id):
    """ edita los atributos del centro con los datos obtenidos del formulario """
    form = CreateCenterForm(request.form)
    if form.validate():
        try:
            center = Center.get_by_id(object_id)
        except NoResultFound as e:
            flash(e, 'danger')
            return redirect(url_for("center_index"))
        form.populate_obj(center)
        center.protocol = request.files['protocol'].read()
        dbSession.commit()
    elif form.errors:
        display_errors(form.errors)
        flash("Error al validar formulario", "danger")
        return update_center_form(object_id)
    flash("se guardaron los cambios", "info")
    return redirect(url_for("center_index"))
Exemple #9
0
def change_state(method, message):
    try:
        center_id = request.args['object_id']
    except BadRequestKeyError:
        flash("ERROR: id Centro no recibido", "danger")
        return redirect(url_for("center_index"))
    try:
        center = Center.get_by_id(center_id)
    except NoResultFound as e:
        flash(e, 'danger')
        return redirect(url_for("center_index"))
    try:
        getattr(center, method)()
    except IntegrityError:
        flash('hubo un problema en la transacción', 'danger')
        return redirect(url_for("center_index"))
    except AttributeError as e:
        flash(e, 'danger')
        return redirect(url_for("center_index"))
    flash(message.format(center.name), "info")
    return redirect(url_for("center_index"))
Exemple #10
0
def avalaible_by_date(id):
    """Devuelve los turnos disponibles para el centro x. Parametro opcional: fecha. Si no recibe fecha, fecha=actual.
    """
    try:
        fecha = datetime.strptime(request.args['fecha'], '%Y-%m-%d').date()
        center = Center.get_by_id(id)
        # fecha2 = datetime.strptime("2020-12-13", '%Y-%m-%d').date()
        # if fecha == fecha2:
        #     return get_json_error_msg(center_info={"centro_id": center.id, "fecha": fecha.isoformat()},
        #                               status="shifts not available", error_code=404,
        #                               error_msg="no hay turnos disponibles".format(center.id))
        if center.published is False:
            raise ValueError("centro id={} no se encuentra activo".format(
                center.id))  # podria implementarse en el metodo
    except (ValueError, NoResultFound, BadRequestKeyError) as e:
        app.logger.info(traceback.format_exc())
        msg, error_code = str(e), 404
        if type(e) == BadRequestKeyError:
            msg, error_code = "error: fecha no recibida", 422
        return get_json_error_msg(error_msg=msg, error_code=error_code)

    except Exception as e:
        app.logger.info(traceback.print_exc())
        return get_json_error_msg(error_code=500,
                                  error_msg="Error en el servidor",
                                  status="internal server error")

    turnos = center.get_shifts_blocks_avalaible(fecha)
    if turnos:
        return get_json_turnos(turnos=turnos, fecha=fecha,
                               centro_id=center.id), 200
    return get_json_error_msg(center_info={
        "centro_id": center.id,
        "fecha": fecha.isoformat()
    },
                              status="shifts not available",
                              error_code=404,
                              error_msg="no hay turnos disponibles".format(
                                  center.id))