Beispiel #1
0
def create(entity: dict, dao: GenericSQLDAO = None):
    entity_to_create = EntityForTest(**entity)

    dao.create(entity=entity_to_create)

    return success_response(message="EntityForTest created",
                            data={"EntityForTest": dict(entity_to_create)})
Beispiel #2
0
def main_menu(user: Usuario) -> str:
    dao = None
    try:
        dao = GenericSQLDAO(database_type=PostgreSQLHelper)
        dao.database.query("SELECT COUNT(checkin_id_) FROM notificacao_view "
                           "WHERE checkin_id_usuario=%s "
                           "AND notificacao_recebida=FALSE;",
                           [user.id_])
        notificacoes = dao.database.get_results()[0][0]
    except:
        pass
    finally:
        if dao:
            dao.close()
    if notificacoes > 0:
        print(f"{bcolors.WARNING}{bcolors.BOLD} Você tem "
              f"{notificacoes} notificações!{bcolors.ENDC}")
    print(f"{bcolors.HEADER}{bcolors.BOLD}"
          f"O que você gostaria de fazer?"
          f"{bcolors.ENDC}\n")
    for key, action in actions.items():
        print(f"\t{key} - {action.get('name', '...')}")
    action = input(">> ").strip()
    if action not in actions.keys():
        raise ValueError(action)
    return action
Beispiel #3
0
def update(id_: str, phone_id: str, entity: dict, dao: GenericSQLDAO = None):
    entity_to_update = dao.get(phone_id)

    if entity_to_update.contact.id_ != id_:
        entity_to_update = None

    if not entity_to_update:
        return error_response(status_code=404,
                              message="Phone not found",
                              data={"id_": id_})

    entity_fields = dao.fields.keys()

    for key, value in entity.items():
        if key not in entity_fields:
            raise KeyError("{key} not in {entity}"
                           .format(key=key,
                                   entity=dao.return_class))

        entity_to_update.__dict__[key] = value

    dao.update(entity_to_update)

    return success_response(message="Phone updated",
                            data={"Phone": dict(entity_to_update)})
Beispiel #4
0
def create(id_: str, entity: dict, dao: GenericSQLDAO = None):
    entity_to_create = Phone(**entity)
    entity_to_create.contact = Contact(id_=id_)

    dao.create(entity=entity_to_create)

    return success_response(message="Phone created",
                            data={"Phone": dict(entity_to_create)})
Beispiel #5
0
def delete(id_: str, dao: GenericSQLDAO):
    entity = dao.get(id_=id_)

    if not entity:
        return error_response(status_code=404,
                              message="EntityForTest not found",
                              data={"id_": id_})

    dao.remove(entity)

    return success_response(message="EntityForTest deleted",
                            data={"EntityForTest": dict(entity)})
 def test_create_table_with_child(self, mysql_mock):
     generic_dao = GenericSQLDAO(return_class=TestEntityWithChild,
                                 prefix='')
     generic_dao.create_table_if_not_exists()
     assert mysql_mock.query.called_with(
         'CREATE table IF NOT EXISTS test_entity_with_childs ('
         'id_ CHAR(32) NOT NULL, '
         'creation_datetime TIMESTAMP NULL, '
         'last_modified_datetime TIMESTAMP NULL, '
         'name VARCHAR(100) NULL, '
         'birthday DATE NULL, '
         'child_id_ CHAR(32) NULL, '
         'PRIMARY KEY(id_)'
         ');')
Beispiel #7
0
def delete(id_: str, phone_id: str, dao: GenericSQLDAO):
    entity = dao.get(id_=phone_id)

    if entity.contact.id_ != id_:
        entity = None

    if not entity:
        return error_response(status_code=404,
                              message="Phone not found",
                              data={"id_": id_})

    dao.remove(entity)

    return success_response(message="Phone deleted",
                            data={"Phone": dict(entity)})
 def test_init_pooled_database_args(self, postgres_mock):
     generic_dao = GenericSQLDAO(database_type=postgres_mock,
                                 fields={
                                     "id_": "id",
                                     "creation_datetime":
                                     "creation_datetime",
                                     "last_modified_datetime":
                                     "last_modified_datetime",
                                     "name": "name",
                                     "birthday": "birthday"
                                 },
                                 return_class=TestEntity,
                                 pooled=True,
                                 database_args={"ssl_ca": "file"})
     assert postgres_mock.mock_calls == [
         call(pooled=True, database_args={"ssl_ca": "file"})
     ]
     assert generic_dao.database == postgres_mock.return_value
     assert generic_dao.table == "test_entitys"
     assert generic_dao.fields == {
         "id_": "id",
         "creation_datetime": "creation_datetime",
         "last_modified_datetime": "last_modified_datetime",
         "name": "name",
         "birthday": "birthday"
     }
     assert generic_dao.return_class == TestEntity
Beispiel #9
0
def read(length: int = 20,
         offset: int = 0,
         dao: GenericSQLDAO = None,
         **kwargs):
    filters = dict()

    entity_attributes = [field.name for field in fields(EntityForTest)]

    for key, value in kwargs.items():
        if key not in entity_attributes:
            continue

        filters[key] = value.split(',') \
                       if len(str(value).split(',')) > 1 \
                       else value

    total, results = dao.get_all(length=length,
                                 offset=offset,
                                 filters=filters if filters else None)
    return success_response(message="List of entityfortest",
                            data={
                                "total": total,
                                "results":
                                [dict(result) for result in results]
                            })
 def test_init_extra_params(self, postgres_mock):
     generic_dao = GenericSQLDAO(database_type=postgres_mock,
                                 fields={
                                     "id_": "id",
                                     "creation_datetime":
                                     "creation_datetime",
                                     "last_modified_datetime":
                                     "last_modified_datetime",
                                     "name": "name",
                                     "birthday": "birthday"
                                 },
                                 return_class=TestEntity,
                                 pooled=False,
                                 host="changed")
     assert postgres_mock.mock_calls == [call(host="changed", pooled=False)]
     assert generic_dao.database == postgres_mock.return_value
     assert generic_dao.table == "test_entitys"
     assert generic_dao.fields == {
         "id_": "id",
         "creation_datetime": "creation_datetime",
         "last_modified_datetime": "last_modified_datetime",
         "name": "name",
         "birthday": "birthday"
     }
     assert generic_dao.return_class == TestEntity
Beispiel #11
0
def read_one(id_: str, dao: GenericSQLDAO = None):
    result = dao.get(id_=id_)

    if not result:
        return success_response(status_code=404,
                                message="EntityForTest not found in database",
                                data={"id_": id_})

    return success_response(message="EntityForTest retrieved",
                            data={"EntityForTest": dict(result)})
 def test_init_parameter_gen_no_prefix(self, mysql_mock):
     generic_dao = GenericSQLDAO(table='test_table',
                                 return_class=TestEntity)
     assert generic_dao.fields == {
         "id_": "test_entity_id_",
         "creation_datetime": "test_entity_creation_datetime",
         "last_modified_datetime": "test_entity_last_modified_datetime",
         "name": "test_entity_name",
         "birthday": "test_entity_birthday"
     }
 def test_init_parameter_gen(self, postgres_mock):
     generic_dao = GenericSQLDAO(database_type=postgres_mock,
                                 table='test_table',
                                 prefix='test_',
                                 return_class=TestEntity)
     assert generic_dao.fields == {
         "id_": "test_id_",
         "creation_datetime": "test_creation_datetime",
         "last_modified_datetime": "test_last_modified_datetime",
         "name": "test_name",
         "birthday": "test_birthday"
     }
Beispiel #14
0
def read(length: int = 20, offset: int = 0,
         dao: GenericSQLDAO = None, **kwargs):
    for key, value in kwargs.items():
        kwargs[key] = value.split(',') \
            if len(value.split(',')) > 1 \
            else value
    total, results = dao.get_all(length=length, offset=offset,
                                 filters=kwargs if len(kwargs) > 0 else None)
    return success_response(message="List of contact",
                            data={"total": total, "results": [dict(result)
                                                              for result
                                                              in results]})
 def generic_dao2(self, mysql_mock):
     generic_dao = GenericSQLDAO(table="test_table",
                                 fields={
                                     "id_": "id",
                                     "creation_datetime":
                                     "creation_datetime",
                                     "last_modified_datetime":
                                     "last_modified_datetime",
                                     "name": "name",
                                     "birthday": "birthday"
                                 },
                                 return_class=TestEntity2)
     return generic_dao
Beispiel #16
0
def read_one(id_: str, phone_id: str, dao: GenericSQLDAO = None):
    result = dao.get(id_=phone_id)

    if result.contact.id_ != id_:
        result = None

    if not result:
        return success_response(status_code=404,
                                message="Phone not found in database",
                                data={"id_": id_})

    return success_response(message="Phone retrieved",
                            data={"Phone": dict(result)})
    def test_get_child(self, mysql_mock):
        generic_dao = GenericSQLDAO(return_class=TestEntityWithChild,
                                    prefix='')
        id_ = "12345678901234567890123456789012"

        db = mysql_mock.return_value
        db.get_results.return_value = [[
            id_,
            datetime(2020, 7, 26, 12, 00, 00),
            datetime(2020, 7, 26, 12, 00, 00), "Anom", None, id_
        ]]

        entity = generic_dao.get(id_=id_)

        assert mysql_mock.mock_calls[1] == call().query(
            "SELECT id_, creation_datetime, last_modified_datetime,"
            " name, birthday, child_id_ "
            "FROM test_entity_with_childs WHERE id_ = %s "
            "LIMIT %s OFFSET %s;", ['12345678901234567890123456789012', 1, 0])
        assert entity == TestEntityWithChild(id_,
                                             datetime(2020, 7, 26, 12, 00, 00),
                                             datetime(2020, 7, 26, 12, 00, 00),
                                             child=TestEntity(id_))
 def generic_dao(self, postgres_mock):
     generic_dao = GenericSQLDAO(database_type=postgres_mock,
                                 table="test_table",
                                 fields={
                                     "id_": "id",
                                     "creation_datetime":
                                     "creation_datetime",
                                     "last_modified_datetime":
                                     "last_modified_datetime",
                                     "name": "name",
                                     "birthday": "birthday"
                                 },
                                 return_class=TestEntity)
     return generic_dao
 def test_init(self, mysql_mock):
     generic_dao = GenericSQLDAO(fields={
         "id_": "id",
         "creation_datetime": "creation_datetime",
         "last_modified_datetime": "last_modified_datetime",
         "name": "name",
         "birthday": "birthday"
     },
                                 return_class=TestEntity)
     assert mysql_mock.mock_calls == [call()]
     assert generic_dao.database == mysql_mock.return_value
     assert generic_dao.table == "test_entitys"
     assert generic_dao.fields == {
         "id_": "id",
         "creation_datetime": "creation_datetime",
         "last_modified_datetime": "last_modified_datetime",
         "name": "name",
         "birthday": "birthday"
     }
     assert generic_dao.return_class == TestEntity
 def generic_dao_with_child(self, mysql_mock):
     generic_dao = GenericSQLDAO(table="test_table",
                                 prefix='',
                                 return_class=TestEntityWithChild)
     return generic_dao
Beispiel #21
0
def probe(dao: GenericSQLDAO = None):
    total, _ = dao.get_all(length=1, offset=0, filters=None)
    return success_response(message="API Ready", data={"available": total})
 def generic_dao_with_child(self, postgres_mock):
     generic_dao = GenericSQLDAO(database_type=postgres_mock,
                                 table="test_table",
                                 prefix='',
                                 return_class=TestEntityWithChild)
     return generic_dao
def view_hospitais(page: int):
    dao = None
    try:
        dao = GenericSQLDAO(database_type=PostgreSQLHelper)
        dao.database.query("SELECT * "
                           "FROM hospitais_view LIMIT %s OFFSET %s",
                           (itens_per_page, page*itens_per_page)
                           )
        results = dao.database.get_results()
        dao.database.query("SELECT COUNT(*) "
                           "FROM hospitais_view"
                           )
        total = dao.database.get_results()[0][0]
        pages = (total - 1) // itens_per_page
        if pages < 0:
            pages = 0
        if page > pages:
            system("clear")
            print(f"{bcolors.WARNING}A página {page} não está disponível,"
                  f" mostrando a última página disponível.{bcolors.ENDC}")
            return pages
        print(f"{bcolors.OKBLUE}{bcolors.BOLD}"
              f"Hospital"
              f"{bcolors.ENDC}\n")
        print(f"{bcolors.OKCYAN}"
              f"|{'Nome':^30}|{'Internações':^20}|{'Médicos':^20}|{'Relação I/M':^20}|"
              f"{bcolors.ENDC}")
        for result in results:
            print(f"|{result[0]:^30}|"
                  f"{result[1] if result[1] else 0:^20}"
                  f"|{result[2] if result[2] else 0:^20}"
                  f"|{result[3] if result [3] else 0:^20.2f}|")
        for i in range(itens_per_page - len(results)):
            print(f"|{'-':^30}|{'-':^20}"
                  f"|{'-':^20}"
                  f"|{'-':^20}|")
        print("\n\t  ", end="")
        for i in range(pages + 1):
            print(i, end=' ')
        print("\n", "\t", " " * page * 2, '^')
        print("Pressione <- ou -> para navegar entre as páginas")
        print("Pressione x para sair da listagem")
        option = ''
        while option != 'x':
            option = getch()
            if option == '[':
                option = getch()
                if option == "C":
                    system("clear")
                    return page + 1 if page + 1 <= pages else page
                if option == "D":
                    system("clear")
                    return page - 1 if page > 0 else page
        system("clear")
        return option
    except Exception as e:
        system("clear")
        print(f"{bcolors.FAIL}Não foi possível listar os hospitais... "
              f"Tente novamente. {e}{bcolors.ENDC}")
        input()
    finally:
        if dao:
            dao.close()
    return page
Beispiel #24
0
def probe(id_: str = None, dao: GenericSQLDAO = None):
    total, results = dao.get_all(length=1, offset=0, filters={"contact": id_})
    return success_response(message="API Ready",
                            data={"available": total})
def view_relatorio_diagnostico_internacoes(page: int):
    dao = None
    try:
        dao = GenericSQLDAO(database_type=PostgreSQLHelper)
        system("clear")
        dao.database.query(
            "SELECT * "
            "FROM internacoes_diagnostico "
            "LIMIT %s OFFSET %s;", (itens_per_page, (page * itens_per_page)))
        results = dao.database.get_results()
        dao.database.query("SELECT COUNT(usuario_id_) "
                           "FROM internacoes_diagnostico;")
        total = dao.database.get_results()[0][0]
        pages = (total - 1) // itens_per_page
        if pages < 0:
            pages = 0
        if page > pages:
            system("clear")
            print(f"{bcolors.WARNING}A página {page} não está disponível,"
                  f" mostrando a última página disponível.{bcolors.ENDC}")
            return pages
        print(f"{bcolors.OKBLUE}{bcolors.BOLD}"
              f"Internações:"
              f"{bcolors.ENDC}\n")
        print(f"{bcolors.OKCYAN}"
              f"|{'Usuário':^34}|{'Dt. Sint.':^10}|{'Dt. Exame':^10}"
              f"|{'Internação':^10}|{'Hospital':^20}|{'UTI':^3}"
              f"|{'Data Alta':^10}|{'Dt. Recu.':^10}|"
              f"{bcolors.ENDC}")
        for result in results:
            print(
                f"|{result[0]:^34}"
                f"|{result[1].strftime(datetime_format):^10}"
                f"|{result[2].strftime(datetime_format):^10}"
                f"|{result[3].strftime(datetime_format) if result[3] else '-':^10}"
                f"|{result[4] if result[4] else '-':^20}"
                f"|{'s' if result[5] is True else 'n':^3}"
                f"|{result[6].strftime(datetime_format) if result[6] else '-':^10}"
                f"|{result[7].strftime(datetime_format) if result[7] else '-':^10}|"
            )
        for i in range(itens_per_page - len(results)):
            print(f"|{'-':^34}"
                  f"|{'-':^10}"
                  f"|{'-':^10}"
                  f"|{'-':^10}"
                  f"|{'-':^20}"
                  f"|{'-':^3}"
                  f"|{'-':^10}"
                  f"|{'-':^10}|")
        print("\n\t  ", end="")
        for i in range(pages + 1):
            print(i, end=' ')
        print("\n", "\t", " " * page * 2, '^')
        print("Pressione <- ou -> para navegar entre os locais")
        print("Pressione s para confirmar a seleção de um local")
        print("Pressione x para cancelar e sair da listagem")
        option = ''
        while option != 'x':
            option = getch()
            if option == '[':
                option = getch()
                if option == "C":
                    system("clear")
                    return page + 1 if page + 1 <= pages else page
                if option == "D":
                    system("clear")
                    return page - 1 if page > 0 else page
        system("clear")
        return option
    except Exception as e:
        system("clear")
        print(f"{bcolors.FAIL}Não foi possível listar as notificações... "
              f"Tente novamente. {e}{bcolors.ENDC}")
        input()
    finally:
        if dao:
            dao.close()
    return page