Beispiel #1
0
 def add_credit():
     """
     Add User Credit
     :return:Response
     """
     db = DAOUtils.get_db()
     input_json = request.get_json()
     user = DAOUtils.get_user_dao().get_user(db,
                                             "USER_ID = '{USER_ID}'",
                                             USER_ID=input_json['user_id'])
     if user:
         try:
             user.CREDIT += input_json['amount']
             LogUtils.insert_user_log(db,
                                      user_id=input_json['user_id'],
                                      action='會員存款',
                                      remark=str(json.dumps(input_json)))
             DAOUtils.commit(db)
             result = dict()
             result['user_id'] = user.USER_ID
             result['name'] = user.NAME
             return Flask(__name__).make_response((jsonify(result), 200))
         except:
             DAOUtils.rollback(db)
             error_result = dict()
             error_result['error'] = str(sys.exc_info())
             return Flask(__name__).make_response(
                 (jsonify(error_result), 406))
         finally:
             DAOUtils.close(db)
     else:
         DAOUtils.close(db)
         return Flask(__name__).make_response(('', 404))
Beispiel #2
0
    def test_login(self):
        db = DAOUtils.get_db()

        response = self.app.post('/login',
                                 data=json.dumps(dict(account='',
                                                      password='')),
                                 headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404)

        account = 'leo.li'
        password = '******'
        body = dict(account=account, password=password)
        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="ACCOUNT = '{ACCOUNT}' AND PASSWORD = '******'",
            ACCOUNT=account,
            PASSWORD=md5(password.encode('utf-8')).hexdigest())
        response = self.app.post('/login',
                                 data=json.dumps(body),
                                 headers={"Content-Type": "application/json"})
        if user:
            response_json = response.get_json()
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response_json['name'], user.NAME,
                             'Login Response User Name Error!')
            self.assertEqual(response_json['user_id'], user.USER_ID,
                             'Login Response User ID Error!')
        else:
            self.assertEqual(response.status_code, 404)
    def test_get_user(self):
        db = DAOUtils.get_db()

        response = self.app.get('/user/',
                                headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404,
                         'User Account Empty Response Error')

        account = 'leo.li'
        user = DAOUtils.get_user_dao().get_user(
            db, condition="ACCOUNT = '{ACCOUNT}'", ACCOUNT=account)

        response = self.app.get('/user/' + account,
                                headers={"Content-Type": "application/json"})

        if user:
            self.assertEqual(response.status_code, 200,
                             'User Get Response Error')
            assert_valid_schema(response.get_json(), 'test_get_user.json')
        else:
            self.assertEqual(response.status_code, 404,
                             'User Account Not Found Response Error')
            self.assertIn('total', response.get_json(),
                          'Cart Response not found total key')
            self.assertIn(
                'item_list',
                response.get_json('Cart Response not found item_list key'))
    def test_add_user(self):
        db = DAOUtils.get_db()

        response = self.app.post('/users', data=json.dumps(dict(account='', password='', name='', credit=0)),
                                 headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 406)

        account = 'leo.li'
        password = '******'
        name = 'Leo.Li'
        credit = 20000
        body = dict(
            account=account,
            password=password,
            name=name,
            credit=credit
        )
        user = DAOUtils.get_user_dao().get_user(db, condition="ACCOUNT = '{ACCOUNT}'",
                                                ACCOUNT=account)

        response = self.app.post('/users', data=json.dumps(body), headers={"Content-Type": "application/json"})
        if user:
            self.assertEqual(response.status_code, 406, 'User Existed Response Error')
        else:
            self.assertEqual(response.status_code, 201, 'User Created Response Error')

        account = name = str(uuid.uuid4())[0:20]

        response = self.app.post('/users', data=json.dumps(dict(account=account, password=password,
                                                                name=name, credit=credit)),
                                 headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 201, 'User Created Response Error')
Beispiel #5
0
    def test_get_user_action_log(self):
        db = DAOUtils.get_db()

        response = self.app.get('/user/action_log/',
                                headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404,
                         'User ID Empty Response Error')

        account = 'leo.li'
        password = '******'
        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="ACCOUNT = '{ACCOUNT}' AND PASSWORD = '******'",
            ACCOUNT=account,
            PASSWORD=md5(password.encode('utf-8')).hexdigest())

        response = self.app.get('/user/action_log/' + user.USER_ID,
                                headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 200, 'User Get Response Error')
        if user.USER_LOGS:
            assert_valid_schema(response.get_json(),
                                'test_get_user_action_log.json')
        else:
            self.assertIn('account', response.get_json(),
                          'User Action Log Response not found account key')
            self.assertIn('name', response.get_json(),
                          'User Action Log Response not found name key')
            self.assertIn(
                'action_list', response.get_json(),
                'User Action Log Response not found action_list key')
    def test_add_order(self):
        db = DAOUtils.get_db()

        response = self.app.post('/order',
                                 data=json.dumps(dict(user_id='')),
                                 headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404)

        account = 'leo.li'
        password = '******'
        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="ACCOUNT = '{ACCOUNT}' AND PASSWORD = '******'",
            ACCOUNT=account,
            PASSWORD=md5(password.encode('utf-8')).hexdigest())

        body = dict(user_id=user.USER_ID)
        response = self.app.post('/order',
                                 data=json.dumps(body),
                                 headers={"Content-Type": "application/json"})
        if user:
            self.assertEqual(response.status_code, 201,
                             'Create Order Response Error')
        else:
            self.assertEqual(response.status_code, 404,
                             'User ID Not Found Response Error')
Beispiel #7
0
    def test_add_user_credit(self):
        db = DAOUtils.get_db()

        response = self.app.post('/user/credit',
                                 data=json.dumps(dict(user_id='', amount=0)),
                                 headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404)

        account = 'leo.li'
        password = '******'
        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="ACCOUNT = '{ACCOUNT}' AND PASSWORD = '******'",
            ACCOUNT=account,
            PASSWORD=md5(password.encode('utf-8')).hexdigest())

        if user:
            user_id = user.USER_ID
            amount = 296
            response = self.app.post(
                '/user/credit',
                data=json.dumps(dict(user_id=user_id, amount=amount)),
                headers={"Content-Type": "application/json"})
            response_json = response.get_json()
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response_json['name'], user.NAME,
                             'Add User Credit Response User Name Error!')
            self.assertEqual(response_json['user_id'], user.USER_ID,
                             'Add User Credit Response User ID Error!')
        else:
            self.assertEqual(response.status_code, 406)
    def test_get_carts(self):
        db = DAOUtils.get_db()

        response = self.app.get('/carts', data=json.dumps(dict(user_id='')),
                                 headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404, 'User ID Empty Response Error')

        account = 'leo.li'
        password = '******'
        user = DAOUtils.get_user_dao().get_user(db, condition="ACCOUNT = '{ACCOUNT}' AND PASSWORD = '******'",
                                                ACCOUNT=account,
                                                PASSWORD=md5(password.encode('utf-8')).hexdigest())

        user_id = user.USER_ID

        cart = DAOUtils.get_cart_dao().get_carts(db, condition="USER_ID = '{USER_ID}'", USER_ID=user_id)

        response = self.app.get('/carts', data=json.dumps(dict(
            user_id=user_id
        )), headers={"Content-Type": "application/json"})

        self.assertEqual(response.status_code, 200, 'Cart Get Response Error')
        if cart and cart[0]:
            assert_valid_schema(response.get_json(), 'test_get_carts.json')
        else:
            self.assertIn('total', response.get_json(), 'Cart Response not found total key')
            self.assertIn('item_list', response.get_json('Cart Response not found item_list key'))
Beispiel #9
0
 def insert_user_log(db=None, user_id=None, action=None, remark=None):
     """
     Add User Action Log
     :param db: Session
     :param user_id: User ID
     :param action: 加入商品至購物車、移除商品至購物車、會員存款、購物車結帳
     :param remark:
     """
     user_log = UserLog(user_id=user_id, action=action, remark=remark)
     try:
         DAOUtils.get_user_log_dao().insert_user_log(db, user_log)
     except:
         raise
Beispiel #10
0
    def test_add_cart(self):
        db = DAOUtils.get_db()

        response = self.app.delete(
            '/cart',
            data=json.dumps(dict(user_id='', item_id=0)),
            headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404,
                         'User ID Empty Response Error')

        account = 'leo.li'
        password = '******'
        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="ACCOUNT = '{ACCOUNT}' AND PASSWORD = '******'",
            ACCOUNT=account,
            PASSWORD=md5(password.encode('utf-8')).hexdigest())

        user_id = user.USER_ID
        item_id = 0

        response = self.app.delete(
            '/cart',
            data=json.dumps(dict(user_id=user_id, item_id=item_id)),
            headers={"Content-Type": "application/json"})
        self.assertEqual(response.status_code, 404,
                         'Cart Item Not Existed Response Error')

        item_id = 1
        item = DAOUtils.get_product_dao().get_product(
            db, condition="ITEM_ID = '{ITEM_ID}'", ITEM_ID=item_id)
        cart = DAOUtils.get_cart_dao().get_carts(
            db,
            condition="USER_ID = '{USER_ID}' AND ITEM_ID = '{ITEM_ID}'",
            USER_ID=user_id,
            ITEM_ID=item_id)

        response = self.app.delete(
            '/cart',
            data=json.dumps(dict(user_id=user_id, item_id=item_id)),
            headers={"Content-Type": "application/json"})
        if item:
            if cart and cart[0]:
                self.assertEqual(response.status_code, 200,
                                 'Cart Delete Response Error')
            else:
                self.assertEqual(response.status_code, 404,
                                 'Cart Item  Response Error')
        else:
            self.assertEqual(response.status_code, 404,
                             'Item Not Found Response Error')
Beispiel #11
0
    def get_user_log(user_id):
        """
        Get User Action Log
        :param user_id:the user_id of user
        :return:Response
        """
        db = DAOUtils.get_db()
        user = DAOUtils.get_user_dao().get_user(db,
                                                "USER_ID = '{USER_ID}'",
                                                USER_ID=user_id)
        if user:
            result = dict()
            result['account'] = user.ACCOUNT
            result['name'] = user.NAME
            result['action_list'] = list()

            for user_log in user.USER_LOGS:
                action_item = dict()
                action_item['action'] = user_log.ACTION
                action_item['created_time'] = int(user_log.CREATED_TIME)
                action_item['remarks'] = user_log.REMARK
                result['action_list'].append(action_item)
            DAOUtils.close(db)
            return Flask(__name__).make_response((jsonify(result), 200))
        else:
            DAOUtils.close(db)
            return Flask(__name__).make_response(('', 404))
 def add_user():
     """
     Add New User
     :return:Response
     """
     db = DAOUtils.get_db()
     input_json = request.get_json()
     user = User(account=input_json['account'],
                 pwd=input_json['password'],
                 name=input_json['name'],
                 credit=input_json['credit'])
     try:
         DAOUtils.get_user_dao().insert_user(db, user)
         DAOUtils.commit(db)
         return Flask(__name__).make_response(('', 201))
     except:
         DAOUtils.rollback(db)
         error_result = dict()
         error_result['error'] = str(sys.exc_info())
         return Flask(__name__).make_response((jsonify(error_result), 406))
     finally:
         DAOUtils.close(db)
Beispiel #13
0
    def login():
        """
        User Login
        :return:Response
        """
        db = DAOUtils.get_db()
        input_json = request.get_json()
        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="ACCOUNT = '{ACCOUNT}' AND PASSWORD = '******'",
            ACCOUNT=input_json['account'],
            PASSWORD=md5(input_json['password'].encode('utf-8')).hexdigest())

        if user:
            result = dict()
            result['user_id'] = user.USER_ID
            result['name'] = user.NAME
            user.LAST_LOGIN_TIME = int(round(time.time() * 1000))
            DAOUtils.commit(db)
            DAOUtils.close(db)
            return Flask(__name__).make_response((jsonify(result), 200))
        else:
            DAOUtils.close(db)
            return Flask(__name__).make_response(('', 404))
Beispiel #14
0
    def __get_carts():
        """
        Get Cart Content By User_ID
        :return:Response
        """
        db = DAOUtils.get_db()
        input_json = request.get_json()

        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="USER_ID = '{USER_ID}'",
            USER_ID=input_json['user_id'])
        if user:
            carts = DAOUtils.get_cart_dao().get_carts(
                db, "USER_ID = '{USER_ID}'", USER_ID=input_json['user_id'])
            result = dict()
            item_list = list()
            for cart in carts:
                item_dict = dict()
                item_dict['item_id'] = int(cart.PRODUCT.ITEM_ID)
                item_dict['item_name'] = cart.PRODUCT.ITEM_NM
                item_dict['item_price'] = int(cart.PRODUCT.ITEM_PRICE)
                item_dict['amount'] = int(cart.AMOUNT)
                item_dict['create_time'] = int(cart.PRODUCT.CREATED_TIME)
                item_dict['subtotal'] = int(cart.PRODUCT.ITEM_PRICE *
                                            cart.AMOUNT)
                item_list.append(item_dict)

            DAOUtils.close(db)
            result['total'] = len(carts)
            result['item_list'] = item_list

            return Flask(__name__).make_response((jsonify(result), 200))
        else:
            DAOUtils.close(db)
            return Flask(__name__).make_response(('', 404))
Beispiel #15
0
 def get_user(account):
     """
     Get User Info
     :param account:the account of user
     :return:Response
     """
     db = DAOUtils.get_db()
     user = DAOUtils.get_user_dao().get_user(db,
                                             "ACCOUNT = '{ACCOUNT}'",
                                             ACCOUNT=account)
     if user:
         result = dict()
         result['account'] = user.ACCOUNT
         result['name'] = user.NAME
         result['credit'] = int(user.CREDIT)
         result['created_time'] = int(user.CREATED_TIME)
         result['last_login_time'] = int(user.LAST_LOGIN_TIME)
         DAOUtils.close(db)
         return Flask(__name__).make_response((jsonify(result), 200))
     else:
         DAOUtils.close(db)
         return Flask(__name__).make_response(('', 404))
Beispiel #16
0
 def __add_cart():
     """
     Add Item to Cart
     :return: Response
     """
     db = DAOUtils.get_db()
     input_json = request.get_json()
     user = DAOUtils.get_user_dao().get_user(
         db,
         condition="USER_ID = '{USER_ID}'",
         USER_ID=input_json['user_id'])
     product = DAOUtils.get_product_dao().get_product(
         db, "ITEM_ID = '{ITEM_ID}'", ITEM_ID=input_json['item_id'])
     if user and product:
         if input_json['amount'] > product.AMOUNT:
             DAOUtils.close(db)
             error_result = dict()
             error_result['error'] = '商品庫存不足'
             return Flask(__name__).make_response(
                 (jsonify(error_result), 403))
         else:
             product.AMOUNT -= input_json['amount']
             cart = Cart(user_id=input_json['user_id'],
                         item_id=input_json['item_id'],
                         amount=input_json['amount'])
             try:
                 DAOUtils.get_cart_dao().insert_cart(db, cart)
                 LogUtils.insert_user_log(db,
                                          user_id=input_json['user_id'],
                                          action='加入商品至購物車',
                                          remark=str(
                                              json.dumps(input_json)))
                 DAOUtils.commit(db)
                 return Flask(__name__).make_response(('', 201))
             except:
                 DAOUtils.rollback(db)
                 error_result = dict()
                 error_result['error'] = str(sys.exc_info())
                 return Flask(__name__).make_response(
                     (jsonify(error_result), 406))
             finally:
                 DAOUtils.close(db)
     else:
         DAOUtils.close(db)
         return Flask(__name__).make_response(('', 404))
    def cart_to_order():
        """
        Generate Order From Cart, and Delete Cart
        :return:Response
        """
        db = DAOUtils.get_db()
        input_json = request.get_json()

        carts = DAOUtils.get_cart_dao().get_carts(
            db, "USER_ID = '{USER_ID}'", USER_ID=input_json['user_id'])

        if carts:
            try:
                ord_no = DAOUtils.get_order_dao().get_max_order_no(db)
                order_header = OrderHeader(ord_no=ord_no,
                                           user_id=input_json['user_id'],
                                           sub_total=0)
                DAOUtils.get_order_dao().insert_order_header(db, order_header)
                sub_total = 0

                for cart in carts:
                    sub_total += cart.AMOUNT * cart.PRODUCT.ITEM_PRICE
                    order_item = OrderItem(ord_no=ord_no,
                                           item_id=cart.ITEM_ID,
                                           amount=cart.AMOUNT)
                    DAOUtils.get_order_dao().insert_order_item(db, order_item)
                    DAOUtils.get_cart_dao().delete_cart(db, cart)

                user = DAOUtils.get_user_dao().get_user(
                    db, "USER_ID = '{USER_ID}'", USER_ID=input_json['user_id'])
                # 額度不足以結帳
                if sub_total > user.CREDIT:
                    error_result = dict()
                    error_result['error'] = '額度不足以結帳'
                    return Flask(__name__).make_response(
                        (jsonify(error_result), 403))
                else:
                    order_header.SUB_TOTAL = sub_total
                    user.CREDIT -= sub_total
                    LogUtils.insert_user_log(db,
                                             user_id=input_json['user_id'],
                                             action='購物車結帳',
                                             remark=ord_no)
                    DAOUtils.commit(db)
                    return Flask(__name__).make_response(('', 201))
            except:
                DAOUtils.rollback(db)
                error_result = dict()
                error_result['error'] = str(sys.exc_info())
                return Flask(__name__).make_response(
                    (jsonify(error_result), 406))
            finally:
                DAOUtils.close(db)
        else:
            DAOUtils.close(db)
            return Flask(__name__).make_response(('', 404))
Beispiel #18
0
    def __delete_cart():
        """
        Remove Item from Cart
        :return: Response
        """
        db = DAOUtils.get_db()
        input_json = request.get_json()
        user = DAOUtils.get_user_dao().get_user(
            db,
            condition="USER_ID = '{USER_ID}'",
            USER_ID=input_json['user_id'])
        product = DAOUtils.get_product_dao().get_product(
            db, "ITEM_ID = '{ITEM_ID}'", ITEM_ID=input_json['item_id'])

        if user and product:
            try:
                carts = DAOUtils.get_cart_dao().get_carts(
                    db,
                    condition="USER_ID = '{USER_ID}' AND ITEM_ID = '{ITEM_ID}'",
                    USER_ID=input_json['user_id'],
                    ITEM_ID=input_json['item_id'])
                if carts:
                    for cart in carts:
                        DAOUtils.get_cart_dao().delete_cart(db, cart)
                        product.AMOUNT += cart.AMOUNT
                    LogUtils.insert_user_log(db,
                                             user_id=input_json['user_id'],
                                             action='移除商品至購物車',
                                             remark=str(
                                                 json.dumps(input_json)))
                    DAOUtils.commit(db)
                    return Flask(__name__).make_response(('', 200))
                else:
                    return Flask(__name__).make_response(('', 404))
            except:
                DAOUtils.rollback(db)
                error_result = dict()
                error_result['error'] = str(sys.exc_info())
                return Flask(__name__).make_response(
                    (jsonify(error_result), 406))
            finally:
                DAOUtils.close(db)
        else:
            DAOUtils.close(db)
            return Flask(__name__).make_response(('', 404))