예제 #1
0
def job_package():
#       Log.info("请异步发送")
        need_do = ''
        orders = Order.get_working_orders()
        for order in orders:
            product = Product.lookup(order['p_id'])
            exchange = Exchange.get_exchange(order['e_id'])
            packages = Package.getPackageByName(order['package_id'])
            for package in packages:
                need_do = need_do+json.dumps({'port':product['port'],'bandwidth':order['bandwidth'],\
                           'status':order['status'],'port_name':product['port'], 'ipAddress':exchange['ipAddress'], \
                          'package_id':package['package_name']})
#             Order.finish_order(order['_id'])   
                                
        need_back=''
        orders = Order.get_back_orders()
        for order in orders:
             custom_time = order['custom_time']
             product = Product.lookup(order['p_id'])
             exchange = Exchange.look(order['e_id'])
             packages = Package.getPackageByName(order['package_id'])
             for package in packages:
                 need_back = need_back+json.dumps({'port':product['port'],'ex_bandwidth':order['bandwidth'],\
                           'status':order['status'],'port_name':product['port'], 'ipAddress':exchange['ipAddress'], \
                          'package_id':package['package_name']})
#              Order.back_order(order['_id'])
        print 'set_package_job end at ',datetime.datetime.now()
예제 #2
0
 def post(self):
     cname = self.get_argument("cname", None) 
     oname = self.get_argument("oname", None) 
     percent = self.get_argument("percent", None)   
     begin_at = datetime.datetime.strptime(self.get_argument("begin_at", None),"%m/%d/%Y %H:%M")
     suspended_at = datetime.datetime.strptime(self.get_argument("suspended_at", None),"%m/%d/%Y %H:%M")
     p_id = self.get_argument("p_id", None)  
     Order.insert(cname, oname, p_id, percent, begin_at, suspended_at) 
     self.finish("finished<script>parent.closeDialog();</script>")  
예제 #3
0
def test_order(session):
    order = add_order()

    order2 = Order.get(order.id)
    assert order2 is not None

    user2 = add_user('testuser2', 'pwd')

    order.designers = [user2]
    order3 = Order.get(order.id)
    assert user2 in order3.designers
예제 #4
0
    def post(self, request):
        # 添加订单
        try:
            customer = request.u
            note = request.json.get("note")
            delivery_information_id = request.json.get("delivery_information_id")
            store_id = request.json.get("store_id")
            food_list = request.json.get("food_list")
            store = Store.objects.get(id=store_id)
            total_price = 0

            if not all([food_list, delivery_information_id, store]):
                return JsonErrorResponse("food_list, delivery_information_id, store_id are needed", 400)

            # 检查food_list
            assert isinstance(food_list, list) and len(food_list) > 0, "food_list format wrong"
            # 检查库存+计算价格
            for order_food in food_list:
                food = store.foods.get(id=order_food['food_id'])
                food_count = int(order_food['count'])
                total_price += food.price * food_count
                assert food.stock > food_count, "food stock is not enough"
            # 检查收货信息
            delivery_information = customer.delivery_informations.get(id=delivery_information_id)
            # 检查账户类型
            assert request.account_type == "customer", "only customer can make order"

            # 创建order
            new_order = Order(
                note=note,
                total_price=total_price,
                customer=customer,
                store=store,
                delivery_information=delivery_information
            )
            new_order.save()

            # 减少库存,创建order_food
            for order_food in food_list:
                food = store.foods.get(id=order_food['food_id'])
                food_count = int(order_food['count'])
                new_stock = food.stock - food_count
                store.foods.filter(id=order_food['food_id']).update(stock=new_stock)
                OrderFood(
                    count=food_count,
                    food=food,
                    order=new_order
                ).save()

        except Exception, e:
            print e
            return JsonErrorResponse("Fail:" + e.message)
예제 #5
0
    def test_normal_scenario_with_two_users(self):
        # First create some users
        user1 = User.create_user(self.session, "user1", "abcd")
        user2 = User.create_user(self.session, "user2", "abcd")

        # Make sure user1 has 1 BTC for later deposit into a futures contract
        btc = Asset.create_asset("BTC")
        user1.increase_volume_of_asset(self.session, btc, Decimal("1"))

        # Create a futures contract worth 1 BTC in +14 days
        contract, asset = FuturesContract.create_contract(
            self.session, user1, datetime.now() + timedelta(days=14), btc, Decimal("1"), "FUTURE", Decimal("100")
        )
        # This will fail if user1 has insufficient funds (i.e. < 1 BTC)
        assert contract is not None
        assert asset is not None
        self.session.commit()

        # Create an order for this contract (i.e. newly created asset)
        usd = Asset.create_asset("USD")
        ask_order = Order.create_order(
            self.session, user1, Decimal("20"), usd, contract, Decimal("50"), False, OrderType.limit_order.value
        )
        # Make sure we have enough funds
        assert ask_order is not None
        self.session.commit()

        # Put order into market
        assert put_order(self.session, ask_order) is None

        # Create a bid order from user2
        user2.increase_volume_of_asset(self.session, usd, Decimal("20"))
        bid_order1 = Order.create_order(
            self.session, user2, Decimal("20"), usd, contract, Decimal("50"), True, OrderType.limit_order.value
        )
        # Make sure we have enough funds
        assert bid_order1 is not None

        transaction = put_order(self.session, bid_order1)
        assert isinstance(transaction, Transaction)
        assert transaction.ask_order is ask_order
        assert transaction.bid_order is bid_order1

        contract.expire(self.session)
        assert user1.volume_of_asset(self.session, btc) == Decimal("0.5")
        assert user2.volume_of_asset(self.session, btc) == Decimal("0.5")

        # Run it again. Must be idempotent.
        contract.expire(self.session)
        assert user1.volume_of_asset(self.session, btc) == Decimal("0.5")
        assert user2.volume_of_asset(self.session, btc) == Decimal("0.5")
예제 #6
0
def items_status_update(order_id, step):
    order = Order.get(order_id)
    if not order:
        abort(404)
    item_ids = request.form.getlist('item_id')
    leaders = request.form.getlist('leader')
    if not item_ids:
        flash(u"请选择订单项")
    else:
        action = int(request.form.get('action'))
        if action in STATUS_APPLLY:
            if not leaders:
                flash(u"请选择Leader")
                return redirect(url_for('schedule.order_detail', order_id=order.id, step=step))
            else:
                apply = ChangeStateApply(step, action, [User.get(m).email for m in leaders], order)
                order_apply_signal.send(current_app._get_current_object(), change_state_apply=apply)
                flash(u"请在2个自然日内与审核Leaer联系")
        if action in ITEM_STATUS_LEADER_ACTIONS:
            apply = ChangeStateApply(
                step,
                action,
                [order.creator.email],
                order)
            reply_apply_signal.send(current_app._get_current_object(), change_state_apply=apply)
        items = AdItem.gets(item_ids)
        AdItem.update_items_with_action(items, action, g.user)
        msg = '\n\n'.join(['%s : %s' % (item.name, ITEM_STATUS_ACTION_CN[action]) for item in items])
        order.add_comment(g.user, msg)
        flash(u'%s个排期项%s。请将理由在留言板上留言说明' % (len(items), ITEM_STATUS_ACTION_CN[action]))
        step = AdItem.get_next_step(step, action)
    return redirect(url_for('schedule.order_detail', order_id=order.id, step=step))
예제 #7
0
def order_items(order_id):
    order = Order.get(order_id)
    if not order:
        abort(404)
    context = {'order': order,
               'SALE_TYPE_CN': SALE_TYPE_CN}
    return tpl('order_detail_ordered.html', **context)
예제 #8
0
def new_outsource():
    form = OutsourceForm(request.form)
    order = Order.get(form.medium_order.data)
    try:
        int(form.num.data)
    except:
        flash(u'保存失败,金额必须为数字!', 'danger')
        return redirect(url_for("outsource.client_outsources", order_id=order.client_order.id))
    status = 0
    if g.user.is_super_leader():
        status = 2
    outsource = OutSource.add(target=OutSourceTarget.get(form.target.data),
                              medium_order=order,
                              num=form.num.data,
                              type=form.type.data,
                              subtype=form.subtype.data,
                              remark=form.remark.data,
                              invoice=False,
                              status=status,
                              pay_num=form.num.data,)
    flash(u'新建外包成功!', 'success')
    outsource.client_order.add_comment(g.user,
                                       u"""新建外包:\n\r %s""" % outsource.name,
                                       msg_channel=2)
    if g.user.is_super_leader():
        _insert_executive_report(order, rtype='reload')
    return redirect(outsource.info_path())
예제 #9
0
def back_money(order_id):
    if not g.user.is_finance():
        abort(404)
    client_order = ClientOrder.get(order_id)
    back_moneys = MediumBackMoney.query.filter_by(client_order_id=order_id)
    if not client_order:
        abort(404)
    if request.method == 'POST':
        money = float(request.values.get('money', 0))
        back_time = request.values.get(
            'back_time', datetime.date.today().strftime('%Y-%m-%d'))
        medium_id = request.values.get('medium')
        order = Order.get(medium_id)
        MediumBackMoney.add(client_order_id=order_id,
                            order_id=medium_id,
                            money=money,
                            back_time=back_time)
        client_order.add_comment(g.user, u"更新了媒体返点回款信息,所属媒体:%s; 回款金额: %s; 回款时间: %s;" % (
            order.medium.name, money, back_time), msg_channel=8)
        apply_context = {
            'order': client_order,
            'num': money,
            'type': 'money',
        }
        medium_back_money_apply_signal.send(
            current_app._get_current_object(), apply_context=apply_context)
        flash(u'回款信息保存成功!', 'success')
        return redirect(url_for('finance_client_order_medium_back_money.back_money', order_id=order_id))
    return tpl('/finance/client_order/medium_back_money/info.html', order=client_order, back_moneys=back_moneys)
예제 #10
0
 def GetContext(self):
         
     tAgent = Agent()
     tAgentList = []
     tAgentOrders = []
     tAgentDonations = []
     tAgentRequest = self.request.get('agent')
     context = {}
     
     tAgentList = Agent.all()
     context['agents'] = tAgentList
     if (tAgentRequest != ""):
         tAgent = Agent.get(tAgentRequest)
         
         tAgentOrdersQuery = Order.all()
         tAgentOrdersQuery.filter('orderAgent', str(tAgentRequest))
         tAgentOrdersQuery.order('-orderCompleted')
         tAgentOrders = tAgentOrdersQuery.fetch(100)
         
         tAgentDonorsQuery = DonorRecord.all()
         tAgentDonorsQuery.filter('donorAgent', tAgent.agentId)
         tAgentDonorsQuery.order('-donorDate')
         tAgentDonations = tAgentDonorsQuery.fetch(100)
         
         #logging.debug("Agent Order Count: " + str(len(tAgentOrders)))
         #logging.debug("Agent Donation Count: " + str(len(tAgentDonations)))
         
         context['agent'] = tAgent
         context['orders'] = tAgentOrders
         context['donations'] = tAgentDonations
         context['extended'] = 'True'
         
     return context
예제 #11
0
def index():
    if not g.user.is_super_admin():
        abort(403)
    form = ClientOrderForm(request.form)
    mediums = [(m.id, m.name) for m in Medium.all()]
    if request.method == 'POST' and form.validate():
        if ClientOrder.query.filter_by(contract=request.values.get('contract')).count() > 0:
            flash(u'合同号已存在', 'danger')
            return redirect(url_for('util_insert_orders.index'))
        order = ClientOrder.add(agent=Agent.get(form.agent.data),
                                client=Client.get(form.client.data),
                                campaign=form.campaign.data,
                                money=int("%.0f" % (form.money.data or 0)),
                                client_start=form.client_start.data,
                                client_end=form.client_end.data,
                                reminde_date=form.reminde_date.data,
                                direct_sales=User.gets(form.direct_sales.data),
                                agent_sales=User.gets(form.agent_sales.data),
                                contract_type=form.contract_type.data,
                                resource_type=form.resource_type.data,
                                sale_type=form.sale_type.data,
                                contract=request.values.get('contract', ''),
                                creator=g.user,
                                contract_status=2,
                                create_time=datetime.now())
        order.add_comment(g.user,
                          u"导入了客户订单:%s - %s - %s" % (
                              order.agent.name,
                              order.client.name,
                              order.campaign
                          ))
        medium_ids = request.values.getlist('medium')
        medium_moneys = request.values.getlist('medium_money')
        medium_moneys2 = request.values.getlist('medium_money2')
        medium_contracts = request.values.getlist('medium_contract')
        if medium_ids and medium_moneys and len(medium_ids) == len(medium_moneys):
            for x in range(len(medium_ids)):
                medium = Medium.get(medium_ids[x])
                mo = Order.add(campaign=order.campaign,
                               medium=medium,
                               sale_money=int("%.0f" % (form.money.data or 0)),
                               medium_money=int(medium_moneys[x] or 0),
                               medium_money2=int(medium_moneys2[x] or 0),
                               medium_contract=medium_contracts[x],
                               medium_start=order.client_start,
                               medium_end=order.client_end,
                               creator=g.user)
                order.medium_orders = order.medium_orders + [mo]
                order.add_comment(g.user, u"导入了媒体订单: %s %s元" %
                                  (medium.name, mo.sale_money))
            order.save()
        flash(u'导入客户订单成功!', 'success')
        insert_executive_report(order, '')
        return redirect(order.info_path())
    else:
        form.client_start.data = datetime.now().date()
        form.client_end.data = datetime.now().date()
        form.reminde_date.data = datetime.now().date()
    return tpl('insert_order.html', form=form, mediums=mediums)
 def GetContext(self):
     tContext = {}
     tOrderKey = str(urllib.unquote(self.request.get('key')))
     if(tOrderKey != None and len(tOrderKey) > 0):
         tOrder = Order.get(tOrderKey)
         tContext['tOrder'] = tOrder            
             
     return tContext
예제 #13
0
파일: order.py 프로젝트: phuclc/dienthoai
def index():
    data = request.args.to_dict()
    filtering_state = data.get('state__icontains', '')

    criteria = {'state__icontains': str(filtering_state)}
     
    orders = Order.objects(**criteria)
    return render.template('admin/order/index.html', orders=orders)
 def GetContext(self):
     tContext = {}
     tOrderQuery = Order.all()
     tOrderQuery.filter("orderDeliver", "False")
     tOrderQuery.order("orderCreated")
     tOrderList = tOrderQuery.fetch(500)
     tContext['orders'] = tOrderList
     
     return tContext
예제 #15
0
    def test_cancel_contract(self):
        # Create a user and asset
        user = User.create_user(self.session, "user", "abcd")
        usd = Asset.create_asset("USD")
        self.session.add_all([user, usd])
        self.session.commit()

        # Add funds to user1 so that we can create a contract
        user.increase_volume_of_asset(self.session, usd, Decimal("1"))

        # Let this user create a contract
        contract, asset = FuturesContract.create_contract(
            self.session, user, datetime.now() + timedelta(days=14), usd, Decimal("1"), "FUTURE", Decimal("100")
        )
        assert contract is not None
        assert asset is not None

        # Now, money have been withdrawn from user1's account
        assert user.volume_of_asset(self.session, usd) == Decimal("0")

        # Cancel the contract
        assert contract.cancel(self.session) is True
        assert inspect(contract).deleted is True
        assert user.volume_of_asset(self.session, usd) == Decimal("1")

        # OK, the contract is cancelled.
        # Now do the same thing, but this time, create an order and verify that the cancelled flag is set instead
        contract, asset = FuturesContract.create_contract(
            self.session, user, datetime.now() + timedelta(days=14), usd, Decimal("1"), "FUTURE", Decimal("100")
        )
        assert contract is not None
        assert asset is not None
        assert user.volume_of_asset(self.session, usd) == Decimal("0")

        ask_order = Order.create_order(
            self.session, user, Decimal("20"), usd, contract, Decimal("50"), False, OrderType.limit_order.value
        )
        assert ask_order is not None
        assert user.volume_of_asset(self.session, asset) == Decimal("50")

        # Assert that we cannot cancel the contract if there are created orders
        assert contract.cancel(self.session) is False

        # Put order into market
        assert put_order(self.session, ask_order) is None

        # Assert that we cannot cancel the contract if there are orders in the market
        assert contract.cancel(self.session) is False

        # It should be possible to cancel this order
        assert ask_order.cancel(self.session) is True
        assert user.volume_of_asset(self.session, asset) == Decimal("100")

        # Check that order is in the expected state
        assert contract.cancel(self.session) is True
        assert inspect(contract).deleted is False
        assert contract.cancelled is True
예제 #16
0
 def post(self):
     cname = self.get_argument("cname", None)
     oname = self.get_argument("oname", None)
     percent = self.get_argument("percent", None)
     begin_at = self.get_argument("begin_at", None)  
     suspended_at = self.get_argument("suspended_at", None)
     p_id = self.get_argument("p_id", None)  
     o_id = Order.insert(cname,oname,p_id,percent,begin_at,suspended_at)
     self.finish("finished<script>parent.closeDialog();</script>")  
예제 #17
0
    def GetContext(self):
        tContext = {}
        tPaypal = PaypalOrder()
        tOrderList = []

        tOrderAmounts = [1000000, 2000000, 5000000, 10000000, 20000000, 40000000, 80000000, 100000000]

        i = 1
        while i < 21:
            i = i + 1
            tOrder = Order()
            tOrder.orderQuantity = choice(tOrderAmounts)
            tAgentId = tPaypal.GetAssignedAgent(tOrder)
            tOrder.orderAgent = tAgentId
            tOrderList.append(tOrder)

        tContext["orders"] = tOrderList

        return tContext
예제 #18
0
def order_detail(order_id, step):
    order = Order.get(order_id)
    if not order:
        abort(404)
    leaders = [(m.id, m.name) for m in User.leaders()]
    context = {'leaders': leaders,
               'order': order,
               'step': step,
               'SALE_TYPE_CN': SALE_TYPE_CN}
    return tpl('order_detail_schedule.html', **context)
예제 #19
0
파일: order.py 프로젝트: ciriarte/laundry
  def get(self):	
	path = os.path.join(os.path.dirname(__file__),
	                    '../views/orders/index.html')
	
	template_values = {
		'name': self.__class__.__name__,
		'orders': Order.all().order('-createdOn'),		
	}
	
	self.response.out.write(template.render(path, template_values))
예제 #20
0
파일: order.py 프로젝트: ciriarte/laundry
  def get(self, id):	
	path = os.path.join(os.path.dirname(__file__),
	                    '../views/orders/edit.html')
	
	template_values = {
		'name': self.__class__.__name__,
		'order': Order.get_by_id(int(id))
	}
	
	self.response.out.write(template.render(path, template_values))
예제 #21
0
def schedules_post(order_id):
    """AJAX 提交排期数据"""
    order = Order.get(order_id)
    if not order:
        abort(404)
    data = request.values.get('data')
    status, msg = check_schedules_post(data)
    if not status:
        add_schedules(order, data)
        flash(u'排期提交成功!', 'success')
    return jsonify({'status': status, 'msg': msg})
def place_order(body):
    """
    Place an order for a pet
    
    :param body: order placed for purchasing the pet
    :type body: dict | bytes

    :rtype: Order
    """
    if connexion.request.is_json:
        body = Order.from_dict(connexion.request.get_json())
    return 'do some magic!'
예제 #23
0
 def post(self):
     from models.order import Order
     from _numbertogp import NumberToGp
     tCalc = CalcReferral()
     tOrderKey = self.request.get('key')
     tOrder = Order()
     tOrder = Order.get(str(tOrderKey))
     
     tReferCode = tOrder.orderReferralCode
     
     if (tReferCode == None):
         tReferCode = ""
     
     #logging.debug("Referrer Code: " + tReferCode)
     
     if (tReferCode == "" or tReferCode == None):
         return None
     
     tRefererQuery = Referrer.all()
     tRefererQuery.filter('referId', tReferCode)
     tReferer = Referrer()
     try:
         tReferer = tRefererQuery.fetch(1)[0]
     except:
         #logging.debug("Referrer Code Not Found: " + tReferCode)
         return None
     
     tGp = 0.0
     tCash = 0.0
     
     #No matching referrers and paypal emails
     if(tReferer.referEmail != None):
         if(str(tReferer.referEmail).lower() == str(tOrder.orderPaypalEmail).lower()):
             return None
     
     if (tReferer.referGp == 0.0 or tReferer.referCash == 0.0):
         tGp = tOrder.orderQuantity * 0.2
         tCash = tOrder.orderCost * 0.2
     else:
         tGp = float(tReferer.referGp) + (tOrder.orderQuantity * 0.1)
         tCash = float(tReferer.referCash) + (tOrder.orderCost * 0.1)
     
     tReferer.referGp = tGp
     tReferer.referCash = tCash
     tReferer.referSimpleGold = NumberToGp.ConvertIntToBet(int(float(tGp)))
     tReferer.referSimpleCash = tCalc.FormatCurrency(tCash)
     
     #logging.debug("Referrer Gp: " + str(tGp))
     #logging.debug("Referrer Cash: " + str(tCash))
     #logging.debug("Referrer Simple Gold: " + str(tReferer.referSimpleGold))
     #logging.debug("Referrer Simple Cash: " + str(tReferer.referSimpleCash))
     
     tReferer.put()
예제 #24
0
파일: stat_control.py 프로젝트: hc990/let
    def post(self):
#       oname = self.get_current_user()['_id']
        orders = Order.getOrders()  
        #page info
        page = self.get_argument('page', 1)
        page = page if page >= 1 else 1  
        #get the document count param
        count = self.get_argument('count', 15)  
        count = count if count >= 1 else 15
        paginator = Paginator(orders, page, count, len(orders))
        template_values={}
        template_values['paginator'] = paginator
        self.render_template('/site/stat_bw.html', **template_values)
예제 #25
0
def new_item(order_id, type):
    order = Order.get(order_id)
    if not order:
        abort(404)
    if not order.can_admin(g.user):
        flash(u'您没有创建排期的权限, 请联系订单创建者和销售同事!', 'danger')
        return redirect(url_for('schedule.order_detail', order_id=order.id, step=0))
    start_date = datetime.today()
    end_date = start_date + timedelta(days=30)
    positions = [(x.id, x.display_name) for x in order.medium.positions]
    return tpl('new_item.html', order=order, positions=positions,
               start_date=start_date, end_date=end_date, type=type,
               SALE_TYPE_CN=SALE_TYPE_CN, SPECIAL_SALE_CN={0: u"否", 1: u"是"})
예제 #26
0
파일: main.py 프로젝트: tanarky/services
def seller_tool_orders(seller):
    T = {"sellername":seller}
    ret = seller_tool_check_login(seller, T)
    if ret is not True:
        return ret

    orders = Order.gql('where seller=:seller', seller=seller).fetch(limit=10)
    T['orders'] = orders
    T["breadcrumbs"] = [{"url":url_for("seller_tool_index",seller=seller),
                         "title":u"ツールトップ"},
                        {"title":u"注文一覧"}]

    return render_template('seller_tool_orders.html', T=T)
예제 #27
0
파일: stat_control.py 프로젝트: hc990/let
 def get(self):
     oname = self.get_current_user()['_id']
     
     bandwidths = Order.get_orders_operators(oname)
     #page info
     page = self.get_argument('page', 1)
     page = page if page >= 1 else 1  
     #get the document count param
     count = self.get_argument('count', 5)
     count = count if count >= 1 else 5
     paginator = Paginator(bandwidths, page, count, len(bandwidths))
     template_values={}
     template_values['paginator'] = paginator
     self.render_template('/site/stat_bw.html', **template_values)
예제 #28
0
 def post(self):
     p_id = self.get_current_user()
     print p_id
     bandwidths = Order.get_orders(p_id)
     # page info
     page = self.get_argument("page", 1)
     page = page if page >= 1 else 1
     # get the document count param
     count = self.get_argument("count", 5)
     count = count if count >= 1 else 5
     paginator = Paginator(bandwidths, page, count, len(bandwidths))
     template_values = {}
     template_values["paginator"] = paginator
     self.render_template("/site/stat_bw.html", **template_values)
예제 #29
0
    def post(self):
        tUrl = "https://api-3t.paypal.com/nvp"
        tPaypalPayload = {}
        tPaypal = PaypalRefund()
        tAgent = Agent()
        tOrder = Order()
        tUser = users.get_current_user()

        tTransId = str(self.request.get("orderid"))

        tAgentEmail = str(tUser.email())
        tAgent = Agent().GetAgentByEmail(tAgentEmail)
        tRefundAgent = tAgentEmail

        tOrderQuery = Order.all()
        tOrderQuery.filter("orderTransactionId", tTransId)
        # logging.debug("Transaction id: " + tTransId)
        tOrder = tOrderQuery.get()

        if tOrder.orderDeliver != "True":

            tPaypalPayload["METHOD"] = "RefundTransaction"
            tPaypalPayload["TRANSACTIONID"] = tTransId

            tPayloadEncoded = tPaypal.GeneratePayload(tPaypalPayload)

            request_cookies = mechanize.CookieJar()
            request_opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(request_cookies))
            request_opener.addheaders = [("Content-Type", "application/x-www-form-urlencoded")]
            mechanize.install_opener(request_opener)

            tResponse = mechanize.urlopen(url=tUrl, timeout=25.0, data=tPayloadEncoded)
            # logging.debug("Mechanize Package")
            # logging.debug("Url: " + tUrl)
            # logging.debug("Data: " + str(tPaypalPayload))

            tResult = tResponse.read()
            # logging.debug(tResult)

            tOrder.orderIsRefunded = "True"
            tOrder.orderRefundAgent = tRefundAgent
            tOrder.orderLocked = "True"
            tOrder.orderRefundId = ""
            tOrder.put()

            self.response.out.write("Order Locked and Refunded")
예제 #30
0
    def post(self):
        
        tPaypalEmail = self.request.get('email')
        tCustomerName = self.request.get('name')
        tGoldAmount = self.request.get('gold')
        tOrderKey = self.request.get('key')
        
        tOrder = Order()
        tOrder = Order.get(tOrderKey)
        
        tVerificationCode = tOrder.orderVerificationCode
        
        tGoldInt = int(tGoldAmount.split('.')[0])
        logging.debug("Gold Int: " + str(tGoldInt))
        
        tGoldAmount = NumberToGp.ConvertIntToBet(tGoldInt)
        
        #logging.debug("Customer Name " + str(tCustomerName))
        #logging.debug("Gold Amount " + str(tGoldAmount))
        
        tMessage = """
        Dear %s,

        Thank you for choosing the eMeMO SmokinShop.
        
        We have received your payment for a code redeemable for %s. If you were not automatically returned to our website after payment, please go to http://smokinshop.com/delivery.php and speak to an eMeMO agent in the live chat.
        
        Your unique verification code is %s. You will also find your code attached to this email in a text file.
        
        Please speak to an eMeMO agent or visit http://smokinshop.com/delivery.php to activate your code and redeem it for RuneScape GP.
        
        Regards,
        
        The eMeMO Team
        """ % (str(tCustomerName), str(tGoldAmount), str(tVerificationCode)) 
                            
        logging.debug(str(tMessage))
        
        message         = mail.EmailMessage()
        message.sender  = "eMeMO SmokinShop Support<*****@*****.**>"
        message.to      = tPaypalEmail
        message.subject = "eMeMO SmokinShop Order Details"
        message.body    = tMessage
        message.cc      = "*****@*****.**"
        message.attachments = [('verification-code.txt', tVerificationCode)]
        
        message.send()
예제 #31
0
def order():
    if request.method == 'POST':
        from models.order import Order
        name = request.form['name']
        email = request.form['email']
        phone = request.form['phone']
        address = request.form['address']
        letters = request.form['letters']
        key_holder = request.form['key_holder']
        item_type = request.form['order_type']
        order = Order(name, email, phone, address, letters, key_holder, item_type)
        if item_type == 'single':
            order.single_letter_calc_price()
        else:
            order.multi_letter_calc_price()
        try:
            order.save_to_db() # we are tring to store this, even this already exisit
        except:
            old_order = Order.find_by_email(email)
            old_order.delete_from_db()
            order.save_to_db()
        return render_template("checkout.html", order=order, key=os.environ['PUBLISHABLE_KEY'])
    return render_template("order.html")
예제 #32
0
    def GetContext(self):
        tContext = {}
        tAgent = Agent()
        tAgentHandler = AgentHandler()
        tOrders = []
        tOrder = Order()
        tUser = self.USER

        tAgentQuery = Agent().all()
        tAgentQuery.filter('agentOnline', True)
        tAgents = tAgentQuery.fetch(100)
        if (len(tAgents) > 0):
            tContext['agentnum'] = len(tAgents)
            tContext['agents'] = tAgents
        try:
            tAgent = Agent().GetAgentByEmail(str(tUser.email()))
        except:
            pass
        if (tAgent.agentId == 'No Agent'):
            tAgent.agentCurrentCommission = 0.0
            tAgent.agentTotalCommission = 0.0
            tAgent.agentOrders = []
            tAgent.agentId = str(tUser.email())
            tAgent.agentGoldSupply = 0
            tAgent.agentOnline = False
            tAgent.put()

        if (tAgent.agentGoldSupply == None):
            tAgent.agentGoldSupply = 0

        tOrderQuery = PaOrder.all()
        tOrderQuery.filter("paDeliveryAgent", tAgent.agentId)
        tOrderQuery.order("-paDateDelivered")
        tOrdersRaw = tOrderQuery.fetch(50)

        tAgentDonorsQuery = DonorRecord.all()
        tAgentDonorsQuery.filter('donorAgent', tAgent.agentId)
        tAgentDonorsQuery.order('-donorDate')
        tAgentDonations = tAgentDonorsQuery.fetch(20)

        for o in tOrdersRaw:
            tOrder = o
            if (tOrder != None):
                tOrders.append(tOrder)

        #tGoldSupply = tAgent.agentGoldSupply

        logging.debug('Original eoc ' + str(tAgent.agentGoldSupplyEoc))
        logging.debug('Original 07 ' + str(tAgent.agentGoldSupply07))

        tEocString = NumberToGp.ConvertIntToBet(tAgent.agentGoldSupplyEoc)
        t07String = NumberToGp.ConvertIntToBet(tAgent.agentGoldSupply07)

        logging.debug('Stringed version eoc ' + tEocString)
        logging.debug('Stringed version 07 ' + t07String)

        #tAgent.__setattr__('agentGoldSupplyEocString', tEocString)
        #tAgent.__setattr__('agentGoldSupply07String', t07String)

        tContext['agent'] = tAgent
        tContext['gpeocstring'] = str(tEocString)
        tContext['gp07string'] = str(t07String)
        #tContext['agentgold'] = locale.format("%d", int(tGoldSupply), grouping = True)
        tContext['orders'] = tOrders
        tContext['agentcomm'] = locale.format("%0.2f",
                                              tAgent.agentCurrentCommission,
                                              grouping=True)
        tContext['agenttotal'] = locale.format("%0.2f",
                                               tAgent.agentTotalCommission,
                                               grouping=True)
        tContext['donations'] = tAgentDonations
        return tContext
예제 #33
0
def check_repeated_order_before(condition, client):
    order = Order.query(Order.client_id == client.key.id(),
                        Order.status.IN(NOT_CANCELED_STATUSES)).get()
    if not order:
        return False
    return not check_repeated_order(condition, client)
예제 #34
0
파일: app.py 프로젝트: culee/c4e
def order_list():
    all_orders = Order.objects(is_accepted=False)
    return render_template("order-list.html", all_orders=all_orders)
예제 #35
0
def add_order():
    user = get_default_user()
    medium = add_medium(TEST_MEDIUM)
    order = Order.add(campaign='testcampaign', medium=medium, order_type=0,
                      creator=user, create_time=datetime.now())
    return order
예제 #36
0
    def query_orders(self, *args, **kwargs):
        from models.order import Order

        if self.venue:
            return Order.query(Order.venue_id == str(self.venue.id()), *args, **kwargs)
        return Order.query(*args, **kwargs)
예제 #37
0
파일: files.py 프로젝트: cash2one/braavos
def medium_contract_upload():
    order_id = request.values.get('order')
    order = Order.get(order_id)
    return attachment_upload(order, FILE_TYPE_CONTRACT)
예제 #38
0
파일: admin.py 프로젝트: UItraman/buy
def clear_order_items():
    os = Order.all()
    for o in os:
        o.items = []
        o.save()
    return redirect(url_for('admin.product_list'))
예제 #39
0
파일: admin.py 프로젝트: UItraman/buy
def order_delivery(orderNo):
    o = Order.find_one(orderNo=orderNo)
    o.delivery()
    return redirect(url_for('admin.order_list'))
예제 #40
0
파일: admin.py 프로젝트: UItraman/buy
def order_edit(orderNo):
    u = current_user()
    m = Order.find_one(orderNo=orderNo)
    m.user = User.get(m.user_id)
    m.ct = time_str(m.ct)
    return render_template('admin_order_edit.html', o=m, u=u)
예제 #41
0
    def PostContext(self):
        tOrder = {}
        tContext = {}
        tPriceDictionary = PriceContainer.GetCurrentPriceDic()

        tType = str(self.request.get('type'))
        #logging.debug("Type: " + tType)

        tRandomAmount = ""
        tRandomPrice = ""
        tRandomAmount = random.choice(tPriceDictionary.keys())
        tRandomPrice = tPriceDictionary[tRandomAmount]
        tRandomNumberList = [str(random.randrange(0, 9)) for i in range(0, 9)]

        #valid for all types of orders
        tOrder['mc_currency'] = 'USD'
        tOrder['receiver_email'] = '*****@*****.**'
        tOrder['receiver_id'] = 'NSKCXUXQEMPBG'
        tOrder['residence_country'] = 'US'
        tOrder['address_city'] = 'Beverly Hills'
        tOrder['address_country'] = 'United States'
        tOrder['address_country_code'] = 'US'
        tOrder['address_name'] = 'Test Address'
        tOrder['address_state'] = 'California'
        tOrder['address_street'] = '9876 Wilshire Boulevard'
        tOrder['address_zip'] = '90210'
        tOrder['notify_version'] = '3.4'

        #logging.debug(str(tOrder))

        tAvailableEligibility = [
            "Ineligible", "Partially Eligible - INR Only", "Eligible"
        ]
        tOrder['protection_eligibility'] = random.choice(tAvailableEligibility)

        tAvailableStatus = ["verified", "unverified"]
        tOrder['payer_status'] = random.choice(tAvailableStatus)

        if (tType == "random" or tType == "me"):
            tOrder['mc_gross'] = tRandomPrice
            tOrder['payment_gross'] = tRandomPrice
            tOrder['txn_type'] = 'web_accept'
            tOrder['discount'] = '0.0'
            tOrder['handling_amount'] = '0.0'
            tOrder['insurance_amount'] = '0.0'
            tOrder['item_number'] = '1'
            tOrder['mc_fee'] = '0.0'
            tOrder['COUNTRYCODE'] = 'US'
            tOrder['address_country'] = 'United States'
            tOrder['payment_fee'] = '0.0'
            tOrder['quantity'] = "1"
            tOrder['shipping'] = "0.0"
            tOrder['shipping_discount'] = "0.0"
            tOrder['shipping_method'] = "Default"
            tOrder['tax'] = "0.0"

            tOrder['item_name'] = tRandomAmount.upper() + "Transfer Code"

            tReferralCodes = ["", "69a8e184"]
            tRandomReferral = random.choice(tReferralCodes)

            tPromoCodes = ["SMELITE10"]
            tRandomPromoCode = random.choice(tPromoCodes)

            tOrder['option_name1'] = 'Test Order Name'  #name
            tOrder['option_name4'] = 'RS Test Name'  #rs name
            tOrder['option_name5'] = tRandomReferral  #referral
            tOrder[
                'option_name5'] = tRandomPromoCode  #promocode formerly option 6
            tOrder['option_name7'] = tRandomAmount  #gold amount

        #logging.debug(str(tOrder))
        if (tType == "random" or tType == "viprandom"):
            tRandomEmail = 'sm-test-email-' + "".join(
                tRandomNumberList) + "@smokinmils.com"
            tOrder['payer_email'] = tRandomEmail
            tOrder['payer_id'] = "".join(tRandomNumberList) + "-testid"
            tOrder['txn_id'] = "".join(tRandomNumberList)
            tOrder['custom'] = '65.91.31.0'
            tOrder['option_name2'] = tRandomEmail  #email
            tOrder['option_name3'] = '310-274-7777'  #number
            tOrder['transaction_subject'] = '65.91.31.0'
        #logging.debug(str(tOrder))
        if (tType == "me" or tType == "vipme"):
            tOrder['custom'] = '75.138.80.254'
            tOrder['payer_email'] = '*****@*****.**'
            tOrder['payer_id'] = 'FE6TJMYCTZ9CA'
            tOrder['txn_id'] = "".join(tRandomNumberList)
            tOrder['option_name2'] = '*****@*****.**'
            tOrder['option_name3'] = '678-499-6457'
            tOrder['transaction_subject'] = '75.138.80.254'
        #logging.debug(str(tOrder))
        if (tType == "viprandom" or tType == "vipme"):
            tOrder['payment_gross'] = "8.99"
            tOrder['transaction_subject'] = "VIP Membership"
            tOrder['item_name'] = "VIP Membership"
            tOrder['item_number'] = "VIP"
            tOrder['mc_gross'] = "8.99"
            tOrder['txn_type'] = "subscr_payment"
            tOrder['subscr_id'] = "".join(tRandomNumberList)
        #logging.debug(str(tOrder))
        tOrder['payment_status'] = 'Completed'
        tOrder['payment_type'] = 'Instant'
        tOrder['last_name'] = "Pleco"
        tOrder['first_name'] = "Kort"

        tOrder['fake'] = 'True'
        #logging.debug("Last call: " + str(tOrder))
        tPayloadEncoded = urllib.urlencode(tOrder)

        #logging.debug("Encoded: " + str(tPayloadEncoded))

        tUrl = "http://smokin-goldshop.appspot.com/paypalipn"
        #logging.debug("Url: " + str(tUrl))

        request_cookies = mechanize.CookieJar()
        request_opener = mechanize.build_opener(
            mechanize.HTTPCookieProcessor(request_cookies))
        request_opener.addheaders = [('Content-Type',
                                      'application/x-www-form-urlencoded')]

        mechanize.install_opener(request_opener)
        tResponse = mechanize.urlopen(url=tUrl,
                                      timeout=25.0,
                                      data=tPayloadEncoded)

        tOrderQuery = Order().all()
        tOrderQuery.filter("orderIsGenerated", True)
        tOrderQuery.order("-orderCreated")
        tOrderList = tOrderQuery.fetch(limit=30)

        tContext['orders'] = tOrderList

        #logging.debug("Response: " + str(tResponse))
        return tContext
예제 #42
0
def create_order():
    """
    Create a new order by placing products and client
    ---
    parameters:
      - in: header
        name: authorization
        required: true
        schema:
          type: string
      - in: query
        name: shop
        required: true
        schema:
          type: object
          parameters:
            id:
              type: integer
      - in: query
        name: total
        required: true
        schema:
          type: integer
    responses:
      200:
        description: Successfully created the order
        schema:
          type: object
          parameters:
            message:
              type: string
              example: Success
    """
    user = request.user
    shop = storage.get(User, user).shops[0]
    in_order = request.get_json()
    order = Order()
    order.date = str(datetime.utcnow())
    order.description = json.dumps(in_order['shop'])
    order.total = in_order['total']
    order.shop = shop.id
    order.origin = 'admin'
    client = storage.get(Client, shop.client)
    if client:
        order.client = client.id
    else:
        client = Client()
        client.username = shop.title
        client.email = storage.get(User, user).username
        client.phone = shop.phone
        order.client = client.id
        client.save()
    order.save()
    print()
    return jsonify(message='Success')
예제 #43
0
from models.staff import Staff
from models.customer import Customer

stores = [
    Store(1, "IUT-WebStore Management System", "Deutga", "156-25-63"),
]

staffs = [
    Staff("Jaiden", "Tashkent", "123465", 12, "Cashier", 5600),
    Staff("Humongus", "Balls", "965412", 15, "Guard", 7600)
]

customers = [
    Customer("5632879", "Dave", "Dventiliga", 256, 10, "589-44-85", ["Wings", "Golden"]),
    Customer("9653287", "Gustavo", "Feritana", 25, 562, "555-44-44", ["Premium"])
]

products = [
    Product(123456, "Chocolate Flavor", "Cookies with chocolate", 25, 1),
    Product(954687, "Meat", "Tasty meat", 50, 5),
    Product(248984, "Brick", "It is just a brick", 900, 3),
    Product(967485, "Secret sause", "Special secret Krabsburger sause", 150, 2),
    Product(336599, "Stick", "Stick for real man", 10, 4)
]

orders = [
    Order(stores[0], customers[0], staffs[0], [{Order.PRODUCT_KEY:product[0], Order.QUANTITY_KEY: product[1]}
                                               for product in [(products[0], 2), (products[1], 3), (products[2], 1)]]),
]

예제 #44
0
파일: files.py 프로젝트: cash2one/braavos
def medium_order_files(order_id):
    co = Order.get(order_id)
    return tpl("order_files.html", order=co)
예제 #45
0
파일: files.py 프로젝트: cash2one/braavos
def medium_schedule_upload():
    order_id = request.values.get('order')
    order = Order.get(order_id)
    return attachment_upload(order, FILE_TYPE_SCHEDULE)
예제 #46
0
파일: admin.py 프로젝트: UItraman/buy
def clear_orders():
    os = Order.all()
    for o in os:
        o.delete()
    return redirect(url_for('admin.product_list'))
예제 #47
0
def close_cart():
    u = User.current_user()
    cart = u.cart
    Book.dec(cart)
    o = Order.new(user=u.id, items=cart, orderType='购买')
    return jsonify(o.json())
예제 #48
0
def order():
    orders = Order.objects()
    return render_template('order.html', orders=orders)
예제 #49
0
    def query_orders(self, *args, **kwargs):
        from models.order import Order

        return Order.query(Order.courier == self.key, *args, **kwargs)
def order_list():
    if "loggedin" in session:
        all_order = Order.objects()
        return render_template('order.html', all_order=all_order)
    else:
        return redirect(url_for("login"))
예제 #51
0
from models.user import User
from models.order import Order
from models.service import Service
import mlab

mlab.connect()
order = Order.objects()
all_user = User.objects()
all_service = Service.objects()
for item in order:
    service = all_service.get(id=item.service_id).name
    user = all_user.get(id=item.user_id).fullname
    time = item.time
    print(service, time)
예제 #52
0
def compute_new_trade(ctx: Context, trust_index: int, pair: str) -> Order:
    """
    Take balance : get trading asset dict : {asset :"USDT",free:10.00,locked:10.00}
    """
    account = get_balance(ctx)
    trading_asset = get_asset_in_binance_account(account, ctx.trading_asset)
    """
    Compute Total asset balancefree and locked balance
    """
    total_asset_balance = float(trading_asset["free"]) + float(
        trading_asset["locked"])
    """
    Compute trade part from risk_division part
    """
    trade_amount = risk_division_from_balance(total_asset_balance,
                                              ctx.risk_division)
    logging.info(
        '📊  Check if trade {} {} | with {} trust_index {} {} is possible...'.
        format(trade_amount, ctx.trading_asset, trust_index,
               apply_trust_index(trade_amount, trust_index),
               ctx.trading_asset))
    if ctx.min_order_value < float(trading_asset["free"]):
        """
        Apply trust index
        """
        trade_amount = apply_trust_index(trade_amount, trust_index)
        if trade_amount < ctx.min_order_value and ctx.risk_force == 1:
            logging.error(
                "⚠️  Balance is too low : {}, RISK_DIVISION cannot be respected, RISK_FORCE is enabled, cancel trade."
                .format(total_asset_balance))
            return None
        if trade_amount < ctx.min_order_value and ctx.risk_force == 0:
            logging.warning(
                "⚠️  Balance is too low : {}, RISK_DIVISION cannot be respected, MIN_ORDER_VALUE as {} will be used"
                .format(total_asset_balance, ctx.min_order_value))
            trade_amount = ctx.min_order_value
        """
        Compute Quantity, stop_loss, tp
        """
        order = dict()
        order["asset_price"] = truncate(get_average_asset_price(ctx, pair), 2)
        order["trade_sl"] = get_out_price_for_percent_loss(
            trade_amount, ctx.target_loss_limit, order["asset_price"])
        order["trade_tp"] = get_out_price_for_percent_win(
            trade_amount, ctx.target_win_limit, order["asset_price"])
        order["quantity"] = get_quantity(order["asset_price"], trade_amount)
        order["pair"] = pair
        order["type"] = "buy"

        logging.info(
            "📊  ORDER BUY {} {} for {} {}, current price : {} {}, STOP : {} {}, TP : {} {}"
            .format(order["quantity"], pair, trade_amount, ctx.trading_asset,
                    order["asset_price"], ctx.trading_asset, order["trade_sl"],
                    ctx.trading_asset, order["trade_tp"], ctx.trading_asset))
        t_order = Order()
        t_order.from_compute(ctx, order)
        return t_order
    logging.error(
        "⚠️  Balance is lower than minimum BINANCE accept orders, check your BINANCE balance account on https://www.binance.com "
    )
    return None
 def __init__(self):
     self.order = Order()
예제 #54
0
def check_first_order(client):
    order = Order.query(Order.client_id == client.key.id(),
                        Order.status.IN(NOT_CANCELED_STATUSES)).get()
    return order is None
예제 #55
0
 def post(self):
     p_id = self.get_argument("p_id", None)
     bandwidths = Order.get_orders(p_id)  
     self.finish(json.dumps(bandwidths))  
예제 #56
0
파일: app.py 프로젝트: AdamF42/acmEat
def abort_order():
    if 'id' not in request.json:
        abort(400)
    order = json.dumps(request.json)
    order = json.loads(order)
    return jsonify(Order.set_abort_for_order(order['id']))
def order_view():
    all_order = Order.objects()
    return render_template('order.html', all_order=all_order)
예제 #58
0
파일: files.py 프로젝트: cash2one/braavos
def finish_medium_order_upload():
    order_id = request.values.get('order')
    order = Order.get(order_id)
    return attachment_upload(order, FILE_TYPE_FINISH)
예제 #59
0
파일: app.py 프로젝트: AdamF42/acmEat
def get_order(id):
    order = Order.get_order_by_id(id)
    if order is not None:
        return jsonify(order)
    else:
        return not_found("Order {} not found".format(id))
예제 #60
0
파일: order.py 프로젝트: GGGGXIN/tests
 def create_order(self, info):
     order = Order(**info)
     db.session.add(order)
     db.session.commit()
     return order