def CouponsGenerate(request, reward_id): amount = 5 reward = get_object_or_404(Reward,pk = reward_id) for i in range(amount): coupon = Coupon(reward = reward) coupon.save() return redirect(reverse('rewards-vendor-coupons', kwargs={'reward_id': reward_id}))
def test_coupon_none(self): """ Retives coupon list when there are none. """ coupon1 = Coupon(rid=12, name="test1", points=10, description="1$ off", level=1, begin=BEGIN, expiration=END, deleted=0) coupon2 = Coupon(rid=12, name="test2", points=20, description="2$ off", level=10, begin=BEGIN, expiration=END, deleted=0) coupon3 = Coupon(rid=12, name="test3", points=30, description="3$ off", level=100, begin=BEGIN, expiration=END, deleted=1) db.session.add(coupon1) db.session.add(coupon2) db.session.add(coupon3) db.session.commit() coupon_list = couponhelper.get_coupons(15) self.assertEqual(coupon_list, [])
def generate_coupon(coin, description, producer): if coin is None or description is None: raise Error("coin and description required") coupon = Coupon(coin=coin, description=description, producer=producer) try: coupon.save() return coupon except ValidationError: raise Error("invalid value")
def on_post(self, req, resp, id): try: coupon = Coupon(id=id) couponBody = req.json for key in couponBody.keys(): coupon[key] = couponBody[key] print(coupon.save()) except Exception as e: ResponseUtil.error(e, resp)
def on_post(self, req, resp, id): try: coupon = Coupon(id=id) couponBody = req.json for key in couponBody.keys(): coupon[key] = couponBody[key] item = coupon.save() ResponseUtil.makeBody(resp, item.to_json()) except Exception as e: print(e) ResponseUtil.error(e, resp)
def addCoupon(): #返回参数结构 responseData = {"status": 0, "message": '', "result": {}} if request.method == "POST": couponId = str(uuid.uuid1()) spendMoney = request.form.get("spendMoney") disCount = request.form.get("disCount") endTime = request.form.get("endTime") title = request.form.get("title") if not all([spendMoney, disCount, endTime, title]): responseData["status"] = 1 responseData["message"] = "缺少必要的业务参数!" else: coupon = Coupon(couponId=couponId, spendMoney=spendMoney, disCount=disCount, endTime=endTime, title=title) db.session.add(coupon) db.session.commit() responseData["status"] = 0 responseData["message"] = "添加成功!" return jsonify(responseData)
def test_coupon_single(self): """ Test getting a coupon, with a coupon in the database. """ coupon = Coupon(rid=12, name="test", points=10, description="1$ off", level=25, begin=BEGIN, expiration=END, deleted=0) db.session.add(coupon) db.session.commit() result = couponhelper.get_coupon_by_cid(coupon.cid) self.assertEqual( result, { "cid": coupon.cid, "rid": coupon.rid, "cname": coupon.name, "cdescription": coupon.description, "clevel": coupon.level, "begin": coupon.begin, "expiration": coupon.expiration, "points": coupon.points, "status": 1 })
def test_coupon_single(self): """ Retives coupon list when there is only one. """ coupon = Coupon(rid=12, name="test", points=10, description="1$ off", level=1, begin=BEGIN, expiration=END, deleted=0) db.session.add(coupon) db.session.commit() coupon_list = couponhelper.get_coupons(12) self.assertEqual(coupon_list, [{ 'begin': BEGIN, 'cid': 1, 'description': '1$ off', 'expiration': END, 'name': 'test', 'points': 10, 'level': 1, "deleted": 0 }])
def insert_coupon(rid, name, points, description, level, begin, expiration, indefinite): """ Inserts a coupon into Coupon table. Args: rid: A restaurant ID that corresponds to a restaurant in the Restaurant table. An integer. name: A name for the coupon. A 64 character string. points: A point value for the coupon. An integer. description: A description of the coupon. A 1024 character string. level: A level that restricts only users reach this level or above in the restaurant can purchase/use(available). An unsigned Int begin: A starting date for the coupon. A DateTime. expiration: An ending date for the coupon. A DateTime. indefinite: A boolean with the following property: true == coupon has no begining/ending date. false == coupon has a begining/ending date. Returns: None if coupon was successfully added to the Coupon table, a list of error messages otherwise. """ errmsg = [] if points == "" or int(points) < 0: errmsg.append("Invalid amount for points.") if name == "": errmsg.append("Invalid coupon name, please give your coupon a name.") if level == "" or int(level) < 0: errmsg.append("Invalid level requirement, please give a non-negative value.") if not indefinite and ((expiration == None or begin == None) or (expiration == "" or begin == "")): errmsg.append("Missing start or expiration date.") elif not indefinite and expiration < begin: errmsg.append("Invalid date interval, begin date must be before expiration date.") if not errmsg: if indefinite: coupon = Coupon(rid = rid, name = name, points = points, description = description, level = level, deleted = 0) else: coupon = Coupon(rid = rid, name = name, points = points, description = description, level = level, expiration = expiration, begin = begin, deleted = 0) db.session.add(coupon) db.session.commit() return None return errmsg
def get(self): if not users.is_current_user_admin(): self.abort(404) for b in Business.query().iter(): b.key.delete() for c in Coupon.query().iter(): c.key.delete() self.init() self.response.write('success')
def post(self): ''' HTTP POST Method Handler Creates new coupon ''' params = self.load_json_params({ 'business': (int, True), 'name': (str, True), 'description': (str, False), 'start': (str_to_datetime, True), 'end': (str_to_datetime, True) }) business_key = ndb.Key('Business', params['business']) authenticate(business_key.get()) params['business'] = business_key key = Coupon(**self.params).put() self.status = '200 OK' self.response.write('/api/coupon/' + str(key.id()))
def on_get(self, req, resp, id): try: coupons = Coupon.objects(id=id) if len(coupons) == 0: ResponseUtil.makeResponse(404, resp) return else: ResponseUtil.makeBody(resp, coupons[0].to_json()) except Exception as e: ResponseUtil.error(e, resp)
def test_no_such_cid_name(self): """ Test that this cid is not exist, the method should return "Not Found". """ coupon = Coupon(rid=100, name="coupon_testing", points=25, description="des", level=36, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() rname = chelper.find_res_name_of_coupon_by_cid(100) self.assertEqual(rname, "Not Found")
def get(self): ''' HTTP POST Method Handler Searches user's coupons ''' authenticate(self.get_uid(), self.get_bid()) self.response.status = '200 OK' for k in Coupon.get_by_user_and_business(self.get_uid(), self.get_bid(), keys_only=True): self.response.write(str(k.id()) + '\n')
def test_indefinite_expiry(self): """ Tests when the coupon's expiry date is indefinite. """ coupon = Coupon(rid=12, name="test", points=10, description="1$ off", begin=None, expiration=None, deleted=0) self.assertEqual(is_today_in_coupon_date_range(coupon), 0)
def test_on_start(self): """ Tests when today's date is equal to the start date. """ begin = date.today() end = date(2099, 6, 30) coupon = Coupon(rid=12, name="test", points=10, description="1$ off", begin=begin, expiration=end, deleted=0) self.assertEqual(is_today_in_coupon_date_range(coupon), 0)
def delete(self): ''' Deletes an existing model ''' b = self.get_entity() authenticate(b) coupons = Coupon.get_by_business(self.get_id(), keys_only=True) if coupons: self.response.status = '409 Conflict' for c in coupons: self.response.write('/api/coupon/{}\n'.format(c.id())) return b.key.delete() self.response.status = '204 No Content'
def test_after_expiry(self): """ Tests when today's date is after the expiry date. """ begin = date(2020, 5, 1) end = date(2020, 6, 30) coupon = Coupon(rid=12, name="test", points=10, description="1$ off", begin=begin, expiration=end, deleted=0) self.assertEqual(is_today_in_coupon_date_range(coupon), 1)
def test_no_such_rid_name(self): """ Test that the coupon's related rid is not exist, the method should return "Not Found", the rid is autoincrement, which cannot be negative. """ res = Restaurant(name="resName", address="Address", uid=404) db.session.add(res) db.session.commit() coupon = Coupon(rid=100, name="coupon_testing", points=10, description="description", level=99, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() rname = chelper.find_res_name_of_coupon_by_cid(coupon.cid) self.assertEqual(rname, "Not Found")
def on_get(self, req, resp, userId, couponId): try: couponResult = Coupon.objects(id=couponId) cartResult = Cart.objects(userId=userId) if len(couponResult) == 0 or len(cartResult) == 0: ResponseUtil.makeResponse(409, resp) return coupon = couponResult[0] cart = cartResult[0] ResponseUtil.makeJson(resp, { 'cart': cart.to_json(), 'coupon': coupon.to_json() }) except Exception as e: ResponseUtil.error(e, resp)
def test_normal_resname_valid_cid(self): """ Test if we can find the correct res name by given the cid of the coupon as we expected. """ res = Restaurant(name="resName", address="Address", uid=404) db.session.add(res) db.session.commit() coupon = Coupon(rid=res.rid, name="coupon_testing", points=10, description="description", level=250, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() rname = chelper.find_res_name_of_coupon_by_cid(coupon.cid) self.assertEqual(rname, "resName")
def create_coupon(): if not session.get('admin'): abort(400) form = Coupon_CreateForm() coupons = Coupon.query.all() if form.validate_on_submit(): number = form.number.data for i in range(number): result = "買100元即減5元(每日每人只可領取一張)" coupon = Coupon(name=result, active_state=True) db.session.add(coupon) flash('增加成功') coupons = Coupon.query.all() return redirect(url_for('admin_coupon.admin_coupon_detail')) return render_template('create_coupon.html', form=form)
def test_no_such_cid_addr(self): """ Test that this cid is not exist, the method should return "Not Found". Expect an error message. """ coupon = Coupon(rid=90, name="coupon_testing", points=10, description="description", level=2, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() raddr = chelper.find_res_addr_of_coupon_by_cid(120) self.assertEqual(raddr, "Not Found")
def test_coupon_no_matching(self): """ Test getting no matching coupon, with a coupon in database. """ coupon = Coupon(rid=12, name="test", points=10, description="1$ off", level=25, begin=BEGIN, expiration=END, deleted=0) db.session.add(coupon) db.session.commit() result = couponhelper.get_coupon_by_cid(coupon.cid + 2) self.assertEqual(result, None)
def post(self): ''' HTTP POST Method Handler Gives user a coupon ''' authenticate(self.get_uid()) user = User.get_by_id(self.get_uid()) coupon = Coupon.get_by_id(self.get_cid()) if not coupon: self.abort(400) if not user: self.abort(400) if coupon.key not in user.held_coupons: user.held_coupons.append(coupon.key) user.put() self.response.status = '200 OK' self.response.write('/api/user/' + str(user.key.id()))
def get(self): ''' HTTP GET Method Handler Returns a JSON list of objects with keys 'name' and 'id' Parameters: - int business: the ID of the business that created the coupon - int user: the ID of the user whose coupons you want to check - int active: 0 if you want non-active coupons ''' params = self.load_http_params({ 'business': (int, False), 'user': (int, False), 'year': (int, False), 'month': (int, False), 'day': (int, False), 'hour': (int, False), 'min': (int, False) }, use_default=True) try: time = datetime.datetime( params['year'], params['month'], params['day'], params['hour'], params['minute'] ) except KeyError: time = None coupon_keys = Coupon.list_coupons( user_id=params['user'], business_id=params['business'], time=time, keys_only=True ) self.status = '200 OK' flag = False for key in coupon_keys: if flag: self.response.write('\n') else: flag = True self.response.write(str(key.id()) + '\n')
def post(self, dkey): if 'use' in self.request.url: self.response.set_status(405) return #create coupon auth = self.request.headers.get("Authorization") if auth is None or len(auth) < 1: auth = self.request.cookies.get("user") user_id = logic.get_current_userid(auth) coupon, status, errcode = logic.coupon_create(dkey, user_id) if status == "OK": try: coupon = Coupon.to_json(coupon, None, None) self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(coupon)) except TypeError, e: self.response.set_status(500) self.response.write(str(e))
def test_normal_resaddr_valid_cid(self): """ Test if we can find the correct res addr by given the cid of the coupon as we expected. Expect output to match correct data. """ res = Restaurant(name="res", address="Address", uid=505) db.session.add(res) db.session.commit() coupon = Coupon(rid=res.rid, name="coupon_testing", points=10, description="description", level=56, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() raddr = chelper.find_res_addr_of_coupon_by_cid(coupon.cid) self.assertEqual(raddr, "Address")
def test_no_such_rid_addr(self): """ Test that the coupon's related rid is not exist, the method should return "Not Found". Expect an error message. """ res = Restaurant(name="resName", address="Address", uid=404) db.session.add(res) db.session.commit() coupon = Coupon(rid=900, name="coupon_testing", points=10, description="description", level=88, expiration=None, begin=None, deleted=0) db.session.add(coupon) db.session.commit() raddr = chelper.find_res_addr_of_coupon_by_cid(coupon.cid) self.assertEqual(raddr, "Not Found")
def get(self): ''' Lists coupons, filtered by optional parameters Parameters: name - Name of the business lat,lon - Location of the business ''' try: lat = float(urllib.unquote(self.request.get('lat'))) lon = float(urllib.unquote(self.request.get('lon'))) except ValueError: query = Business.query() else: query = Business.query_location(lat=lat, lon=lon) name = urllib.unquote(self.request.get('name')) if name: query = query.filter(Business.name == name) coupons = [c for business in query.map(lambda x: Coupon.get_by_business(x.key.id())) for c in business] coupons = sorted(coupons, lambda x, y: cmp(x.end, y.end)) now = datetime.datetime.now() i = 0 expired_index = None for i in range(len(coupons)): if expired_index is None and now < coupons[i].end: expired_index = i if now < coupons[i].start: break expired = coupons[0:expired_index] active = coupons[expired_index:i] inactive = coupons[i:] self.response.status = '200 OK' self.response.write(self.template.render( coupons=active+inactive+expired ))
def add_coupon(): if not logged_in(): return redirect(url_for("admin_login")) couponForm = AddCouponForm(request.form) # THIS NEEDS TYPE CHECKING if request.method == 'POST': company_id = couponForm.company_id.data pts_required = couponForm.pts_required.data summary = couponForm.summary.data max_use = couponForm.max_use.data # attempt to get numbers or throw error try: company_id = int(couponForm.company_id.data) pts_required = int(couponForm.pts_required.data) max_use = int(couponForm.max_use.data) except (ValueError, TypeError): return jsonify({"error": HTML_ERR_JSON}) # new_id = 0 # old_id = Coupon.query.count() # doesn't include 0th item # if old_id: # new_id = old_id + 2 # hence + 2 to account for 0 offset new_id = Coupon.query.count() + 1 newCoupon = Coupon(new_id, company_id, pts_required, summary, max_use) db.session.add(newCoupon) db.session.commit() # redirect to main overview return redirect(url_for("overview")) elif request.method == 'GET': c = Company.query.all() return render_template("add_coupon.html", form=couponForm, companies=c)
def get(self, dkey): auth = self.request.headers.get("Authorization") if auth is None or len(auth) < 1: auth = self.request.cookies.get("user") user_id = logic.get_current_userid(auth) code = self.request.GET.get('code') if 'use' in self.request.url: #use coupon coupon, status, errcode = logic.coupon_use(dkey, user_id, code) else: #get coupon coupon, status, errcode = logic.coupon_get_by_code(dkey, user_id, code) if status == "OK": try: coupon = Coupon.to_json(coupon, None, None) self.response.headers['Content-Type'] = 'application/json' self.response.write(json.dumps(coupon)) except TypeError, e: self.response.set_status(500) self.response.write(str(e))
def on_get(self, req, resp, userId, couponId): try: couponResult = Coupon.objects(id=couponId) cartResult = Cart.objects(userId=userId) if len(couponResult) == 0: ResponseUtil.makeJson(resp, { 'status': False, 'reason': 'Coupon not found' }) return if len(cartResult) == 0: ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'Cart does not exist for userId' }) return coupon = couponResult[0] cart = cartResult[0] cartItems = {} pids = [] for item in cart.items.keys(): if cart.items[item]['quantity'] > 0: cartItems[int(item)] = cart.items[item] pids.append(item) if len(pids) == 0: ResponseUtil.makeJson(resp, { 'status': False, 'reason': 'Cart is Empty' }) return products = Product.objects(productId__in=pids) filteredList = products if coupon.artist: filteredList = list( filter((lambda x: x.artist == coupon.artist), filteredList)) if coupon.product: filteredList = list( filter((lambda x: x.product == coupon.product), filteredList)) if coupon.category: filteredList = list( filter((lambda x: x.category == coupon.category), filteredList)) if len(filteredList) == 0: ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'Supplied Products do not have required category,artist or product' }) return totalQuantity = 0 totalCost = 0.00 for product in filteredList: totalCost += cartItems[product.productId]['quantity'] * float( product.price) totalQuantity += cartItems[product.productId]['quantity'] print(coupon.to_json()) if (coupon.constraint['type'] == 'cartTotal'): if (totalCost <= float(coupon.constraint['value'])): ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'cartValue less than required', 'totalCost': totalCost, 'totalQuantity': totalQuantity }) return elif (coupon.constraint['type'] == 'buy'): if (totalQuantity < int(coupon.constraint['value'])): ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'number of items less than required', 'totalCost': totalCost, 'totalQuantity': totalQuantity }) return elif coupon.discount['type'] == 'get': offItems = totalQuantity - int(coupon.constraint['value']) maxDiscounted = int(coupon.discount['value']) if maxDiscounted > offItems: coupon.discount['value'] = offItems else: coupon.discount['value'] = maxDiscounted newPrice = {} coupon.discount['value'] = int(coupon.discount['value']) if coupon.discount['type'] == 'get': sortedProducts = sorted(filteredList, key=(lambda x: float(x.price))) for item in sortedProducts: if (coupon.discount['value'] == 0): break itemQuantity = int(cartItems[item.productId]['quantity']) if (coupon.discount['value'] >= itemQuantity): coupon.discount['value'] -= itemQuantity print('decreasingQuantity') newPrice[str(int(item.productId))] = 0 else: newPrice[str(int(item.productId))] = ( itemQuantity - coupon.discount['value']) * int( float(item.price)) coupon.discount['value'] = 0 elif coupon.discount['type'] == 'getPercentage': percent = 1 - (float(coupon.discount['value']) / 100) for item in filteredList: if (coupon.discount['value'] == 0): break itemQuantity = int(cartItems[item.productId]['quantity']) itemPrice = float(item.price) itemTotal = itemPrice * itemQuantity itemTotal *= percent newPrice[str(int(item.productId))] = int(itemTotal) ResponseUtil.makeJson(resp, { 'status': True, 'newPrice': newPrice }) except Exception as e: print(e) ResponseUtil.error(e, resp)
def collection_callback(business): return Coupon.get_by_business(business.key.id())
def acquire_coupons(username, couponname): # select for update example auth_info = get_auth_info() if auth_info['kind'] != 0: response = jsonify(errMsg='saler could not acquire a coupon') response.status_code = 204 return response db = DBSession() user_kind = rs.get(username) # user_kind=='2'means it does exist if not user_kind: user = db.query(User).filter(User.username == username).first() if not user: rs.set(username, 2) response = jsonify(errMsg="the username must be valid") response.status_code = 204 DBSession.remove() return response if user.kind == 0: rs.set(username, 0) response = jsonify(errMsg="the username must be a saler") response.status_code = 204 DBSession.remove() return response rs.set(username, 1) elif user_kind == '2': response = jsonify(errMsg="the username must be valid(from redis)") response.status_code = 204 DBSession.remove() return response elif user_kind == '0': response = jsonify(errMsg="the username must be a saler(from redis)") response.status_code = 204 DBSession.remove() return response key = auth_info['username'] + "_" + couponname if not rs.get(key): # get the coupon of a saler coupon=db.query(Coupon).filter(Coupon.username==username)\ .filter(Coupon.coupon_name == couponname).with_for_update().first() if coupon and coupon.left > 0: db.add( Coupon(username=auth_info['username'], coupon_name=coupon.coupon_name, stock=coupon.stock, description=coupon.description)) coupon.left -= 1 try: db.commit() except Exception: # the user already has the coupon rs.set(key, 'has') response = jsonify(errMsg="coupons acquired failed") response.status_code = 204 DBSession.remove() return response # acquire the coupon successfully rs.set(key, 'has') response = jsonify(msg="coupon acquired successfully") response.status_code = 201 DBSession.remove() return response # the key is in the redis, it means the customer has the coupon response = jsonify(errMsg="coupons acquired failed(from redis)") response.status_code = 204 DBSession.remove() return response
def addreadcoupons(username): auth_info = get_auth_info() # get method to get the page for different kinds of users if request.method == 'GET': try: page = int(request.args.get('page')) except Exception: page = 1 if page <= 0: page = 1 #check if username exists db = DBSession() user = db.query(User).filter(User.username == username).first() if not user: response = jsonify(errMsg="username does not exist") response.status_code = 401 DBSession.remove() return response # usernames different if auth_info['username'] != username: # the asked username is a customer if user.kind == 0: response = jsonify( errMsg= "usernames different and the asked username is a customer") response.status_code = 401 DBSession.remove() return response # the asked username is a saler else: # return the left 20 coupons of that saler data, status_code = returnsalercoupons(db, username, page) response = jsonify(data=data) response.status_code = status_code DBSession.remove() return response else: # usernames identical if auth_info['kind'] == 1: # saler # return the left 20 coupons of that saler data, status_code = returnsalercoupons(db, username, page) response = jsonify(data=data) response.status_code = status_code DBSession.remove() return response else: # customer # return the acquired coupons for that customer data, status_code = returncustomercoupons(db, username) response = jsonify(data=data) response.status_code = status_code DBSession.remove() return response # post method to add coupons try: coupon_info = json.loads(request.data.decode('utf8')) except Exception: response = jsonify(errMsg='wrong coupon information') response.status_code = 400 return response coupon_name = coupon_info.get('name') amount = coupon_info.get('amount') description = coupon_info.get('description') stock = coupon_info.get('stock') # check legality of inputs # only salers could create coupons if auth_info['kind'] != 1: response = jsonify(errMsg='Customers can not add a coupon') response.status_code = 400 return response if coupon_name == None or amount == None or stock == None: response = jsonify(errMsg='fields not complete') response.status_code = 400 return response try: amount = int(amount) stock = int(stock) except ValueError: response = jsonify(errMsg='amount or stock must be numbers') response.status_code = 400 return response # add coupon to the database db = DBSession() coupon_info = Coupon(username=auth_info['username'], coupon_name=coupon_name, amount=amount, left=amount, stock=stock, description=description) try: db.add(coupon_info) db.commit() except Exception: response = jsonify(errMsg="coupons already exists") response.status_code = 400 DBSession.remove() return response response = jsonify(msg="coupon added successfully") response.status_code = 201 DBSession.remove() return response
def on_get(self, req, resp, userId, couponId): try: couponResult = Coupon.objects(id=couponId) cartResult = Cart.objects(userId=userId) if len(couponResult) == 0: ResponseUtil.makeJson(resp, { 'status': False, 'reason': 'Coupon not found' }) return if len(cartResult) == 0: ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'Cart does not exist for userId' }) return coupon = couponResult[0] cart = cartResult[0] cartItems = {} pids = [] for item in cart.items.keys(): if cart.items[item]['quantity'] > 0: cartItems[int(item)] = cart.items[item] pids.append(item) if len(pids) == 0: ResponseUtil.makeJson(resp, { 'status': False, 'reason': 'Cart is Empty' }) return products = Product.objects(productId__in=pids) filteredList = products if coupon.artist: filteredList = list( filter((lambda x: x.artist == coupon.artist), filteredList)) if coupon.product: filteredList = list( filter((lambda x: x.product == coupon.product), filteredList)) if coupon.category: filteredList = list( filter((lambda x: x.category == coupon.category), filteredList)) if len(filteredList) == 0: ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'Supplied Products do not have required category,artist or product' }) return totalQuantity = 0 totalCost = 0.00 print(cartItems) for product in filteredList: totalCost += cartItems[product.productId]['quantity'] * float( product.price) totalQuantity += cartItems[product.productId]['quantity'] print(coupon.to_json()) if (coupon.constraint['type'] == 'cartTotal'): if (totalCost <= float(coupon.constraint['value'])): ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'cartValue less than required', 'totalCost': totalCost, 'totalQuantity': totalQuantity }) return elif (coupon.constraint['type'] == 'buy'): if (totalQuantity < int(coupon.constraint['value'])): ResponseUtil.makeJson( resp, { 'status': False, 'reason': 'number of items less than required', 'totalCost': totalCost, 'totalQuantity': totalQuantity }) return ResponseUtil.makeJson( resp, { 'status': True, 'totalCost': totalCost, 'totalQuantity': totalQuantity }) except Exception as e: print(e) ResponseUtil.error(e, resp)
def test_coupon_multi(self): """ Retives coupon list when there are many. """ coupon1 = Coupon(rid=12, name="test1", points=10, description="1$ off", level=1, begin=BEGIN, expiration=END, deleted=0) coupon2 = Coupon(rid=12, name="test2", points=20, description="2$ off", level=2, begin=BEGIN, expiration=END, deleted=1) coupon3 = Coupon(rid=12, name="test3", points=30, description="3$ off", level=3, begin=BEGIN, expiration=END, deleted=0) db.session.add(coupon1) db.session.add(coupon2) db.session.add(coupon3) db.session.commit() coupon_list = couponhelper.get_coupons(12) self.assertEqual(coupon_list, [{ 'begin': BEGIN, 'cid': 1, 'description': '1$ off', 'expiration': END, 'name': 'test1', 'points': 10, 'level': 1, "deleted": 0 }, { 'begin': BEGIN, 'cid': 2, 'description': '2$ off', 'expiration': END, 'name': 'test2', 'points': 20, 'level': 2, "deleted": 1 }, { 'begin': BEGIN, 'cid': 3, 'description': '3$ off', 'expiration': END, 'name': 'test3', 'points': 30, 'level': 3, "deleted": 0 }])
def run(self): # global statistics gs = {} gs['users'] = User.count({'active': True}) # FIXME: remove beta levels gs['achievements'] = Achievement.count() gs['expired_coupons'] = Coupon.count({ 'validations_left': 0, }) gs['coupons'] = Coupon.count() gs['level_bought'] = OrganizationLevel.count() gs['level_finished'] = OrganizationLevel.count({ 'status': { '$in': ['pending validation', 'validated'], }, }) gs['levels'] = Level.count() gs['organization_achievements'] = OrganizationAchievement.count() gs['organization_coupons'] = OrganizationCoupon.count() gs['organizations'] = Organization.count() last_record = GlobalStatistics.last_record() if not last_record or not all(item in last_record.items() for item in gs.items()): GlobalStatistics.post_internal(gs) # level statistics levels = mongo_list_to_dict(Level.all()) for level in levels.values(): amount_bought = OrganizationLevel.count({ 'level': level['_id'], }) # FIXME: filter, only 1 by organization amount_finished = OrganizationLevel.count({ 'level': level['_id'], 'status': { '$in': ['pending validation', 'validated'], }, }) level['amount_bought'] = amount_bought LevelStatistics.update_by_id( level['statistics'], { '$set': { 'amount_bought': amount_bought, 'amount_finished': amount_finished, # FIXME: fivestar average # FIXME: duration average # FIXME: amount hints bought }, }) sessions = Session.all() for session in sessions: organization_levels = OrganizationLevel.find({ 'session': session['_id'], }) organizations = mongo_list_to_dict( Organization.find({ 'session': session['_id'], })) validations = OrganizationLevelValidation.all() for validation in validations: if validation['status'] == 'refused': continue organization = organizations.get(validation['organization']) if not organization: continue level = levels.get(validation['level']) if not level: continue level['validations'] = level.get('validations', 0) defaults = { 'validated_levels': [], 'gold_medals': 0, 'silver_medals': 0, 'bronze_medals': 0, } for key, value in defaults.items(): if key not in organization: organization[key] = value if level['validations'] == 0: organization['gold_medals'] += 1 elif level['validations'] == 1: organization['silver_medals'] += 1 elif level['validations'] == 2: organization['bronze_medals'] += 1 organization['validated_levels'].append(level['_id']) level['validations'] += 1 for organization in organizations.values(): coupons = OrganizationCoupon.count({ 'organization': organization['_id'], }) achievements = OrganizationAchievement.count({ 'organization': organization['_id'], }) validated_levels = list( set(organization.get('validated_levels', []))) score = 0 score += organization.get('gold_medals', 0) * 9 score += organization.get('silver_medals', 0) * 5 score += organization.get('bronze_medals', 0) * 2 score += len(validated_levels) * 10 score += achievements * 2 for validated_level in validated_levels: level = levels[validated_level] percent = float(level['validations']) / float( level['amount_bought']) score += int(round(-math.log(percent) * 2)) OrganizationStatistics.update_by_id( organization['statistics'], { '$set': { 'coupons': coupons, 'score': score, 'achievements': achievements, 'gold_medals': organization.get('gold_medals', 0), 'silver_medals': organization.get('silver_medals', 0), 'bronze_medals': organization.get('bronze_medals', 0), 'finished_levels': len(validated_levels), 'bought_levels': OrganizationLevel.count({ 'organization': organization['_id'], }) }, })