Ejemplo n.º 1
0
    def post(self):
        student = request.form['student']
        subject = request.form['subject']
        address = request.form['address']
        duration = int(request.form['duration'])
        payment_type = request.form['payment_type']

        balance = requests.get(
            'http://go-teach-balance.herokuapp.com/balances/{}'.format(
                student)).json()
        total_cost = COST_PER_HOUR * duration
        if (total_cost > 0) and (balance['amount'] >= total_cost
                                 or payment_type == 'cash'):
            order = OrderModel(student=student,
                               teacher='',
                               subject=subject,
                               address=address,
                               duration=duration,
                               payment_type=payment_type,
                               status='available')
            if payment_type != 'cash':
                requests.post(
                    'http://go-teach-balance.herokuapp.com/balances/{}/charge',
                    data={'amount': total_cost})
            order.save_to_db()
            return {'status': 'OK'}
        else:
            return {'status': 'Balance not enough'}
Ejemplo n.º 2
0
def submit():
    user_name = request.form.get('user_name')
    user_depart = request.form.get('user_depart')
    reason = request.form.get('reason')
    start_hour = request.form.get('start_hour')
    end_hour = request.form.get('end_hour')
    select_week = request.form.get('select_week', '0')
    office = request.form.get('office').strip()

    office_model = OfficeModel.query.filter(OfficeModel.desc == office).first()
    if not office_model:
        return '未能查到办公室' + '"' + office + '"'

    new_order = OrderModel(user_name=user_name,
                           depart_name=user_depart,
                           reason=reason,
                           order_from=start_hour,
                           order_to=end_hour,
                           office_id=office_model.id)
    new_order.order_day = time_offset(select_week)
    db.session.add(new_order)
    db.session.commit()

    flask_whooshalchemyplus.index_one_model(OrderModel)
    return ''
Ejemplo n.º 3
0
  def post(self):
    log.info("create")
    try:
      
      user = users.get_current_user()
      user_id = user.user_id()

      self.response.headers['Content-Type'] = 'text/json'

      cart_entity = CartModel(id=user_id).get_by_id(user_id)
      log.info(cart_entity)
      if "to_dict" in dir(cart_entity):
        new_order = OrderModel(
          user_id    = user_id,
          cart  = cart_entity
        )
      else:
        self.response.set_status(404)
        self.response.write(json.dumps({
          "message": "Could not place order. No cart Found.",
          "success": False
        }))
        return
      
      result = new_order.put()
      if result:
        entity = result.get().to_dict()
        entity['success'] = True
        self.response.set_status(201)
        self.response.write(json.dumps(entity))
    
    except users.UserNotFoundError, e:
      # Should never happen - just incase of solar flares
      log.debug('User was not found...')
Ejemplo n.º 4
0
def cart():
    # Проверяем наличие товаров в корзине
    if not session.get('cart_id'):
        error = "Ваша корзина пуста. Для оформления заказа необхоимо выбрать блюда."
        return render_template('error.html', error=error)

    form = OrderForm()
    # проверяем правильно заполнена ли форма (запрос POST)
    if form.validate_on_submit():
        order = OrderModel()
        user = session.get('user_id')
        # проверяем авторизирован ли пользователь, если нет - добавляем его в базу но без пароля и роль=guest
        if not user:
            user = UserModel(name=form.name.data,
                             email=form.email.data,
                             address=form.address.data,
                             phone=form.phone.data,
                             role='guest')
            db.session.add(user)
            db.session.commit()
        # пользователь авторизирован, можно из базы подгрузить его данные сразу в форму заказа
        else:
            user = db.session.query(UserModel).get(session.get('user_id'))
        # проверяем есть ли выбранные для заказа блюда, если да - делаем заказ
        if session.get('cart_id'):
            order.users = user
            order.summa = sum(list(map(int, session.get('cart_price'))))
            meals = list(map(int, session.get('cart_id')))
            for meal in meals:
                meal = db.session.query(MealModel).get(meal)
                order.meals.append(meal)
            db.session.add(order)
            db.session.commit()
            session['cart_id'] = []
            session['cart_price'] = []
            return redirect('/ordered/')
        else:
            flash('У вас нет блюд в корзине. Дбавьте блюдо и повторите оформление заказа.')
            return redirect('/')

    # Проверяем прошел ли пользователь аутентификацию
    if session.get('user_id'):
        user = db.session.query(UserModel).get(session['user_id'])
        form.name.data = user.name
        form.email.data = user.email
        form.address.data = user.address
        form.phone.data = user.phone
    meals = []
    for meal in session.get('cart_id'):
        meal = db.session.query(MealModel).get(meal)
        meals.append(meal)
    return render_template('cart.html', meals=meals, form=form)
Ejemplo n.º 5
0
    def get(self):
        current_user = get_jwt_identity()
        logged_user = UserModel.find_by_username(current_user)

        db_result = OrderModel.find_valid_by_user(logged_user)

        result = list()
        for item in db_result:
            menu_list = list()
            for menu in item.menus:
                menu_list.append({
                    'menu_id': menu.menu.id,
                    'menu_name': menu.menu.name,
                    'taste_level': menu.menu.taste_level,
                    'water_level': menu.menu.water_level,
                    'foam_level': menu.menu.foam_level,
                    'grind_size': menu.menu.grind_size,
                    'menu_type': menu.menu.menu_type,
                    'coffee_option': menu.menu.coffee_option,
                    'counts': menu.counts
                })
            result.append({
                'order_id':
                item.id,
                'order_contents':
                menu_list,
                'order_date':
                item.create_date.strftime("%Y-%m-%d %H:%M:%S")
            })

        return result
Ejemplo n.º 6
0
  def get(self):
    try:

      self.response.headers['Content-Type'] = 'text/json'

      user = users.get_current_user()
      user_id = user.user_id()

      entities = OrderModel.query( OrderModel.user_id == user_id )
      
      response = {"success": True, "entities":{}}

      for entity in entities.fetch():
        key_id = entity.key.id()
        response['entities'][key_id] = (entity.to_dict())

      self.response.write(json.dumps(response))

    except Exception, e: 
      # Should Log to console - exception message
      log.debug(e)
      self.response.write(
        json.dumps({
          "success": False, 
          "message": "ViewHandler Exception: " + e.message
      }))
Ejemplo n.º 7
0
    def get(self, order_id=None):
        if not order_id:
            return {'message': 'user not found'}, 404

        order = OrderModel.get_by_id(order_id)
        if order:
            if order.is_obsolete and order.id != 1:
                return {'message': 'order was obsoleted'}, 400
            else:
                menu_list = list()
                for menu in order.menus:
                    menu_list.append({
                        'menu_id': menu.menu.id,
                        'menu_name': menu.menu.name,
                        'coffee_option': menu.menu.coffee_option,
                        'taste_level': menu.menu.taste_level,
                        'water_level': menu.menu.water_level,
                        'foam_level': menu.menu.foam_level,
                        'grind_size': menu.menu.grind_size,
                        'menu_type': menu.menu.menu_type,
                        'counts': menu.counts
                    })
                return {
                    'order_id': order.id,
                    'order_contents': menu_list,
                    'order_date':
                    order.create_date.strftime("%Y-%m-%d %H:%M:%S")
                }
        else:
            return {'message': 'order not found'}, 404
Ejemplo n.º 8
0
    def mutate(root, info, productId, qty):
        order = OrderModel(qty=qty, productId=productId)
        db_session.add(order)
        db_session.commit()

        ok = True
        return CreateOrder(order=order, ok=ok)
Ejemplo n.º 9
0
    def get(self, received):
        order_id = received.get('order_id')
        serial_number_str = received.get('serial_number')

        result = list()
        if order_id:
            order = OrderModel.get_by_id(order_id=received.get('order_id'))
            if order:
                db_result = SerialNumberModel.find_by_order(order=order)
                for item in db_result:
                    result.append({
                        'serial_number': item.serial_number,
                        'menu_id': item.menu.id,
                        'order_id': item.order.id
                    })
            else:
                return {'message': 'order_id not found'}, 404
        elif serial_number_str:
            serial = SerialNumberModel.get_by_serial_number(
                serial_number=serial_number_str)

            if serial:
                logging.error(serial.order.customized_message)
                result = {
                    'serial_number': serial.serial_number,
                    'customized_message': serial.order.customized_message
                }
            else:
                return {'message': 'serial_number not found'}, 404
        else:
            return {'message': 'order or serial is required.'}, 400

        return result
Ejemplo n.º 10
0
 def mutate(self, info, dealer_id, customer_id, price):
     order = OrderModel(dealer_id=dealer_id,
                        customer_id=customer_id,
                        price=price)
     db_session.add(order)
     db_session.commit()
     return makeOrder(dealer_id=order.dealer_id,
                      customer_id=order.customer_id,
                      price=order.price)
Ejemplo n.º 11
0
    def RemoveListeners(self):
        """Called when the frame is closed (destroyed).

        This ensures we don't try to push updates to a non-existent
        object.

        """

        omodel = OrderModel.Instance()
        omodel.RemoveListener(self._bpanel.lst.OnNewOrderInformation)
Ejemplo n.º 12
0
    def patch(self, order_id=None):
        if not order_id:
            return {'message': 'order not found'}, 404

        order = OrderModel.get_by_id(order_id)
        if order:
            order.is_obsolete = True
            order.save_to_db()
            return {'order_id': order.id, 'is_obsoleted': order.is_obsolete}
        else:
            return {'message': 'user not found'}, 404
Ejemplo n.º 13
0
  def delete(self, id):
    try:

      self.response.headers['Content-Type'] = 'text/json'

      if not id:
        self.response.set_status(204)
        self.response.write("{\"id value missing from url. aborted update.\"}")
        return

      user = users.get_current_user()
      user_id = user.user_id()

      try:
        error = False
        entity = OrderModel(id=int(id)).get_by_id(int(id))
        if "key" in dir(entity):
          if user_id == entity.user_id:
            entity.key.delete()
            self.response.set_status(200)
            self.response.write(json.dumps( {"success": True, "entity": { "id": user_id } } ))
          else:
            error = True
            msg = "Not authorized to delete this record. Bad user!"    
        else:
          error = True
          msg = "Whahey it's like Jimmy Hoffa, No body... I mean entity found"

        if error:
          self.response.set_status(200)
          self.response.write(json.dumps( {"success": False, "message": msg } ))


      except AttributeError, e:

        log.debug(e)
        self.response.set_status(404)
        self.response.write(
        json.dumps({
          "success": False, 
          "message": "DeleteHandler Exception: " + e.message
        }))  
      
    except Exception, e: 
      # Should Log to console - exception message
      log.debug(e)
      self.response.set_status(404)      
      self.response.write(
        json.dumps({
          "success": False, 
          "message": "DeleteHandler Exception: " + e.message
      }))
Ejemplo n.º 14
0
    def post(self, received_item):
        current_user = get_jwt_identity()
        logged_user = UserModel.find_by_username(current_user)

        try:
            new_order = OrderModel(
                user_id=logged_user.id,
                customized_message=received_item.get("message"),
                create_date=datetime.datetime.utcnow())

            for item in received_item.get("order"):
                found_menu = MenuModel.get_by_id(item.get("menu_id"))
                a = AssociationModel(counts=item.get("counts"))
                a.menu = found_menu
                new_order.menus.append(a)

            new_order.save_to_db()
            result = {"message": "successful"}
        except (Exception, ):
            logger.exception("create order failed")
            result = {"message": "failed"}
        return result
Ejemplo n.º 15
0
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, size=(1200, 200), title='Live Bets')

        psizer = wx.BoxSizer(wx.HORIZONTAL)
        self._bpanel = LiveBetsPanel(self)
        psizer.Add(self._bpanel, 1, wx.EXPAND | wx.ALL | wx.ALIGN_CENTER)

        # model for MVC
        omodel = OrderModel.Instance()
        omodel.AddListener(self._bpanel.lst.OnNewOrderInformation)

        # force initial update
        omodel.UpdateViews()

        self.SetSizer(psizer)
Ejemplo n.º 16
0
def setupDB():
    # This function sets up the database. After processing the input file function and getting each dictionary
    # the dataframes need to be put into the SQL database for the information to be used later and throughout
    # each simulation

    num_rows, num_columns, num_drones, max_time, max_cargo, products, wh_list, order_list, order_product, warehouse_products = read_file(
        './assets/busy_day.in')
    dbms = hash_database.HashDataBase(
        hash_database.SQLITE,
        dbname='hash.sqlite')  # Creating database session to call on
    dbms.create_db_tables()
    Session = sessionmaker(bind=dbms.db_engine)
    session = Session()

    # add each product, order, order products, warehouse, and warehouse products to database
    for product in products:
        session.add(
            ProductModel(**product))  # append database with product types
    for order in order_list:
        session.add(OrderModel(**order))  # append database with order ids
    for order in order_product:
        # session.add(order_product_model.OrderModel(**order))
        order_id = order["order_id"]
        for key in dict(order["items"]).keys(
        ):  # for each product of the orders, add with an id, qty, weight, etc
            order["items"][key]
            session.add(
                OrderProductModel(      # order product model file arguments
                    **{
                        "order_id":order_id,
                        "product_id": key,
                        "qty": order["items"][key]
                    }
                )
            )
    for warehouse in wh_list:
        session.add(
            WarehouseModel(**warehouse))  # append database with warehouse ids

    for wh_product in warehouse_products:  # append database with warehouse product ids and quantities
        for wh_pr in wh_product:
            session.add(WarehouseProductModel(**wh_pr))
    session.commit()
Ejemplo n.º 17
0
 def food(self, request):
     print "food method"
     if request.user.is_superuser:
         return
     food_id = request.GET["food"]
     food_list = list(FoodModel.objects.filter(id=food_id))
     if not food_list:
         return
     order = list(OrderModel.objects.filter(user=request.user.id, confirm=False))
     if not order:
         p = OrderModel(user=request.user.id, address="", confirm=False, time=timezone.now())
         p.save()
         order = p
     else:
         order = order.pop()
     food_object = food_list.pop()
     p = BasketModel(order=order, food=food_object)
     p.save()
     self.getorderinfo(order)
Ejemplo n.º 18
0
  def put(self, id):
    try:

      self.response.headers['Content-Type'] = 'text/json'

      user = users.get_current_user()
      user_id = user.user_id()

      if not id:
        self.response.set_status(204)
        self.response.write("{\"id value missing from url. aborted update.\"}")
        return

      try:
        jdata = json.loads(self.request.body)
      except ValueError, e:
        log.debug(e)
        self.response.set_status(404)
        msg = {'success': False, 'message': "Failed to read JSON body"}
        self.response.write(json.dumps(msg))
        return
    
      entity = OrderModel(id=int(id)).get_by_id(int(id))
      
      entity.id        = id 
      entity.user_id   = user_id
      entity.cart      = jdata['cart']
      entity.created   = jdata['created'] 

      result = entity.put()

      if result:
        entity = result.get().to_dict()
        entity['success'] = True

        self.response.set_status(200)
        self.response.write(json.dumps(entity))