def test_first_save_registers_purchase(): for account in Account.get_many(): account.delete() for article in Article.get_many(): article.delete() for purchase in Purchase.get_many(): purchase.delete() score = random.randint(0, 100) purchaser_id = Account({ 'user_id': user_id, 'email': fake.email(), 'name': fake.sentence(), 'score': score }).save() article_id = Article({ 'name': fake.word(), 'description': fake.sentence(), 'available_units': fake.pyint(), 'price': 20.0, 'latitude': 0.0, 'longitude': 0.0, 'user': '******', }).save() purchase_id = Purchase({ 'user_id': purchaser_id, 'article_id': article_id, 'units': 1 }).save() assert Account.get_one(purchaser_id).score() == score + 5 Purchase.get_one(purchase_id).save() assert Account.get_one(purchaser_id).score() == score + 5
def test_first_save_registers_publication(): for account in Account.get_many(): account.delete() for article in Article.get_many(): article.delete() user_id = 'user_id' score = random.randint(0, 100) account_id = Account({ 'user_id': user_id, 'email': fake.email(), 'name': fake.sentence(), 'score': score }).save() article_id = Article({ 'name': fake.word(), 'description': fake.sentence(), 'available_units': fake.pyint(), 'price': 20.0, 'latitude': 0.0, 'longitude': 0.0, 'user': user_id, }).save() assert Account.get_one(account_id).score() == score + 1 Article.get_one(article_id).save() assert Account.get_one(account_id).score() == score + 1
def account(extra_attrs: dict = None) -> Account: attrs = { 'user_id': fake.word(), 'email': fake.email(), 'name': fake.sentence() } if extra_attrs is not None: attrs = {**attrs, **extra_attrs} _id = Account(attrs).save() return Account.get_one(_id)
def shipment_cost(article: Article, lat: float, lon: float, payment_method: str): account = Account.current() now = datetime.now() return request('POST', 'shipment-cost', json={ 'antiquity': account.antiquity(), 'email': account['email'], 'userScore': account.score(), 'paymentMethod': payment_method, 'distance': haversine((lat, lon), (article['latitude'], article['longitude'])), 'latitude': lat, 'longitude': lon, 'tripDate': now.strftime('%Y/%m/%d'), 'tripTime': now.strftime('%H:%M') })
def create_question(_id): try: article = Article.get_one(_id) except ValueError as e: return response(message=str(e), ok=False), 400 if not article: return response(message=f"Article {_id} not found", ok=False), 400 account = Account.current() resp, status_code = create(Question, additional_fields={ 'created_at': datetime.utcnow(), 'article_id': _id, 'user_id': account.get_id() }) if status_code == 200: question = Question.get_one(resp.json['_id']) FirebaseMessage( { 'title': f'Nueva pregunta de {account["name"]}', 'message': f'{question["question"]}', 'question': question.get_id(), 'type': 'new_question' }, to=article.account()).send() return resp, status_code
def get_purchases(): return jsonify({ 'data': add_payment_and_shipment_status( Purchase.get_for_user(Account.current())), 'ok': True }), 200
def get_by_owner(self): account = Account.get_one(self.owner) article_ids = [a.get_id() for a in Article.get_many(user=account['user_id'])] questions = [] for article_id in article_ids: questions.extend( Question.get_many(article_id=article_id) ) return self.append_article_to_questions(questions)
def current_account(): account = Account.current() return jsonify({ "ok": True, "data": { **account.to_json(), **{ 'events': [event.to_json() for event in account.events()] } } }), 200
def create(room_id): purchase_id = request.get_json(silent=True).get('purchase_id') account = Account.current() response, status_code = \ utils.create(ChatMessage, additional_fields={'room': room_id, 'name': account['name'], 'sender_user_id': account.get_id()}) if status_code == 200 and purchase_id is not None: send_firebase_message(response.json['_id'], purchase_id) return response, status_code
def patch_question(): resp, status_code = patch(Question) if status_code == 200: question = Question.get_one(resp.json['data']['_id']) article = Article.get_one(question['article_id']) FirebaseMessage( { 'title': f'Nueva respuesta sobre {article["name"]}', 'message': f'{question["answer"]}', 'article_id': question['article_id'], 'type': 'new_answer' }, to=Account.get_one(question['user_id'])).send() return resp, status_code
def update_current_account(): body = request.get_json(silent=True) if not body: return response("Invalid or empty request body", ok=False), 400 account = Account.current() account['email'] = body.get('email') account['name'] = body.get('name') account['profile_picture_url'] = body.get('profile_picture_url') account['instance_id'] = body.get('instance_id') account.save() return response(message="Successfully updated current account!", ok=True)
def answer_question(article_id, question_id): try: article = Article.get_one(article_id) except ValueError as e: return response(message=str(e), ok=False), 400 if not article: return response(message=f"Article {article_id} not found", ok=False), 400 try: question = Question.get_one(question_id) except ValueError as e: return response(message=str(e), ok=False), 400 body = request.get_json(silent=True) if not body: return response("Invalid or empty request body", ok=False), 400 answer = body.get('answer') if not answer: return response("No answer specified", ok=False), 400 answered_at = datetime.utcnow() question.update(**{'answer': answer, 'answered_at': answered_at}) account = Account.current() FirebaseMessage( { 'title': f'Nueva respuesta de {account["name"]}', 'message': f'{question["answer"]}', 'article_id': article_id, 'type': 'new_answer' }, to=Account.get_one(question['user_id'])).send() return jsonify({"ok": True, "data": question.to_json()}), 200
def buy(): body = request.json error_response = check_required_fields(body) if error_response: return error_response article, error_response = get_article(body) if error_response: return error_response account = Account.current() account_id = account.get_id() if user_id() == article['user']: return response("You can't purchase your own article", ok=False), 400 article['available_units'] -= body.get('units') if article['available_units'] < 0: return response("not enough units", ok=False), 400 article.save() resp, status_code = create(Purchase, additional_fields={ 'user_id': account_id, 'requested_shipment': bool(body.get('shipment_address')) }, after_save=after_purchase( body.get('price'), body.get('payment_method'), body.get('shipment_address'))) if status_code == 200: msg = f'Vendiste {body.get("units")} de ' \ f'{article["name"]} a {account["name"]})' FirebaseMessage( { 'title': "Artículo vendido", "message": msg, "type": "product_sold", }, to=Purchase.get_one(resp.json['_id']).seller()).send() return resp, status_code
def create(self, username, password): account = self.session.query(Account).filter( Account.username == username).first() if account: raise AccountAlreadyExistsError() hashed = base64.b64encode(hashlib.sha256(password.encode()).digest()) account = Account(username=username, password_hash=bcrypt.hashpw(hashed, bcrypt.gensalt()), logged_in=False) self.session.add(account) try: self.session.flush() except IntegrityError: self.session.rollback() raise AccountAlreadyExistsError()
def send_firebase_message(message_id, purchase_id): # ☢️☢️☢️☢️☢️ # Sends a firebase message, to the inferred recipient message = ChatMessage.get_one(message_id) sender_id = message['sender_user_id'] purchase = Purchase.get_one(purchase_id) seller = purchase.seller() buyer = Account.get_one(purchase['user_id']) if sender_id == seller.get_id(): sender = seller recipient = buyer else: sender = buyer recipient = seller FirebaseMessage(message_data={ 'title': sender['name'], 'message': message['text'], 'purchase_id': purchase_id, "type": "chat" }, to=recipient).send()
def get_or_create_account(claims): if Account.get_many(user_id=claims['user_id']): return default_attrs = ['user_id', 'email', 'name'] Account({attr: claims[attr] for attr in default_attrs}).save()
def get_for_user(cls, user: Account): user_id = user.get_id() purchases = cls.get_many(user_id=user_id) return cls.expand(purchases)
def purchaser(self) -> Optional[Account]: return Account.get_one(self['user_id'])
def account(self) -> Optional[Account]: accounts = Account.get_many(user_id=self['user']) return accounts[0] if accounts else None
def test_register_sale(): _account = account({'score': random.randint(0, 100)}) previous_score = _account.score() _account.register('sale', 'article_name') assert Account.get_one(_account.get_id()).score() == previous_score + 10