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, [])
Exemple #2
0
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
     }])
Exemple #5
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 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")
Exemple #7
0
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")
Exemple #8
0
    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 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)
Exemple #10
0
    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 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 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 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)
Exemple #14
0
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_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")
Exemple #16
0
 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)
Exemple #18
0
 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")
Exemple #19
0
 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")
Exemple #20
0
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)
Exemple #21
0
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
Exemple #22
0
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 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
     }])