Ejemplo n.º 1
0
    def getSuperAdmin(self):
        query = '''SELECT id, lazada_user_name, lazada_user_id, lazada_api_key
                    FROM t_user
                    WHERE lazada_user_id = '{}' '''.format(UserConfig.SUPER_ADMIN)
        try:
            conn = DatabaseHelper.getConnection()
            cur = conn.cursor()
            cur.execute(query)

            row = cur.fetchone()
            if not row:
                conn.close()
                return ExceptionUtils.error('''Dont have any super admins''')

            user = {
                'id': row[0],
                'username': row[1],  # Using lazada user name instead.
                'lazada_user_name': row[1],
                'lazada_user_id': row[2],
                'lazada_api_key': row[3]
            }

            conn.close()
            return user
        except Exception as ex:
            return ExceptionUtils.error('''Get super admin exception: {}'''.format(str(ex)))
Ejemplo n.º 2
0
 def deleteHistories(self, sku, millisecond):
     try:
         query = '''DELETE FROM sku_history WHERE sku = '{}' and created_at < {} '''.format(StringUtils.toString(sku['sku']), millisecond)
         DatabaseHelper.execute(query)
         return ExceptionUtils.success()
     except Exception as ex:
         return ExceptionUtils.error('''Delete history failed: {}'''.format(str(ex)))
Ejemplo n.º 3
0
 def insertHistory(self, history, sku, user):
     try:
         query = '''INSERT INTO sku_history(sku, enemy_json, user_id, status, created_at) VALUES ('{}', '{}', {}, {}, {}) '''.format(
                 sku['sku'], history['enemy_json'], user['id'], history['status'], history['created_at'])
         DatabaseHelper.execute(query)
         return ExceptionUtils.success()
     except Exception as ex:
         return ExceptionUtils.error('''Insert new history failed: {}'''.format(str(ex)))
Ejemplo n.º 4
0
 def delete(self, sku, user):
     query = '''DELETE from price_by_time where id = '{}' '''.format(
         sku['id'])
     try:
         DatabaseHelper.execute(query)
         return ExceptionUtils.success()
     except Exception as ex:
         return ExceptionUtils.error(
             '''User: {}-{}, delete price by time: {}, exception: {}'''.
             format(user['username'], user['id'], sku['id'], str(ex)))
Ejemplo n.º 5
0
 def updateSpecialPrice(self, sku, user, newSpecialPrice):
     query = '''UPDATE price_by_time
                 set special_price = '{}'
                 WHERE id = '{}'
             '''.format(newSpecialPrice, sku['id'])
     try:
         DatabaseHelper.execute(query)
         return ExceptionUtils.success()
     except Exception as ex:
         return ExceptionUtils.error(
             '''User: {}-{}, update special price of sku: {}, exception: {}'''
             .format(user['username'], user['id'], sku['id'], str(ex)))
Ejemplo n.º 6
0
 def insert(self, sku, user):
     query = '''INSERT INTO price_by_time(sku, name, link, price_by_time, special_price, user_id)
                 VALUES ('{}', '{}', '{}', '{}', '{}', '{}')'''.format(
         StringUtils.toString(sku['sku']),
         StringUtils.toString(sku['name']),
         StringUtils.toString(sku['link']), sku['price_by_time'],
         sku['special_price'], user['id'])
     try:
         DatabaseHelper.execute(query)
         return ExceptionUtils.success()
     except Exception as ex:
         return ExceptionUtils.error(
             '''User: {}-{}, Insert price by time exception: {}'''.format(
                 user['username'], user['id'], str(ex)))
Ejemplo n.º 7
0
    def getAllHistory(self, user):
        try:
            query = '''SELECT * from sku_history WHERE user_id = '{}' ORDER BY created_at DESC '''.format(user['id'])
            conn = DatabaseHelper.getConnection()
            cur = conn.cursor()
            cur.execute(query)

            histories = []
            rows = cur.fetchall()
            if not rows:
                conn.close()
                return histories

            for row in rows:
                histories.append({
                    'id': row[0],
                    'sku': row[1],
                    'enemy_json': row[2],
                    'status': row[4]
                })

            conn.close()
            return histories
        except Exception as ex:
            return ExceptionUtils.error('''Get history failed: {}'''.format(str(ex)))
Ejemplo n.º 8
0
    def getStatistic(self, user, shop):
        parameters = {
            'Action': 'GetStatistics',
            'Format': 'JSON',
            'Timestamp': LazadaApiHelper.getCurrentUTCTime(),
            'UserID': shop['email'],
            'Version': '1.0'
        }

        parameters['Signature'] = LazadaApiHelper.generateSignature(
            parameters, shop['api_key'])
        url = "{}/?Action={}&Format={}&Timestamp={}&UserID={}&Version={}&Signature={}".format(
            LazadaAPI.ENDPOINT, parameters["Action"], parameters["Format"],
            LazadaApiHelper.formatTimestamp(parameters["Timestamp"]),
            parameters["UserID"], parameters["Version"],
            parameters["Signature"])

        try:
            resp = requests.get(url)
            if resp.status_code == 200:
                response = json.loads(resp.text)
                if ('ErrorResponse' in response):
                    errorMessage = ExceptionUtils.getBodyMessage(response)
                    return None, '''User: {}-{}, Get-Statistic: {}'''.format(
                        user['username'], user['id'], errorMessage)

                # Request API Success
                return response['SuccessResponse']['Body'], None

            # Request error
            return None, '''User: {}-{}, Get-Statistic: {}'''.format(
                user['username'], user['id'], resp.status_code)
        except Exception as ex:
            return None, '''User: {}-{}, Get-Statistic: {}'''.format(
                user['username'], user['id'], str(ex))
Ejemplo n.º 9
0
    def getAll(self, user):
        query = '''SELECT * from price_by_time WHERE user_id = '{}'
                '''.format(user['id'])
        try:
            conn = DatabaseHelper.getConnection()
            cur = conn.cursor()
            cur.execute(query)

            skus = []
            rows = cur.fetchall()
            for row in rows:
                skus.append({
                    "id": row[0],
                    "sku": row[1],
                    "name": row[2],
                    "link": row[3],
                    "price_by_time": row[4],
                    "special_price": row[5]
                })

            conn.close()
            return skus
        except Exception as ex:
            return ExceptionUtils.error(
                '''User: {}-{}, get by time skus exception: {}'''.format(
                    user['username'], user['id'], str(ex)))
Ejemplo n.º 10
0
    def setStatusToPackedByMarketplace(self, user, orderItems):
        parameters = {
            'Action': 'SetStatusToPackedByMarketplace',
            'DeliveryType': 'dropship',
            'Format': 'json',
            'OrderItemIds': '''[{}]'''.format(
                orderItems
            ),  # orderItems format should be string like this: 3,425,234
            'Timestamp': LazadaApiHelper.getCurrentUTCTime(),
            'UserID': user['lazada_user_id'],
            'Version': '1.0'
        }

        parameters['Signature'] = LazadaApiHelper.generateSignature(
            parameters, user['lazada_api_key'])
        url = "{}/?Action={}&DeliveryType={}&Format={}&OrderItemIds={}&&Timestamp={}&UserID={}&Version={}&Signature={}".format(
            LazadaAPI.ENDPOINT, parameters["Action"],
            parameters['DeliveryType'], parameters["Format"],
            parameters['OrderItemIds'],
            LazadaApiHelper.formatTimestamp(parameters["Timestamp"]),
            parameters["UserID"], parameters["Version"],
            parameters["Signature"])
        try:
            resp = requests.get(url)
            if resp.status_code == 200:
                response = json.loads(resp.text)
                if 'ErrorResponse' in response:
                    return ExceptionUtils.error(
                        '''User: {}-{}, Set Status to Packed is error: {}'''.
                        format(
                            user['id'], user['username'],
                            response['ErrorResponse']['Head']['ErrorMessage']))

                return ExceptionUtils.success(
                    "Set status to Parked is done")  # Can't return None

            # Request except
            return ExceptionUtils.error(
                '''User: {}-{}, Set Status to Packed is error: {}'''.format(
                    user['id'], user['username'], resp.status_code))
        except Exception as ex:
            return ExceptionUtils.error(
                '''User: {}-{}, Set Status to Packed is error: {}'''.format(
                    user['id'], user['username'], str(ex)))
Ejemplo n.º 11
0
    def getSku(self, sku, user):
        parameters = {
            'Action': 'GetProducts',
            'Format': 'JSON',
            'Timestamp': LazadaApiHelper.getCurrentUTCTime(),
            'UserID': user['lazada_user_id'],
            'Version': '1.0',
            'SkuSellerList': '''["{}"]'''.format(sku['sku'])
        }

        parameters['Signature'] = LazadaApiHelper.generateSignature(
            parameters, user['lazada_api_key'])
        url = "{}/?Action={}&Format={}&Timestamp={}&UserID={}&Version={}&SkuSellerList={}&Signature={}".format(
            LazadaAPI.ENDPOINT, parameters["Action"], parameters["Format"],
            LazadaApiHelper.formatTimestamp(parameters["Timestamp"]),
            parameters["UserID"], parameters["Version"],
            parameters["SkuSellerList"], parameters["Signature"])

        try:
            resp = requests.get(url)
            if resp.status_code == 200:
                response = json.loads(resp.text)
                if 'SuccessResponse' in response:
                    data = response['SuccessResponse']['Body']
                    if data['TotalProducts'] == 1:
                        return data['Products'][0]
                    else:
                        return ExceptionUtils.error(
                            '''Invalide Seller SKU !''')
                else:
                    return ExceptionUtils.returnError(
                        '''Can't get this product with error: ''', response)
            else:
                return ExceptionUtils.error(
                    '''Get product got error's response-code: {}'''.format(
                        resp.status_code))
        except Exception as ex:
            return ExceptionUtils.error(
                '''Get product got exception: {}'''.format(str(ex)))
Ejemplo n.º 12
0
    def updateProductSpecialPrice(self, sku, user, newSpecialPrice):
        parameters = {
            'Action': 'UpdateProduct',
            'Format': 'JSON',
            'Timestamp': LazadaApiHelper.getCurrentUTCTime(),
            'UserID': user['lazada_user_id'],
            'Version': '1.0'
        }

        parameters['Signature'] = LazadaApiHelper.generateSignature(
            parameters, user['lazada_api_key'])
        url = "{}/?Action={}&Format={}&Timestamp={}&UserID={}&Version={}&Signature={}".format(
            LazadaAPI.ENDPOINT, parameters["Action"], parameters["Format"],
            LazadaApiHelper.formatTimestamp(parameters["Timestamp"]),
            parameters["UserID"], parameters["Version"],
            parameters["Signature"])

        # Must use xmlBody to update
        xmlBody = LazadaApiHelper.getUpdateProductSpecialPriceXML(
            sku, newSpecialPrice)

        try:
            resp = requests.post(url, data=xmlBody)
            if resp.status_code != 200:
                return ExceptionUtils.error(
                    '''Request error with response-code: {}'''.format(
                        resp.status_code))

            response = resp.json()
            if ('SuccessResponse' in response):
                return ExceptionUtils.success(
                    "Update procduct special price success")
            else:
                return ExceptionUtils.returnError(
                    "Update product special price error: ", response)
        except Exception as ex:
            return ExceptionUtils.error(
                '''Update product special price got exception: {}'''.format(
                    str(ex)))
Ejemplo n.º 13
0
    def getOrdersByUpdatedAfter(self, user, offset, updatedAfter):
        parameters = {
            'Action': 'GetOrders',
            'Format': 'JSON',
            'Timestamp': LazadaApiHelper.getCurrentUTCTime(),
            'UserID': user['lazada_user_id'],
            'Version': LazadaAPI.VERSION,
            'Limit': LazadaAPI.LIMIT,
            'Offset': offset,
            'UpdatedAfter':
            LazadaApiHelper.formatToLazadaTimestamp(updatedAfter),
            'SortBy': 'updated_at',
            'SortDirection': 'ASC'
        }

        parameters['Signature'] = LazadaApiHelper.generateSignature(
            parameters, user['lazada_api_key'])
        url = "{}/?Action={}&Format={}&Timestamp={}&UserID={}&Version={}&Limit={}&Offset={}&UpdatedAfter={}&SortBy={}&SortDirection={}&Signature={}".format(
            LazadaAPI.ENDPOINT, parameters["Action"], parameters["Format"],
            LazadaApiHelper.formatTimestamp(parameters["Timestamp"]),
            parameters["UserID"], parameters["Version"], parameters["Limit"],
            parameters["Offset"],
            LazadaApiHelper.formatTimestamp(parameters["UpdatedAfter"]),
            parameters["SortBy"], parameters["SortDirection"],
            parameters["Signature"])
        try:
            resp = requests.get(url)
            if resp.status_code == 200:
                response = json.loads(resp.text)
                # Request API error
                if ('ErrorResponse' in response):
                    errorMessage = ExceptionUtils.getBodyMessage(response)
                    return None, '''User: {}-{}, Get-Orders: {}'''.format(
                        user['username'], user['id'], errorMessage)

                # Request API Success
                return response['SuccessResponse']['Body']['Orders'], None

            # Request error
            return None, '''User: {}-{}, Get-Orders: {}'''.format(
                user['username'], user['id'], resp.status_code)
        except Exception as ex:
            return None, '''User: {}-{}, Get-Orders: {}'''.format(
                user['username'], user['id'], str(ex))
Ejemplo n.º 14
0
    def getProductByUpdatedAfter(self, user, offset, updatedAfter):
        parameters = {
            'Action': 'GetProducts',
            'Format': 'JSON',
            'Timestamp': LazadaApiHelper.getCurrentUTCTime(),
            'UserID': user['lazada_user_id'],
            'Version': '1.0',
            'UpdatedAfter':
            LazadaApiHelper.formatToLazadaTimestamp(updatedAfter),
            'Filter': 'all',
            'Limit': LazadaAPI.LIMIT,
            'Offset': offset
        }

        parameters['Signature'] = LazadaApiHelper.generateSignature(
            parameters, user['lazada_api_key'])
        url = "{}/?Action={}&Format={}&Timestamp={}&UserID={}&Version={}&Signature={}&UpdatedAfter={}&Filter={}&Offset={}&Limit={}".format(
            LazadaAPI.ENDPOINT, parameters["Action"], parameters["Format"],
            LazadaApiHelper.formatTimestamp(parameters["Timestamp"]),
            parameters["UserID"], parameters["Version"],
            parameters["Signature"],
            LazadaApiHelper.formatTimestamp(parameters["UpdatedAfter"]),
            parameters["Filter"], parameters["Offset"], parameters["Limit"])
        try:
            resp = requests.get(url)
            if resp.status_code == 200:
                response = json.loads(resp.text)
                if ('ErrorResponse' in response):
                    return None, ExceptionUtils.returnError(
                        '''Get Products is error: ''', response)

                data = response['SuccessResponse']['Body']
                return data['Products'], None

            return None, '''Get Products is error: {}'''.format(
                resp.status_code)
        except Exception as ex:
            return None, '''Get Products is error: {}'''.format(str(ex))