예제 #1
0
    def patch(self, user_id):

        data = user_id or None

        if data is None or data is ' ':
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        try:
            user = get_user_by_id(user_id)

            user.active = True
            user.save()

        except DoesNotExist as e:
            return resp_does_not_exist('Users', 'Usuário')

        except FieldDoesNotExist as e:
            return resp_exception('Users', description=e.__str__())

        except NotUniqueError:
            return resp_already_exists('Users', 'usuário')

        except ValidationError as e:
            return resp_exception('Users',
                                  msg=MSG_INVALID_DATA,
                                  description=e.__str__()
                                  )

        return resp_ok('Users', MSG_RESOURCE_ACTIVE.format('Usuário'))
예제 #2
0
    def post(self, *args, **kwargs):
        req_data = request.get_json() or None
        data, errors, result = None, None, None
        schema = PlanetRegistrationSchema()

        if req_data is None:
            return resp_data_invalid('Planets', [], msg=MSG_INVALID_DATA)

        data, errors = schema.load(req_data)

        if errors:
            return resp_data_invalid('Planets', errors)

        try:
            model = Planet(**data)
            model.save()

        except NotUniqueError:
            return resp_already_exists('Planets', 'planet')

        except ValidationError as e:
            return resp_exception('Planets',
                                  msg=MSG_INVALID_DATA,
                                  description=e.__str__())

        except Exception as e:
            return resp_exception('Planets', description=e.__str__())

        schema = PlanetSchema()
        result = schema.dump(model)

        # statuscode 200
        return resp_ok('Planets',
                       MSG_RESOURCE_CREATED.format('Planet'),
                       data=result.data)
예제 #3
0
    def delete(self, user_id):
        # Busco o usuário na coleção users pelo seu id
        user = get_user_by_id(user_id)

        # se não for uma instancia do modelo User retorno uma resposta
        # da requisição http do flask
        if not isinstance(user, User):
            return user

        try:
            user.active = False
            user.save()

        except NotUniqueError:
            return resp_already_exists('Users', 'usuário')

        except ValidationError as e:
            return resp_exception('Users',
                                  msg=MSG_INVALID_DATA,
                                  description=e.__str__())

        except Exception as e:
            return resp_exception('Users', description=e.__str__())

        return resp_ok('Users', MSG_RESOURCE_DELETED.format('Usuário'))
    def delete(self, rf):
        # Fetch collaborator by rf
        collaborator = get_collaborator_by_rf(rf)

        if not isinstance(collaborator, Collaborator):
            return collaborator

        try:
            collaborator.active = False
            collaborator.save()

        except NotUniqueError:
            return resp_already_exists(
                        'CollaboratorServices',
                        'colaborador'
                    )

        except ValidationError as e:
            return resp_exception(
                        'CollaboratorServices',
                        msg=MSG_INVALID_DATA,
                        description=e.__str__()
                    )

        except Exception as e:
            return resp_exception(
                        'CollaboratorServices',
                        description=e.__str__()
                    )

        return resp_ok(
                    'CollaboratorServices',
                    MSG_RESOURCE_DELETED.format('Colaborador')
                )
예제 #5
0
    def get(self, page_id=1):
        schema = UserSchema(many=True)
        page_size = 10

        if 'page_size' in request.args:
            if int(request.args.get('page_size')) < 1:
                page_size = 10
            else:
                page_size = int(request.args.get('page_size'))

        try:

            users = User.objects().paginate(page_id, page_size)

        except FieldDoesNotExist as e:
            return resp_exception('Users', description=e.__str__())

        except Exception as e:
            return resp_exception('Users', description=e.__str__())

        extra = {
            'page': users.page,
            'pages': users.pages,
            'total': users.total,
            'params': {
                'page_size': page_size
            }
        }

        result = schema.dump(users.items)

        return resp_ok('Users',
                       MSG_RESOURCE_FETCHED_PAGINATED.format('usuários'),
                       data=result.data,
                       **extra)
예제 #6
0
    def get(self):
        schema = UserSchema(many=True)

        args = request.args
        page_id = int(args["page"]) if args.get("page") else 1
        page_size = int(args["page_size"]) if args.get("page_size") and args.get("page_size") < 1 \
                else 10

        try:

            users = User.objects()
            count = users.count()
            if count == 0:
                return resp_does_not_exist_resources("User", "usuário")

            if count <= ((page_id-1)*page_size):
                page_id = ceil(count/page_size)
            users = users.paginate(page_id, page_size)

        except FieldDoesNotExist as e:
            return resp_exception("Users", description=e.__str__()+"field")

        except Exception as e:
            return resp_exception("Users", description=e.__str__())

        extra = {
            "page": users.page, "pages": users.pages, "total": users.total, 
            "params": {"page_size":page_size}
        }

        result = schema.dump(users.items)
        return resp_ok(
                "Users", MSG_RESOURCE_FETCHED_PAGINATED.format("Usuários"), result, **extra)
    def delete(self, point_id):
        # Fetch point by rf
        point = get_point_by_id(point_id=point_id)

        if not isinstance(point, Point):
            return point

        try:
            point.active = False
            point.save()

        except ValidationError as e:
            return resp_exception(
                        'PointServices',
                        msg=MSG_INVALID_DATA,
                        description=e.__str__()
                    )

        except Exception as e:
            return resp_exception(
                        'PointServices',
                        description=e.__str__()
                    )

        return resp_ok(
                    'PointServices',
                    MSG_RESOURCE_DELETED.format('Ponto')
                )
    def post(self, *args, **kwargs):
        # Inicializo todas as variaveis utilizadas
        req_data = request.get_json() or None
        data, errors, result = None, None, None
        password, confirm_password = None, None
        schema = UserRegistrationSchema()

        # Se meus dados postados forem Nulos retorno uma respota inválida
        if req_data is None:
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        password = req_data.get('password', None)
        confirm_password = req_data.get('confirm_password', None)

        # verifico através de uma função a senha e a confirmação da senha
        # Se as senhas não são iguais retorno uma respota inválida
        if not check_password_in_signup(password, confirm_password):
            errors = {'password': MSG_PASSWORD_DIDNT_MATCH}
            return resp_data_invalid('Users', errors)

        # Desserialização os dados postados ou melhor meu payload
        data, errors = schema.load(req_data)

        # Se houver erros retorno uma resposta inválida
        if errors:
            return resp_data_invalid('Users', errors)

        # Crio um hash da minha senha
        hashed = hashpw(password.encode('utf-8'), gensalt(12))

        # Salvo meu modelo de usuário com a senha criptografada e email em lower case
        # Qualquer exceção ao salvar o modelo retorno uma resposta em JSON
        # ao invés de levantar uma exception no servidor

        try:
            data['password'] = hashed
            data['email'] = data['email'].lower()
            model = User(**data)
            model.save()
        except NotUniqueError:
            return resp_already_exists('Users', 'fornecedor')

        except ValidationError as e:
            return resp_exception('Users', msg=MSG_INVALID_DATA, description=e)

        except Exception as e:
            return resp_exception('Users', description=e)

        # Realizo um dump dos dados de acordo com o modelo salvo
        schema = UserSchema()
        result = schema.dump(model)

        # Retorno 200 o meu endpoint
        return resp_ok(
            'Users',
            MSG_RESOURCE_CREATED.format('Usuário'),
            data=result.data,
        )
    def get(self, rf, month_id):        
        try:
            # Fetch point by rf
            points = Point.objects(
                Q(date__contains=month_id) & Q(rf=rf)
            ).order_by('date')
            
        except DoesNotExist:
            return resp_does_not_exist('PointServices', 'ponto')

        except FieldDoesNotExist as e:
            return resp_exception('PointServices', description=e.__str__())

        except Exception as e:
            return resp_exception('PointServices', description=e.__str__())

        # It will be auxiliar for changing date
        # Convert string to datetime
        staticDate = datetime.strptime(points.first().date, '%Y-%m-%d').date()
        result = {}
        hoursPerDay = 0
        hoursPerMonth = 0
        for point in range(0, points.count()):
            date = datetime.strptime(
                points[point].date, '%Y-%m-%d'
            ).date()

            if (date != staticDate):
                staticDate = date
                hoursPerDay=0
            
            if point%2 == 0:
                punchIn = datetime.strptime(
                    points[point].time, '%H:%M:%S'
                ).hour
            else:
                punchOut = datetime.strptime(
                    points[point].time, '%H:%M:%S'
                ).hour

            if point%2 == 1:
                hoursPerDay = hoursPerDay + (punchOut-punchIn)
                
                # Take work hours per day,
                # Convert datetime to string
                result["Day " + date.strftime('%Y-%m-%d')] = hoursPerDay
                
                hoursPerMonth = hoursPerMonth + punchOut - punchIn
        
        result["Month " + month_id] = hoursPerMonth
        return resp_ok(
            'ReportService',
            MSG_RESOURCE_FETCHED.format('Relatorio'),
            result
        )
        
    def post(self, *args, **kwargs):
        # Initialize variables
        #print(request.json)
        req_data = request.get_json(force=True) or None
        #print(req_data)
        data, errors, result = None, None, None
        password, confirm_password = None, None
        schema = CollaboratorRegistrationSchema()

        # When datas are null
        if req_data is None:
            return resp_data_invalid('CollaboratorsServices', [], msg=MSG_NO_DATA)

        password = req_data.get('password', None)
        confirm_password = req_data.pop('confirm_password', None)
        req_data['rf'] = random.randint(100000,999999)
        

        # Verify passwords provided
        if not check_password_in_signup(password, confirm_password):
            errors = {'password': MSG_PASSWORD_WRONG}
            return resp_data_invalid('CollaboratorsServices', errors)

        # Desserialize data
        data, errors = schema.load(req_data)

        # Return invalid response when there is a error
        if errors:
            return resp_data_invalid('CollaboratorsServices', errors)

        # Create hash
        hashed = hashpw(password.encode('utf-8'), gensalt(12))

        # Save the model. If get Exception, return JSON response.
        try:
            data['password'] = hashed
            data['email'] = data['email'].lower()
            model = Collaborator(**data)
            model.save()

        except NotUniqueError:
            return resp_already_exists('CollaboratorsServices', 'colaborador')

        except ValidationError as e:
            return resp_exception('CollaboratorsServices', msg=MSG_INVALID_DATA, description=e)

        except Exception as e:
            return resp_exception('CollaboratorsServices', description=e)

        # Dump data of model
        schema = CollaboratorSchema()
        result = schema.dump(model)

        return resp_ok(
            'CollaboratorsServices', MSG_RESOURCE_CREATED.format('Colaborador'),  data=result.data,
        )
예제 #11
0
    def put(self, user_id):
        result = None
        schema = UserSchema()
        update_schema = UserUpdateSchema()
        req_data = request.get_json() or None
        email = None

        if req_data is None:
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        user = get_user_by_id(user_id)

        if not isinstance(user, User):
            return user

        # carrega os dados de acordo com o schema de atualização
        data, errors = update_schema.load(req_data)

        # em caso de erros retorno uma resposta 422 com os erros de
        # validação do schema
        if errors:
            return resp_data_invalid('Users', errors)

        email = data.get('email', None)

        if email and exists_email_in_users(email, user):
            return resp_data_invalid('Users', [{
                'email': [MSG_ALREADY_EXISTS.format('usuário')]
            }])

        try:
            # para cada chave dentro do dados do update schema
            # atribuimos seu valor
            for i in data.keys():
                user[i] = data[i]

            user.save()

        except NotUniqueError:
            return resp_already_exists('Users', 'usuário')

        except ValidationError as e:
            return resp_exception('Users',
                                  msg=MSG_INVALID_DATA,
                                  description=e.__str__())

        except Exception as e:
            return resp_exception('Users', description=e.__str__())

        result = schema.dump(user)

        return resp_ok('Users',
                       MSG_RESOURCE_UPDATED.format('Usuário'),
                       data=result.data)
예제 #12
0
def get_user_by_document(cpf: str):
    try:
        return User.objects.get(cpf=cpf)

    except DoesNotExist:
        return resp_does_not_exist('Users', 'Usuário')

    except FieldDoesNotExist as e:
        return resp_exception('Users', description=e.__str__())

    except Exception as e:
        return resp_exception('Users', description=e.__str__())
예제 #13
0
def get_order_by_id(order_id: str):
    try:
        return OrderModel.objects.get(id=order_id)

    except DoesNotExist:
        return resp_does_not_exist('Order', 'Pedido')

    except FieldDoesNotExist as e:
        return resp_exception('Order', description=e.__str__())

    except Exception as e:
        return resp_exception('Order', description=e.__str__())
예제 #14
0
    def post(self, *args, **kwargs):
        '''
        Create an user

        payload:
        {
            "name": "Lucas Simon",
            "email": "*****@*****.**",
            "password": "******"
        }
        '''
        req_data = request.get_json() or None
        schema = UserCreateSchema()

        if req_data is None:
            return resp_form_invalid('Users', [], msg=_MSG312)

        data, errors = schema.load(req_data)

        if errors:
            return resp_form_invalid('Users', errors)

        if exists_email_in_database(data.get('email')):
            errors = {
                'errors': {
                    'email': [_MSG302]
                }
            }

            return resp_form_invalid('Users', errors)

        # TODO: Encrypt password with bcrypt

        try:
            model = User(**data)
            model.save()

        except NotUniqueError:
            return resp_already_exists('Users', 'usuário')

        except ValidationError as e:
            return resp_exception('Users', msg=_MSG300, description=e)

        except Exception as e:
            return resp_exception('Users', description=e)

        schema = UserSchema()
        result = schema.dump(model)

        return resp_ok(
            'Users', _MSG200.format('Usuário'), data=result.data
        )
예제 #15
0
def get_planet_by_name(name: str):
    try:
        # Search planet by name
        return Planet.objects.get(name=name)

    except DoesNotExist as e:
        return resp_does_not_exist('Planets', 'Planet')

    except FieldDoesNotExist as e:
        return resp_exception('Planets', description=e.__str__())

    except Exception as e:
        return resp_exception('Planets', description=e.__str__())
예제 #16
0
def get_planet_by_id(planet_id: str):
    try:
        # Search planet by id
        return Planet.objects.get(id=planet_id)

    except DoesNotExist as e:
        return resp_does_not_exist('Planets', 'Planet')

    except FieldDoesNotExist as e:
        return resp_exception('Planets', description=e.__str__())

    except Exception as e:
        return resp_exception('Planets', description=e.__str__())
def get_collaborator_by_rf(rf: str):
    try:
        # Fetch collaborator by rf
        return Collaborator.objects.get(rf=rf)

    except DoesNotExist:
        return resp_does_not_exist('CollaboratorServices', 'Colaborador')

    except FieldDoesNotExist as e:
        return resp_exception('ColaboratorServices', description=e.__str__())

    except Exception as e:
        return resp_exception('ColaboratorServices', description=e.__str__())
예제 #18
0
def get_user_by_email(email: str):
    try:
        # buscamos todos os usuários da base utilizando o paginate
        return User.objects.get(email=email)

    except DoesNotExist as e:
        return resp_does_not_exist('Users', 'Usuário')

    except FieldDoesNotExist as e:
        return resp_exception('Users', description=e.__str__())

    except Exception as e:
        return resp_exception('Users', description=e.__str__())
def get_point_by_id(point_id: int):
    try:
        # Fetch point by rf
        return Point.objects.get(id=point_id)

    except DoesNotExist:
        return resp_does_not_exist('PointServices', 'ponto')

    except FieldDoesNotExist as e:
        return resp_exception('PointServices', description=e.__str__())

    except Exception as e:
        return resp_exception('PointServices', description=e.__str__())
예제 #20
0
    def put(self, user_id):
        result = None
        schema = UserSchema()
        update_schema = UserUpdateSchema()
        req_data = request.get_json() or None
        email = None

        
        if req_data is None:
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        
        user = get_user_by_id(user_id)

        
        if not isinstance(user, User):
            return user

        data, errors = update_schema.load(req_data)

        if errors:
            return resp_data_invalid('Users', errors)

        email = data.get('email', None)

        if email and exists_email_in_users(email, user):
            return resp_data_invalid(
                'Users', [{'email': [MSG_ALREADY_EXISTS.format('usuário')]}]
            )

        try:
            for i in data.keys():
                user[i] = data[i]

            user.save()

        except NotUniqueError:
            return resp_already_exists('Users', 'usuário')

        except ValidationError as e:
            return resp_exception('Users', msg=MSG_INVALID_DATA, description=e.__str__())

        except Exception as e:
            return resp_exception('Users', description=e.__str__())

        result = schema.dump(user)

        return resp_ok(
            'Users', MSG_RESOURCE_UPDATED.format('Usuário'),  data=result.data
        )
예제 #21
0
    def get(self, page_id=1):
        # inicializa o schema podendo conter varios objetos
        schema = UserSchema(many=True)
        # incializa o page_size sempre com 10
        page_size = 10

        current_user = get_user_by_email(get_jwt_identity())

        if not isinstance(current_user, User):
            return current_user

        if not (current_user.is_active()) and current_user.is_admin():
            return resp_notallowed_user('Users')

        # se enviarmos o page_size como parametro
        if 'page_size' in request.args:
            # verificamos se ele é menor que 1
            if int(request.args.get('page_size')) < 1:
                page_size = 10
            else:
                # fazemos um type cast convertendo para inteiro
                page_size = int(request.args.get('page_size'))

        try:
            # buscamos todos os usuarios da base utilizando o paginate
            users = User.objects().paginate(page_id, page_size)

        except FieldDoesNotExist as e:
            return resp_exception('Users', description=e.__str__())

        except Exception as e:
            return resp_exception('Users', description=e.__str__())

        # criamos dados extras a serem respondidos
        extra = {
            'page': users.page,
            'pages': users.pages,
            'total': users.total,
            'params': {
                'page_size': page_size
            }
        }

        # fazemos um dump dos objetos pesquisados
        result = schema.dump(users.items)

        return resp_ok('Users',
                       MSG_RESOURCE_FETCHED_PAGINATED.format('usuários'),
                       data=result.data,
                       **extra)
예제 #22
0
    def post(self, *args, **kwargs):
        req_data = request.get_json() or None
        data, errors, result = None, None, None
        schema = CarSchema()

        if req_data is None:
            return resp_data_invalid('Car', [], MSG_NO_DATA)

        data, errors = schema.load(req_data)

        if errors:
            return resp_data_invalid('Car', [], MSG_INVALID_DATA)

        try:
            model = Car(**data)
            model.save()

            schema = CarSchema()
            result = schema.dump(model)

            return resp_ok('Car',
                           MSG_RESOURCE_CREATED.format('Car'),
                           data=result.data)
        except Exception as e:
            return resp_exception('Car', 'Exception to save car',
                                  MSG_EXCEPTION)
예제 #23
0
 def get(self):
     try:
         waitList = ListaEsperaModel.objects()
         return resp_ok('Lista de Espera', MSG_SUCCESS,
                        json.loads(waitList.to_json()))
     except Exception as e:
         return resp_exception('Lista de Espera', description=e.__str__())
예제 #24
0
    def get(self):

        try:
            diagnosticoList = DiagnosticoModel.objects()
            return resp_ok('Diagnostico', MSG_SUCCESS,
                           json.loads(diagnosticoList.to_json()))
        except Exception as e:
            return resp_exception('Diagnostico', description=e.__str__())
예제 #25
0
    def post(self, *args, **kwargs):
        
        req_data = request.get_json() or None
        data, errors, result = None, None, None
        senha, confirma_senha = None, None
        schema = UserSchema()

        if req_data is None:
            return resp_data_invalid('Users', [], msg=MSG_NO_DATA)

        senha = req_data.get('senha', None)
        confirma_senha = req_data.pop('confirma_senha', None)

        if not check_password_in_signup(senha, confirma_senha):
            errors = {'senha': MSG_PASSWORD_DIDNT_MATCH}
            return resp_data_invalid('Users', errors)

        data, errors = schema.load(req_data)

        if errors:
            return resp_data_invalid('Users', errors)

        hashed = hashpw(senha.encode('utf-8'), gensalt(12))

        try:
            data['senha'] = hashed
            data['email'] = data['email'].lower()
            model = User(**data)
            model.save()

        except NotUniqueError:
            return resp_already_exists('Users', 'usuario')

        except ValidationError as e:
            return resp_exception('Users', description=str(e),msg=MSG_INVALID_DATA)

        except Exception as e:
            return resp_exception('Users', description=str(e), msg=MSG_INVALID_DATA)

        schema = UserSchema()
        result = schema.dump(model)

        return resp_ok(
            'Users', MSG_RESOURCE_CREATED.format('Usuário'),  data=result.data,
        )
    def put(self, user_id):
        result = None
        schema = UserSchema(many=True)
        update_schema = UserUpdateSchema()
        req_data = request.json or None
        email = None

        if req_data is None:
            return resp_invalid_data('Users', {}, msg=MSG_NO_DATA)

        confirm_password = req_data.pop('confirm_password')

        if not check_password_in_singup(req_data.get('password'),
                                        confirm_password):
            errors = {'password': MSG_PASSWORD_DIDNT_MATCH}
            return resp_invalid_data('Users', errors)

        try:
            query = get_user_by_id(user_id)
            user = schema.dump(query)
            data = update_schema.load(req_data)

        except IntegrityError:
            return resp_invalid_data('Users', IntegrityError.orig)

        email = data.get('email', None)

        if email and exists_email_in_user(email, user):
            return resp_ok('Users',
                           {'email': MSG_ALREADY_EXISTS.format('user')})
        try:
            query.update(request.json)
            current_app.db.session.commit()

        except IntegrityError as err:
            return resp_already_exists('Users', err.orig)
        except ValidationError as err:
            return resp_exception('Users', description=err.__str__())
        except Exception as err:
            return resp_exception('Users', description=err.__str__())
        result = re.search("'.*'", str(data.keys())).group()
        return resp_ok('Users',
                       MSG_RESOURCE_UPDATED.format('Fields'),
                       data=result)
예제 #27
0
    def get(self):
        try:
            cpf = request.args.get('cpf')
            historicoPaciente = TriagemModel.objects(cpf=cpf)
            return resp_ok('Histórico do Paciente', MSG_SUCCESS,
                           json.loads(historicoPaciente.to_json()))

        except Exception as e:
            return resp_exception('Histórico do Paciente',
                                  description=e.__str__())
예제 #28
0
def get_user_by_user_name(username):
    try:
        return User.objects.get(user_name=username)
    except DoesNotExist as e:
        return resp_resource_not_exists("Resource", "Usuário", username)

    except FieldDoesNotExist as e:
        return resp_expection("Users", description=e.__str__())

    except Exception as e:
        return resp_exception("Resource", description=e.__str__())
예제 #29
0
    def get(self):
        schema = CarSchema(many=True)

        try:
            cars = Car.objects()
            
            result = schema.dump(cars)
            
            return resp_ok('Car', MSG_RESOURCE_FETCHED.format('Cars'), data=result.data)
        except Exception as e:
            return resp_exception('Car', description=e.__str__())
예제 #30
0
    def delete(self, planet_id):

        planet = get_planet_by_id(planet_id)

        try:

            planet.delete()

        except NotUniqueError:
            return resp_already_exists('Planets', 'planet')

        except ValidationError as e:
            return resp_exception('Planets',
                                  msg=MSG_INVALID_DATA,
                                  description=e.__str__())

        except Exception as e:
            return resp_exception('Planets', description=e.__str__())

        return resp_ok('Planets', MSG_RESOURCE_DELETED.format('Planet'))