def get_user_purchases(user, db=None): """ Gets all purchases by user. :param user: User, the user to find purchases for :param db: optional, the database connection """ db = db or get_db() cur = db.cursor() # insert the purchase cur.execute(""" SELECT PurchaseID, TotalPrice, CreditCard, Address FROM Purchase WHERE Username=? """, [user.username]) purchases = [] for row1 in cur.fetchall(): purchase = Purchase(username=user.username, id_=row1[0], total_price=row1[1], credit_card=row1[2], address=Address().from_str(row1[3])) cur.execute(""" SELECT InventoryItemID, Price, Quantity FROM PurchaseItem WHERE PurchaseID=? """, [purchase.id_]) for row2 in cur.fetchall(): item = get_inventory_item(InventoryItem(row2[0]), db) purchase.items.append(ShoppingCartItem(item=item, price=row2[1], qty=row2[2])) purchases.append(purchase) cur.close() return purchases
def create_purchases(self, matched_expenses): purchases = [] for expense_match in matched_expenses: expense_category = self.find_expense_category(expense_match.note) status = PurchaseStatus.closed if expense_category else PurchaseStatus.open epoch = datetime.fromtimestamp(self.message_datetime) purchases.append( Purchase( user_message_id=self.message_id, conversation_id=self.conversation.id, position=expense_match.position, status=status, currency=expense_match.currency, user_id=self.user_id, epoch=epoch, price=expense_match.price, note=expense_match.note, expense=expense_category, )) self.conversation.bot_message_id = self.message_id + len(purchases) + 1 self.session.add_all(purchases) self.session.commit() return purchases
def purchase(request): if "pokemon" in request.GET: pokemon = Pokemon.objects.get(pk=float(request.GET["pokemon"])) if "currently_purchasing" in request.session: purchase = Purchase.objects.get(pk=request.session["currently_purchasing"]) purchase.pokemons.add(pokemon) messages.success(request, "Pokemon añadido correctamente.") return render(request, "index.html", {"pokemons": [pokemon for pokemon in Pokemon.objects.all()]}) else: purchase = Purchase(user=request.user) purchase.save() request.session["currently_purchasing"] = purchase.id purchase.pokemons.add(pokemon) messages.success(request, "Pokemon añadido correctamente.") return render(request, "index.html", {"pokemons": [pokemon for pokemon in Pokemon.objects.all()]}) elif "clean" not in request.GET: if "currently_purchasing" in request.session: purchase = Purchase.objects.get(pk=request.session["currently_purchasing"]) return render(request, "purchase.html", { "purchase_pokemons": purchase.pokemons.all() }) else: return render(request, "purchase.html") if "clean" in request.GET: if "currently_purchasing" in request.session: purchase = Purchase.objects.get(pk=request.session["currently_purchasing"]) purchase.delete() del request.session["currently_purchasing"] messages.success(request, "Pedido borrado correctamente.") return render(request, "index.html", {"pokemons": [pokemon for pokemon in Pokemon.objects.all()]})
def add(): if request.method == 'POST': store_id = request.form['store'] product_id = request.form['product'] price = request.form['price'] has_error = False if db_session.query(Store).filter(Store.id == store_id).count == 0: flash('No such store', 'error') has_error = True if db_session.query(Product).filter( Product.id == product_id).count == 0: flash('No such product', 'error') has_error = True if price is None: flash('Price is not set', 'error') has_error = True if not has_error: db_session.add(Purchase(g.user.id, store_id, product_id, price)) db_session.commit() flash('Purchase successfully added', 'success') render_params = { 'products': db_session.query(Product).order_by(Product.name), 'stores': db_session.query(Store).order_by(Store.name) } return render_template('purchase/add.html', **render_params)
def post(self): args = parser.parse_args() print("Printing categoryName") print(args['categoryName']) new = Purchase(args['amountSpent'], args['purchaseName'], datetime.fromisoformat(args['purchaseDate']), args['categoryName'], g.user.username ) #add the purchase to the database db.session.add(new) db.session.commit() return args, 201 #or purchases or what x
def addPurchases(self, date, amount, currency, name): if not validateDate(date): raise Exception(errors.INCORRECT_DATE) if not validatePrice(amount): raise Exception(errors.INCORRECT_PRICE) if not validateCurrency(currency): raise Exception(errors.INCORRECT_CURRENCY) return self.controller.addPurchase( Purchase(date, amount, currency, name))
def mutate(self, info, **kwargs): user = User.query.filter_by(id=kwargs.get('user_id')).first() purchase = Purchase(name=kwargs.get('name'), tags=kwargs.get('tags'), is_done=kwargs('is_done')) if user is not None: purchase.user = user db.session.add(purchase) db.session.commit() return CreatePurchase(purchase=purchase)
def to_purchase(self, address, credit_card_num): """ Converts ShoppingCart to Purchase. :param address: Address, address for purchase :param credit_card_num: String, credit card number :return: Purchase, associated with order """ return Purchase(username=self.user.username, items=self.items, address=address, credit_card=credit_card_num, total_price=self.total_price)
def update_order(purchase_id): # ------------------------- # Update data of order # ------------------------- if request.form.get('_method') != 'PUT': app.logger.Info( 'Cannot perform this action. Please contact administrator') abort(405) purchase = Purchase(id=purchase_id) try: purchase = purchase.list_one_or_none_purchase() if purchase_id is None: app.logger.info( f'No data with Purchase ID =\ {purchase_id} could be found!') abort(422) except BaseException: app.logger.info( f'An error occurred. No data with Purchase ID\ = {purchase_id} could be found!') abort(422) purchase.id = purchase_id product_name = request.form.get('product') purchase.quantity = request.form.get('quantity', purchase.quantity) customer_name = request.form.get('customer_id') purchase.purchase_date = request.form.get( 'purchase_date', purchase.purchase_date) purchase.total = request.form.get('total', purchase.total) product = Product.query.filter( Product.name == product_name).one_or_none() customer = Customer.query.filter( Customer.name == customer_name).one_or_none() purchase.product_id = product.product_id purchase.customer_id = customer.customer_id try: purchase.update_purchase_in_database() flash( f'Purchase {purchase_id} was successfully updated!', 'success') except BaseException: app.log.info(f'An error occurred. Purchase {purchase_id} \ could not be updated!') abort(422) return redirect(url_for('purchases'))
def post(self): purch_arg = purch_parser.parse_args() d = datetime.datetime.fromtimestamp( time.mktime(email.utils.parsedate(purch_arg["date"]))) p = Purchase(purch_arg["amount"], purch_arg["spentOn"], d, purch_arg["cat_id"]) print(purch_arg["amount"], file=sys.stderr) for c in allCats: if (c.cat_id == purch_arg["cat_id"]): c.spent = c.spent + purch_arg["amount"] allPurcheses.append(p) return p, 201
def create_purchase(): req = request.get_json() purchase_date = datetime.now() purchase_address = req['address'] purchase_payment_method_id = req['paymentMethod'] purchase_user_id = current_user.get_id() total_cost = 0 total_discount = 0 purchase_discounts = req['discounts'] for item in req['cart']: clothes_incart_item = req['cart'][item] clothes_item_size = ClothesSizes.query.get(clothes_incart_item['sizeId']) clothes_incart_quantity = clothes_incart_item['inCart'] clothes_price = ClothesItem.query.get(clothes_incart_item['id']).clothes_price total_cost += clothes_price * clothes_incart_quantity quantity_errors = 0 if clothes_item_size.count < clothes_incart_quantity: quantity_errors += 1 if quantity_errors: resp = make_response() resp.headers['redirect'] = '/cart' return resp for discount in purchase_discounts: discount_value = Coupon.query.get(discount).coupon_discount total_discount += discount_value total_cost = total_cost - (total_cost / 100 * total_discount) purchase = Purchase(purchase_date=purchase_date, purchase_cost=total_cost, purchase_discount=total_discount, purchase_address=purchase_address, purchase_payment_method_id=purchase_payment_method_id, purchase_user_id=purchase_user_id ) db.session.add(purchase) db.session.commit() for item in req['cart']: clothes_incart_item = req['cart'][item] clothes_item_size = ClothesSizes.query.get(clothes_incart_item['sizeId']) clothes_incart_quantity = clothes_incart_item['inCart'] sold_clothes_item = SoldClothes(sold_clothes_quantity=clothes_incart_quantity, sold_clothes_size_id=clothes_incart_item['sizeId'], sold_clothes_purchase_id=purchase.id ) db.session.add(sold_clothes_item) db.session.commit() return make_response(jsonify(req), 200)
def setUp(self, mockedPurchasesList): self.testDate = '2019-05-08' self.testAmount = '120' self.testCurrency = 'UAH' self.testName = 'test purchase' mock = mockedPurchasesList.return_value testPurchases = [Purchase(self.testDate, self.testAmount, self.testCurrency, self.testName)] mock.addPurchase.return_value = testPurchases mock.removeByDate.return_value = [] mock.getPurchases.return_value = testPurchases self.PurchaseController = PurchaseController()
def post(self): args = pur_parser.parse_args() db.session.add(Purchase(description=args['description'], value=args['value'], category=args['category'], date=datetime.strptime(args['date'], '%Y-%m-%d').date())) db.session.commit() newPurchases = Purchase.query.filter_by(description=args['description'], value=args['value'], category=args['category'], date=args['date']).order_by(Purchase.p_id.desc()).first() newPurchases = PurchaseData(p_id=newPurchases.p_id, value=newPurchases.value, date=newPurchases.date, category=newPurchases.category, description=newPurchases.description) return newPurchases, 201
def purchase_prod(request, id): purchases = Purchase.objects.filter() if request.method == 'POST': purchase = Purchase() form = PurchaseForm(request.POST, instance=purchase) if form.is_valid(): form.save() return HttpResponseRedirect('/mobile/confirmation/' + str(purchase.id)) else: form = PurchaseForm() t = loader.get_template('civ/purchase.html') c = Context({'form': form.as_p()}) return HttpResponse(t.render(c))
def createPurchase(): if request.method == 'POST': params = request.json total_amount = float(params['amount']) customer_id = params['client_id'] try: purchase = Purchase( customer_id, total_amount, ) db.session.add(purchase) db.session.commit() return str(purchase.id) except Exception as e: return (str(e))
def buy(): if request.method == 'POST': user = User.get(session['email']) item = Item.query.filter(Item.id == request.form['item_id']).first() purchase = Purchase(user, item) dbs.add(purchase) dbs.commit() flash('Purchase successful, return to buy.', 'alert alert-success') return redirect(url_for('history')) else: data = {'nav_urls': get_urls(), 'active_url': url_for('buy')} data['items'] = Item.query.filter(Item.active) response = make_response(render_template('buy.html', data=data)) response.headers['Cache-Control'] = 'no-cache' return response
def setUp(self, mockedController): self.testDate = '2019-05-04' self.testAmount = '120' self.testCurrency = 'UAH' self.testName = 'test purchase' testPurchases = [ Purchase(self.testDate, self.testAmount, self.testCurrency, self.testName) ] mock = mockedController.return_value mock.addPurchase.return_value = testPurchases mock.removeByDate.return_value = [] self.mockReportResult = 100 mock.report.return_value = self.mockReportResult self.purchaseCommands = PurchaseCommands()
def purchases(self): # ------------------------- # List all orders # ------------------------- try: purchases = Purchase().list_all_purchases() if purchases is None: app.logger.info('Purchases table is empty?') abort(422) return render_template( 'grocery/purchases.html', data=purchases, nickname=session[conf_profile_key]['nickname'] if 'POSTMAN_TOKEN' not in request.headers and 'test_permission' not in request.headers else 'Guest') except BaseException: app.logger.info('An error occurred. Suppliers not available') abort(422)
def add_to_cart(): quantity = (request.form['quantity']) price = (request.form['price']) print('@@@@@@@@@@@@@@@@@@@') print('@@@@@@@@@@@@@@@@@@@', price) product_id = (int)(request.form['product_id']) if quantity == 0: error = 'quantity is required before proceding with purchase' return redirect("/catalog?=" + error) if price is None: error = 'price is required before proceding with purchase' return redirect("/catalog?=" + error) quantity = (int)(quantity) pri = (float)(price) new_purchase = Purchase( quantity, price, product_id, ) db.session.add(new_purchase) db.session.commit() temp_qty = new_purchase.quantity temp_id = new_purchase.id bottle = 0 while bottle < temp_qty: new_inventory = Inventory_check(100.00, 1400, temp_id, None) db.session.add(new_inventory) bottle += 1 db.session.commit() products = Product.query.filter_by().all() return render_template( 'catalog.html', title="Catalog", products=products, )
def cart_purchase(): credit_card = request.form.get("card") street = request.form.get("address") street2 = request.form.get("address2") city = request.form.get("city") state = request.form.get("state") zip_code = request.form.get("zip") user = db.get_user(User(current_user.get_id())) user_cart = db.get_shopping_cart(user) if len(user_cart.items) == 0: flask.flash("You don't have anything to purchase!", "info") elif '' not in [credit_card, street, city, state, zip_code]: address = Address(street=street, street2=street2, city=city, state=state, zip_code=zip_code) # make sure int zip code try: int(zip_code) except ValueError: flask.flash("Invalid zip code.", "error") return redirect("/cart") purchase = Purchase(username=user.username, items=user_cart.items, total_price=user_cart.total_price, address=address, credit_card=credit_card) db.add_purchase(purchase) db.clear_shopping_cart(user) flask.flash("<b>Success:</b> Purchase complete!", "success") else: flask.flash("<b>Error:</b> Invalid purchase! Did you fill all fields?", "error") return redirect("/cart")
def post(self): args = pur_parser.parse_args() db.session.add( Purchase(description=args['description'], amount=args['amount'], category=args['category'], date=datetime.strptime(args['date'], '%Y-%m-%d').date())) db.session.commit() pur_new = Purchase.query.filter_by(description=args['description'], amount=args['amount'], category=args['category'], date=args['date']).order_by( Purchase.pur_id.desc()).first() pur_new = PurchaseDao(pur_id=pur_new.pur_id, description=pur_new.description, amount=pur_new.amount, category=pur_new.category, date=pur_new.date) return pur_new, 201
def quick_buy(): users = User.query.filter(User.activated).order_by(User.email.asc()) items = Item.query.filter(Item.active) if request.method == 'POST': user = User.query.filter(User.id == request.form['user_id']).first() if user is not None and Authentication.authenticate( user, request.form['password']): item = Item.query.filter( Item.id == request.form['item_id']).first() purchase = Purchase(user, item) dbs.add(purchase) dbs.commit() flash('Quick-buy successful!', 'alert alert-success') else: flash( 'Quick-buy failed, please try again with the right password.', 'alert alert-danger') return render_template('quick_buy.html', users=users, items=items)
def post(self): data = self.token_parser.parse_args() current_user_id = get_jwt_identity() logged_in = current_user_id is not None app_id = data['app_id'] amount = data['amount'] lifetime = shortRepoTokenLifetime # TODO: Actually attempt stripe purchase if amount > 0 if amount > 0: # And purchase succeeds lifetime = longRepoTokenLifetime if logged_in: new_purchase = Purchase(app_id=app_id, user_id=current_user_id) try: new_purchase.save_to_db() except: pass token = jwt.encode( { 'sub': 'users/%d' % (current_user_id if current_user_id else 0), 'prefixes': [app_id], 'exp': datetime.utcnow() + lifetime, 'name': 'auth.py', }, repo_secret, algorithm='HS256').decode('utf-8') return_data = {"token": token} if amount > 0: return_data["store"] = True else: return_data["store"] = False return return_data
def purchase(): global all_user_purch if not g.user: flash("Must be logged in!") return "Forbidden", 403 if request.method == "POST": data = request.get_json() date = re.compile('\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}') if not date.match(data["date"]): return "IMPROPER FORMAT", 400 if Category.query.filter_by(name=data["cat"], user_id=g.user.user_id).first() == None: return "CAT NOT FOUND", 400 new_purch = Purchase( data["amount"], data["description"], data["date"], Category.query.filter_by(name=data["cat"], user_id=g.user.user_id).first(), g.user) db.session.add(new_purch) db.session.commit() all_user_purch[int(new_purch.purchase_id)] = 0 return "OK!", 200 elif request.method == 'GET': purchs = Purchase.query.filter_by(user_id=g.user.user_id).all() dictPurch = {} for purch in purchs: if all_user_purch[int( purch.purchase_id )] == 0 and purch.date[:2] == "11": #only return a purchase if it has changed or in the current month, only need to support current month so hard code 11 dictPurch[purch.purchase_id] = [ purch.amount, purch.category_id ] all_user_purch[int(purch.purchase_id)] = 1 if len(dictPurch) == 0: return "No updates", 100 return json.dumps(dictPurch), 200 return "Forbidden", 403
def get_purchase(purchase, db=None): """ Gets a purchase from the database based on PurchaseID :param purchase: Purchase, must have id :param db: optional, the database connection """ db = db or get_db() cur = db.cursor() cur.execute(""" SELECT Username, TotalPrice, CreditCard, Address FROM Purchase WHERE PurchaseID = ? """, [purchase.id_]) row = cur.fetchone() try: purchase = Purchase(id_=purchase.id_, username=row[0], total_price=row[1], credit_card=row[2], address=Address().from_str(row[3])) except Exception as e: print("invalid purchase:", e) cur.execute(""" SELECT InventoryItemID, Price, Quantity FROM PurchaseItem WHERE pi.PurchaseID = ? """, [purchase.id_]) for row in cur.fetchall(): try: item = get_inventory_item(InventoryItem(id_=row[0]), db) purchase.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2])) except Exception as e: print("invalid purchase item:", e) cur.close() return purchase
def add_order(self): # ------------------------- # Add an order # ------------------------- product_name = request.form.get('product', '') quantity = request.form.get('quantity', 0) customer_name = request.form.get('customer', '') purchase_date = request.form.get( 'purchase_date', datetime.today().strftime('%m/%d/%Y')) total = request.form.get('total', 0) product = Product.query.filter( Product.name == product_name).one_or_none() customer = Customer.query.filter( Customer.name == customer_name).one_or_none() purchase = Purchase( product_id=product.id, quantity=quantity, customer_id=customer.id, purchase_date=purchase_date, total=total ) try: purchase = purchase.add_purchase_to_database() flash( f'Product ID {product.id} was successfully added \ to purchases table!') except BaseException: app.logger.info( f'An error occurred. Product ID {product.id} could not be added!') abort(422) return redirect(url_for('purchases'))
def save(): # import ipdb; ipdb.set_trace() create_merchant() create_purchase() lines = [] i = 0 receita_total = 0 file_upload = request.files.get('file') content = file_upload.read() lines = content.split('\n') for line in lines: #pula o cabecalho if i == 0: i = i + 1 continue if line == '': continue line = line.split('\t') merchant = Merchant(line[index_merchant_name], line[index_merchant_adress]) purchase = Purchase(line[index_puchaser_name], line[index_item_description], float(line[index_item_price]), int(line[index_purchase_count]), line[index_merchant_name]) receita_total = float(line[index_item_price]) * int( line[index_purchase_count]) + receita_total insere_merchant(merchant) insere_purchase(purchase) return render_template('save.html', receita=receita_total)
# configuration DEBUG = True app.config.from_object(__name__) app.config.from_envvar('CHAT_CONFIG', silent=True) # global vars allCats = [] allPurcheses = [] # debug c = Category("test", 100, 100) allCats.append(c) c = Category("Uncategorized", 0, 0, -1) allCats.append(c) p = Purchase(55, "shoose", datetime.datetime.now()) allPurcheses.append(p) ############################################ # Routes ############################################ @app.route('/') def main_page(): """ This is the seleton page """ return redirect(url_for('budget')) @app.route('/budget') def budget():
def test_addPurchase(self): purchases = self.PurchaseController.addPurchase(Purchase(self.testDate, self.testAmount, self.testCurrency, self.testName)) self.assertGreater(len(purchases), 0)
def test_removeByDate(self): testDate = '2019-05-12' self.PurchaseController.addPurchase(Purchase(self.testDate, self.testAmount, self.testCurrency, self.testName)) purchases = self.PurchaseController.removeByDate(testDate) for purchase in purchases: self.assertNotEqual(purchase.date, testDate)