def vouchers_new(): form = NewVoucherForm(flask.request.form) choices = [] if current_user.has_role('gateway-admin'): choices = [[ current_user.gateway_id, '%s - %s' % (current_user.gateway.network.title, current_user.gateway.title) ]] else: if current_user.has_role('network-admin'): networks = Network.query.filter_by(id=current_user.network_id).all() else: networks = Network.query.all() for network in networks: for gateway in network.gateways: choices.append([ gateway.id, '%s - %s' % (network.title, gateway.title) ]) form.gateway_id.choices = choices if form.validate_on_submit(): voucher = Voucher() form.populate_obj(voucher) if current_user.has_role('gateway-admin'): voucher.gateway_id = current_user.gateway_id db.session.add(voucher) db.session.commit() return flask.redirect(flask.url_for('.vouchers_new', code=voucher.code)) return flask.render_template('vouchers/new.html', form=form)
def vouchers_new(): form = NewVoucherForm(flask.request.form) choices = [] if current_user.has_role('gateway-admin'): choices = [[ current_user.gateway_id, '%s - %s' % (current_user.gateway.network.title, current_user.gateway.title) ]] else: if current_user.has_role('network-admin'): networks = Network.query.filter_by(id=current_user.network_id).all() else: networks = Network.query.all() for network in networks: for gateway in network.gateways: choices.append([ gateway.id, '%s - %s' % (network.title, gateway.title) ]) form.gateway_id.choices = choices if form.validate_on_submit(): voucher = Voucher() form.populate_obj(voucher) if current_user.has_role('gateway-admin'): voucher.gateway_id = current_user.gateway_id db.session.add(voucher) db.session.commit() return flask.redirect(flask.url_for('.vouchers_new', id=voucher.id)) return flask.render_template('vouchers/new.html', form=form)
def create_voucher(gateway, minutes=60, id=None, quiet=True): voucher = Voucher() # Allow explicit setting of ID (for tests) if id is not None: voucher.id = id voucher.gateway_id = gateway voucher.minutes = minutes db.session.add(voucher) db.session.commit() if not quiet: print 'Voucher created: %s' % voucher.id
def create_voucher(gateway, minutes=60, code=None, quiet=True): voucher = Voucher() # Allow explicit setting of code (for tests) if code is not None: voucher.code = code voucher.gateway_id = gateway voucher.minutes = minutes db.session.add(voucher) db.session.commit() if not quiet: print 'Voucher created: %s:%s' % (voucher.id, voucher.code)
def download(self, req): resp = API(self.authorization).downloadVouchers(req['id']) data = resp.json()['vouchers'] vouchers = {} if(int(req['isRemoveOld']) == 1): Voucher.query.delete() db.session.commit() for voucher in data: if voucher['redemptionStatus'] == 'UNREDEEMED': voucherObj = Voucher( voucher = voucher['voucherCode'], maxPax = voucher['totalQuantity'], name = "{} {}".format(voucher['owner']['firstName'], voucher['owner']['lastName']), isUploaded = 0, usedPax = 0, numOfDays = 1, dayUsed = 0, events_id = req['id'], events_day = voucher['reservationDate'].split('T')[0], type = voucher['passType']) vouchers.update({voucher['voucherCode']:voucherObj}) for each in Voucher.query.filter(Voucher.voucher.in_(vouchers.keys())).all(): vouchers.pop(each.voucher) db.session.add_all(vouchers.values()) db.session.commit() return jsonify(vouchers_schema.dump(vouchers.values()))
def test_voucher_update(self): """Test API can update a Voucher (PUT request)""" start1 = datetime.strptime('2018-09-01 17:00:00', "%Y-%m-%d %H:%M:%S") end1 = datetime.strptime('2019-09-15 17:00:00', '%Y-%m-%d %H:%M:%S') v1 = Voucher(code='SNSD', value=5000, start=start1, end=end1) v1.save() params = dict(code='ABCD', value=10000, start='2018-09-01 17:00:00', end='2019-09-15 17:00:00') res = self.client().put('/api/v1.0/vouchers/{}'.format(v1.id), data=json.dumps(params, indent=4), content_type='application/json') self.assertEqual(res.status_code, 201) self.assertIn('ABCD', str(res.data))
def delete_voucher(voucher_id): """delete voucher""" voucher = Voucher.get(voucher_id).first_or_404() if len(voucher) == 0: abort(404) db.session.delete(voucher) db.session.commit() return make_response(jsonify({'result': True}))
def add_voucher(): json_dict = request.json if 'name' not in json_dict: return Responses.OPERATION_FAILED(Messages.VOUCHER_NAME_EMPTY) existing_item = Voucher.get_voucher(json_dict['name']) if existing_item: return Responses.OBJECT_EXIST(Messages.VOUCHER_EXISTS) if (('discount_percent_off' in json_dict and float(json_dict['discount_percent_off']) > 0) and ('discount_fixed_amount' in json_dict and float(json_dict['discount_fixed_amount']) > 0)): return Responses.OPERATION_FAILED(Messages.VOUCHER_DETAILS_WRONG) item = Voucher(json_dict['name']) error = item.insert_as_new_item(json_dict, ['name', 'redeem_by']) if len(error) > 0: return Responses.OPERATION_FAILED(error) return res(item.as_dict())
def post(self, request): form = VoucherForm(request.POST) if form.is_valid(): n = form.cleaned_data['n'] price = form.cleaned_data['amount'] startTime = form.cleaned_data['startTime'] endTime = form.cleaned_data['endTime'] for i in range(0, n): s = ''.join(choice(ascii_uppercase) for i in range(10)) u = Voucher(code=s, amount=price, startTime=startTime, endTime=endTime, redeemed=False, assigned=False) u.save() form = VoucherForm() args = {'form': form, 'text': "Vouchers Generated"} return render(request, 'index.html', args)
def new_voucher(): voucher = Voucher('LUO20') voucher.product_id = 1 voucher.discount_fixed_amount = 8.00 voucher.max_redemptions = 2 voucher.no_of_redemptions = 1 voucher.redeem_by = datetime.strptime('8-8-2020', '%d-%m-%Y') return voucher
def member_order(new_product): order = Order() first_order_item = OrderItem() first_order_item.quantity = 1 first_order_item.product_id = 2 first_order_item.variation_id = 3 first_order_item.start_date = datetime.strptime('1-4-2020', '%d-%m-%Y') first_order_item.end_date = datetime.strptime('8-4-2020', '%d-%m-%Y') second_order_item = OrderItem() second_order_item.quantity = 1 second_order_item.product_id = 3 second_order_item.variation_id = 2 second_order_item.start_date = datetime.strptime('1-4-2020', '%d-%m-%Y') second_order_item.end_date = datetime.strptime('8-4-2020', '%d-%m-%Y') third_order_item = OrderItem() third_order_item.quantity = 1 third_order_item.product_id = 4 third_order_item.variation_id = 2 third_order_item.start_date = datetime.strptime('1-4-2020', '%d-%m-%Y') third_order_item.end_date = datetime.strptime('8-4-2020', '%d-%m-%Y') voucher = Voucher('LUO20') voucher.product_id = 1 voucher.discount_fixed_amount = 8.00 order.order_items = [] order.vouchers = [] order.user_id = 2 order.id = 43 order.order_items.append(first_order_item) order.order_items.append(second_order_item) order.order_items.append(third_order_item) order.vouchers.append(voucher) return order
def test_overlap_with_others(self): """Test unit overlap with others for updating""" start1 = datetime.strptime('2018-09-01 17:00:00', "%Y-%m-%d %H:%M:%S") end1 = datetime.strptime('2019-09-15 17:00:00', '%Y-%m-%d %H:%M:%S') start2 = datetime.strptime('2019-09-01 17:00:00', '%Y-%m-%d %H:%M:%S') end2 = datetime.strptime('2019-09-15 17:00:00', '%Y-%m-%d %H:%M:%S') v1 = Voucher(code='SNSD', value=5000, start=start1, end=end1) v2 = Voucher(code='SNSD', value=10000, start=start2, end=end2) db.session.add(v1) db.session.add(v2) db.session.commit() v2.start = datetime.strptime('2018-09-01 17:00:00', "%Y-%m-%d %H:%M:%S") v2.end = datetime.strptime('2019-09-15 17:00:00', '%Y-%m-%d %H:%M:%S') self.assertEqual(v2.is_overlap_with_other(), True) v2.start = datetime.strptime('2020-09-01 17:00:00', "%Y-%m-%d %H:%M:%S") v2.end = datetime.strptime('2021-09-01 17:00:00', "%Y-%m-%d %H:%M:%S") self.assertEqual(v2.is_overlap_with_other(), False)
def calculate_order_discount(): json_dict = request.json item = Order() order_items_dict = json_dict['order_items'] for order_item_dict in order_items_dict: order_item = OrderItem() if order_item.update_from_dict(order_item_dict): item.order_items.append(order_item) voucher_codes = json_dict['voucher_codes'] number_vouchers_allowed = int( ConfigValues.get_config_value('max_no_of_vouchers')) if len(voucher_codes) > number_vouchers_allowed: return Responses.NO_VOUCHERS_EXCEEDED() vouchers = Voucher.get_vouchers(voucher_codes) if not vouchers[0]: return Responses.INVALID_VOUCHER() valid = Voucher.validate_voucher(vouchers) if valid: item.vouchers = vouchers item.calculate_discounted_cost() return res(item.as_dict())
def get_vouchers(name=None): """ get_vouchers gets all vouchers """ page, per_page = get_page_from_args() sort_by = request.args.get('sort_by') is_desc = parse_int(request.args.get('is_desc')) items = Voucher.get_items(name=name, page=page, per_page=per_page, sort_by=sort_by, is_desc=is_desc) return res([item.as_dict() for item in items])
def test_overlap(self): """Test unit overlap""" start1 = datetime.strptime('2018-09-01 17:00:00', "%Y-%m-%d %H:%M:%S") end1 = datetime.strptime('2019-09-15 17:00:00', '%Y-%m-%d %H:%M:%S') start2 = datetime.strptime('2019-09-01 17:00:00', '%Y-%m-%d %H:%M:%S') end2 = datetime.strptime('2019-09-15 17:00:00', '%Y-%m-%d %H:%M:%S') v1 = Voucher(code='SNSD', value=5000, start=start1, end=end1) v2 = Voucher(code='SNSD', value=10000, start=start2, end=end2) db.session.add(v1) db.session.add(v2) db.session.commit() start3 = datetime.strptime('2019-09-14 17:00:00', "%Y-%m-%d %H:%M:%S") end3 = datetime.strptime('2019-09-15 17:00:00', "%Y-%m-%d %H:%M:%S") v3 = Voucher(code='SNSD', value=10000, start=start3, end=end3) self.assertEqual(v3.is_overlap(), True) """Test unit overlap Fails""" v3.start = datetime.strptime('2020-09-14 17:00:00', "%Y-%m-%d %H:%M:%S") v3.end = datetime.strptime('2021-09-14 17:00:00', "%Y-%m-%d %H:%M:%S") self.assertEqual(v3.is_overlap(), False)
def get_vouchers_pages(name=None): """ get_vouchers gets all vouchers """ page, per_page = get_page_from_args() sort_by = request.args.get('sort_by') is_desc = parse_int(request.args.get('is_desc')) page_details = Voucher.get_items_pages(name=name, page=page, per_page=per_page, sort_by=sort_by, is_desc=is_desc) return res({ "total_items": page_details.total, "no_of_pages": page_details.pages, "per_page": page_details.per_page })
def create_voucher(): """register new voucher""" data = request.get_json(silent=True) if not data or not 'code' or not 'value' or not 'start' or not 'end' in data: abort(400) start = datetime.strptime(data['start'], '%Y-%m-%d %H:%M:%S') end = datetime.strptime(data['end'], '%Y-%m-%d %H:%M:%S') if end <= start: abort(400) voucher = Voucher(code=data['code'], value=data['value'], start=start, end=end) if voucher.is_overlap(): abort(400) voucher.save() return make_response(jsonify(voucher=voucher.serialize()), 201)
def test_apply_voucher_to_cart(self): with self.app.app_context(): res = self.client.get('/cart/1/voucher/1') self.assertEqual(404, res.status_code) store = Store(name='Test Store') db.session.add(store) db.session.commit() today = date.today() voucher = Voucher(code='TESTCODE', store_id=store.id, start_date=today, end_date=today + timedelta(days=5)) cart = Cart(store_id=store.id) db.session.add(cart) db.session.add(voucher) db.session.commit() res = self.client.get(f'/cart/{cart.id}/voucher/{voucher.id}') self.assertEqual(200, res.status_code) self.assertIn(b'original_price', res.data) self.assertIn(b'discounted_price', res.data) self.assertTrue(self.is_json_content_type(res.content_type))
def update_vouchers(name): """ update_voucher updates voucher by using name Args: name (string): Returns: (string,int): update succesful, otherwise response no need to update """ item = Voucher.get_voucher(name) if not item: return Responses.NOT_EXIST() json_dict = request.json if (('discount_percent_off' in json_dict and float(json_dict['discount_percent_off']) > 0) and ('discount_fixed_amount' in json_dict and float(json_dict['discount_fixed_amount']) > 0)): return Responses.OPERATION_FAILED(Messages.VOUCHER_DETAILS_WRONG) if len(item.update(json_dict)) > 0: return Responses.OPERATION_FAILED() return Responses.SUCCESS()
def init_database(): db = AC().db # Create the database and the database table db.create_all() member = Role("member") admin = Role("admin") user = User("*****@*****.**", "1q2w3e4r") user.email_confirmed = True user2 = User("*****@*****.**", "1q2w3e4r") user3 = User("*****@*****.**", "1q2w3e4r") user4 = User("*****@*****.**", "1q2w3e4r") user.role = admin user2.email_confirmed = True user2.subscribed = True user3.email_confirmed = True user3.subscribed = True user4.email_confirmed = False max_no_products_per_month = ConfigValues('max_no_products_per_month', 20) max_no_free_products_adayalite_user = ConfigValues( 'max_no_free_products_adayalite_user', 4) max_no_of_items_per_order_adayalifestyle = ConfigValues( 'max_no_of_items_per_order_adayalifestyle', 4) max_no_products_per_order = ConfigValues('max_no_products_per_order', 4) min_duration_of_rental = ConfigValues('min_duration_of_rental', 4) max_duration_of_rental = ConfigValues('max_duration_of_rental', 7) max_no_of_vouchers = ConfigValues('max_no_of_vouchers', 2) MAIL_USERNAME = ConfigValues('MAIL_USERNAME', '*****@*****.**') MAIL_PASSWORD = ConfigValues('MAIL_PASSWORD', 'adaya1234') MAIL_SERVER = ConfigValues('MAIL_SERVER', 'smtp.gmail.com') MAIL_PORT = ConfigValues('MAIL_PORT', 465) MAIL_DEFAULT_SENDER = ConfigValues('MAIL_DEFAULT_SENDER', '*****@*****.**') EMAIL_PASSWORD_RESET_SECRET_KEY = ConfigValues( 'EMAIL_PASSWORD_RESET_SECRET_KEY', 'Thisisasecret!') SIB_KEY = ConfigValues('SIB_KEY', 'gzryVUPZHa1GW7n6') subtype = SubscriptionType(plan='Adaya Lite', price=10) subtype2 = SubscriptionType(plan='Adaya Premium', price=40) usersubscription = UserSubscription() usersubscription.user_id = 2 usersubscription.current_start_date = datetime.now() usersubscription.current_end_date = datetime.strptime( '2020-09-06 05:58:00', '%Y-%m-%d %H:%M:%S') usersubscription.subscription_type = subtype usersubscription2 = UserSubscription() usersubscription2.user_id = 3 usersubscription2.current_start_date = datetime.now() usersubscription2.current_end_date = datetime.strptime( '2020-08-06 05:58:00', '%Y-%m-%d %H:%M:%S') usersubscription2.subscription_type = subtype2 voucher = Voucher('HAO20') voucher.discount_fixed_amount = 100 voucher.product_id = 3 voucher.redeem_by = datetime.strptime('2020-8-13 00:00:00', '%Y-%m-%d %H:%M:%S') voucher2 = Voucher('LUO20') voucher2.discount_fixed_amount = 8.00 voucher2.product_id = 1 voucher2.redeem_by = datetime.strptime('2020-8-13 00:00:00', '%Y-%m-%d %H:%M:%S') for x in range(1, 11): variation = Variation('S') variation.product_id = x variation.price = 10 variation.stock = 1 variation1 = Variation('M') variation1.product_id = x variation1.price = 20 variation1.stock = 1 variation2 = Variation('L') variation2.product_id = x variation2.price = 30 variation2.stock = 1 variation3 = Variation('XL') variation3.product_id = x variation3.price = 40 variation3.stock = 1 db.session.add(variation) db.session.add(variation1) db.session.add(variation2) db.session.add(variation3) db.session.add(max_no_products_per_order) db.session.add(max_no_products_per_month) db.session.add(max_no_free_products_adayalite_user) db.session.add(max_no_of_items_per_order_adayalifestyle) db.session.add(min_duration_of_rental) db.session.add(max_duration_of_rental) db.session.add(max_no_of_vouchers) db.session.add(MAIL_USERNAME) db.session.add(MAIL_PASSWORD) db.session.add(MAIL_SERVER) db.session.add(MAIL_PORT) db.session.add(MAIL_DEFAULT_SENDER) db.session.add(EMAIL_PASSWORD_RESET_SECRET_KEY) db.session.add(SIB_KEY) db.session.add(voucher) db.session.add(voucher2) db.session.add(member) db.session.add(user) db.session.add(user2) db.session.add(user3) db.session.add(user4) db.session.add(subtype) db.session.add(subtype2) db.session.add(usersubscription) db.session.add(usersubscription2) food_category = ProductCategory('food') clothes_category = ProductCategory('cloth') food_article = ArticleCategory('food-article') clothes_article = ArticleCategory('cloth-article') status = ArticleStatus('draft') order_status = OrderStatus('completed') db.session.add(order_status) db.session.add(food_article) db.session.add(clothes_article) db.session.add(food_category) db.session.add(clothes_category) for x in range(10): product = Product('Haoluo') article = Article(randomString(10)) order = Order() order_item = OrderItem() order_item.quantity = 1 order_item.variation_id = 2 order_item.start_date = datetime.strptime('2020-4-1 00:00:00', '%Y-%m-%d %H:%M:%S') order_item.end_date = datetime.strptime('2020-4-8 00:00:00', '%Y-%m-%d %H:%M:%S') order.order_items = [] order.order_items.append(order_item) article_category = food_article category = food_category if x % 2 == 0: category = clothes_category article_category = clothes_article product.category = category article.category = article_category article.status = status db.session.add(order) db.session.add(product) db.session.add(order_item) db.session.add(article) db.session.commit() yield db db.drop_all()
def get_vouchers(): """Get all new vouchers""" vouchers = Voucher.get_all() result = jsonify(vouchers=[e.serialize() for e in vouchers]) return make_response(result)
def member_order(): order = Order() first_order_item = OrderItem() first_order_item.quantity = 1 first_order_item.product_id = 2 first_order_item.variation_id = 3 first_order_item.start_date = datetime.datetime.strptime( '2020-8-1 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') first_order_item.end_date = datetime.datetime.strptime( '2020-8-8 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') second_order_item = OrderItem() second_order_item.quantity = 1 second_order_item.product_id = 5 second_order_item.variation_id = 2 second_order_item.start_date = datetime.datetime.strptime( '2020-8-1 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') second_order_item.end_date = datetime.datetime.strptime( '2020-8-8 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') third_order_item = OrderItem() third_order_item.quantity = 1 third_order_item.product_id = 4 third_order_item.variation_id = 2 third_order_item.start_date = datetime.datetime.strptime( '2020-8-1 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') third_order_item.end_date = datetime.datetime.strptime( '2020-8-8 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') fourth_order_item = OrderItem() fourth_order_item.variation_id = 2 fourth_order_item.product_id = 3 fourth_order_item.quantity = 1 fourth_order_item.start_date = datetime.datetime.strptime( '2020-8-1 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') fourth_order_item.end_date = datetime.datetime.strptime( '2020-8-8 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') fifth_order_item = OrderItem() fifth_order_item.variation_id = 2 fifth_order_item.product_id = 6 fifth_order_item.quantity = 1 fifth_order_item.start_date = datetime.datetime.strptime( '2020-8-1 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') fifth_order_item.end_date = datetime.datetime.strptime( '2020-8-8 00:00:00', '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S') voucher = Voucher('HAO20') voucher.product_id = 3 order.order_items = [] order.vouchers = [] order.user_id = 2 order.id = 43 order.order_items.append(first_order_item) order.order_items.append(second_order_item) order.order_items.append(third_order_item) order.order_items.append(fourth_order_item) order.order_items.append(fifth_order_item) order.vouchers.append(voucher) return order
def get_voucher(voucher_id): """get voucher detail""" voucher = Voucher.get(voucher_id).first_or_404() return make_response(jsonify(voucher=voucher.serialize()))
def test_calculate_discounted_cost(test_client, init_database, new_voucher): valid = Voucher.validate_voucher([new_voucher, new_voucher]) assert valid == True
variation1 = Variation('M') variation1.product_id = x variation1.price = 20 variation1.retail_price = variation1.price * 3 variation1.stock = 1 variation2 = Variation('L') variation2.product_id = x variation2.price = 30 variation2.retail_price = variation2.price * 3 variation2.stock = 1 variation3 = Variation('XL') variation3.product_id = x variation3.price = 40 variation3.retail_price = variation3.price * 3 variation3.stock = 1 db.session.add(variation) db.session.add(variation1) db.session.add(variation2) db.session.add(variation3) voucher = Voucher('HAO20') voucher.discount_fixed_amount = 5 voucher.product_id = 1 voucher.redeem_by = datetime.strptime('13-4-2020', '%d-%m-%Y') voucher2 = Voucher('LUO20') voucher2.discount_fixed_amount = 20 voucher2.product_id = 2 voucher2.redeem_by = datetime.strptime('18-4-2020', '%d-%m-%Y') db.session.add(voucher) db.session.add(voucher2) db.session.commit()
def toolbox(): form = WithdrawFundsForm(current_user.username) form2 = AddPromotedTweet(current_user.username) form3 = CreateVouchersForm(current_user.username) giveaiq_username = current_user.username giveaiq_displayname = giveaiq_username[3:] giveaiq_accounttype = giveaiq_username[0:3] giveaiq_wallet_name = giveaiq_accounttype + giveaiq_displayname.lower() cmd = "UPDATE promoted_tweet set status={0} where added_date<date()-1 and user_id={1} and status={2}".format( get_status_id("Tweet Order Expired"), current_user.id, get_status_id("Tweet Awaiting Confirmation")) db.session.execute(cmd, ) db.session.commit() twitter_followers, total_supply, circulating_supply, btc_price, fiat_price, currency_json = get_api_coingecko( ) # cat_1_price = 2.5/float(fiat_price) # cat_2_price = 0.5/float(fiat_price) # cat_3_price = 0 # uppsymb = "USD" # decplace = 4 cmd = "SELECT SUM(amount) FROM withdraw where user_id={0} and status={1}".format( current_user.id, get_status_id("Withdraw Awaiting Confirmation")) planned_ammount = db.session.execute(cmd, ).fetchone()[0] if planned_ammount is None: planned_ammount = 0 cmd = "select SUM(tweet_category.price) from promoted_tweet, tweet_category where promoted_tweet.cat_id=tweet_category.id and promoted_tweet.user_id={0} and promoted_tweet.status={1}".format( current_user.id, get_status_id("Tweet Awaiting Confirmation")) planned_ammount2 = db.session.execute(cmd, ).fetchone()[0] if planned_ammount2 is None: planned_ammount2 = 0 cmd = "SELECT SUM(amount) FROM voucher where user_id={0} and status={1}".format( current_user.id, get_status_id("Voucher Awaiting Confirmation")) planned_ammount3 = db.session.execute(cmd, ).fetchone()[0] if planned_ammount3 is None: planned_ammount3 = 0 if form.submit.data and form.validate(): address = ''.join(str(e) for e in form.target.data) amount = float(form.amount.data) balance = get_user_balance(giveaiq_wallet_name) cmd = "SELECT SUM(amount) FROM withdraw where user_id={0} and status={1}".format( current_user.id, get_status_id("Withdraw Awaiting Confirmation")) planned_ammount = db.session.execute(cmd, ).fetchone()[0] if planned_ammount is None: planned_ammount = 0 if balance - float(planned_ammount) < amount: flash('Sorry, you have unsuficient funds.') else: withdraw = Withdraw( target_wallet=address, amount=amount, user_id=current_user.id, status=get_status_id("Withdraw Awaiting Confirmation")) db.session.add(withdraw) db.session.commit() change_user_tweet(current_user.id) cmd = "SELECT SUM(amount) FROM withdraw where user_id={0} and status={1}".format( current_user.id, get_status_id("Withdraw Awaiting Confirmation")) planned_ammount = db.session.execute(cmd, ).fetchone()[0] if planned_ammount is None: planned_ammount = 0 if form2.submit2.data and form2.validate(): pattern = r"http[s]{0,1}://twitter.com/[a-zA-Z0-9_]*/status/(\d+).*" match = re.match(pattern, form2.tweet_id.data) tweet_id = match.group(1) cat_id = int(get_category_id(form2.cat_id.data)) cmd = "select price from tweet_category where id={0}".format(cat_id) amount = db.session.execute(cmd, ).fetchone()[0] balance = get_user_balance(giveaiq_wallet_name) cmd = "select SUM(tweet_category.price) from promoted_tweet, tweet_category where promoted_tweet.cat_id=tweet_category.id and promoted_tweet.user_id={0} and promoted_tweet.status={1}".format( current_user.id, get_status_id("Tweet Awaiting Confirmation")) planned_ammount2 = db.session.execute(cmd, ).fetchone()[0] if planned_ammount2 is None: planned_ammount2 = 0 if balance - float(planned_ammount2) < amount: flash('Sorry, you have insuficient funds.') else: promotedtweet = PromotedTweet( tweet_id=tweet_id, cat_id=cat_id, status=get_status_id("Tweet Awaiting Confirmation"), user_id=current_user.id) db.session.add(promotedtweet) db.session.commit() change_user_tweet(current_user.id) cmd = "select SUM(tweet_category.price) from promoted_tweet, tweet_category where promoted_tweet.cat_id=tweet_category.id and promoted_tweet.user_id={0} and promoted_tweet.status={1}".format( current_user.id, get_status_id("Tweet Awaiting Confirmation")) planned_ammount2 = db.session.execute(cmd, ).fetchone()[0] if planned_ammount2 is None: planned_ammount2 = 0 if form3.submit3.data and form3.validate(): voucher_pin = ''.join(str(e) for e in form3.password.data) voucher_value = float(form3.voucher_value.data) voucher_number = int(form3.voucher_number.data) total_value = voucher_value * voucher_number balance = get_user_balance(giveaiq_wallet_name) print(voucher_pin) print(voucher_value) print(voucher_number) # cmd = "SELECT SUM(amount) FROM voucher where user_id={0} and status={1}".format(current_user.id, get_status_id("Voucher Awaiting Confirmation")) # planned_ammount3 = db.session.execute(cmd, ).fetchone()[0] # if planned_ammount3 is None: # planned_ammount3=0 if balance - float(planned_ammount3) < total_value: flash('Sorry, you have unsuficient funds.') else: status = get_status_id("Voucher Awaiting Confirmation") for x in range(voucher_number): voucher = Voucher(amount=voucher_value, user_id=current_user.id, status=status) voucher.set_password(voucher_pin) db.session.add(voucher) db.session.commit() change_user_tweet(current_user.id) cmd = "SELECT SUM(amount) FROM voucher where user_id={0} and status={1}".format( current_user.id, get_status_id("Voucher Awaiting Confirmation")) planned_ammount3 = db.session.execute(cmd, ).fetchone()[0] if planned_ammount3 is None: planned_ammount3 = 0 confirm_my_stuff = db.session.execute( "SELECT confirm_my_stuff FROM user where username=:username", { "username": giveaiq_username }).fetchone()[0] if confirm_my_stuff is None: confirm_my_stuff = "Please change your password first at give.artiqox.com/register" if giveaiq_accounttype == "TW-": tweet = "@GiveAIQ you guys rock! " + confirm_my_stuff + " #AIQ $AIQ #cryptocurrency @artiqox" tweet2 = "@GiveAIQ AIQ supercrypto! " + confirm_my_stuff + " #AIQ $AIQ #cryptocurrency @artiqox" tweet3 = "@GiveAIQ AIQ cryptovouchers, so cool! " + confirm_my_stuff + " #AIQ $AIQ #cryptocurrency @artiqox" elif giveaiq_accounttype == "TG-": tweet = "/withdrawmystuff " + confirm_my_stuff tweet2 = "/promotemystuff " + confirm_my_stuff tweet3 = "/cryptovouchers " + confirm_my_stuff cmd = "SELECT id, target_wallet, amount FROM withdraw WHERE user_id={0} and status={1}".format( current_user.id, get_status_id("Withdraw Awaiting Confirmation")) withdraws = db.session.execute(cmd, ).fetchall() cmd = "SELECT promoted_tweet.id, promoted_tweet.tweet_id, tweet_category.price FROM promoted_tweet, tweet_category WHERE promoted_tweet.cat_id=tweet_category.id and promoted_tweet.user_id={0} and promoted_tweet.status={1}".format( current_user.id, get_status_id("Tweet Awaiting Confirmation")) promotedtweets = db.session.execute(cmd, ).fetchall() cmd = "SELECT voucher.id, voucher.amount, voucher.comment, voucher.status FROM voucher WHERE voucher.user_id={0}".format( current_user.id) vouchers = db.session.execute(cmd, ).fetchall() vouchers_awaiting = [] vouchers_valid = [] if vouchers: status_awaiting = get_status_id("Voucher Awaiting Confirmation") status_active = get_status_id("Voucher Active") status_used = get_status_id("Voucher Used") for worder in vouchers: id = worder[0] if worder[3] == status_awaiting: vouchers_awaiting.append({ 'voucher_number': get_voucher_number(worder[0]), 'voucher_amount': worder[1], 'voucher_comment': worder[2] }) elif worder[3] == status_active: vouchers_valid.append({ 'voucher_number': get_voucher_number(worder[0]), 'voucher_amount': worder[1], 'voucher_comment': worder[2], 'voucher_status': "Active" }) elif worder[3] == status_used: vouchers_valid.append({ 'voucher_number': get_voucher_number(worder[0]), 'voucher_amount': worder[1], 'voucher_comment': worder[2], 'voucher_status': "Used" }) fiat_balance, btc_balance, balance, walletid, transactions, giveaiq_stats = get_user_dashboard( current_user.username, fiat_price, btc_price) print(vouchers_awaiting) return render_template('toolbox.html', title='Toolbox', form=form, form2=form2, form3=form3, planned_ammount=planned_ammount, planned_ammount2=planned_ammount2, planned_ammount3=planned_ammount3, withdraws=withdraws, promotedtweets=promotedtweets, tweet=tweet, tweet2=tweet2, tweet3=tweet3, balance=balance, fiat_balance=fiat_balance, btc_balance=btc_balance, walletid=walletid, circulating_supply=circulating_supply, total_supply=total_supply, twitter_followers=twitter_followers, giveaiq_stats=giveaiq_stats, vouchers_awaiting=vouchers_awaiting, vouchers_valid=vouchers_valid, giveaiq_accounttype=giveaiq_accounttype, giveaiq_displayname=giveaiq_displayname, telegram_bot_name=telegram_bot_name)
def init(): mer1 = Merchant(999, 'Test Company', 'Testing', 5.0) mer2 = Merchant(998, 'Test Company2', 'Testing', 5.2) mer3 = Merchant(997, 'Test Company3', 'Testing', 5.3) mer4 = Merchant(996, 'Test Company4', 'Testing', 5.5) mer5 = Merchant(995, 'Test Company5', 'Testing', 5.6) mer6 = Merchant(994, 'Test Company6', 'Testing', 5.7) sc1 = Subcategory(ps_id=999, ps_name="sc1") sc2 = Subcategory(ps_id=998, ps_name="sc2") sc3 = Subcategory(ps_id=997, ps_name="sc3") sc4 = Subcategory(ps_id=996, ps_name="sc4") sc5 = Subcategory(ps_id=995, ps_name="sc5") sc6 = Subcategory(ps_id=994, ps_name="sc6") c1 = Category(pc_id=999, pc_name="c1", ps_id=999) c2 = Category(pc_id=998, pc_name="c2", ps_id=998) c3 = Category(pc_id=997, pc_name="c3", ps_id=997) c4 = Category(pc_id=996, pc_name="c4", ps_id=996) c5 = Category(pc_id=995, pc_name="c5", ps_id=995) c6 = Category(pc_id=994, pc_name="c6", ps_id=994) p5 = Product(pid=995, pname='Disney Toy Story', qty=3, price=155, mid=995, status="Good", pc_id=995, ps_id=995, link="https://images.hktv-img.com/images/HKTV/18800/H1283ToyStoryBook_main_36832182_20200409124617_01_1200.jpg") p6 = Product(pid=994, pname='FRONTLINE - Plus for Cats & Kittens 8 Weeks or Older', qty=4, price=159, mid=994, status="Good", pc_id=994, ps_id=994, link="https://images.hktvmall.com/h0888001/129563/h0888001_10130629_171018034423_01_1200.jpg") d1 = Disney(id=995, name="Disney Toy Story", link="https://images.hktv-img.com/images/HKTV/18800/H1283ToyStoryBook_main_36832182_20200409124617_01_1200.jpg", price=155, product_id=995) pet1 = Pets(id=995, name="FRONTLINE - Plus for Cats & Kittens 8 Weeks or Older", link="https://images.hktvmall.com/h0888001/129563/h0888001_10130629_171018034423_01_1200.jpg", price=159, product_id=994) p1 = Product(pid=999, pname='Testing Product1', qty=1, price=45, mid=999, status="Good", pc_id=999, ps_id=999, link="https://picsum.photos/273/190") p2 = Product(pid=998, pname="TW Disposable Mask Protective Pad", qty=1, price=55, mid=998, status="Good", pc_id=998, ps_id=998, link="https://images.hktv-img.com/images/HKTV/10787/MIT-001A_main_35311815_20200310182421_01_1200.jpg") p3 = Product(pid=997, pname="FitBoxx - Everlast Evercool Gloves Bag", qty=1, price=56, mid=997, status="Good", pc_id=997, ps_id=997, link="https://images.hktvmall.com/h0395001/m/photos/8831465193522_1_1200.jpg") p4 = Product(pid=996, pname="HKQgamers - Switch Game - Pokemon Sword", qty=2, price=44, mid=996, status="no", pc_id=996, ps_id=996, link="https://images.hktv-img.com/images/HKTV/10823/GA20191104A08_main_31312491_20191112141038_01_1200.jpg") h1 = Housewares(id=995, name="TW Disposable Mask Protective Pad", link="https://images.hktv-img.com/images/HKTV/10787/MIT-001A_main_35311815_20200310182421_01_1200.jpg", price=55, product_id=998) s1 = SportsAndTravel(id=995, name="FitBoxx - Everlast Evercool Gloves Bag", link="https://images.hktvmall.com/h0395001/m/photos/8831465193522_1_1200.jpg", price=65, product_id=997) t1 = ToysAndBooks(id=995, name="HKQgamers - Switch Game - Pokemon Sword", link="https://images.hktv-img.com/images/HKTV/10823/GA20191104A08_main_31312491_20191112141038_01_1200.jpg", price=44, product_id=996) admin = User(id=0, first_name="a", last_name="a", username="******", email="*****@*****.**", phone=132, password_hash="pbkdf2:sha256:50000$K1aBNTtq$a627489faa2332223c5225bbc26a9c875d57437fa4865b83875eeb957b3f04dd") db.session.add(admin) v1 = Voucher(v_id=1,code="hktv",discount="10") db.session.add(v1) db.session.add(mer1) db.session.add(mer2) db.session.add(mer3) db.session.add(mer4) db.session.add(mer5) db.session.add(mer6) db.session.add(sc1) db.session.add(sc2) db.session.add(sc3) db.session.add(sc4) db.session.add(sc5) db.session.add(sc6) db.session.commit() db.session.add(c1) db.session.add(c2) db.session.add(c3) db.session.add(c4) db.session.add(c5) db.session.add(c6) db.session.commit() db.session.add(p1) db.session.add(p2) db.session.add(p3) db.session.add(p4) db.session.add(p5) db.session.add(p6) db.session.commit() db.session.add(h1) db.session.add(s1) db.session.add(t1) db.session.add(d1) db.session.add(pet1) db.session.commit() return redirect(url_for('main.index'))