Esempio n. 1
0
 def __parse_order(self, node, day_index):
     try:
         order = Order()
         order.parse(node)
         self.schedule[day_index].add_order(order)
     except ET.ParseError, e:
         raise ET.ParseError('Day "%s" contains a bad order: %s' % (self.day_names[day_index], e.message))
Esempio n. 2
0
def process():
    # pulls the form information from the post query
    form = request.form
    user = User.load_from_db_by_student_id(form["student_id"])
    # if the user doesn't exist in the database already, then creates a new user
    # users are classified by student id
    if not user:
        user = User(form["first_name"], form["last_name"], form["student_id"],
                    None)
        user.save_to_db()
        user = User.load_from_db_by_student_id(form["student_id"])
    # compiles a list of the seats chosen in the form from the post query
    seats = ""
    seat_list = form.getlist('seats')
    for seat in seat_list:
        seats += seat + " "
        new_seat = Seat(seat, form["screening"], None)
        new_seat.save_to_db()
    # updates attending in the screening database, then creates a new order in the database. all the fields that are
    # passed as None are filled by the database itself.
    Screening.update_attending(len(seat_list), form["screening"])
    new_order = Order(None, user.id, seats, form["screening"], None, None)
    new_order.save_to_db()
    new_order = Order.load_from_db_by_user_id(user.id)
    screening = Screening.load_from_db_by_screening_id(new_order.screening_id)
    movie = Movie.load_from_db_by_id(screening.movie_id)
    order_date = new_order.order_date.strftime("%B %d, %Y %I:%M %p")
    screening_date = screening.date.strftime("%B %d, %Y %I:%M %p")
    return render_template('orderdetails.html',
                           user=user,
                           order=new_order,
                           movie=movie,
                           screening=screening,
                           order_date=order_date,
                           screening_date=screening_date)
 def place_order(self):
     try:
         order = Order("sweet tv", 7)
         order.complete(correct=False)
     except BaseOrderException as e:
         print e.message
         print e.friendly_message
Esempio n. 4
0
 def test_put_order_to_queue(self):
     r = Reception(MTList())
     data = r.read_orders(config.filename)
     r.put_order_to_queue(data[0])
     self.assertEqual(
         Order(data[0]).__str__(),
         r.get_cooking_queue().get().__str__())
Esempio n. 5
0
    def _make_order(self, mkt_obj, quantity, price=None, side='buy', order_type='limit'):
        mkt_symbol = mkt_obj.symbol

        if side not in ['buy', 'sell']:
            raise ValueError("make order: -side- parameter must be either 'buy' or 'sell'")
        if order_type not in ['limit', 'market']:
            raise ValueError("make order: -order_type- parameter must be either 'limit' or 'market'")
        
        try:
            if order_type == 'limit':
                if side == 'buy':
                    response = self.ccxt_obj.create_limit_buy_order(mkt_symbol, quantity, price)
                else:
                    response = self.ccxt_obj.create_limit_sell_order(mkt_symbol, quantity, price)

            else:
                if side == 'buy':
                    response = self.ccxt_obj.create_market_buy_order(mkt_symbol, quantity)
                else:
                    response = self.ccxt_obj.create_market_sell_order(mkt_symbol, quantity)
            
            order = Order(self, response['id'])
            self.orders_alive.append(order)
            self.orders_history.append(order)
        except:
            raise
        else:
            return order
Esempio n. 6
0
 def makePayment(self, customer: Customer):
     if customer.cart.numOfProducts == 0:
         print(
             "Cart is Empty!! Please first add some products in cart to make payment.."
         )
         return
     try:
         cardNum = int(input("Enter card number: "))
     except ValueError:
         print("Card number must be an integer")
         return
     deliveryAddress = input("Enter Delivery address: ")
     orderAmount = customer.cart.cartTotal
     prodList = []
     for product in customer.cart.prodList:
         prodList.append(product)
     #   customer.cart.removeProductFromCart(product)
     order = Order(customer.userId, prodList, orderAmount, cardNum,
                   deliveryAddress)
     customer.orderList.append(order)
     dataLists.orderList.append(order)
     customer.cart.prodList.clear()
     customer.totalPurchasedAmt += customer.cart.cartTotal
     customer.productsBought += customer.cart.numOfProducts
     customer.cart.cartTotal = 0
     customer.cart.numOfProducts = 0
     print("Payment Completed. Your order is placed..")
     print("You can now check the status of the order..")
Esempio n. 7
0
 def action_pay(self, resource, context, form):
     from orders import Order
     cart = ProductCart(context)
     root = context.root
     # Check if cart is valid
     if not cart.is_valid():
         return context.come_back(CART_ERROR, goto='/')
     # Calcul total price
     total_price_with_tax = decimal(0)
     total_price_without_tax = decimal(0)
     total_weight = decimal(0)
     for cart_elt in cart.products:
         product = context.root.get_resource(cart_elt['name'])
         quantity = cart_elt['quantity']
         declination = cart_elt['declination']
         unit_price_with_tax = product.get_price_with_tax(declination)
         unit_price_without_tax = product.get_price_without_tax(declination)
         total_price_with_tax += unit_price_with_tax * quantity
         total_price_without_tax += unit_price_without_tax * quantity
         total_weight += product.get_weight(declination) * quantity
     # Get Shipping price
     shipping_price = cart.get_shipping_ns(resource, context)['price']
     total_price_with_tax += shipping_price
     total_price_without_tax += shipping_price
     # Arrondi
     total_price_with_tax = get_arrondi(total_price_with_tax)
     total_price_without_tax = get_arrondi(total_price_without_tax)
     # Guess ref number
     # We take last order name + 1
     search = root.search(format='order')
     orders =  search.get_documents(sort_by='creation_datetime',
                                    reverse=True)
     if orders:
         ref = str(int(orders[0].name) + 1)
     else:
         ref = '1'
     # We create a new order
     kw = {'user': context.user,
           'payment_mode': form['payment'],
           'shipping_price': shipping_price,
           'total_price': total_price_with_tax,
           'total_weight': total_weight,
           'cart': cart,
           'shop': resource,
           'shop_uri': context.uri.resolve('/')}
     orders = resource.get_resource('orders')
     order = Order.make_resource(Order, orders, ref,
                         title={'en': u'#%s' % ref},
                         **kw)
     # We clear the cart
     cart.clear()
     # We show the payment form
     kw = {'ref': ref,
           'amount': total_price_with_tax,
           'amount_without_tax': total_price_without_tax,
           'resource_validator': str(order.get_abspath()),
           'mode': form['payment']}
     payments = resource.get_resource('payments')
     return payments.show_payment_form(context, kw)
Esempio n. 8
0
 def load_orders_from_json(filename = 'order_data.json'):
     with open(filename) as odf:
         orders_from_file = json.load(odf)
         order_list = []
         for order_dict in orders_from_file:
             order = Order(order_dict['product name'],Decimal(order_dict['cost']),order_dict['quantity'])
             order_list.append(order)
         return order_list
Esempio n. 9
0
 def setUp(self):
     self.o = Order({
         u'id': u'a8cfcb76-7f24-4420-a5ba-d46dd77bdffd',
         u'prepTime': 4,
         u'name': u'Banana Split'
     })
     cooking = MTList()
     cooking.put(self.o)
     self.c = Cook(MTList(), cooking)
Esempio n. 10
0
 def sell_order(self, decision, value):
     return Order(order_type=OrderType.SELL,
                  transaction_currency=decision.transaction_currency,
                  counter_currency=decision.counter_currency,
                  timestamp=decision.timestamp,
                  value=value,
                  unit_price=self._get_price(decision),
                  transaction_cost_percent=transaction_cost_percents[
                      decision.source],
                  time_delay=self._time_delay,
                  slippage=self._slippage,
                  original_price=decision.signal.price
                  if decision.signal is not None else None)
Esempio n. 11
0
def gen_orders(user_lis, item_lis, total_orders=50):
    for _ in range(total_orders):
        random_item = choice(item_lis)
        random_user = choice(user_lis)
        dic = {
            "user_id": random_user.obj_id(),
            "obj_id": random_item.obj_id(),
            "coll_name": "item",
            "quantity": choice(range(1, 2)),
            "special_notes": loremipsum.sentence(),
            "status": OrderStatus.OK,
        }
        order_obj = Order.unserialize(dic)
        save(order_obj)
Esempio n. 12
0
def orders_list(request, tmpl, action=None):
    msg_ok = msg_err = None
    if action == 'validate':
        cart = Cart(request)
        if not cart.has_gcs_ckecked():
            return HttpResponseRedirect('/resa/cart/uncheckedgcs/')
        if not cart.is_valid():
            return HttpResponseRedirect('/resa/cart/invalid/')
        elif not cart.empty():
            order = Order(user=request.user, creation_date=date.now(), donation = cart.donation)
            order.save_confirm(cart)
            cart.clear()
            cart.save(request)
            msg_ok = _(u"Order successfully confirmed")

    pending_orders = request.user.order_set.filter(payment_date__isnull=True)
    validated_orders = request.user.order_set.filter(payment_date__isnull=False)
    return tmpl, {
        'pending_orders': pending_orders,
        'validated_orders': validated_orders,
        'msg_err': msg_err, 'msg_ok': msg_ok,
        'user_obj': request.user,
        'currency': settings.CURRENCY, 'currency_alt': settings.CURRENCY_ALT,
    }
Esempio n. 13
0
 def processOrders(self):
     """
     process each line in orders text as dictory
     fields: id,ticker,side,shares,price
     store the order objects in dictonary with id as key
     """
     ordersreader = Reader(self.sentfile)
     for d in ordersreader:
         id     = d["id"]
         ticker = d["ticker"]
         side   = d["side"]
         shares = d["shares"]
         price  = d["price"]
         order = Order(id, side, ticker, shares, price)
         self.ordersdict[id] = order
Esempio n. 14
0
def order_details():
    query = request.args.get('q')
    # if the query is not valid, returns a 404
    if query:
        order = Order.load_from_db_by_order_id(query)
        # if the requested order id doesn't exist in the database, returns a 404
        if order:
            user = User.load_from_db_by_id(order.user_id)
            screening = Screening.load_from_db_by_screening_id(
                order.screening_id)
            movie = Movie.load_from_db_by_id(screening.movie_id)
            order_date = order.order_date.strftime("%B %d, %Y %I:%M %p")
            screening_date = screening.date.strftime("%B %d, %Y %I:%M %p")
            return render_template('orderdetails.html',
                                   user=user,
                                   order=order,
                                   movie=movie,
                                   screening=screening,
                                   order_date=order_date,
                                   screening_date=screening_date)
        else:
            return render_template('404.html', content="Order")
    return render_template('404.html', content=query)
Esempio n. 15
0
def main():
    print ("employee name and salary")
    setEmployee()
    print("Customer name and status")
    setCustomer()

    item1=Item(1, 'Cheezeburger', 3.00)
    item2=Item(2, 'Orange Juice', 4.00)
    item3=Item(3, 'Milk', 5.00)

    orderitem1=orderitem(item1, 2)
    orderitem2=orderitem(item2, 3)
    orderitem3=orderitem(item3, 1)


    order=Order()
    order.addorderitems(orderitem1)
    order.addorderitems(orderitem2)
    order.addorderitems(orderitem3)

    payment=order.calctotal()
    print(payment)
Esempio n. 16
0
def main():
    Menu()
    price_Menu()

    exit = False
    Orders = Order()

    while exit == False:
        order = None

        drink = input(
            "what do you want to order? Type SL for Soy Latte , JCF for Java chip Frappucino, ICJ for Ice Coffe Jelly and CM for Caramel macchiato.\n"
        ).lower()

        if drink == "sl":
            order = SoyLatte("soy latte", 4.25, "tall", "normal",
                             "without topping")

        elif drink == "jcf":
            order = Frappucino("java chip frappucino", 3.45, "tall", "normal",
                               "without topping")

        elif drink == "icj":
            order = IceCoffee("ice coffee jelly", 3.55, "tall", "normal",
                              "without topping")

        elif drink == "cm":
            order = Macchiato("caramel macchiato", 4.99, "tall", "normal",
                              "without topping")

        info = input(
            "\nDo you want to know about the ingredients in your drink? Type (y/n)\n"
        ).lower()

        if info == "y":
            print(order.details())

        sugar = input(
            "\ndo you want your drink to be less sugar or normal? type 'less'/'normal' \n"
        ).lower()

        if sugar == "less":
            order.less_sugar()

        size = input(
            "\nwhat size do you want? Type T for Tall, G for Grande, V for Venti. \n"
        ).lower()

        if size == "t":
            order.change_size(0, "Tall")

        elif size == "g":
            order.change_size(0.7, "Grande")

        elif size == "v":
            order.change_size(1, "Venti")

        boolean = input(
            "\ndo you want to add topping for your coffee? Type Yes or no. *some toppings are not available for specific drinks\n"
        ).lower()

        if boolean == "yes":
            topping_present = False
            while topping_present == False:
                topping = input(
                    "\nWhich topping do you want? Type AS to add extra 2 shots, WC for extra Whip Cream, J for extra Jelly and CF for extra Cloud Foam.\n"
                ).lower()

                if topping == "as":
                    order.add_topping("with 2 extra shots", 0.5)

                elif topping == "j":
                    order.add_topping("with extra jelly", 2)

                elif topping == "wc":
                    order.add_topping("with extra whip cream", 2)

                elif topping == "cf":
                    order.add_topping("with extra cloud foam", 1)

                if order.topping != "without topping":
                    topping_present = True

        Orders.add_order(order)
        another_drink = input(
            "\ndo you want to order another drink?Type (y/n) to continue\n"
        ).lower()

        if another_drink == "n":
            exit = True

    else:
        total_price = Orders.verify_payment()

        print(f'Your total bill is ${total_price["payment"][0]}')
        if total_price["payment"][1] == "cash":
            dollars = int(input("How much Dollars do you want to give? \n"))

            print(f'Your change is ${(dollars - total_price["payment"][0])}')

        elif total_price["payment"][1] == "credit":
            print(
                f'${total_price["payment"][0]} have been deducted from you account.'
            )

        print("thank you for ordering at starbucks")
Esempio n. 17
0
 def action_pay(self, resource, context, form):
     from orders import Order
     cart = ProductCart(context)
     root = context.root
     # Check if cart is valid
     if not cart.is_valid():
         return context.come_back(CART_ERROR, goto='/')
     # Calcul total price
     total_price_with_tax = decimal(0)
     total_price_without_tax = decimal(0)
     total_weight = decimal(0)
     for cart_elt in cart.products:
         product = context.root.get_resource(cart_elt['name'])
         quantity = cart_elt['quantity']
         declination = cart_elt['declination']
         unit_price_with_tax = product.get_price_with_tax(declination)
         unit_price_without_tax = product.get_price_without_tax(declination)
         total_price_with_tax += unit_price_with_tax * quantity
         total_price_without_tax += unit_price_without_tax * quantity
         total_weight += product.get_weight(declination) * quantity
     # Get Shipping price
     shipping_price = cart.get_shipping_ns(resource, context)['price']
     total_price_with_tax += shipping_price
     total_price_without_tax += shipping_price
     # Arrondi
     total_price_with_tax = get_arrondi(total_price_with_tax)
     total_price_without_tax = get_arrondi(total_price_without_tax)
     # Guess ref number
     # We take last order name + 1
     search = root.search(format='order')
     orders = search.get_documents(sort_by='creation_datetime',
                                   reverse=True)
     if orders:
         ref = str(int(orders[0].name) + 1)
     else:
         ref = '1'
     # We create a new order
     kw = {
         'user': context.user,
         'payment_mode': form['payment'],
         'shipping_price': shipping_price,
         'total_price': total_price_with_tax,
         'total_weight': total_weight,
         'cart': cart,
         'shop': resource,
         'shop_uri': context.uri.resolve('/')
     }
     orders = resource.get_resource('orders')
     order = Order.make_resource(Order,
                                 orders,
                                 ref,
                                 title={'en': u'#%s' % ref},
                                 **kw)
     # We clear the cart
     cart.clear()
     # We show the payment form
     kw = {
         'ref': ref,
         'amount': total_price_with_tax,
         'amount_without_tax': total_price_without_tax,
         'resource_validator': str(order.get_abspath()),
         'mode': form['payment']
     }
     payments = resource.get_resource('payments')
     return payments.show_payment_form(context, kw)
Esempio n. 18
0
        print(f"Your total cost is: £{total}")

    #my_order = Order(f"{my_product.name.title()}", f"{my_product.cost}", "2")

    print("\nMy first order:\n")
    display_order(first_order)

    def display_orders(orders):
        """display many orders function"""
        print("Product Name: Cost: Quantity:")
        for order in orders:
            print(f"{order.product_name.title()} £{order.cost} {order.qty}")
            total = order.total_cost()
            print(f"Your total cost is: £{total}")

    my_order = Order("the hobbit", Decimal("9.99"), 3)
    another_order = Order("alice in wonderland", Decimal("10.00"), 2)
    orders_list = [my_order, another_order, first_order]

    def save_orders_to_json(orders, filename = 'order_data.json'):
        order_dicts = []
        for order in orders:
            order_dict = {'product name': order.product_name, 'cost': str(order.cost), 'quantity': order.qty}
            order_dicts.append(order_dict)
        with open(filename, 'w') as od:
            json.dump(order_dicts, od, indent=1)

    save_orders_to_json(orders_list)

    def load_orders_from_json(filename = 'order_data.json'):
        with open(filename) as odf:
Esempio n. 19
0
# https://ftx.com/volume-monitor
from orders import Order, Ladder

if __name__ == "__main__":
    ladder = Ladder(fills=[Order("10700", "100"), Order("10800", "100")])
    stop = ladder.breakeven()
    pyramid_add = ladder.next_price_add(adjustment="50")
    profit_stop = ladder.next_price_add(adjustment="10")
    print((profit_stop, pyramid_add, stop))

    feeding = False
    while feeding == True:
        if current_bid > pyramid_add:
            # buy(pyramid_add)
            enable('buy', price=pyramid_add)
        if filled:
            pass
Esempio n. 20
0
def take_purchase(product_instance, qty):
    """Take a purchase"""
    new_order = Order(product_instance.name, product_instance.cost, qty)
    return new_order
Esempio n. 21
0
 def test_str(self):
     order1 = Order('alice in wonderland', Decimal("10.00"), 2)
     self.assertEqual(str(order1), "Order: 2 of alice in wonderland.")
Esempio n. 22
0
 def test_total_cost(self):
     order = Order('alice in wonderland', Decimal("10.00"), 2)
     self.assertEqual(order.total_cost(), Decimal("20.00"))
Esempio n. 23
0
import unittest
from reception import Reception
from config import config
from orders import Order

from mt_list import MTList

from cook import Cook

Order({
    u'id': u'a8cfcb76-7f24-4420-a5ba-d46dd77bdffd',
    u'prepTime': 4,
    u'name': u'Banana Split'
})


class Testing(unittest.TestCase):
    def setUp(self):
        self.o = Order({
            u'id': u'a8cfcb76-7f24-4420-a5ba-d46dd77bdffd',
            u'prepTime': 4,
            u'name': u'Banana Split'
        })
        cooking = MTList()
        cooking.put(self.o)
        self.c = Cook(MTList(), cooking)

    def test_cook_order(self):
        self.c.cook_order()
        self.assertEqual(self.o, self.c.get_delivery_queue().get())
Esempio n. 24
0
 def test_order(self):
     order = Order('alice in wonderland', Decimal("10.00"), 2)
     self.assertEqual(order.product_name, 'alice in wonderland')
     self.assertEqual(order.cost, Decimal("10.00"))
     self.assertEqual(order.qty, 2)
Esempio n. 25
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from events import Event
from orders import Order

e = Event('2018-01-01')
o = Order(10)
o1 = Order(10)
print(o1 == o)

Esempio n. 26
0
import json
import pprint
from orders import Order, OrderLeg
from enums import ORDER_SESSION, DURATION, ORDER_INSTRUCTIONS, ORDER_ASSET_TYPE

# initalize a Saved Order Object
new_saved_order = Order()

# define the session of this saved order.
new_saved_order.order_session(session=ORDER_SESSION.NORMAL)

# define the duration
new_saved_order.order_duration(duration=DURATION.GOOD_TILL_CANCEL)

# define the duration, with string
new_saved_order.order_duration(duration='GOOD_TILL_CANCEL')

new_order_leg = OrderLeg()
new_order_leg.order_leg_instruction(instruction=ORDER_INSTRUCTIONS.SELL)
new_order_leg.order_leg_price(price=112.50)
new_order_leg.order_leg_quantity(quantity=10)
new_order_leg.order_leg_asset(asset_type=ORDER_ASSET_TYPE.EQUITY,
                              symbol='MSFT')

copied_order_leg = new_order_leg.copy()

new_saved_order.add_order_leg(order_leg=new_order_leg)
new_saved_order.add_order_leg(order_leg=copied_order_leg)

# pprint.pprint(new_saved_order.grab_order())
Esempio n. 27
0
def manage_cart(request, tmpl, user_id=None, action=None, product_id=None):
    user = None
    if user_id:
        try:
            user = User.objects.get(id=user_id)
        except:
            user = None
    msg_ok = msg_err = products = cart = None
    products = None
    if user:
        cart = Cart(request, user.id)
        if request.user.is_staff:
            products = Article.objects.all().order_by('order')
        else:
            products = Article.objects.filter(enabled=True).order_by('order')
        if action == 'add':
            product_id = int(request.POST.get('cart_add'))
            if cart.add(product_id, 1):
                msg_ok = _(u"Product successfully added to cart")
            else:
                msg_err = _(u"Error while adding product to cart")
        elif action == 'del':
            if cart.delete(int(product_id)):
                msg_ok = _(u"Product successfully removed from cart")
            else:
                msg_err = _(u"Error while removing product from cart")
        elif action == 'update':
            update = True
            for k,v  in request.POST.iteritems():
                product_id = 0
                try:
                    quantity = int(v)
                except:
                    quantity = 0
                if k.startswith('product_'):
                    product_id = int(k[8:])
                    update = update and cart.update(product_id, quantity)
            if update:
                msg_ok = _(u"Product(s) successfully updated")
            else:
                msg_err = _(u"Error while updating product(s)")
        elif action == 'validate':
            valid = cart.is_valid()
            if not valid and request.user.is_staff:
                valid = request.POST.get('force') == '1'
            if not valid:
                msg_err = _(u"Unable to confirm this order, one (or more) product(s) in the cart exceed the available quantity")
            else:
                order = Order(user=user, creation_date=date.now())
                order.save_confirm(cart)
                cart.clear()
                msg_ok = _(u"Order successfully confirmed")
        cart.save(request)
    return tmpl, {
        'user_obj': user,
        'products': products,
        'cart': cart,
        'msg_err': msg_err, 'msg_ok': msg_ok,
        'is_admin': request.user.is_staff,
        'currency': settings.CURRENCY, 'currency_alt': settings.CURRENCY_ALT,
    }
Esempio n. 28
0
 def put_order_to_queue(self, order):
     self.cooking_queue.put(Order(order))
     if self.matched_queue != None:
         self.matched_queue.put(order["id"])