class OfficeControllerById(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self, office_id): dic = {"data": self.interface.getData("offices", office_id)} data = json.dumps(dic) data_json = json.loads(data) return data_json def delete(self, office_id): self.interface.deleteData("offices", office_id) def put(self, office_id): http_return_code = 201 result = request.get_json() try: Office(result) self.interface.addData(result, "offices", office_id) except Exception as e: http_return_code = 400 result = str(e) return result, http_return_code
class UsersControllerById(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self, user_mail): dic = {"data": self.interface.getData("users", user_mail)} data = json.dumps(dic) data_json = json.loads(data) return data_json def delete(self, user_mail): self.interface.deleteData("users", user_mail) def put(self, user_mail): result = request.get_json() http_return_code = 200 try: User(result) self.interface.addData(result, "users", user_mail) except Exception as e: http_return_code = 400 result = str(e) return result, http_return_code
def buildObject(self, req): interface = FirebaseInterface() user_id = req["id_usuario"] self.mecanico = interface.getData("users", user_id) truck_board = req["placa_caminhao"] self.caminhao = interface.getDataByField("trucks", "placa", truck_board) self.data = req["data"] self.titulo = req["titulo"]
class TrucksController(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self): dic = {"data": self.interface.getData("trucks")} data = json.dumps(dic) data_json = json.loads(data) return data_json def post(self): result = request.get_json() self.interface.addData(result, "trucks", None)
def __init__(self, dict_office_data): self.interface = FirebaseInterface() self.office_keys = { 'cpf': False, 'endereco': { 'CEP': False, 'bairro': False, 'cidade': False, 'complemento': False, 'estado': False, 'numero': False, 'pais': False, 'rua': False }, 'nome': False, 'telefone': False } self.validateOfficeData(dict_office_data)
def __init__(self, dict_user_data): self.interface = FirebaseInterface() self.user_keys = { 'cargo': False, 'cpf': False, 'ddn': False, 'dependentes': False, 'email': False, 'endereco': False, 'nome': False, 'nomemae': False, 'nomepai': False, 'ocorrencias': False, 'senha': False, 'sexo': False, 'tipocnh': False, 'status': False } self.validateUserData(dict_user_data)
class UsersControllerByRegion(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self, region): dic = {"data": self.interface.getDataByField("users", "pais", region)} data = json.dumps(dic) data_json = json.loads(data) return data_json
class OfficeControllerByUser(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self, cpf): dic = {"data": self.interface.getDataByField("offices", "cpf", cpf)} data = json.dumps(dic) data_json = json.loads(data) return data_json
class UsersControllerByJob(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self, job): dic = {"data": self.interface.getDataByField("users", "cargo", job)} data = json.dumps(dic) data_json = json.loads(data) http_return_code = 200 return data_json, http_return_code
class OfficesController(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self): dic = {"data": self.interface.getData("offices")} data = json.dumps(dic) data_json = json.loads(data) return data_json def post(self): http_return_code = 201 result = request.get_json() try: Office(result) result["agenda"] = [] self.interface.addData(result, "offices", None) except Exception as e: http_return_code = 400 result = str(e) return result, http_return_code
class UsersController(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self): dic = {"data": self.interface.getData("users")} data = json.dumps(dic) data_json = json.loads(data) return data_json def post(self): http_return_code = 201 result = request.get_json() try: User(result) self.interface.addData(result, "users", result["email"]) except Exception as e: http_return_code = 400 result = str(e) return result, http_return_code def put(self): http_return_code = 200 result = request.get_json() cpf = result["cpf"] status = result["status"] try: user = self.interface.getDataByField("users", "cpf", cpf) if user: user[0]["status"] = status self.interface.updateData(user[0], "users", user[0]["id"]) result = "Status atualizado com sucesso" else: result = "Usuario não encontrado" http_return_code = 400 except Exception as e: http_return_code = 400 result = str(e) return result, http_return_code
class User: def __init__(self, dict_user_data): self.interface = FirebaseInterface() self.user_keys = { 'cargo': False, 'cpf': False, 'ddn': False, 'dependentes': False, 'email': False, 'endereco': False, 'nome': False, 'nomemae': False, 'nomepai': False, 'ocorrencias': False, 'senha': False, 'sexo': False, 'tipocnh': False, 'status': False } self.validateUserData(dict_user_data) def validateUserData(self, dict_user_data): for key, value in dict_user_data.items(): if key in self.user_keys: self.user_keys[key] = True else: raise Exception( 'Usuario possui um campo inválido: {}'.format(key)) not_found_values = [] for key, value in self.user_keys.items(): if not value: not_found_values.append(key) if len(not_found_values) > 0: raise Exception( 'Usuario deve conter os campos: {}'.format(not_found_values)) self.validateCargo(dict_user_data['cargo']) self.validateCPF(dict_user_data['cpf']) self.validateName(dict_user_data['nomemae']) self.validateDDN(dict_user_data['ddn']) self.validateFathersName(dict_user_data['nomepai']) self.validateName(dict_user_data['nome']) self.validateGenre(dict_user_data['sexo']) self.vallidateAddress(dict_user_data['endereco']) self.vallidateStatus(dict_user_data['status']) def validateCargo(self, cargo): firebase_jobs = self.interface.getData('const_data', 'jobs') if not cargo in firebase_jobs['available']: raise Exception('Cargo do usuario inválido: {}'.format(cargo)) def validateCPF(self, cpf): if not cpfcnpj.validate(cpf): raise Exception('CPF inválido') def validateName(self, name): if not re.search("^[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ]+$", name): raise Exception('Nome {} é inválido'.format(name)) def validateDDN(self, ddn): try: date = datetime.datetime.strptime(ddn, '%d/%m/%Y') if (date.year > 2000 or date.year < 1919): raise Exception except: raise Exception('Data de nascimento invalida') def validateFathersName(self, fathersName): if fathersName and not re.search( "^[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ]+$", fathersName): raise Exception('Nome do pai inválido') def validateGenre(self, genre): if genre != 'm' and genre != 'f': raise Exception('Sexo do usuario inválido') def vallidateAddress(self, address): if not address: raise Exception('Endereco inválido') def vallidateStatus(self, status): if status is not True and status is not False: raise Exception('Status inválido')
def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() self.schedule = Schedule()
class SchedulesController(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() self.schedule = Schedule() def post(self): req = request.get_json() try: office_id = req["id_oficina"] office = self.interface.getData("offices", office_id) if office is None: raise Exception("Oficina não encontrada") self.schedule.buildObject(req) self.schedule.validateFields(office["agenda"]) self.schedule.setId() office["agenda"].append(self.schedule.__dict__) self.interface.updateData(office, "offices", office["id"]) result = "Evento criado com sucesso" http_return_code = 201 except Exception as e: http_return_code = 400 result = str(e) return result, http_return_code def delete(self, office_id, event_id): try: office = self.interface.getData("offices", office_id) if office is None: raise Exception("Oficina não encontrada") index = self.schedule.findIdIndex(int(event_id), office["agenda"]) office["agenda"].pop(index) self.interface.updateData(office, "offices", office_id) result = "Evento removido com sucesso" http_return_code = 200 except Exception as e: http_return_code = 400 result = str(e) return result, http_return_code def get(self, office_id): try: office = self.interface.getData("offices", office_id) if office is None: raise Exception("Oficina não encontrada") schedule = {"data": office["agenda"]} data = json.dumps(schedule) result = json.loads(data) http_return_code = 200 except Exception as e: result = str(e) http_return_code = 400 return result, http_return_code def put(self): req = request.get_json() try: office_id = req["id_oficina"] office = self.interface.getData("offices", office_id) if office is None: raise Exception("Oficina não encontrada") self.schedule.buildObject(req) self.schedule.validateFields(office["agenda"]) id = req["id_evento"] index = self.schedule.findIdIndex(id, office["agenda"]) self.schedule.id = id office["agenda"][index] = self.schedule.__dict__ self.interface.updateData(office, "offices", office_id) result = "Evento alterado com sucesso" http_return_code = 200 except Exception as e: result = str(e) http_return_code = 400 return result, http_return_code
class Office: def __init__(self, dict_office_data): self.interface = FirebaseInterface() self.office_keys = { 'cpf': False, 'endereco': { 'CEP': False, 'bairro': False, 'cidade': False, 'complemento': False, 'estado': False, 'numero': False, 'pais': False, 'rua': False }, 'nome': False, 'telefone': False } self.validateOfficeData(dict_office_data) def validateOfficeData(self, dict_office_data): for key, value in dict_office_data.items(): if key in self.office_keys: self.office_keys[key] = True else: raise Exception( 'Oficina possui um campo inválido: {}'.format(key)) not_found_values = [] for key, value in self.office_keys.items(): if not value: not_found_values.append(key) if len(not_found_values) > 0: raise Exception( 'Usuario deve conter os campos: {}'.format(not_found_values)) self.validateCPF(dict_office_data['cpf']) self.validateTel(dict_office_data['telefone']) self.validateCep(dict_office_data['endereco']['CEP']) self.validateName(dict_office_data['endereco']['bairro']) self.validateName(dict_office_data['endereco']['cidade']) self.validateName(dict_office_data['endereco']['estado']) self.validateNumber(dict_office_data['endereco']['numero']) self.validatePais(dict_office_data['endereco']['pais']) self.validateName(dict_office_data['endereco']['rua']) def validateCPF(self, cpf): if not cpfcnpj.validate(cpf): raise Exception('CPF inválido') else: allow = ["supervisor", "gerente", "diretor"] user = self.interface.getDataByField('users', 'cpf', cpf) if not user: raise Exception('Não foi encontrado usuário com esse cpf') print (user) c = 0 for a in allow: if a in str(user): c += 1 if c == 0: raise Exception('Esse usuário não tem permissão') def validateName(self, name): if not re.search("^[A-Za-záàâãéèêíïóôõöúçñÁÀÂÃÉÈÍÏÓÔÕÖÚÇÑ ]+$", name): raise Exception('Campo {} é inválido'.format(name)) def validateNumber(self, num): if not re.search("\d+", num): raise Exception('Número inválido'.format(num)) def validateTel(self, tel): if not re.search("(\(?\d{2}\)?\s?)(\d{4,5}\-?\d{4})", tel): raise Exception('Telefone inválido'.format(tel)) def validateCep(self, cep): if not re.search("\d{5}-\d{3}", cep): raise Exception('CEP inválido'.format(cep)) def validatePais(self, pais): list_paises = self.interface.getData('const_data', 'countries') if pais not in list_paises['available']: raise Exception('País inválido {}'.format(pais))
class ServicesController(Resource): def __init__(self): self.parser = reqparse.RequestParser() self.interface = FirebaseInterface() def get(self): try: dic = {"data": self.interface.getData("services")} data = json.dumps(dic) result = json.loads(data) http_return_code = 200 except Exception as e: result = str(e) http_return_code = 400 return result, http_return_code def post(self): req = request.get_json() try: name = req["nome"] price = req["preco"] service = Service(name, price) service.validateFields() self.interface.setData(service.__dict__, "services", name) result = "Serviço cadastrado com sucesso" http_return_code = 200 except Exception as e: result = str(e) http_return_code = 400 return result, http_return_code def delete(self, service): try: self.interface.deleteData("services", service) result = "Serviço removido com sucesso" http_return_code = 200 except Exception as e: result = str(e) http_return_code = 400 return result, http_return_code def put(self): req = request.get_json() try: name = req["nome"] price = req["preco"] service = Service(name, price) service.validateFields() self.interface.updateData(service.__dict__, "services", name) result = "Serviço alterado com sucesso" http_return_code = 200 except Exception as e: result = str(e) http_return_code = 400 return result, http_return_code
def setId(self): interface = FirebaseInterface() event_id = interface.getData("const_data", "office_id") self.id = event_id["id"] + 1 interface.updateData({"id": event_id["id"] + 1}, "const_data", "office_id")