def forgot_password_client(): if session.get('id', '') != '': if not Business.check_confirmed(session.get('id', '')): session['id'] = '' return redirect(url_for('business.business_card', business_id=session.get('id', ''))) session['id_client'] = '' form = ForgotPasswordForm() if form.validate_on_submit(): if Process.query.filter_by(number=form.number.data).first(): client_password = Client.random_password(10) rows = Process.query.filter_by(id=Process.get_id(form.number.data)).update( {'password': generate_password_hash(client_password)}) db.session.commit() Business.send_password_client(Client.get_email(Process.get_client_id(Process.get_id(form.number.data))), form.number.data, client_password) return redirect( "/business/feedback/Мы отправили вам новый пароль на почту! Если вы не получили письмо, \ проверьте, что вы написали номер правильно!") else: form.number.errors = ('Неправильный номер', '') return render_template('forgot_password_client.html', title='Забыли пароль?', form=form)
class TestBusiness(unittest.TestCase): def setUp(self): """create new instance of business""" self.business = Business("pakjel", "local supermarket", "landless", "0702848032") def test_initilize_business(self): self.assertEqual(self.business.name, "pakjel") def test_save_adds_business_to_list(self): self.business.save_business(self.business.name, self.business.description, self.business.location, self.business.contact) self.assertTrue(len(Business.business_list) > 0) def test_find_business_by_id(self): self.business.save_business(self.business.name, self.business.description, self.business.location, self.business.contact) found_business = Business.find_business_id(self.business.id) self.assertEqual(found_business[0]["name"], self.business.name) def tearDown(self): """clears list after every test""" Business.business_list = []
def post(self): """Endpoint to save the data to the database""" data = request.get_json() name = data.get('name') description = data.get('description') category = data.get('category') location = data.get('location') user_id = get_jwt_identity() data = dict(name=name, description=description, category=category, location=location) if check_missing_field(**data): return jsonify(check_missing_field(**data)), 422 user = User.query.filter_by(id=user_id).first() name = remove_more_spaces(name) description = remove_more_spaces(description) if not user: return self.generate_response(messages['valid_login'], 403) business = Business(name, description, category, location, user_id) business.save() return self.generate_response(messages['business_created'], 201)
def create_business(): '''register a business''' current_user = get_jwt_identity() bizdata = request.get_json() new_business = Business( bizdata["bizname"], bizdata["bizlocation"], bizdata["bizcategory"], current_user ) new_business.save() # this displays the created business layout business_info[new_business.id]={ "bizID": new_business.id, "bizname": new_business.bizname, "bizlocation":new_business.bizlocation, "bizcategory": new_business.bizcategory, "owner": current_user } response = {"message": "you have registered a business", "business": business_info[new_business.id] } return make_response(jsonify(response),201)
def test_func_save(self): business = Business(name='name', password='******', email='email', confirmed=True) business.save() committed_business = Business.query.get(business.id) self.assertEqual(business, committed_business)
def test_func_get_email(self): business = Business(name='name', password='******', email='email', confirmed=True) db.session.add(business) db.session.commit() self.assertEqual(business.email, Business.get_email(business.id))
def registerBusiness(): """ This is to register a business""" current_user = get_jwt_identity() if request.method == 'POST': # Check for blank key try: required_fields = ['name', 'description', 'category', 'location'] data = check_blank_key(request.get_json(), required_fields) except AssertionError as err: msg = err.args[0] return jsonify({"message": msg}), 422 # Check if user entered a name and location name = validate_buss_data_null(data['name']) description = validate_buss_data_null(data['description']) location = validate_buss_data_null(data['location']) category = validate_buss_data_null(data['category']) if not location or not description or not name: return jsonify( {'message': 'You need a business name' + ' and location to Register'}), 403 # Check if business is registered exist_business = Business.query.filter_by(name=name).first() if exist_business: return jsonify( {'message': 'This Business is already registered'}), 409 new_business = Business( name=name, description=description, category=category, location=location, user_id=current_user) new_business.save() current_business = Business.query.filter_by( name=name).first() new_business_id = current_business.id new_business_name = current_business.name return jsonify( {'message': 'New business has been created', 'businesses ID': new_business_id, 'business name': new_business_name }), 201 # Get all businesses all_businesses = Business.get_all(Business) def func(business): return business.accesible() all_businesses = map(func, all_businesses) data = list(all_businesses) if data == []: return jsonify({'message': 'No businesses available', }), 200 return jsonify({'message': 'These are the businesses', 'businesses': data }), 200
def test_func_email_is_free(self): business = Business(name='name', password='******', email='email', confirmed=True) business.registered_on -= timedelta(days=32) db.session.add(business) db.session.commit() self.assertTrue(Business.email_is_free('email1')) self.assertFalse(Business.email_is_free('email'))
def registration_business(): if session.get('id', '') != '': if not Business.check_confirmed(session.get('id', '')): session['id'] = '' return redirect(url_for('business.business_card', business_id=session.get('id', ''))) session['id_client'] = '' form = RegistrationBusinessForm(csrf_enabled=False) if form.validate_on_submit(): free_name = Business.name_is_free(form.name.data) free_email = Business.email_is_free(form.email.data) check_pass = (form.password.data == form.check_password.data) password_is_valid = Business.password_is_valid(form.password.data) if free_name and check_pass and password_is_valid and free_email: Business.send_token(form.email.data) business = Business(name=form.name.data, password=form.password.data, email=form.email.data, confirmed=False) Business.save(business) return redirect( "/business/feedback/Регистрация прошла успешно. Пройдите по ссылке, \ которую мы отправили вам на почту, чтобы подтвердить её") elif not free_name: form.name.errors = ('Название занято', '') elif not free_email: form.email.errors = ('Почта занята', '') elif not password_is_valid: form.check_password.errors = ('Пароль не может содержать пробелы', '') elif not check_pass: form.check_password.errors = ('Пароли не совпадают', '') return render_template('registration_business.html', title='Регистрация бизнеса', form=form)
def possible_process_list(): if session.get('id', '') == '': return redirect('/business') elif not Business.check_confirmed(session.get('id', '')): return redirect('/business/unconfirmed') form = FindForm() possible_process_list = Business.get_possible_processes(session['id']) if form.validate_on_submit(): possible_process_list = PossibleProcess.find(form.words.data, session['id']) if possible_process_list[0] == 0: form.words.errors = ("Ничего не найдено", "") return render_template('possible_process_list.html', possible_process_list=possible_process_list[::-1], title='Список возможных услуг', form=form)
def reviews(current_user, id): """ route allows user review a a business """ if request.method == 'POST': ''' Reviewing a business ''' data = request.get_json() is_valid_review = re.match('^[A-Za-z]+[A-Za-z0-9 ]{,200}$', data['review']) #if the data passes our validity check if not is_valid_review: return jsonify({ 'Status': 'Failed', 'Message': 'Only characters and not beyond 200 charaters!' }), 403 business = Business.get_business(id) if business is None: return jsonify({ 'Status': 'Failed', 'Message': 'Business not registered here!' }), 404 new_review = Review(review=data['review'], business_id=id) db.session.add(new_review) db.session.commit() return jsonify({ 'Status': 'Success', 'Message': 'Review has been successfully added!' }), 201 elif request.method == 'GET': ''' Get request ''' reviews = Review.query.filter_by(business_id=id).all() author = User.query.filter_by(id=current_user).first() business = Business.get_business(id) review_list = [] for review in reviews: review_info = {} review_info['review'] = review.review review_info['business_name'] = business.business_name review_info['reviewed_on'] = review.reviewed_on review_info['review_author'] = author.username review_list.append(review_info) return jsonify({'Status': 'Success', 'Review': review_list}), 200
def created_process(process_id): if session.get('id', '') == '': return redirect('/business/') elif not Process.is_real(process_id): return redirect('/business/created_process_list') elif Process.get_business(process_id) != session.get('id', ''): return redirect('/business/created_process_list') elif not Business.check_confirmed(session.get('id', '')): return redirect('/business/unconfirmed') form = ChangeForm() s_form = SelectFieldStageForm() d_form = DateForm() if form.validate_on_submit() and d_form.validate_on_submit(): if int(Process.get_stages(process_id)) != int(s_form.select_stage.data): Business.send_stages(Client.get_email(Process.get_client_id(process_id)), s_form.select_stage.data, Business.get_name(session.get('id', '')), Process.get_number(process_id), PossibleProcess.get_type(Process.get_type_id(process_id))) rows = Process.query.filter_by(id=process_id).update({'desc': form.desc.data}) rows = Process.query.filter_by(id=process_id).update({'current_stage': s_form.select_stage.data}) rows = Process.query.filter_by(id=process_id).update({'data': d_form.dt.data}) rows = Process.query.filter_by(id=process_id).update({'percent': round(form.percent.data)}) rows = Process.query.filter_by(id=process_id).update({'price': form.price.data}) db.session.commit() return redirect('/business/created_process_list') number = Process.get_number(process_id) client = Client.get_email(Process.get_client_id(process_id)) type = PossibleProcess.get_type(Process.get_type_id(process_id)) form.desc.data = Process.get_desc(process_id) percent = Process.get_percent(process_id) form.percent.data = percent form.price.data = Process.get_price(process_id) s_form.select_stage.choices = [(s.id, s.type) for s in Stage.sort_by_id_for_business(Process.get_type_id(process_id))] s_form.select_stage.default = Process.get_stages(process_id) s_form.process() d_form.dt.data = Process.get_data(process_id) desc_type = PossibleProcess.get_desc(Process.get_type_id(process_id)) star = Process.get_star(process_id) chat = Chat.get_by_proc(process_id).id picture = PossibleProcess.get_picture(Process.get_type_id(process_id)) is_picture = (PossibleProcess.get_picture(Process.get_type_id(process_id)) != "-1") return render_template('created_process.html', title='Созданная услуга', desc_type=desc_type, percent=percent, d_form=d_form, id=process_id, form=form, s_form=s_form, number=number, type=type, client=client, Process=Process, chat=chat, rating=star, picture=picture, is_picture=is_picture)
def unconfirmed(): if session.get('id', '') == '': return redirect('/business') elif Business.check_confirmed(session.get('id', '')): return redirect(url_for('business.business_card', business_id=session.get('id', ''))) form = UnconfirmedForm() id = session.get('id', '') if request.method == 'POST': Business.send_token(Business.get_email(id)) session['id'] = '' return redirect( "/business/feedback/Пройдите по ссылке, \ которую мы отправили вам на почту, чтобы подтвердить её") return render_template('unconfirmed.html', title="Аккаунт не подтвержден", form=form)
def test_func_it_works(self): business1 = Business(name='name', password='******', email='email', confirmed=True) business2 = Business(name='name', password='******', email='email', confirmed=True) business2.registered_on -= timedelta(days=32) business3 = Business(name='name', password='******', email='email', confirmed=False) business3.registered_on -= timedelta(days=32) business4 = Business(name='name', password='******', email='email', confirmed=False) db.session.add(business1) db.session.add(business2) db.session.add(business3) db.session.add(business4) db.session.commit() self.assertTrue(Business.it_works(business1.id)) self.assertTrue(Business.it_works(business2.id)) self.assertFalse(Business.it_works(business3.id)) self.assertTrue(Business.it_works(business4.id))
def change_business(): if session.get('id', '') == '': return redirect('/business') if not Business.check_confirmed(session.get('id', '')): return redirect('/business/unconfirmed') changename = "" changepassword = "" form_name = ChangeBusinessNameForm() form_password = ChangeBusinessPasswordForm() id = session.get('id', '') if form_name.submit1.data and form_name.validate_on_submit(): free_name = Business.name_is_free(form_name.new_name.data) b_password = Business.query.filter_by(id=id).first().password b_name = Business.get_name(id) if free_name or b_name == form_name.new_name.data \ and check_password_hash(b_password, form_name.password.data): rows = Business.query.filter_by(id=id).update({'name': form_name.new_name.data}) db.session.commit() if BusinessCard.is_real(session.get('id', '')): rows = BusinessCard.query.filter_by(business_id=session.get('id', '')).update( {'name': form_name.new_name.data}) db.session.commit() changename = "Название было изменено" # return redirect('/change_business') elif not free_name and form_name.new_name.data != b_name: form_name.new_name.errors = ('Название занято', '') elif not check_password_hash(b_password, form_name.password.data): form_name.password.errors = ('Неправильный пароль', '') if form_password.submit2.data and form_password.validate_on_submit(): b_password = Business.query.filter_by(id=id).first().password check_new = form_password.new_password.data == form_password.check_new_password.data check_old = check_password_hash(b_password, form_password.old_password.data) password_is_valid = Business.password_is_valid(form_password.new_password.data) if check_old and check_new and password_is_valid: new_password = generate_password_hash(form_password.new_password.data) rows = Business.query.filter_by(id=id).update({'password': new_password}) db.session.commit() changepassword = "******" # return redirect('/change_business') elif not password_is_valid: form_password.new_password.errors = ('Пароль не может содержать пробелы', '') elif not check_new: form_password.check_new_password.errors = ('Пароли не совпадают', '') elif not check_old: form_password.old_password.errors = ('Неправильный пароль', '') form_name.new_name.data = Business.query.filter_by(id=id).first().name return render_template('change_business.html', title='Изменить настройки бизнеса', form=form_name, p_form=form_password, changename=changename, changepassword=changepassword)
def test_func_get_all(self): business1 = Business(name='name', password='******', email='email', confirmed=True) business2 = Business(name='name2', password='******', email='email2', confirmed=False) db.session.add(business1) db.session.add(business2) db.session.commit() businesses = Business.get_all() self.assertEqual(businesses[0], business1) self.assertEqual(businesses[1], business2)
def test_func_account_is_old(self): business1 = Business(name='name', password='******', email='email', confirmed=True) business2 = Business(name='name', password='******', email='email', confirmed=True) business2.registered_on -= timedelta(days=32) db.session.add(business1) db.session.add(business2) db.session.commit() self.assertFalse(Business.account_is_old(business1.id)) self.assertTrue(business2.id)
def test_func_check_confirmed(self): business = Business(name='name', password='******', email='email', confirmed=True) db.session.add(business) db.session.commit() self.assertTrue(Business.check_confirmed(business.id)) next_business = Business(name='name', password='******', email='email', confirmed=False) db.session.add(next_business) db.session.commit() self.assertFalse(Business.check_confirmed(next_business.id))
def one_business(business_id): current_user = get_jwt_identity() #Current_user is username targetbusiness = Business.get_business(business_id) if request.method == 'GET': return make_response(jsonify(targetbusiness)), 200 elif request.method == 'DELETE': if current_user == targetbusiness['username']: deletebusiness = Business.delete_business(business_id) return make_response(jsonify(deletebusiness)), 200 else: return jsonify( {'message': 'You cannot delete a business that is not yours'})
def editBusiness(business_id): current_user = get_jwt_identity() exist_business = Business.query.filter_by(id=business_id).first() # Check if business exists if not exist_business: return jsonify({'message': 'Bussniess does not exist'}), 404 if request.method == 'GET': business_info = exist_business.accesible() return jsonify({'business': business_info, 'message': 'Here is the searched business' }), 200 if current_user != exist_business.user_id: return jsonify( {'message': 'You can only change your own business'}), 403 elif request.method == 'DELETE': exist_business.delete() return jsonify( {'message': 'Business successfully deleted'}), 202 # Check for blank key try: required_fields = ['name', 'description', 'category', 'location'] data = check_blank_key(request.get_json(), required_fields) except AssertionError as err: msg = err.args[0] return jsonify({"message": msg}), 422 # Check for null user data name = validate_buss_data_null(data['name']) description = validate_buss_data_null(data['description']) location = validate_buss_data_null(data['location']) category = validate_buss_data_null(data['category']) if not name or not description or not location: return jsonify( {'message': 'Business name and Location have to be entred'}), 403 exist_name_business = Business.query.filter_by(name=name).first() if exist_name_business: return jsonify( {'message': 'This Business is name is already used'}), 409 Business.update(Business, business_id, name=name, description=description, location=location, category=category, user_id=current_user) display_business = Business.query.filter_by(name=name).first() info = display_business.accesible() return jsonify({'Edited business is': info, 'message': 'Business edited successfully' }), 201
def add_review(id): businesses = Business.check_business_exists(id) all_business = [] for business in businesses: obj = { "name": business.name } all_business.append(obj) if not all_business: message = "cannot add review business that does not exist" response = jsonify({"message": message, "status_code": 404}) # 404 if business does not exist response.status_code = 404 return response opinion = str(request.data.get('opinion', '')) rating = int(request.data.get('rating', '')) if rating and opinion: new_review = Review(opinion=opinion, rating=rating, business_main=id) new_review.save() message = "succesfully added the review" response = jsonify({"message": message}) response.status_code = 201 return response message = "make sure the opinion and rating are included" response = jsonify({"message": message, "status_code": 400}) response.status_code = 400 return response
def test_retrieve_a_business(self): # Tests that a business id exists self.setUpBusinessInstance() self.assertIn(self.setUpBusinessInstance().id, known_business_ids) self.assertIs( type(Business.get_business_by_id(self.setUpBusinessInstance().id)), list)
def dashboard(): auth_header = request.headers.get('Authorization') if auth_header: access_token = auth_header.split(" ")[1] # return true if token is valid valid_token = Access_token.query.filter_by(token=access_token).first() if not valid_token: # this user is legit and authorized get the id user_id = User.decode_token(access_token) # use the user id to get businesses owned by the user businesses = Business.get(user_id) final_result = [] for business in businesses: obj = { 'id': business.id, 'name': business.name, 'description': business.description, 'location': business.location, 'contact': business.contact, 'category': business.category } final_result.append(obj) response = jsonify(final_result) response.status_code = 200 return response message = "You must be logged in to access the dashboard" response = jsonify({"message": message, "status": 403}) response.status_code = 403 return response
def createQuery(row): business_id = row.get("business_id") name = row.get("name") neighborhood = row.get("neighborhood") address = row.get("address") city = row.get("city") state = row.get("state") postal_code = row.get("postal_code") latitude = row.get("latitude") longitude = row.get("longitude") stars = row.get("stars") is_open = row.get("is_open") review_count = row.get("review_count") attributes = json.dumps(row.get("attributes")) categories = row.get("categories") hours = json.dumps(row.get("hours")) # queryStr = "INSERT INTO business (business_id, name, neighborhood, address, city, state, postal_code, latitude, longitude, stars, review_count, is_open, attributes, categories, hours) VALUES ('%s', '%s', '%s', '%s', '%s', '%s','%s', %s, %s, %s, %s, %s, '%s', '%s', '%s')" %(business_id, name, neighborhood, address, city, state, postal_code, latitude, longitude, stars, review_count, is_open, attributes, categories, hours) obj = Business(business_id=business_id, name=name, neighborhood=neighborhood, address=address, city=city, state=state, postal_code=postal_code, latitude=latitude, longitude=longitude, stars=stars, is_open=is_open, review_count=review_count, attributes=attributes, categories=categories, hours=hours) print(obj)
def add_review(id): """get the id from the url""" business_found = Business.find_business_id(id) description = str(request.data.get('description', '')) if not business_found: response = jsonify({ "message": "cannot add review to business that does not exist", "status_code": 404 }) response.status_code = 404 return response if description: """create review object""" new_review = Review.save_review(description, id) response = jsonify({"review": new_review, "status_code": 201}) response.status_code = 201 return response else: response = jsonify({ "message": "enter all details", "status_code": 400 }) response.status_code = 400 return response
def confirm_email(token): try: email = Business.confirm_token(token) except: return redirect('/business/feedback/Ссылка не действительна') business = Business.query.filter_by(email=email).first_or_404() if business.confirmed: return redirect('/business/feedback/Аккаунт был подтвержден. Пожалуйста, войдите.') else: if Business.account_is_old(business.id): return redirect('/feedback/Ссылка не действительна! Попробуйте зарегистрироваться еще раз!') business.confirmed = True business.confirmed_on = datetime.now() db.session.add(business) db.session.commit() return redirect('/business/feedback/Аккаунт был подтвержден. Пожалуйста, войдите.')
def get_reviews(id): businesses = Business.check_business_exists(id) all_business = [] for business in businesses: obj = { "name": business.name } all_business.append(obj) if not all_business: message = "cannot get review business that does not exist" response = jsonify({"message": message, "status_code": 404}) # 404 if business does not exist response.status_code = 404 return response reviews = Review.get_business_review(id) all_reviews = [] for review in reviews: obj = { "opinion": review.opinion, "rating": review.rating } all_reviews.append(obj) if not all_reviews: message = "no reviews available" response = jsonify({"message": message, "status_code": 404}) # 404 if business does not exist response.status_code = 404 return response response = jsonify(all_reviews) response.status_code = 200 return response
def post(self): if self.validate_json(): return self.validate_json() data = request.get_json() name = data.get('name') category = data.get('category') location = data.get('location') current_user = get_jwt_identity() data_ = dict(name=name, category=category, location=location) if self.validate_null(**data_): return self.validate_null(**data_) user_ = [user for user in users if current_user == user.email] if not user_: response = {'message': 'Login in to register business'} return jsonify(response), 401 data = self.remove_extra_spaces(**data_) available = [ business for business in store if data['name'] == business.name ] if available: name = data['name'] response = {'message': f'Business with name {name} already exists'} return jsonify(response), 409 business = Business(**data, created_by=current_user) store.append(business) response = {'message': 'Business with name {} created'.format(name)} return jsonify(response), 201
def register_business(): if request.method == 'POST': current_user = get_jwt_identity() biz_data = request.get_json() business_name = biz_data.get('business_name') category = biz_data.get('category') location = biz_data.get('location') description = biz_data.get('description') biz = Business.business.items() existing_business = { k: v for k, v in biz if biz_data['business_name'] in v['business_name'] } if business_name == "": return jsonify( {'message': 'Business name should not be an empty string'}), 406 elif category == "": return jsonify( {'message': 'Category should not be an empty string'}), 406 elif location == "": return jsonify( {'message': 'Location should not be an empty string'}), 406 elif description == "": return jsonify( {'message': 'Description should not be an empty string'}), 406 elif existing_business: return jsonify({"message": "Business name already exists"}) else: new_biz = Business(business_name, category, location, description, current_user) new_biz.register_business() response = { 'message': 'Business Successfully Registered', 'Registered by': current_user } return make_response(jsonify(response)), 201 #If GET method businesses = Business.get_all_businesses() return make_response(jsonify(businesses)), 200
def profile_business(): if session.get('id', '') == '': return redirect('/business') if not Business.check_confirmed(session.get('id', '')): return redirect('/business/unconfirmed') name = Business.query.filter_by(id=session.get('id', '')).first().name email = Business.query.filter_by(id=session.get('id', '')).first().email return render_template('profile_business.html', title='Профиль бизнеса', name=name, email=email)