예제 #1
0
def createOrder():
    current_user = get_jwt_identity()

    vir = Order(current_user)
    db.session.add(vir)
    db.session.commit()

    carts = Cart.query.filter_by(creator_id=current_user, removed=False).all()
    orders = []
    for cart in carts:
        product = Product.query.filter_by(id=cart.product_id,
                                          shelved=True,
                                          archived=False).first()
        description = Description.query.filter_by(product_id=cart.product_id,
                                                  active=True,
                                                  removed=False).first()
        # 限购暂未实现
        print(description.remain, cart.count)
        if (not product) or (not description) or (description.remain <
                                                  cart.count):
            orders.append([False, cart.id])
            continue
        description.remain = description.remain - cart.count
        order = Order(current_user)
        order.fill(cart.product_id, cart.count, description.price, vir.id)
        db.session.add(order)
        cart.removed = True
        db.session.commit()
        orders.append(
            [True, cart.id, cart.product_id, cart.count, description.price])
    return jsonify(orders=orders, price=vir.cost()), 200
def booking(id):
    apartment = Apartment.query.filter_by(id=id).first()
    if request.method == 'POST':
        daterange = request.values.get('daterange')
        if daterange:
            l = daterange.split('-')
            checkin = datetime.strptime(l[0].strip(), '%m/%d/%Y').date()
            checkout = datetime.strptime(l[1].strip(), '%m/%d/%Y').date()

            if not apartment.checkbooking(checkin, checkout):
                booking = Order(user_id=current_user.id,
                                apartment_id=id,
                                checkin_date=checkin,
                                checkout_date=checkout)

                db.session.add(booking)
                db.session.commit()

                flash('This booking ordered.', 'success')
                return redirect(url_for('apartment', id=id))
            else:
                flash('This apartment is booked in this daterange', 'info')
        else:
            flash('Booking date not selected.', 'warning')
    return render_template('booking.html', data=apartment)
예제 #3
0
    def get(self):
        orderitems = []
        user = self.current_user

        try:
            order = Order.get(uid=user.id, status=0)

            for orderitem in OrderItem.select().where(
                    OrderItem.oid == order.id).dicts():
                try:
                    orderitem['shop'] = Shop.get(id=orderitem['sid'])
                    if orderitem['said'] > 0:
                        orderitem['shopattr'] = ShopAttr.get(
                            id=orderitem['said'])
                    orderitems.append(orderitem)
                except:
                    pass
        except:
            order = Order()

        ashops = Shop.select().where((Shop.cid == 2) & (Shop.status != 9))
        self.render("shop/order.html",
                    orderitems=orderitems,
                    order=order,
                    ashops=ashops)
예제 #4
0
def create_order():
    global order_counter
    parser = reqparse.RequestParser()
    parser.add_argument('coffee_id', type=int, required=True)
    parser.add_argument('additions', type=str, action='append')
    args = parser.parse_args()

    coffee_id = args.get("coffee_id")
    additions = args.get("additions")
    for row in coffee_db:
        if int(row.coffee_id) == int(coffee_id):
            coffee = row
            break
    else:
        return jsonify(coffee_id=False), 404

    order_counter += 1
    new = Order(order_counter, coffee_id, coffee.coffee_name, coffee.cost,
                'open', additions)
    order_db.append(new)
    return jsonify({
        'data': new.__dict__,
        'payment': {
            'link': url_for('create_payment', order_id=order_counter),
            'method': 'POST'
        }
    }), 201
예제 #5
0
    def accept_mission(self, mission: Mission) -> Mission:
        # Missionの更新であれば(=IDが同じであれば)既存のものを消す
        if mission.get_id() in self.missions:
            self.remove_mission(mission.get_id())

        # 部下のOrderを生成・割り当てる
        target_subs = []
        if mission.place == "All":
            target_subs = list(self.subordinates.values())
        for sol in target_subs:
            m_req = mission.requirement
            values = list(set(m_req.values).intersection(sol.weapons))
            order = Order(author=sol.id,
                          values=values,
                          trigger=m_req.trigger,
                          purpose=mission.get_id())
            sol.orders.append(order)

        # 自身のデータ送信スレッドを生成する
        th = WorkingThread(self, mission)
        self.working_threads.append(th)
        th.start()

        self.missions[mission.get_id()] = mission
        return mission
예제 #6
0
    def test_job_transmission(self):
        self.awake_single()
        # campaignをセット
        campaign = Campaign(author="cxxx0",
                            requirement=Requirement(values=["zero", "random"],
                                                    trigger={"timer": 1}),
                            trigger={"timer": 5},
                            place="All",
                            purpose="test_purpose",
                            destination="mongodb://localhost:27017/")
        clients["cxxx0"].post('/commander/campaigns',
                              data=json.dumps(campaign.to_dict()),
                              content_type='application/json')
        time.sleep(1.5)  # heartbeatを待つ; 0.7 + 0.4 + alpha

        # missionを確認
        mission = Mission(author="lxxx0",
                          requirement=Requirement(values=["zero", "random"],
                                                  trigger={"timer": 1}),
                          trigger={"timer": 5},
                          place="All",
                          purpose=campaign.get_id())
        self.assertIn(mission, self.models["lxxx0"].missions.values())

        # orderを確認
        order = Order(author="sxxx0",
                      values=["zero", "random"],
                      trigger={"timer": 1},
                      purpose=mission.get_id())
        self.assertIn(order, self.models["sxxx0"].orders.values())
예제 #7
0
def add_order_details(order_id, address, user_id):
    try:
        order = Order(order_id=order_id, address=address, user=user_id)
        db.session.add(order)
        db.session.commit()
        return True
    except IntegrityError:
        return make_response(
            jsonify({'response': "user name or email already exists"}), 400)
    except (InvalidRequestError, OperationalError):
        raise InvalidUsageError('sql connection or syntax is improper', 500)
예제 #8
0
def save_order(order_data):
    order = Order(order_id=order_data.get("id"),
                  side=order_data.get("side"),
                  state=order_data.get("state"),
                  price=float(order_data.get("price")),
                  symbol=order_data.get("symbol"),
                  amount=float(order_data.get("amount")),
                  filled_amount=float(order_data.get("filled_amount")),
                  fill_fees=float(order_data.get("fill_fees")))
    with DBSession() as session:
        session.add(order)
예제 #9
0
def order_item(order_event):
    logger.info('order_item: {}'.format(order_event))
    try:
        order = Order(order_event['order_id'],
                      order_date=order_event['order_date'],
                      customer_id=order_event['customer_id'],
                      items=order_event['items'],
                      order_status='APPROVED_PENDING')
        return order
    except Exception as e:
        logging.error('Error: order_item: {}'.format(vars(e)))
        raise e
예제 #10
0
 def insert_order(self, order_dict):
     order = Order(id=order_dict.get('id'),
                   reqId=order_dict.get('reqId'),
                   createTime=datetime.now(),
                   updateTime=None,
                   status=order_dict.get('status'),
                   total=order_dict.get('total'),
                   payWay=order_dict.get('pay_way'))
     session = self.get_session()
     session.add(order)
     session.commit()
     session.close()
def reject_order(order_event):
    status = 'REJECTED'
    try:
        order = Order(order_event['order_id'])
        order.update(actions=[
            Order.order_status.set(status)
            # Order.cause.set(order_event['error']['Error'])
        ])
        return
    except UpdateError as e:
        error_message = 'update_order Error: {}'.format(vars(e))
        logging.exception(error_message)
        raise ErrorOrderUpdate(error_message)
예제 #12
0
def submit_order():
    headers = request.headers
    if headers['Authorization'] != os.getenv("WEBHOOK_PSWD"):
        return ""

    data = request.json
    data['order_id'] = data['id']
    del data['id']
    del data['status']
    order = Order(**data)
    order.save()

    return jsonify({"success": True})
예제 #13
0
    def post(self):

        result = {'status': False, 'msg': 0}
        user = self.get_current_user()

        if user:
            sid = int(self.get_argument("sid", 0))
            said = int(self.get_argument("said", 0))
            num = int(self.get_argument("num", 1))

            #判断商品是否下架
            if sid > 0 and said > 0 and num > 0:
                try:
                    Shop.get(id=sid)
                    ShopAttr.get(id=said)

                    #判断是否有未使用的订单或生成新订单
                    try:
                        try:
                            order = Order.get(uid=user.id, status=0)
                        except:
                            order = Order()
                            order.uid = user.id
                            order.mobile = user.mobile
                            order.ordered = int(time.time())
                            try:
                                order.save()
                            except Exception, ex:
                                logging.error(ex)

                        try:
                            orderitem = OrderItem.get(oid=order.id,
                                                      sid=sid,
                                                      said=said)
                        except:
                            orderitem = OrderItem()

                        orderitem.oid = order.id
                        orderitem.sid = sid
                        orderitem.said = said
                        orderitem.num = orderitem.num + num
                        orderitem.save()

                        result['status'] = True
                        result['msg'] = 200

                    except Exception, ex:
                        logging.error(ex)
                        result['msg'] = 500

                except:
예제 #14
0
def approve_order(order_event):
    status = 'APPROVED'
    try:
        order = Order(order_event['order_id'])
        order.update(
            actions=[
                Order.order_status.set(status)
            ]
        )
        return

    except UpdateError as e:
        error_message = 'update_order Error: {}'.format(vars(e))
        logging.exception(error_message)
        raise ErrorOrderUpdate(error_message)
예제 #15
0
def new_order(customer_id, product_list):

    order = Order(customer_id)

    db.session.add(order)
    db.session.commit(
    )  # order id has to be generated first to add products in order

    for product in product_list:

        link = product.get('link')
        description = product.get('description')
        quantity = product.get('quantity')

        new_product(order.id, link, description, quantity)
예제 #16
0
파일: seed.py 프로젝트: tessajules/Cartsee
def add_order(amazon_fresh_order_id, delivery_date, delivery_day_of_week,
              delivery_time, user_gmail, line_items_one_order):
    """Adds information for one order to database"""

    order = Order.query.filter_by(
        amazon_fresh_order_id=amazon_fresh_order_id).first()

    if order:
        print "Order # %s already in database" % amazon_fresh_order_id
    else:
        order = Order(amazon_fresh_order_id=amazon_fresh_order_id,
                      delivery_date=delivery_date,
                      delivery_day_of_week=delivery_day_of_week,
                      delivery_time=delivery_time,
                      user_gmail=user_gmail)
        db.session.add(order)

        print "Order # %s added to database" % amazon_fresh_order_id

        for line_item_info in line_items_one_order:  # line_item_info is a list of info for one line item ex [1, 5.50, "description"]
            quantity, unit_price_cents, description = line_item_info

            description_key = ""
            for char in description:
                if char.isalpha():
                    description_key += char
            description_key = description_key.lower()

            item = Item.query.filter_by(
                description_key=description_key).first()

            if item:
                print "General item description '%s' already in database." % (
                    description)
            else:
                add_item(description, description_key)
                print "General item description '%s' added to database." % (
                    description)

            item = Item.query.filter_by(
                description_key=description_key).first()

            add_line_item(amazon_fresh_order_id, item.item_id,
                          unit_price_cents, quantity)
            print "Line item '%s', added to database for order # %s" % (
                description, amazon_fresh_order_id)

    db.session.commit()
예제 #17
0
def postUserPublishContent():
    #if not request.args or not 'userId' in request.args:
    #    abort(400)
    #else:
    try:
        data = json.loads(request.get_data(as_text=True))
        orderid = Order.query.count()
        newOrder = Order(orderid, request.args.get('userId'),
                         data['entrepotlist'], data['description'], "", "", 0,
                         data['timeProposed'], data['price'], "", "", "")
        db.session.add(newOrder)
        db.session.commit()
    except:
        abort(500)
    else:
        return jsonify(request.form), 201
예제 #18
0
    def create_order(self, rq_user_id, products):
        session = self.Session()

        try:
            user = session.query(User).get(rq_user_id)

            if user is None:
                raise Exception('Unable to find user with id = %s' %
                                rq_user_id)

            order_line_list = []
            user_order = Order(user_id=rq_user_id, order_total=0)

            for prod_def in products:
                db_product = session.query(Product).get(prod_def['productId'])
                if db_product is None:
                    raise Exception('Product not found with ProductID: %s' %
                                    prod_def['productId'])
                order_line = OrderLine(product=db_product,
                                       order=user_order,
                                       quantity=prod_def['quantity'])
                order_line_list.append(order_line)
                user_order.order_total = user_order.order_total + db_product.price * prod_def[
                    'quantity']

            session.add(user_order)
            session.add_all(order_line_list)
            session.commit()

            the_order = session.query(Order).get(user_order.order_id)

            return the_order.to_json()

        except Exception as e:
            logging.error('*** Exception in create_order: %s' % e)
            traceback.print_exc()

            session.rollback()
            raise
        finally:
            session.close()
예제 #19
0
def main():

    start_mapper()

    # create all the tables
    metadata.create_all(bind=engine)

    order = Order("ORD-1", "John Doe")
    line1 = Line(order, "Product-1", 10)
    line2 = Line(order, "Product-2", 20)
    line3 = Line(order, "Product-3", 12)

    # save
    uow = SqlAlchemyUnitOfWork()

    with uow:
        uow.repo.add(order)

    with uow:
        order = uow.repo.get("ORD-1")
        print(order.lines)
예제 #20
0
파일: crud.py 프로젝트: vsgit-lsd/kursas
def create_order():
    options_list(Customer)
    customer_id = input("\nCustomer Id: ")
    order = Order(customer_id=customer_id, status_id=1)
    session.add(order)
    session.commit()
    last_order_id = session.query(Order).all()[-1].id
    print('Products available:')
    options_list(Product)
    while True:
        product_id = input('\nProduct Id: ')
        quantity = input('Quantity: ')
        if product_id and quantity:
            order_product = OrderProduct(order_id=last_order_id,
                                         product_id=product_id,
                                         quantity=quantity)
            session.add(order_product)
            session.commit()
        else:
            print('created!\n')
            break
예제 #21
0
def create_order():
    order = Order()

    form = OrderForm(request.form, obj=order)

    if form.validate():
        form.populate_obj(order)

        order.keychain_text = order.keychain_text.strip()
        order.cost_satoshis = 100 + 25 * len(order.keychain_text)

        invoice = make_invoice(order.cost_satoshis)

        order.payment_request = invoice["pay_req"]
        order.request_hash = invoice["r_hash"]

        order.save()

        return redirect(url_for('retrieve_order', order_id=order.id))
    else:
        return render_template('order.jinja2', form=form)
예제 #22
0
파일: views.py 프로젝트: giskar/shop
def buy():
    if request.method == 'POST' and request.form['name']:

        order = Order(
            # goods = request.form['goods'],
            name=request.form['name'],
            phone=request.form['phone'],
            pay_method=request.form['payment'],
            del_method=request.form['delivery'],
        )
        order.save()

        # huey = Goods.get(Goods.id == 2)
        # cs1 = Order.get(Order.id == 2)
        # huey.orders.add(cs1)
        #
        id_goods = request.form['goods'].split()
        for id in id_goods:
            huey = Goods.get(Goods.id == id)
            huey.orders.add(Order.get(Order.id == order.id))

    return redirect(url_for('goods_list'))
예제 #23
0
    def test_order_do(self):
        self.soldier.superior_ep = "test://lxxx0/leader/"
        order = Order(author="sxxx0",
                      values=["zero", "random"],
                      trigger={"timer": 0.7},
                      purpose="some purpose hash")

        def post_work(url, data=None, json=None, etag=None, **kwargs):
            res = requests.Response()
            res.status_code = 200
            res_dict = {
                "_status": {
                    "msg": "ok",
                    "success": True
                },
                "accepted": json
            }
            res._content = dumps(res_dict).encode()
            return res, None

        with patch("utils.rest.post", side_effect=post_work) as m:
            self.soldier.accept_order(order)
            time.sleep(1)
            self.assertEqual(m.call_count, 1)
            self.assertEqual(m.call_args[0][0],
                             "test://lxxx0/leader/subordinates/sxxx0/work")

            # workのチェック
            actual = m.call_args[1]["json"]
            self.assertEqual(set(actual.keys()), {"time", "purpose", "values"})
            self.assertEqual(actual["purpose"], "some purpose hash")
            self.assertEqual(len(actual["values"]), 2)
            for v in actual["values"]:
                self.assertEqual({"type", "value", "unit"}, set(v.keys()))

        self.soldier.superior_ep = ""  # shutdownでDELETEを送信するのを阻止
예제 #24
0
def post_order():
    userid = g.current_user.id
    userphone = g.current_user.phone
    orderitems = request.get_json().get('orderitems')
    addressid = request.get_json().get('addressid')
    teamid = g.current_user.teamid

    # 设计订单编号
    nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M")  #生成当前时间
    randomNum = random.randint(10000, 100000)  #生成的随机5位整数n,其中1000<=n<=10000
    phnumber = str(userphone)[-4:]
    ordernumber = '%s%s%s%s' % (int(nowTime), int(phnumber), int(teamid),
                                int(randomNum))

    # 订单类型
    order_type = orderitems[0]['order_type']

    # 计算订单总金额 和 图片真实地址 和 购物车id
    cartid = []
    all_total = 0
    if 'cartid' not in orderitems[0]:
        all_total = orderitems[0]['color_total']
    else:
        for i in range(len(orderitems)):
            # 计算订单总金额
            all_total += orderitems[i]['color_total']
            # 得到购物车id
            cartid.append(orderitems[i]['cartid'])

    if len(orderitems) > 0:

        addorder = Order(number=ordernumber,
                         userid=userid,
                         teamid=teamid,
                         addressid=addressid,
                         state=0,
                         order_total=all_total,
                         order_type=order_type,
                         addtime=datetime.datetime.now())

        try:
            db_session.add(addorder)
            db_session.commit()
            # 获取刚加添加的id
            db_session.flush()
            order_id = addorder.id
            order_item = [
                OrderDetailed(proid=int(orderitems[i]['proid']),
                              pronumber=orderitems[i]['pronumber'],
                              size=orderitems[i]['size'],
                              color=orderitems[i]['color'],
                              unit=int(orderitems[i]['unit']),
                              price=int(float(orderitems[i]['price'])),
                              color_total=int(orderitems[i]['color_total']),
                              order_id=int(order_id))
                for i in range(len(orderitems))
            ]

            try:
                db_session.add_all(order_item)
                db_session.commit()
            except Exception as e:
                print(e)
                db_session.rollback()
                return jsonify({'code': 3, 'message': '数据库错误'})

        except Exception as e:
            print(e)
            db_session.rollback()
            return jsonify({'code': 3, 'message': '数据库错误'})

        # 删除购物车
        delcart = db_session.query(UserCart).filter(UserCart.id.in_(
            (cartid))).all()
        try:
            [db_session.delete(n) for n in delcart]
            db_session.commit()
            db_session.close()
        except Exception as e:
            print(e)
            db_session.rollback()
            return jsonify({'code': 3, 'message': '数据库错误'})

        return jsonify({'code': 1, 'message': '下单成功'})
예제 #25
0
def create_order(user_id, book_id, quantity, total):
    order = Order(user_id = user_id, book_id = book_id, quantity = quantity, total = total)
    db.session.add(order)
    db.session.commit()
    return order
    def add_val():
        # add user to database
        admin = User(username='******', phone='12345')
        admin.set_password('12345678')
        user = User(username='******', phone='0000')
        user.set_password('12345678')
        u1 = User(username='******', phone='0001')
        u1.set_password('test01')
        u2 = User(username='******', phone='0002')
        u2.set_password('test02')
        # add the data to session
        db.session.add_all([admin, user, u1, u2])
        db.session.flush()
        # add apartment to database
        a1 = Apartment(a_name='Stroll around Victoria Park from a Stylish Loft',
                       location='Ultimo',
                       address='348 Bulware Rd,Ultimo, New South Wales, Australia',
                       postcode='2007', longtitude='151.1993252', altitude='-33.8808471',
                       price='150', type='loft', bedroom= 1, guest= 2, wifi= True, owner_id=user.id,
                       description= "<p>4 guests  1 bedroom  1 bed  1 bath</p>" + \
                                    "<p> Entire loft</p>" + \
                                    "<p>This split-level modest but cozy studio has been recently renovated, making excellent use of the space with high ceilings and nice modern new flooring. Choice of queen bed (upstairs) or sofa bed (downstairs). Our unit is located in a large twin building complex (apartment, student accommodation, hotel, mall) and is perfectly located next to a bus stop (every 2-3min). 10-15min walk to Central station and Paddy's Market, 20min walk to Darling Harbor.</p>")
        a2 = Apartment(a_name='Designer Apartment close CBD & Airport & Beach',
                       location='Rosebery',
                       address='11 rosebery avenue, rosebery, 2018,Sydney',
                       postcode='2018', longtitude='151.2076137', altitude='-33.9137544',
                       price='130', type='apartment', bedroom=1, guest=3, wifi=True, parking=True, tv=True, bathroom=True, owner_id=admin.id,
                       description="<p>3 guests  1 bedroom  2 beds  1 bathroom</p>" + \
                                   "<p> Entire apartment</p>" + \
                                   "<p>Welcome to Rosebery!This modern town is just 5.5 km from Sydney. This one-bedroom apartment with special designer awards is limited to 1 minute walk to Sydney city centre / CBD, University of New South Wales and Bondi Junction / Bondi Beach / Coogee Beach (no transfer required)- 14 minutes walk to Green Square Station- 10 minutes drive from CBD and Sydney Airport- Walking distance to East Village Shopping Centre, public schools, restaurants, medical clinics and other facilities.</p>")
        a3 = Apartment(a_name='Newtown - Entire house, BEST location & parking',
                       location='Newtown',
                       address='267 king street,newtown,2042, Sydney',
                       postcode='2042', longtitude='151.1802630', altitude='-33.8960238',
                       price='141', type='townhouse', bedroom=2, guest=4, wifi=True, parking=True, tv=True, bathroom=True, owner_id=admin.id,
                       description="<p>4 guests  2 bedrooms   3 beds  1.5 bathrooms</p>" + \
                                   "<p>This cute 2 bedroom Victorian terrace is in the heart of Newtown's. 50 metres to the King St/ Enmore Rd junction - where you will find over 600 cafes, restaurants and bars to choose from as well as Newtown train station and buses. 2 minute walk to Enmore Theatre. 5 minute walk to Royal Prince Alfred (RPA) Hospital and 10 minutes to Sydney University.</p>")
        a4 = Apartment(a_name='The Lucky Dog Bondi Beach 3 Bed+ 2 Bath + garden',
                       location='Bondi',
                       address='3 Jaques avenue, Bondi Beach, 2036, Sydney',
                       postcode='2036', longtitude='151.2725109', altitude='-33.8910443',
                       price='412', type='house', bedroom=3, guest=7, wifi=True, parking=True, tv=True, bathroom=True, owner_id=user.id,
                       description="<p>7 guests   3 bedrooms    4 beds    2 bathrooms</p>" + \
                                   "<p>Cool, sleek and sophisticated, this newly renovated 3 bedroom, 2 bathroom home is enveloped in light and comfort. White interiors are complimented by accents of blue and yellow to radiate beach vibes. Walk to cafes, shops and the beach just minutes away<p/>")
        a5 = Apartment(a_name='Studio in the heart of Sydney CBD',
                       location='the rocks',
                       address='4 bridge street,the rocks,2000',
                       postcode='2000', longtitude='151.2078309', altitude='-33.8634198',
                       price='170', type='apartment', bedroom=1, guest=3, wifi=True, parking=False, tv=True, bathroom=True, owner_id=u1.id,
                       description="<p>3 guests  Studio   1 bedroom   1 bathroom</p>" + \
                                   "<p>My apartment is amazingly located in the heart of Sydney CBD, near Circular Quay, Opera House, Royal Botanic Garden and many restaurants, pubs and the shopping area, all the best Sydney can offer. The unit has everything you need to spend a great time in the city. Access to all public transport, unfortunately no parking on the building. *we may expect some noise coming from the street due to construction work on the new light rail*</p>")
        a6 = Apartment(a_name='Darling Harbour: Entire apartment one bedroom',
                       location='darling harbour',
                       address='243 pyrmont street,darling harbor,2007',
                       postcode='2007',longtitude='151.1971769',altitude='-33.8739808',
                       price='175',type='apartment', bedroom=1, guest=4, wifi=True, parking=False, tv=True, bathroom=True, owner_id=u2.id,
                       description="<p>4 guests  1 bedroom  2 beds   1 bathroom</p>" + \
                                   "<p>1 bedroom apartment sleeps 4. light filled , stylish with an internal courtyard Gym /Pool /Spa amenities/ WIFI in unit. 2nd level via lift access in the historic Goldsborough Mort Hotel Pyrmont 245 Pyrmont st, Superb position at Darling harbour with direct undercover access to The International Conference Centre ,Star City Casino ,shops & restaurants. Easy access Sydney City 10 minute walk. Major Attractions inc Harbour bridge ,Opera House, Galleries 30 mins walk Or 2 minute walk to Transport</p>")
        a7 = Apartment(a_name='1BR Apt close to Allianz Stadium & Centennial Park',
                       location='kensington',
                       address='10 anzac pde,kensington,2033',
                       postcode='2033', longtitude='151.2238032', altitude='-33.9031929',
                       price='130', type='apartment', bedroom=1, guest=4, wifi=True, parking=True, tv=True, bathroom=True, owner_id=admin.id,
                       description="<p>4 guests  1 bedroom  2 beds  1 bathroom</p>" + \
                                   "<p>This apartment is ideal for those on holiday, family visit and work trip. Walk to Centennial Park or Watch the NRL's Sydney Roosters, A-League powerhouse Sydney FC & NSW Super Rugby! It can accommodate 2-4 adults, with a Queen size bed in the bedroom and a sofa bed in the living area. Linen and towels are included. For those who drives, there is a private underground parking lot in the Building.</p>")
        a8 = Apartment(a_name='Savour Minimal, Designer Style in a Heritage-listed Terrace',
                       location='surry hills',
                       address='54 Cooper St, Surry Hills, New South Wales, Australia',
                       postcode='2010', longtitude='151.2101872',altitude='-33.8857102',
                       price='132', type='loft', bedroom=1, guest=2, wifi=True, parking=False, tv=True, bathroom=True,owner_id=user.id,
                       description="<p>2 guests  1 bedroom  1 bed  1 bath</p>" + \
                                   "<p>Entire apartment</p>" + \
                                   "<p>A uniquely spacious 1 bedroom flat — it is 1 of 2 flats in a charming heritage listed terrace nestled on a lovely residential street in Sydney's hippest hood. Your home away from home flows over the entire ground floor and you will have exclusive access to your own stylishly designed apartment with slouchy leather lounges, custom designed lighting and thoughtful design throughout.</p>")
        a9 = Apartment(a_name='Cosy 11th floor apartment in the heart of Sydney',
                       location='surry hills',
                       address='4 Little Riley St, New South Wales, Australia',
                       postcode='2010', longtitude='151.2132994', altitude='-33.8806270',
                       price='82', type='apartment', bedroom=1, guest=2, wifi=True, parking=False, tv=True, bathroom=True, owner_id=user.id,
                       description="<p>2 guests  1 bedroom  1 bed  1 bath</p>" + \
                                   "<p>Entire apartment</p>" + \
                                   "<p>Cosy 11th floor studio apartment close to Oxford Street. Walking distance to Hyde Park, surrounded by cafes, bars and restaurants. 7 minutes walk form Museum train station and 2 minutes walk for many bus stops. Entire private use of the apartment including kitchen and bathroom. Rooftop pool and terrace access on level 14 until midnight. Shared access to communal laundry for the building.</p>")
        a10 = Apartment(a_name='Architect Designed Private Studio',
                        location='Redfern',
                        address='767 Maddison Ln, Redfern New South Wales, Australia',
                        postcode='2016', longtitude='151.2157247',altitude='-33.8949822',
                        price='100', type='apartment', bedroom=1, guest=2, wifi=True, parking=False, tv=True, bathroom=True, owner_id=u1.id,
                        description="<p>2 guests  1 bedroom  1 bed  1 bath</p>" + \
                                    "<p>Latest news, just updated the bed to a queen sized bed. With brand new mattress and linen. Also, if there is more than one guest, please specify the amount of guests when requesting to book. Thank you. The Studio is your escape pad in the heart of Redfern / Surry Hills. Architecturally designed. Where industrial and urban combine to give a true inner city experience. Surrounded by wonderful parks and amenities. Close to transport. Walk everywhere</p>")
        a11 = Apartment(a_name='❤️Character Filled, Cosy Federation Terrace Home❤️',
                        location='Redfern',
                        address='28 Marriott St, Redfern, New South Wales, Australia',
                        postcode='2016', longtitude='151.2112483', altitude='-33.8923530',
                        price='65', type='house', bedroom=2, guest=6, wifi=True, parking=True, tv=True, bathroom=True, owner_id=u2.id,
                        description="<p>6 guests  2 bedrooms  3 beds  1 bath</p>" + \
                                    "<p>STAY LIKE A LOCAL. Discover the essence and secrets of Redfern & Surry Hills like locals do. If you enjoy living in a house where it is filled with characters then you won't disappoint!</p>")
        a12 = Apartment(a_name='Spacious Airy Apartment',
                        location='Redfern',
                        address='85 Redfern St,Redfern, New South Wales, Australia',
                        postcode='2016', longtitude='151.2046664', altitude='-33.8930867',
                        price='31', type='apartment', bedroom=1, guest=1, wifi=True, parking=False, tv=False, bathroom=True, owner_id=admin.id,
                        description="<p>1 guest  1 bedroom  1 bed  1 shared bath</p>" + \
                                    "<p>Private room in apartment</p>" + \
                                    "<p>The place is wonderfully situated in close proximity to Redfern station but just tucked in a quiet corner, allowing for both access to Sydney and comfortable, undisturbed sleep. It is also just a few blocks away from Woolies, so grocery shopping is no issue.</p>")
        a13 = Apartment(
            a_name='Luxury designer 2 bedrooms Apt @syd Olympic Park',
            location='Sydney olympic park',
            address=
            '4 Herb Elliott Ave, Sydney Olympic Park, New South Wales, Australia',
            postcode='2127',
            longtitude='151.0707466',
            altitude='-33.8477265',
            price='185',
            type='apartment',
            bedroom=2,
            guest=6,
            wifi=True,
            parking=False,
            tv=True,
            bathroom=True,
            owner_id=user.id,
            description=
            "<p>Complimentary tea and coffee for our guests. *5star two bedrooms high level luxury apartment *modern designer home for everyone *iconic Australia tower with amazing city views *two queen size beds and two additional single beds available *can accommodate up to 6 people *easy access to every event, transport and major facilities in Sydney Olympic Park</p>"
        )
        a14 = Apartment(
            a_name='l21 ”Amazing Sky view”Sydney Olympic Park”2bedroom',
            location='Sydney olympic park',
            address=
            '1 Bennelong Pkwy, Sydney Olympic Park, New South Wales, Australia',
            postcode='2127',
            longtitude='151.0741738',
            altitude='-33.8488338',
            price='70',
            type='apartment',
            bedroom=2,
            guest=5,
            wifi=True,
            parking=True,
            tv=True,
            bathroom=True,
            owner_id=u1.id,
            description=
            "<p>*Sydney olympic park / 2 bedroom / free parking Come and experience the relaxing Australian lifestyle and urban oasis that is Sydney Olympic Park. We are centrally located right in the geographic heart of the Greater Sydney Metropolitan area with world class amenities right at your door step.<p/>"
        )
        a15 = Apartment(
            a_name='Stunning views, great location, close to the CBD',
            location='Balmain',
            address='13 Gilchrist Pl, Balmain, New South Wales, Australia.',
            postcode='2041',
            longtitude='151.1906512',
            altitude='-33.8560522',
            price='60',
            type='apartment',
            bedroom=1,
            guest=2,
            wifi=True,
            parking=False,
            tv=True,
            bathroom=True,
            owner_id=u2.id,
            description=
            "<p>Private room with a queen size bed (shared bathroom and a second toilet) in a top floor apartment, ( the whole top floor ), 2 minutes walk to Balmain high street with lots of restaurants and cafes. You’ll love my place - the views are absolutely stunning - Cockatoo Island and the top of the Sydney Harbour Bridge. My place is good for couples, solo adventurers, and business travelers. The room can take a maximum of 2 people - there is a single mattress if you want to sleep separately.</p>"
        )
        # add the data to the session
        db.session.add_all(
            [a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15])
        db.session.flush()

        # add order to database
        o1 = Order(user_id=u1.id,
                   apartment_id=a1.id,
                   checkin_date=date.today(),
                   checkout_date=date.today() + timedelta(days=7),
                   status=0)
        o2 = Order(user_id=u2.id,
                   apartment_id=a1.id,
                   checkin_date=date.today() + timedelta(days=10),
                   checkout_date=date.today() + timedelta(days=11),
                   status=1)
        db.session.add_all([o1, o2])
        # add review to database
        r1 = Review(
            score=3,
            user_id=u1.id,
            apartment_id=a1.id,
            content=
            'Absolutely incredible hosts. Went out of their way to help me out and gave me some valuable info about some of the must see things in Sydney.'
        )
        r2 = Review(
            score=4,
            user_id=u2.id,
            apartment_id=a1.id,
            content=
            'Great little place to stay in Sydney. It was very clean and nicely decorated.'
        )
        db.session.add_all([r1, r2])
        db.session.flush()

        # add messages to database
        m1 = Message(content='test01', from_id=u1.id, to_id=u2.id)
        m2 = Message(content='test 02', from_id=admin.id, to_id=u2.id)
        db.session.add_all([m1, m2])
        db.session.flush()
        m3 = Message(content='test reply to test01',
                     from_id=u2.id,
                     to_id=u1.id,
                     parent_id=m1.id)
        m4 = Message(content='test reply to test02',
                     from_id=u2.id,
                     to_id=admin.id,
                     parent_id=m2.id)
        db.session.add_all([m3, m4])

        # commit the data to the database
        db.session.commit()
예제 #27
0
    def setUp(self):
        """Sets up user and multiple orders, items and line items in db session for
        testing methods on Order, Item, and User classes that are used in prediction algorithm"""

        test_gmail = "*****@*****.**"
        self.user = User(user_gmail=test_gmail, access_token="test_token")

        db.session.add(self.user)

        date_string_1 = "16 November 2014"
        delivery_date_1 = datetime.strptime(date_string_1, "%d %B %Y")
        amazon_fresh_order_id_1 = "test1"

        self.order_1 = Order(amazon_fresh_order_id=amazon_fresh_order_id_1,
                             delivery_date=delivery_date_1,
                             delivery_day_of_week="Sunday",
                             delivery_time="10:00am - 1:00pm",
                             user_gmail=test_gmail)

        date_string_2 = "13 February 2015"
        delivery_date_2 = datetime.strptime(date_string_2, "%d %B %Y")
        amazon_fresh_order_id_2 = "test2"

        self.order_2 = Order(amazon_fresh_order_id=amazon_fresh_order_id_2,
                             delivery_date=delivery_date_2,
                             delivery_day_of_week="Friday",
                             delivery_time="3:00pm - 6:00pm",
                             user_gmail=test_gmail)

        date_string_3 = "13 May 2015"
        delivery_date_3 = datetime.strptime(date_string_3, "%d %B %Y")
        amazon_fresh_order_id_3 = "test3"

        self.order_3 = Order(amazon_fresh_order_id=amazon_fresh_order_id_3,
                             delivery_date=delivery_date_3,
                             delivery_day_of_week="Monday",
                             delivery_time="3:00pm - 6:00pm",
                             user_gmail=test_gmail)

        db.session.add(self.order_1)
        db.session.add(self.order_2)
        db.session.add(self.order_3)

        self.item_1 = Item(description="Test item 1",
                           description_key="testitem1")

        self.item_2 = Item(description="Test item 2",
                           description_key="testitem2")

        db.session.add(self.item_1)
        db.session.add(self.item_2)

        db.session.flush()

        self.order_line_item_1 = OrderLineItem(
            amazon_fresh_order_id=amazon_fresh_order_id_1,
            item_id=self.item_1.item_id,
            unit_price_cents=100,
            quantity=2)

        self.order_line_item_2 = OrderLineItem(
            amazon_fresh_order_id=amazon_fresh_order_id_1,
            item_id=self.item_2.item_id,
            unit_price_cents=200,
            quantity=3)

        self.order_line_item_3 = OrderLineItem(
            amazon_fresh_order_id=amazon_fresh_order_id_2,
            item_id=self.item_2.item_id,
            unit_price_cents=100,
            quantity=1)

        self.order_line_item_4 = OrderLineItem(
            amazon_fresh_order_id=amazon_fresh_order_id_3,
            item_id=self.item_2.item_id,
            unit_price_cents=50,
            quantity=1)

        db.session.add(self.order_line_item_1)
        db.session.add(self.order_line_item_2)
        db.session.add(self.order_line_item_3)
        db.session.add(self.order_line_item_4)

        db.session.flush()
예제 #28
0
def load_orders():
    data = request.data.strip().split('\n')
    if len(data) > 1:
        columns = data[0].strip().split('|')
        current_line = None
        for line in data[1:]:
            split_line = line.strip().split('|')
            # mapped example:
            # mapped = {'name': 'Stone Dominguez', 'zipcode': '05938',
            #           'id': '4877', 'state': 'IA', 'birthday': 'Feb 27, 1963',
            #          'email': '*****@*****.**'}
            mapped = {}
            for i in range(len(columns)):
                mapped[columns[i]] = split_line[i]
            # populate `Order` table
            order_id = mapped['id']
            o_name = mapped['name']
            o_email = mapped['email']
            o_state = mapped['state']
            o_zip_code = mapped['zipcode']
            o_DOB = mapped['birthday']
            next_line = Order(order_id=order_id,
                              o_name=o_name,
                              o_email=o_email,
                              o_state=o_state,
                              o_zip_code=o_zip_code,
                              o_DOB=o_DOB,
                              valid=0,
                              errors=[])
            # if order is valid populate valid column with `1` otherwise `0`.
            # set_valid(current_line, next_line)
            if current_line:
                set_valid(current_line, next_line)
                db.session.add(current_line)
                db.session.commit()
            current_line = next_line
        set_valid(current_line, None)
        db.session.add(current_line)
        db.session.commit()
    orders = db.session.query(Order).all()

    result = []
    for order in orders:
        errors = []
        for error in order.errors:
            errors.append({
                'primary_key': error.primary_key,
                'e_name': error.e_name,
                'order_key': error.order_key
            })

        result.append({
            'primary_key': order.primary_key,
            'order_id': order.order_id,
            'o_name': order.o_name,
            'o_email': order.o_email,
            'o_state': order.o_state,
            'o_zip_code': order.o_zip_code,
            'o_DOB': order.o_DOB,
            'valid': order.valid,
            'errors': errors
        })

    return jsonify(result)
예제 #29
0
def orderInit():

    Order.query.delete()
    users = User.query.all()
    id = 0

    # personal order
    for i in range(len(orderList)):
        ownerindex = randint(0, len(users) - 1)
        ownerid = users[ownerindex].id
        depart = str(users[ownerindex].latitude) + "," + str(
            users[ownerindex].longitude)
        arrival = str(orderList[i]["latitude"]) + "," + str(
            orderList[i]["longitude"])
        entrepotlist = depart + ";" + arrival
        description = descriptionList[randint(0, 1)]
        selectedperson = ""
        requestlist = ""

        for j in range(len(orderList[i]["requestlist"])):
            requestlist = requestlist + str(
                orderList[i]["requestlist"][j]) + ","

        state = 0
        time = orderList[i]["time"]
        price = randint(0, 300) / 100

        db.session.add(
            Order(id, ownerid, entrepotlist, description, selectedperson,
                  requestlist, state, time, price, 0, "", ""))
        id = id + 1
    # farm order

    requestId = 10

    for i in range(len(farmList)):

        farm = Farm.query.filter(Farm.name == farmList[i]["name"])[0]

        ownerid = farm.userid
        depart = str(farm.latitude) + "," + str(farm.longitude)
        entrepotlist = depart
        description = ""
        selectedperson = ""
        requestlist = ""

        clients = []
        for i in range(randint(3, 25)):
            client = randint(0, len(users) - 6)
            while client in clients:
                client = randint(0, len(users) - 1)

            clients.append(client)
            requestlist = requestlist + str(requestId) + ","
            requestId = requestId + 1

        farmRequests.append(clients)

        state = 0
        time = ""
        price = ""
        db.session.add(
            Order(id, ownerid, entrepotlist, description, selectedperson,
                  requestlist, state, time, price, 0, "", ""))

        id = id + 1
예제 #30
0
def pay_for_cart():
    """Utilize stripe API"""

    placed_at = arrow.utcnow()
    print("placed at ", placed_at)
    customer = db.session.query(Customer).filter(
        Customer.email == session['email']).one()
    print("customer ", customer)
    order = Order(customer_id=customer.user_id,
                  placed_at=placed_at,
                  total=session["cart_total"],
                  pickup_id=1)  # change pickup!!!

    print("order = ", order)
    db.session.add(order)
    print "added order"
    db.session.commit()
    print "committed order"

    order_id = db.session.query(Order.order_id).filter(
        Order.customer_id == customer.user_id,
        Order.placed_at == placed_at).one()
    print order_id, " is the order_id!!!!!!!!!!!!"

    token = request.form.get('stripeToken')

    print "token is ", token

    stripe.api_key = environ["STRIPE_TEST_SECRET"]

    try:
        stripe.Charge.create(
            amount=int(session["cart_total"] * 100),
            currency="usd",
            source=token,  # obtained with Stripe.js
            metadata={
                'order_id': order_id[0],
                'customer_id': customer.user_id
            },
            statement_descriptor="Farm to Front Door CSA",
            description="Farm to Front Door CSA")
        del session['cart']
        del session['cart_total']
    except stripe.error.CardError as e:
        # Since it's a decline, stripe.error.CardError will be caught
        body = e.json_body
        err = body['error']

        print "Status is: %s" % e.http_status
        print "Type is: %s" % err['type']
        print "Code is: %s" % err['code']
        # param is '' in this case
        print "Param is: %s" % err['param']
        print "Message is: %s" % err['message']
    except stripe.error.RateLimitError as e:
        # Too many requests made to the API too quickly
        pass
    except stripe.error.InvalidRequestError as e:
        # Invalid parameters were supplied to Stripe's API
        pass
    except stripe.error.AuthenticationError as e:
        # Authentication with Stripe's API failed
        # (maybe you changed API keys recently)
        pass
    except stripe.error.APIConnectionError as e:
        # Network communication with Stripe failed
        pass
    except stripe.error.StripeError as e:
        # Display a very generic error to the user, and maybe send
        # yourself an email
        pass
    except Exception as e:
        # Something else happened, completely unrelated to Stripe
        pass