Ejemplo n.º 1
0
    def setUp(self):
        self.stuff = FoodStuff(name='some stuff 3')
        self.stuff.save()

        recipe = Recipe(name='some recipe 3')
        recipe.save()

        ingredient = RecipeIngredient(
            stuff  = self.stuff,
            recipe = recipe,
            count  = 1.5
        )
        ingredient.save()

        self.product = Product(
            name   = 'some product 3',
            recipe = recipe,
            markup = 1.5
        )
        self.product.save()

        provider = FoodProvider(name='some provider')
        provider.save()

        purchase = Purchase(
            provider   = provider,
            stuff      = self.stuff,
            cost       = 200,
            unit_count = 10,
            unit_size  = 1,
        )
        purchase.save()

        self.offer = SaleOffer(product=self.product)
        self.offer.save()
Ejemplo n.º 2
0
    def test_save(self):
        stuff = FoodStuff(name = 'some stuff')
        stuff.save()

        provider = FoodProvider(name='some provider')
        provider.save()

        purchase = Purchase(
            provider   = provider,
            stuff      = stuff,
            cost       = 100,
            unit_count = 10,
            unit_size  = 1,
        )
        purchase.save()

        self.assertEqual(3, purchase.transactions.count())

        self.assertEqual(10, stuff.material_account.balance())
        self.assertEqual(100, stuff.monetary_account.balance())

        self.assertEqual(-10, provider.material_account.balance())

        main_cashbox = get_main_cashbox()
        self.assertEqual(-100, main_cashbox.account.balance())
Ejemplo n.º 3
0
def checkout(request):
    cart = []

    if request.POST:
        cj = request.POST.get("cart")
    else:
        cj = request.GET.get("cart")
        # Open cash drawer

    fail = False
    for f in json.loads(cj):
        try:
            product = Product.objects.get(pk=f['id'])
            if f['num'] > product.stocked:
                fail = True
            cart.append({
                'product': product,
                'amount': f['num'],
                'price': f['num'] * product.price,
            })
        except Product.DoesNotExist:
            continue

    if request.POST:
        purchase = Purchase()
        purchase.salesperson = request.user
        purchase.total = sum([i['product'].price * i['amount'] for i in cart])
        purchase.save()
        for i in cart:
            i['product'].stocked -= i['amount']
            i['product'].save()
            ProductPurchase.objects.create(
                purchase=purchase,
                product=i['product'],
                amount=i['amount'])
        template = loader.get_template('cashdesk/bon.txt')
        context = RequestContext(
            request,
            {
                'purchase': purchase,
                'productpurchases': ProductPurchase.objects.filter(
                    purchase=purchase),
            }
        )
        bon = template.render(context)
        printer.print_and_cut(
            request.session['printer'],
            bon, True)
        return HttpResponseRedirect("/")

    ctx = {
        'cart': cart,
        'fail': fail,
        'cartjson': request.GET.get("cart"),
        'total': sum([i['product'].price * i['amount'] for i in cart]),
    }
    return render(request, 'cashdesk/checkout.html', ctx)
Ejemplo n.º 4
0
 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)
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
    def post(self):
        data = self.token_parser.parse_args()
        current_user_id = get_jwt_identity()

        logged_in = current_user_id is not None

        denied = []
        tokens = {}
        for app_id in data['ids']:
            denied.append(app_id)

        if logged_in:
            current_user = UserModel.find_by_id(current_user_id)
            if not current_user:
                return {'message': 'Invalid token'}, 401

            for app_id in denied:
                if Purchase.find_purchase(current_user_id, app_id):
                    denied.remove(app_id)
                    tokens[app_id] = jwt.encode(
                        {
                            'sub': 'users/%d' % current_user_id,
                            'prefixes': [app_id],
                            'exp': datetime.utcnow() + longRepoTokenLifetime,
                            'name': 'auth.py',
                        },
                        repo_secret,
                        algorithm='HS256').decode('utf-8')

        return {'denied': denied, 'tokens': tokens}
Ejemplo n.º 8
0
def load_file(filename):
    purchases = []
    with open(filename, 'r', encoding='utf-8') as fin:
        reader = csv.DictReader(fin)
        for row in reader:
            purchases.append(Purchase.create_from_dict(row))
    return purchases
Ejemplo n.º 9
0
    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
Ejemplo n.º 10
0
 def save(self, commit=True):
     item = super(customerForm, self).save(commit=False)
     item.set_password(self.cleaned_data["password"])
     account = Account(name=self.cleaned_data["name"], access=self.cleaned_data["access"],
                        args2=self.cleaned_data["args2"], num_threads=self.cleaned_data["num_threads"])
     purchase = Purchase(startDate=self.cleaned_data["startDate"], endDate=self.cleaned_data["endDate"],
                         initial=self.cleaned_data["initial"], available=self.cleaned_data["initial"])
     if commit:            
         item.save()
         self.save_m2m()
         
         account.customer = item
         account.save()
         
         purchase.account = account
         purchase.save()    
     return item
Ejemplo n.º 11
0
    def test_create(self):
        provider = FoodProvider(name='some provider')
        provider.save()

        purchase = Purchase(
            provider   = provider,
            stuff      = self.stuff,
            cost       = 200,
            unit_count = 10,
            unit_size  = 1,
        )
        purchase.save()

        check = Calculation.create(self.offer, self.ingredient)
        self.assertEqual(1.5, check.material_count)
        self.assertTrue(check.feasible)
        self.assertEqual(30, check.monetary_count)
Ejemplo n.º 12
0
	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
Ejemplo n.º 13
0
def purchase_item(request, item_id):
    if request.method == 'POST':
        item = get_object_or_404(Item, id=item_id)
        form = PurchaseForm(request.POST)
        if form.is_valid():
            bidder = form.cleaned_data['bidder']
            unit_price = item.unit_price if item.fixed_price else form.cleaned_data['unit_price']
            quantity = form.cleaned_data['quantity']
            if bidder and item and (quantity <= item.quantity_remaining() or item.quantity_remaining() == -1):
                p = Purchase(bidder=bidder, item=item, quantity=quantity, unit_price=unit_price)
                p.save()
                messages.info(request, "%s successfully purchased %s" % (bidder.name, item.name))
                return redirect(item)
        else:
            messages.error(request, "Invalid Form %s" % form.errors)
        messages.error(request, "Unable to complete purchase.")
        return redirect(item) #TODO go back to form with errors
    return redirect('/')
    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))
Ejemplo n.º 15
0
def create_purchase(customer_id, business_id, total_cost, notify_on_completion,
                    quoted_completion_date, actual_completion_date):
    from models import Purchase

    return Purchase.create(customer_id=customer_id,
                           business_id=business_id,
                           total_cost=total_cost,
                           notify_on_completion=notify_on_completion,
                           quoted_completion_date=quoted_completion_date,
                           actual_completion_date=actual_completion_date)
Ejemplo n.º 16
0
    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)
Ejemplo n.º 17
0
 def add_purchase(self, buyer, drink_type, purchase_date, num_cans):
     logger.debug("Creating purchase %s ", num_cans)
     try:
         with db.atomic():
             return Purchase.create(buyer=buyer,
                                    drink_type=drink_type,
                                    purchase_date=purchase_date,
                                    num_cans=num_cans)
     except ieerror as ie:
         logger.debug("Error: %s", ie.message)
         return None
Ejemplo n.º 18
0
    def list(self, *args, **kwargs):
        l = "%s: %s cans of %s on %s\n"
        total = ""
        for p in Purchase.select():
            total += l % (p.buyer.username, p.num_cans, p.drink_type.name,
                          p.purchase_date.strftime("%A, %m-%d %H:%M"))

        slack_client.api_call("chat.postMessage",
                              channel=self.channel,
                              text="Totals: \n%s" % total,
                              as_user=True)
Ejemplo n.º 19
0
 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
Ejemplo n.º 20
0
    def test_list(self):
        command = ["list"]

        channel = 'bottystuff'

        user = User(username="******")

        b = commands.PepsiCommand(command, channel, user)

        for p in Purchase.select():
            logger.warn(p.buyer)
            logger.warn(p.drink_type)
Ejemplo n.º 21
0
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()]})
Ejemplo n.º 22
0
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)
Ejemplo n.º 23
0
    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()
Ejemplo n.º 24
0
    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 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
Ejemplo n.º 26
0
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))
Ejemplo n.º 27
0
    def test_gets(self):
        stuff = FoodStuff(name='foobar 2')
        stuff.save()

        self.assertEqual(0, stuff.get_material_count())
        self.assertEqual(0, stuff.get_unit_cost())
        self.assertFalse(stuff.is_feasible())

        provider = FoodProvider(name='some provider')
        provider.save()

        purchase = Purchase(
            provider   = provider,
            stuff      = stuff,
            cost       = 200,
            unit_count = 10,
            unit_size  = 1,
        )
        purchase.save()

        self.assertEqual(10, stuff.get_material_count())
        self.assertEqual(20, stuff.get_unit_cost())
        self.assertTrue(stuff.is_feasible())
Ejemplo n.º 28
0
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'))
Ejemplo n.º 29
0
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))
Ejemplo n.º 30
0
 def post(self, id):
   """
   TODO: accept multiple json objects which present purchases.
   """
   event_id = long(id)
   response = {}
   try:
     jsons = simplejson.loads(self.request.body)
     purchases = [Purchase.create_from_json(event_id, json) for json in jsons]
     for purchase in purchases:
       purchase.put()
     response = {'status': 'success',
                 'redirect': '/e/%d/list' % event_id,
                 'n_purchase':len(purchases)}
   except Exception, e:
     response = {'status': str(e), 'n_purchase':0}
Ejemplo n.º 31
0
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
Ejemplo n.º 32
0
    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()
Ejemplo n.º 33
0
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,
    )
Ejemplo n.º 34
0
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)
Ejemplo n.º 35
0
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
Ejemplo n.º 37
0
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)
Ejemplo n.º 38
0
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
Ejemplo n.º 39
0
def pay_for_a_plan_success(request,pending_purchase,context,user_existing_coupons,selected_plan):

    # add the purchase to the database
    new_purchase = Purchase()
    new_purchase.user = pending_purchase.user
    new_purchase.data_transfer_plan = pending_purchase.data_transfer_plan

    if user_existing_coupons:
        new_purchase.amount_paid = selected_plan.discounted_price
    else:
        new_purchase.amount_paid = selected_plan.original_price

    new_purchase.remaining_allowance_frequency = pending_purchase.data_transfer_plan.freq
    new_purchase.save()

    # save follow_up number using hash
    follow_up_number = generate_md5_hash(str(new_purchase.id))
    new_purchase.follow_up_number = follow_up_number
    new_purchase.save()
    context['follow_up_number'] = follow_up_number

    # if necessary, remove user's best coupon
    if user_existing_coupons:
        best_coupon = utility_functions.get_best_coupon(user_existing_coupons)
        best_coupon.delete()

    # send an email
    plaintext = loader.get_template('payment/pay_for_a_plan_complete_email.txt')
    htmly = loader.get_template('payment/pay_for_a_plan_complete_email.html')
    subject = loader.get_template('payment/pay_for_a_plan_complete_email_subject.html')

    subject_content = subject.render(context).replace('\n',' ')
    text_content = plaintext.render(context)
    html_content = htmly.render(context)

    from_email = '*****@*****.**'
    recipient_list = [new_purchase.user.email]

    msg = EmailMultiAlternatives(subject_content, text_content, from_email, recipient_list)
    msg.attach_alternative(html_content, "text/html")
    msg.send()

    # return response to the user.
    return render(request,'payment/successful_payment.html',context)
Ejemplo n.º 40
0
def viewSingleOrderOpportunity(request, pk):
    """Displays the contents of a single OrderOpportunity"""
    if request.method == "GET":
        try:
            order = Order.objects.filter(order_opportunity=pk).get(user=request.user)
            order_opportunity = OrderOpportunity.objects.get(pk=pk)
            purchases = Purchase.objects.filter(order__user=request.user).filter(order__order_opportunity=pk)
            PurchaseFormSet = formset_factory(PurchaseForm, extra=0)
            formset_initial_data = [{'qty': i.qty,
                                     'product_pk': i.pk, 
                                     'price': i.product_for_sale.price, 
                                     #'price': i.qty * i.product_for_sale.price, 
                                     'name': i.product_for_sale.name} for i in purchases]
            formset = PurchaseFormSet(initial=formset_initial_data)
            total = reduce(lambda x, y: x+y, [p.qty * p.product_for_sale.price for p in purchases], 0)
            total = total + order_opportunity.fuel_surcharge
            return render_to_response('ReadOnlyOrder.html',
                                      {'order_opportunity': order_opportunity,
                                      'formset': formset,
                                      'total': total},
                                      context_instance=RequestContext(request))
        except Order.DoesNotExist:
            order_opportunity = OrderOpportunity.objects.get(pk=pk)
            products_for_sale = ProductForSale.objects.filter(order_opportunity=pk)
            PurchaseFormSet = formset_factory(PurchaseForm, extra=0)
            formset_initial_data = [{'product_pk': i.pk, 
                                     'price': i.price, 
                                     'name': i.name} for i in products_for_sale]
            formset = PurchaseFormSet(initial=formset_initial_data)
            agreement = PurchaseAgreementForm()
            return render_to_response('PlaceOrder.html',
                                      {'order_opportunity': order_opportunity,
                                      'agreement': agreement,
                                      'formset': formset},
                                      context_instance=RequestContext(request))
    elif request.method == "POST":
        PurchaseFormSet = formset_factory(PurchaseForm)
        formset = PurchaseFormSet(request.POST)
        agreement = PurchaseAgreementForm(request.POST)
        order_opportunity = OrderOpportunity.objects.get(pk=pk)
        if formset.is_valid() and agreement.is_valid():
            order_opportunity = OrderOpportunity.objects.get(pk=pk)
            order = Order(order_opportunity=order_opportunity, user=request.user)
            order.save()
            num_purchases = 0
            for form in formset.forms:
                if int(form['qty'].data) == 0: continue
                product_for_sale = ProductForSale.objects.get(pk=form['product_pk'].data)
                purchase = Purchase(qty=form['qty'].data, 
                                    product_for_sale=product_for_sale, 
                                    order=order)
                purchase.save()
                num_purchases = num_purchases + 1
            if num_purchases == 0:
                order.delete()
        else:
            return render_to_response('PlaceOrder.html',
                                      {'order_opportunity': order_opportunity,
                                      'agreement': agreement,
                                      'formset': formset},
                                      context_instance=RequestContext(request))
        return HttpResponseRedirect(reverse('single-order-opportunity', args=[pk]))