Exemplo n.º 1
0
def judge_promoted(productID):
    """
    获取商品是否加钻(促销)
    :param productID: 在线listing的ID
    :return: 加钻返回True,不加钻返回False
    """
    classlisting_obj = classlisting(db_conn=connection, redis_conn=redis_conn)
    return classlisting_obj.get_is_promoted_listingid(productID)
Exemplo n.º 2
0
def all_shipping_list(paramlsit):
    classshopsku_obj = classshopsku(db_conn=connection,
                                    redis_conn=redis_coon,
                                    shopname=paramlsit[0])
    classlisting_obj = classlisting(db_conn=connection, redis_conn=redis_coon)
    shopskulist = classlisting_obj.getShopSKUList(paramlsit[1])
    shippinglist = []
    for shopsku in shopskulist:
        shipping = classshopsku_obj.getShipping(shopsku)
        shippinglist.append(float(shipping))
    return shippinglist
def get_data_from_haiying_task(pagnum):
    redis_conn = get_redis_connection(alias='product')
    classlisting_obj = classlisting(connection,redis_conn)
    hy_data_in_db_obj = haiying_data_in_db()
    hy = Haiying()
    try:
        cursor = connection.cursor()
        rt = None
        rt = hy.data(pagnum)
        if rt is None:
            cursor.close()
            return False;# 容错机制:海鹰返回错误时,本页数据忽略
        for obj in rt:
            if obj:
                if classlisting_obj.getvaluefromredis(obj['pid']) is not None:
                    continue
                else:
                    hy_data_in_db_obj.t_config_wishapi_product_analyse_info(obj, cursor)
                    classlisting_obj.setvaluefromredis(obj['pid'],HYCONFIG['hyflag'])
        print ('haiying data pagnum:%s success' % (pagnum))
        cursor.close()
    except Exception, ex:
        print '-------------%s:%s' % (Exception, ex)
        cursor.close()
Exemplo n.º 4
0
from brick.pydata.py_redis.py_SynRedis_tables import py_SynRedis_tables
from brick.classredis.classlisting import classlisting
from brick.classredis.classshopsku import classshopsku
from brick.classredis.classmainsku import classmainsku
# from mymall_app.table.t_mymall_online_info import t_mymall_online_info
from mymall_app.table.t_mymall_online_info_detail import t_mymall_online_info_detail
from mymall_app.views import syndata_by_mymall_api
# from mymall_app.table.t_mymall_cutprice_log import t_mymall_cutprice_log
from skuapp.table.t_store_configuration_file import t_store_configuration_file
from brick.classredis.classsku import classsku
from brick.pricelist.calculate_price import calculate_price

redis_conn = get_redis_connection(alias='product')
py_SynRedis_tables_obj = py_SynRedis_tables()
classsku_obj = classsku()
listingobjs = classlisting(connection, redis_conn)
classshopskuobjs = classshopsku(connection, redis_conn)
classmainsku_obj = classmainsku(connection, redis_conn)


class t_online_info_amazon_listing_Admin(object):
    amazon_listing_plugin = True
    # search_box_flag = True
    # amazon_listing_secondplugin = True

    # site_left_menu_flag = True
    search_box_flag = True
    amazon_site_left_menu_tree_flag = True

    def show_SKU_list(self, obj):
        if obj.is_fba == 0:
Exemplo n.º 5
0
def Wish_Data_Syn(list, synname=''):
    sresult = {'Code': 0, 'messages': ''}
    try:
        shopname = list[0]
        productid = list[1]
        parentsku = list[2]

        upstatus = 'over'  # 日志 状态 更新
        uptext = None

        t_store_configuration_file_obj = t_store_configuration_file(connection)
        t_wish_store_oplogs_obj = t_wish_store_oplogs(connection)
        t_online_info_wish_obj = t_online_info_wish(connection)

        store_status = t_store_configuration_file_obj.getshopStatusbyshopcode(
            shopname)  # 获取店铺状态
        assert store_status['errorcode'] == 0, store_status['errortext']

        if store_status['status'] == '0':  # 店铺状态正常的
            snstatus = '0'  # listing 店铺状态标记
            cwishapi_obj = cwishapi()
            classlisting_obj = classlisting(db_conn=connection,
                                            redis_conn=redis_coon)
            t_online_info_obj = t_online_info(shopname, connection, redis_coon)

            params = CreateParam(shopname, productid, parentsku)

            result = cwishapi_obj.update_wish_goods_data(param=params,
                                                         timeout=30)
            _content = eval(result._content)

            if result.status_code == 200 and _content['code'] == 0:  # api 调用成功
                t_online_info_obj.insertWishV2([_content.get('data', [])
                                                ])  # 更新到t_online_info

                toResult = ToCalculateADS(productid, shopname, connection)
                assert toResult in [
                    '0', '1'
                ], toResult['errortext']  # 获取该product的在线不在线的状态

                sresult['messages'] = u'%s:同步成功' % (productid, )
            else:  # 调用失败
                if _content.get('code') in [1000, 1028, 1006, 1031]:  #
                    toResult = ToCalculateADS(productid, shopname, connection)
                    assert toResult in [
                        '0', '1'
                    ], toResult['errortext']  # 获取该product的在线不在线的状态
                else:
                    toResult = '-1'

                upstatus = 'error'
                uptext = business_Terms(_content)

                # 更新下 redis中shopskulist
                classlisting_db = classlisting(db_conn=connection)
                all_shopsku = classlisting_db.getShopSKUList(productid)
                classlisting_obj.setShopSKUList(productid,
                                                '|'.join(all_shopsku))
                sresult['messages'] = u'%s:%s' % (productid,
                                                  business_Terms(_content))

            refreshwishlisting.run({
                'ShopName': shopname,
                'dbcnxn': connection,
                'ProductID': productid
            })  # Wish数据更新操作

            adResult = t_online_info_wish_obj.UpdateWishStatusAD(
                productid, toResult)  # listing
            assert adResult['errorcode'] == 1, adResult['errortext']
        else:
            upstatus = 'error'
            snstatus = '-1'  # listing 店铺状态标记
            uptext = u'店铺状态被标记为异常'
            sresult['messages'] = u'%s:%s' % (productid, uptext)

        SNResult = t_online_info_wish_obj.UpdateWishSNameByShopName(
            shopname, snstatus)  # listing
        assert SNResult['errorcode'] == 1, SNResult['errortext']

        uResult = t_wish_store_oplogs_obj.updateStatusP(
            synname, productid, upstatus, uptext)  # 更新日志表状态
        assert uResult['errorcode'] == 0, uResult['errortext']

        sresult['Code'] = 1
    except Exception, e:
        sresult['Code'] = -1
        sresult['messages'] = '%s:%s;%s' % (Exception, e,
                                            traceback.format_exc())
Exemplo n.º 6
0
def download_excel_by_porductid(list, opname='', warehouse='STANDARD'):
    myresult = {}
    try:
        classlisting_obj = classlisting(connection, redis_coon)

        t_wish_store_oplogs_obj = t_wish_store_oplogs(connection)

        username = opname.split('-')[-1]
        path = MEDIA_ROOT + 'download_xls/' + username
        mkdir_p(MEDIA_ROOT + 'download_xls')
        os.popen('chmod 777 %s' % (MEDIA_ROOT + 'download_xls'))

        mkdir_p(path)
        os.popen('chmod 777 %s' % (path, ))

        datalist = []
        datalist.append(
            ['shopname', 'productid', 'sku', 'shopsku', 'Inventory'])

        num = len(list)
        for i, elist in enumerate(list):
            shopname = elist[0]
            productid = elist[1]
            parentsku = elist[2]

            classshopsku_obj = classshopsku(connection,
                                            redis_coon,
                                            shopname=shopname)

            shopskulist = classlisting_obj.getJoomShopSKUList(productid)
            for shopsku in shopskulist:
                sku = classshopsku_obj.getSKU(shopsku)

                if warehouse == 'STANDARD':
                    inventory = classshopsku_obj.getQuantity(shopsku)
                else:
                    q = getattr(classshopsku_obj,
                                'getWish%sQuantity' % warehouse)
                    inventory = q(shopsku)
                datalist.append([shopname, productid, sku, shopsku, inventory])

            if i < num - 1:
                uResult = t_wish_store_oplogs_obj.updateStatusP(
                    opname, opname, 'runing', '')
                assert uResult['errorcode'] == 0, uResult['errortext']

        filename = username + '_' + syntime.now().strftime(
            '%Y%m%d%H%M%S') + '.xls'

        eResult = generate_excel(datalist, path + '/' + filename)
        assert eResult['code'] == 0, eResult['error']

        os.popen(r'chmod 777 %s' % (path + '/' + filename))

        upload_to_oss_obj = upload_to_oss(BUCKETNAME_XLS)
        upResult = upload_to_oss_obj.upload_to_oss({
            'path':
            username,
            'name':
            filename,
            'byte':
            open(path + '/' + filename),
            'del':
            0
        })
        assert upResult['errorcode'] == 0, upResult['errortext']

        filepath = upResult['result']

        uResult = t_wish_store_oplogs_obj.updateStatusP(
            opname, opname, 'over', filepath)
        assert uResult['errorcode'] == 0, uResult['errortext']

        myresult['Code'] = 1
        myresult['messages'] = u'文件生成成功! \n 下载链接:%s' % (filepath, )
    except Exception, e:
        myresult['Code'] = -1
        myresult['messages'] = '%s:%s:%s' % (opname, Exception, e)
Exemplo n.º 7
0
def OnTheShelf_OR_LowerFrame(list, flag, synname):
    sresult = {'Code': 0, 'messages': ''}
    try:
        shopname = list[0]
        productid = list[1]
        parentsku = list[2]

        upstatus = 'over'  # 日志
        uptext = None

        t_store_configuration_file_obj = t_store_configuration_file(connection)
        t_wish_store_oplogs_obj = t_wish_store_oplogs(connection)
        t_online_info_wish_obj = t_online_info_wish(connection)

        store_status = t_store_configuration_file_obj.getshopStatusbyshopcode(
            shopname)  # 获取店铺状态
        assert store_status['errorcode'] == 0, store_status['errortext']

        if store_status['status'] == '0':  # 店铺状态正常的
            snstatus = '0'  # listing 店铺状态标记

            classlisting_obj = classlisting(db_conn=connection,
                                            redis_conn=redis_coon)
            cwishapi_obj = cwishapi()
            classshopsku_obj = classshopsku(redis_conn=redis_coon,
                                            shopname=shopname)

            t_online_info_obj = t_online_info(shopname, connection, redis_coon)

            params = CreateParam(shopname, productid, parentsku)

            if flag == 'enable':
                Status = 'Enabled'
                result = cwishapi_obj.enable_by_wish_api(params, timeout=30)
            else:
                Status = 'Disabled'
                result = cwishapi_obj.disable_by_wish_api(params, timeout=30)

            _content = eval(result._content)

            if result.status_code == 200 and _content['code'] == 0:
                aResult = t_online_info_wish_obj.UpdateWishStatus(
                    productid, Status)
                assert aResult['errorcode'] == 1, aResult['errortext']

                iResult = t_online_info_obj.update_status_by_productid(
                    Status, productid)
                assert iResult[
                    'errorcode'] == 0, "SynSuccess:%s" % iResult['errortext']

                shopskulist = classlisting_obj.getShopSKUList(productid)
                if shopskulist is None:
                    shopskulist = []
                for shopsku in shopskulist:
                    classshopsku_obj.setStatus(shopsku, Status)

                toResult = ToCalculateADS(productid, shopname, connection)
                assert toResult in [
                    '0', '1'
                ], toResult['errortext']  # 获取该product的在线不在线的状态

                if flag == 'enable':
                    sresult['messages'] = u'%s:上架成功' % (productid, )
                else:
                    sresult['messages'] = u'%s:下架成功' % (productid, )
            else:
                if _content.get('code') in [1000, 1028, 1006,
                                            1031]:  # 平台禁止修改加钻产品标题
                    toResult = ToCalculateADS(productid, shopname, connection)
                    assert toResult in [
                        '0', '1'
                    ], toResult['errortext']  # 获取该product的在线不在线的状态

                else:
                    toResult = '-1'  # 单链接操作状态

                upstatus = 'error'
                uptext = business_Terms(_content)
                sresult['messages'] = u'%s:%s' % (productid,
                                                  business_Terms(_content))

            refreshwishlisting.run({
                'ShopName': shopname,
                'dbcnxn': connection,
                'ProductID': productid
            })  # Wish数据更新操作

            adResult = t_online_info_wish_obj.UpdateWishStatusAD(
                productid, toResult)
            assert adResult['errorcode'] == 1, adResult['errortext']
        else:
            upstatus = 'error'
            snstatus = '-1'  # listing 店铺状态标记
            uptext = u'店铺状态被标记为异常'
            sresult['messages'] = u'%s:%s' % (productid, uptext)

        uResult = t_wish_store_oplogs_obj.updateStatusP(
            synname, productid, upstatus, uptext)
        assert uResult['errorcode'] == 0, uResult['errortext']

        SNResult = t_online_info_wish_obj.UpdateWishSNameByShopName(
            shopname, snstatus)  # listing
        assert SNResult['errorcode'] == 1, SNResult['errortext']

        sresult['Code'] = 1
    except Exception, e:
        sresult['Code'] = -1
        sresult['messages'] = '%s:%s' % (Exception, e)
Exemplo n.º 8
0
    def insertWishV2(self, data):
        refreshdict = {}
        refreshdict['ShopName'] = ''
        prolist = []
        #cnxn = MySQLdb.connect(DATABASES['HOST'],DATABASES['USER'],DATABASES['PASSWORD'],DATABASES['NAME'] )
        cursor = self.cnxn.cursor()
        #ShopIP = socket.gethostbyname(socket.gethostname())
        #sql_delete = 'delete from t_online_info where ShopName =\'%s\' '%self.ShopName.strip()
        #cursor.execute(sql_delete)

        classlisting_obj = classlisting.classlisting(self.cnxn,
                                                     self.redis_conn)

        classshopsku_obj = classshopsku.classshopsku(self.cnxn,
                                                     self.redis_conn,
                                                     self.ShopName)

        # classshopname_obj = classshopname.classshopname(db_conn = self.cnxn)
        t_store_configuration_file_obj = t_store_configuration_file(self.cnxn)

        classsku_obj = classsku.classsku(self.cnxn, self.redis_conn)
        t_event_class_obj = t_event_class()

        cwishapi_obj = cwishapi()
        insert_product = []
        delete_product = []
        update_product = []
        # logger = logging.getLogger('sourceDns.webdns.views')
        for row in data:
            #print(row)
            ProductID = row['Product']['id']
            # logger.error("ProductID===%s" % (ProductID, ))
            prolist.append(ProductID)

            is_promoted = row['Product'].get('is_promoted', '')
            classlisting_obj.set_is_promoted_listingid(ProductID, is_promoted)

            WishExpress = '%s' % row['Product'].get(
                'wish_express_country_codes', '[]')

            classlisting_obj.set_WishExpress_listingid(ProductID, WishExpress)

            ProductName = row['Product']['name']
            if '\u' in ProductName:
                try:
                    ProductName = ProductName.decode("unicode_escape")
                except:
                    pass

            OfWishes = row['Product']['number_saves']
            OfSales = row['Product']['number_sold']
            ParentSKU = row['Product']['parent_sku'].replace(
                '&lt;', '<').replace('&gt;',
                                     '>').replace("&#39;",
                                                  "'").replace('\\/', '/')

            if '\u' in ParentSKU:
                try:
                    ParentSKU = ParentSKU.decode("unicode_escape")
                except:
                    pass

            ReviewState = row['Product']['review_status']  #当前 wish查看状态
            be_sql = "select DISTINCT ReviewState,BeforeReviewState from t_online_info WHERE ProductID=%s LIMIT 1;"
            cursor.execute(be_sql, (ProductID, ))
            beforers = cursor.fetchone()
            BeforeReviewState = None  # 上一个wish查看状态
            if beforers and len(beforers) == 2:
                if ReviewState == 'rejected' and beforers[
                        0] == 'rejected' and beforers[1]:
                    BeforeReviewState = beforers[1]
                elif beforers[0]:
                    BeforeReviewState = beforers[0]

            ImageURL = row['Product']['main_image'].replace('\\', '')
            DateUploaded = time.strftime(
                "%Y-%m-%d",
                time.strptime(
                    row['Product']['date_uploaded'],
                    "%m-%d-%Y"))  # row['Product']['date_uploaded'] 07-01-2017
            LastUpdated = time.strftime(
                "%Y-%m-%dT%H:%M:%S",
                time.strptime(row['Product']['last_updated'],
                              "%m-%d-%YT%H:%M:%S")
            )  # row['Product']['last_updated']  08-03-2017T10:21:09
            ExtraImages = row['Product']['extra_images'].replace('\\', '')
            Description = row['Product']['description']
            if '\u' in Description:
                try:
                    Description = Description.decode("unicode_escape")
                except:
                    pass

            ShopName = self.ShopName.strip()
            refreshdict['ShopName'] = ShopName
            PlatformName = 'Wish'
            Tags_dict = row['Product']['tags']
            Title = ProductName

            DepartmentID = t_store_configuration_file_obj.getDepartmentbyshopcode(
                ShopName)  # 获取该店铺的部门编号
            seller = t_store_configuration_file_obj.getsellerbyshopcode(
                ShopName)  # 获取该店铺的 销售员 目前没有走redis
            Published = t_store_configuration_file_obj.getPublishedbyshopcode(
                ShopName)  # 获取该店铺的 刊登人 目前没有走redis
            if seller is None or seller.strip() == '':
                seller = Published

            SKU = ''
            RefreshTime = datetime.datetime.now()
            #print RefreshTime
            Tags = ''
            for Tag_dict in Tags_dict:
                if Tags == '':
                    Tags = Tag_dict['Tag']['name']
                else:
                    Tags = '%s,%s' % (Tags, Tag_dict['Tag']['name'])

            # cursor.execute('Delete from t_online_info where  ProductID= %s ; ',(ProductID,))

            shopskulist = []  # 定义ShopSKU列表

            filterdict = {}  # 用于 存放 需要修改的 商品SKU
            vidlist = []
            fbw_flag_list = []  # fbw标记列表
            for variant in row['Product']['variants']:
                VariationID = variant['Variant']['id']  # 平台唯一ID
                vidlist.append(VariationID)

                shopskutmp = variant['Variant']['sku'].replace(
                    '&lt;', '<').replace('&gt;',
                                         '>').replace('&amp;', '&').replace(
                                             "&#39;", "'").replace('\\/', '/')
                # logger.error("shopskutmp===%s" % (shopskutmp, ))

                if '\u' in shopskutmp:
                    try:
                        shopskutmp = shopskutmp.decode('unicode-escape')
                    except:
                        pass

                eshopsku = shopskutmp

                # 刷新fbw标记
                fbw_flag = refresh_fbw_flag(product_id=ProductID,
                                            shopsku=eshopsku,
                                            shopname=ShopName,
                                            connection=self.cnxn)
                fbw_flag_list.append(fbw_flag)

                SKU = classshopsku_obj.getSKU(eshopsku)  # 商品SKU get

                sku_goodsstatus = None
                if SKU is not None and SKU.strip() != '':
                    sku_goodsstatus = classsku_obj.get_goodsstatus_by_sku(
                        SKU)  # 获取商品SKU的商品状态
                # 下面是简单的转换
                if sku_goodsstatus == u'正常':
                    sku_goodsstatus = '1'
                elif sku_goodsstatus == u'售完下架':
                    sku_goodsstatus = '2'
                elif sku_goodsstatus == u'临时下架':
                    sku_goodsstatus = '3'
                elif sku_goodsstatus == u'停售':
                    sku_goodsstatus = '4'

                #print sku_goodsstatus
                ShopSKUImage = ''
                if variant['Variant'].has_key('main_image'):
                    ShopSKUImage = variant['Variant']['main_image'].replace(
                        '\\', '')
                classshopsku_obj.setImage(eshopsku, ShopSKUImage)  # 变体图 set

                Price = variant['Variant']['price']
                classshopsku_obj.setPrice(eshopsku, Price)  # 价格 set

                Inventory = variant['Variant']['inventory']
                if Inventory == '':
                    Inventory = None
                classshopsku_obj.setQuantity(eshopsku, Inventory)  # 库存 set

                Status = variant['Variant'].get('enabled',
                                                '')  # "enabled": "False",
                if Status.strip() == 'False':
                    Statusssss = 'Disabled'
                elif Status.strip() == 'True':  # True
                    Statusssss = 'Enabled'
                else:
                    Statusssss = Status
                classshopsku_obj.setStatus(eshopsku, Statusssss)  # 状态 set

                if Statusssss == 'Enabled':
                    filterdict[SKU] = 0

                Shipping = variant['Variant']['shipping']
                if Shipping == '':
                    Shipping = None
                classshopsku_obj.setShipping(eshopsku, Shipping)  # 运费 set

                Color = ''
                if variant['Variant'].has_key('color'):
                    Color = variant['Variant']['color'].replace('&amp;',
                                                                '&')  #  &
                classshopsku_obj.setColor(eshopsku, Color)  # 颜色 set

                Size = ''
                if variant['Variant'].has_key('size'):
                    Size = variant['Variant']['size'][:30]
                classshopsku_obj.setSize(eshopsku, Size)  # 尺寸 set

                msrp = variant['Variant']['msrp']
                classshopsku_obj.setmsrp(eshopsku, msrp)  # 标签价 set

                ShippingTime = variant['Variant']['shipping_time']
                classshopsku_obj.setshippingtime(eshopsku,
                                                 ShippingTime)  # 运输时间 set
                # Quantity = Inventory

                cursor.execute(
                    "select count(VariationID) from t_online_info WHERE ProductID=%s and VariationID=%s;",
                    (
                        ProductID,
                        VariationID,
                    ))
                somecount = cursor.fetchone()
                if somecount[0] > 0:
                    sql_update = "update t_online_info set Title=%s,Price=%s,Quantity=%s,RefreshTime=%s,Image=%s,Status=%s," \
                                 "ReviewState=%s,OfWishes=%s,OfSales=%s,LastUpdated=%s,Shipping=%s,Color=%s,`Size`=%s,msrp=%s," \
                                 "ShippingTime=%s,ExtraImages=%s,Description=%s,Tags=%s,ShopSKUImage=%s,is_promoted=%s," \
                                 "WishExpress=%s,seller=%s,Published=%s,SKU=%s,MainSKU=%s,BeforeReviewState=%s,ShopSKU=%s" \
                                 " WHERE ProductID=%s and VariationID=%s;"

                    cursor.execute(
                        sql_update,
                        (Title, Price, Inventory, RefreshTime, ImageURL,
                         Statusssss, ReviewState, OfWishes, OfSales,
                         LastUpdated, Shipping, Color, Size, msrp,
                         ShippingTime, ExtraImages, Description, Tags,
                         ShopSKUImage, is_promoted, WishExpress,
                         seller, Published, SKU,
                         classsku_obj.get_bemainsku_by_sku(SKU),
                         BeforeReviewState, shopskutmp, ProductID,
                         VariationID))
                    # if not SKU:
                    update_product.append(ProductID)
                else:
                    sql_insert = 'INSERT INTO t_online_info(ShopIP,ShopName,PlatformName,ProductID,Title,' \
                                 'SKU,ShopSKU,Price,Quantity,RefreshTime,Image,Status,DateUploaded,ParentSKU,' \
                                 'ReviewState,OfWishes,OfSales,LastUpdated,Shipping,Color,`Size`,msrp,' \
                                 'ShippingTime,ExtraImages,VariationID,Description,Tags,' \
                                 'MainSKU,ShopSKUImage,is_promoted,WishExpress,DepartmentID,seller,Published,' \
                                 'GoodsStatus,filtervalue,APIState,BeforeReviewState)' \
                                 ' VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,' \
                                 '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) ; '
                    cursor.execute(
                        sql_insert,
                        (self.ShopIP, ShopName, PlatformName, ProductID, Title,
                         SKU, shopskutmp, Price, Inventory, RefreshTime,
                         ImageURL, Statusssss, DateUploaded, ParentSKU,
                         ReviewState, OfWishes, OfSales, LastUpdated, Shipping,
                         Color, Size, msrp, ShippingTime, ExtraImages,
                         VariationID, Description, Tags,
                         classsku_obj.get_bemainsku_by_sku(SKU), ShopSKUImage,
                         is_promoted, WishExpress, DepartmentID, seller,
                         Published, sku_goodsstatus, 1, 'nothing',
                         BeforeReviewState))
                    insert_product.append(ProductID)
                # sql_update = "update  py_db.b_goodsskulinkshop a, t_online_info b set b.sku = a.sku ,b.MainSKU  = getMainSKU(a.SKU) ,b.MainShopSKU = getMainSKU(b.shopSKU) where a.shopsku =  b.shopsku and  b.ProductID  = %s and b.ShopSKU = %s "
                # cursor.execute(sql_update,(ProductID,ShopSKU))

                shopskulist.append(shopskutmp)
                # logger.error("shopskulist===%s" % (shopskulist, ))
                # logger.error("join===%s" % ('|'.join(shopskulist), ))
                #sql_update_mainsku = 'update t_online_info set MainSKU  = getMainSKU(SKU) ,MainShopSKU = getMainSKU(shopSKU)  where   ProductID= %s and ShopSKU =%s '
                #cursor.execute(sql_update_mainsku,(ProductID,ShopSKU))

            # 获取该产品的海外仓运费和库存

            for we in eval(WishExpress):  # 是属于海外仓的
                # raise Exception(self.warehouse)
                if self.warehouse.has_key(we) and we in ['DE', 'GB', 'US']:
                    warehouseid = self.warehouse[we]
                    vgoodsinfos = cwishapi_obj.warehouse_vgoodsinfo(
                        self.access_token, ProductID, warehouseid)
                    # assert vgoodsinfos['errorcode'] == 1, vgoodsinfos['errortext']
                    if vgoodsinfos['errorcode'] == 1:
                        for vgoods in vgoodsinfos['data']:
                            wvid = vgoods['Variant']['id']

                            shopsku = vgoods['Variant']['sku'].replace(
                                '&lt;', '<').replace('&gt;', '>').replace(
                                    '&amp;',
                                    '&').replace("&#39;",
                                                 "'").replace('\\/', '/')
                            if '\u' in shopsku:
                                try:
                                    shopsku = shopsku.decode('unicode-escape')
                                except:
                                    pass

                            wshipping = vgoods['Variant'][
                                'shipping']  # DEExpressShipping
                            if wshipping == '':
                                wshipping = None
                            ws = getattr(classshopsku_obj,
                                         "setWish%sShipping" % we)
                            ws(shopsku, wshipping)
                            # eval("classshopsku_obj.setWish%sShipping" % we)(shopsku, wshipping)

                            winventory = vgoods['Variant'][
                                'inventory']  # DEExpressInventory
                            if winventory == '':
                                winventory = None
                            wi = getattr(classshopsku_obj,
                                         "setWish%sQuantity" % we)
                            wi(shopsku, winventory)
                            # eval("classshopsku_obj.setWish%sQuantity" % we)(shopsku, winventory)

                            vsql = "update t_online_info set " + we + "ExpressShipping=%s," + we + \
                                   "ExpressInventory=%s WHERE ProductID=%s and VariationID=%s;"

                            cursor.execute(
                                vsql, (wshipping, winventory, ProductID, wvid))

            if vidlist:  # 删除多余的变体信息
                del_param_list = []
                old_shopsku_list = classlisting_obj.getShopSKUList(ProductID)
                if old_shopsku_list:
                    for del_shopsku in old_shopsku_list:
                        if del_shopsku not in shopskulist:
                            del_param_list.append([ProductID, del_shopsku])
                            delete_product.append(ProductID)
                            # del_sku = classshopsku_obj.getSKU(del_shopsku)
                            # if del_sku:
                            #     delete_sku.append(del_sku)

                cursor.executemany(
                    "delete from t_online_info WHERE ProductID=%s and ShopSKU=%s ;",
                    del_param_list)

            classlisting_obj.setShopSKUList(
                ProductID, '|'.join(shopskulist))  # ProductID ShopSKUList
            # for k,v in filterdict.items():
            #     cursor.execute("update t_online_info set filtervalue = 0 WHERE ProductID=%s and SKU=%s;",(ProductID,k,))

            if fbw_flag_list and 'True' in fbw_flag_list:
                cursor.execute(
                    "update t_online_info set FBW_Flag = 'True' WHERE ProductID=%s ;",
                    (ProductID, ))
            elif 'False' in fbw_flag_list:
                cursor.execute(
                    "update t_online_info set FBW_Flag = 'False' WHERE ProductID=%s ;",
                    (ProductID, ))

        self.cnxn.commit()

        for inproduct in set(insert_product):
            iResult = t_event_class_obj.t_online_info_insert_trigger(inproduct)

        for delproduct in set(delete_product):
            del_Result = t_event_class_obj.t_online_info_delete_trigger(
                delproduct)

        for updproduct in set(update_product):
            upd_Result = t_event_class_obj.t_online_info_update_trigger(
                updproduct)

        cursor.close()
        refreshdict['ProductID'] = prolist
        return refreshdict
Exemplo n.º 9
0
def run(params):
    # 获取需要刷新的数据
    t_online_info_objs = t_online_info(params['ShopName'], params['dbcnxn'])
    t_report_orders1days_objs = t_report_orders1days(params['dbcnxn'])
    t_store_configuration_file_obj = t_store_configuration_file(
        params['dbcnxn'])
    classlisting_obj = classlisting(params['dbcnxn'])
    classmainsku_obj = classmainsku(params['dbcnxn'])
    t_templet_wish_upload_result_obj = t_templet_wish_upload_result(
        params['dbcnxn'])
    classshopsku_obj = classshopsku(params['dbcnxn'],
                                    shopname=params['ShopName'])
    t_online_info_wish_obj = t_online_info_wish(params['dbcnxn'])
    t_distribution_product_to_store_result_obj = t_distribution_product_to_store_result(
        params['dbcnxn'])
    t_large_small_corresponding_cate_obj = t_large_small_corresponding_cate(
        params['dbcnxn'])
    t_wish_pb_campaignproductstats_obj = t_wish_pb_campaignproductstats(
        params['dbcnxn'])

    infodata = t_online_info_objs.getshopproductdata(params['ProductID'])

    for obj in infodata:
        datedict = {}
        datedict['ProductID'] = obj['ProductID']
        datedict['ShopName'] = obj['ShopName']
        datedict['Title'] = obj['Title']
        datedict['SKU'] = obj['SKU']
        datedict['ShopSKU'] = obj['ShopSKU']
        datedict['Price'] = obj['Price']
        datedict['RefreshTime'] = obj['RefreshTime']

        yyyymmdd = obj['RefreshTime'].strftime('%Y%m%d')

        datedict['SoldTheDay'] = t_report_orders1days_objs.getSoldTheDay(
            obj['ProductID'], yyyymmdd)

        datedict['SoldYesterday'] = t_report_orders1days_objs.getSoldYesterday(
            obj['ProductID'], yyyymmdd)

        datedict['Orders7Days'] = t_report_orders1days_objs.getOrders7Days(
            obj['ProductID'], yyyymmdd)  # 默认 普通仓

        # 海外仓 7天订单数,总销量 订单不足 数值偏小
        datedict[
            'Order7daysDE'] = t_report_orders1days_objs.getOrders7Days_WarehouseName(
                obj['ProductID'], yyyymmdd, 'DE')
        datedict[
            'Order7daysGB'] = t_report_orders1days_objs.getOrders7Days_WarehouseName(
                obj['ProductID'], yyyymmdd, 'GB')
        datedict[
            'Order7daysUS'] = t_report_orders1days_objs.getOrders7Days_WarehouseName(
                obj['ProductID'], yyyymmdd, 'US')
        datedict[
            'Order7daysFBW'] = t_report_orders1days_objs.getOrders7Days_WarehouseName(
                obj['ProductID'], yyyymmdd, 'FBW')

        datedict[
            'OfsalesDE'] = t_report_orders1days_objs.ofSales_Of_ProductID_WarehouseName(
                obj['ProductID'], 'DE')
        datedict[
            'OfsalesGB'] = t_report_orders1days_objs.ofSales_Of_ProductID_WarehouseName(
                obj['ProductID'], 'GB')
        datedict[
            'OfsalesUS'] = t_report_orders1days_objs.ofSales_Of_ProductID_WarehouseName(
                obj['ProductID'], 'US')
        datedict[
            'OfsalesFBW'] = t_report_orders1days_objs.ofSales_Of_ProductID_WarehouseName(
                obj['ProductID'], 'FBW')

        classlisting_obj.set_order7days_listingid(datedict['ProductID'],
                                                  datedict['Orders7Days'])

        datedict['SoldXXX'] = int(datedict['SoldTheDay']) - int(
            datedict['SoldYesterday'])

        datedict['DateOfOrder'] = None
        datedict['Image'] = obj['Image']
        datedict['Status'] = obj['Status']
        datedict['ReviewState'] = obj['ReviewState']
        datedict['DateUploaded'] = obj['DateUploaded']
        datedict['LastUpdated'] = obj['LastUpdated']
        datedict['OfSales'] = obj['OfSales']
        datedict['ParentSKU'] = obj['ParentSKU']

        datedict['is_promoted'] = obj['is_promoted']
        datedict['WishExpress'] = obj['WishExpress']

        datedict[
            'Seller'] = t_store_configuration_file_obj.getsellerbyshopcode(
                params['ShopName'][0:9])

        datedict['MainSKU'] = obj['MainSKU']

        datedict['TortInfo'] = 'N'
        mainskulist = classlisting_obj.getmainsku(obj['ProductID'])
        if mainskulist:
            tortlist = []
            for mainsku in set(mainskulist):
                tortsite = classmainsku_obj.get_tort_by_mainsku(mainsku)
                if tortsite is not None:
                    tortlist = tortlist + tortsite
            if tortlist:
                if 'Wish' in tortlist:
                    datedict['TortInfo'] = 'WY'
                else:
                    datedict['TortInfo'] = 'Y'

        datedict['DataSources'] = "NORMAL"
        if t_templet_wish_upload_result_obj.get_count_num(
                obj['ParentSKU'], obj['ShopName']) >= 1:
            datedict['DataSources'] = "UPLOAD"
        else:
            if t_distribution_product_to_store_result_obj.get_count_num(
                    obj['ParentSKU'], obj['ShopName']) >= 1:
                datedict['DataSources'] = "UPLOAD"

        datedict['OperationState'] = 'No'
        if obj['Status'] == 'Disabled':
            datedict['OperationState'] = 'Yes'

        # MainSKU,大类,小类
        datedict['MainSKULargeCate'] = None
        datedict['MainSKUSmallCate'] = None

        mlist = []
        if datedict['MainSKU']:
            mlist = re.findall(r'[0-9]+|[a-z]+|[A-Z|]+|[-]',
                               datedict['MainSKU'])
        if len(mlist) >= 1:
            datedict['MainSKUSmallCate'] = mlist[0]  # 小类
            lResult = t_large_small_corresponding_cate_obj.getLargeClassBySmallClass(
                datedict['MainSKUSmallCate'])
            if lResult['code'] == 1:
                datedict['MainSKULargeCate'] = lResult['largecode']

        datedict['SName'] = '0'  # 店铺状态 0 正常 -1 异常
        # 1 正常(在线); 0 正常(不在线); -1 api调用错误; -2 执行代码异常;
        if datedict['ReviewState'] == 'approved' and datedict[
                'Status'] == 'Enabled':
            datedict['AdStatus'] = '1'  # 1 正常(在线)
        else:
            datedict['AdStatus'] = '0'  # 0 正常(不在线)

        datedict['Published'] = None
        if obj['ShopSKU'] is not None and obj['ShopSKU'].strip() != '':
            pub = None
            for shopsku in obj['ShopSKU'].split(','):
                for each_shopsku in shopsku.split('+'):
                    pub = classshopsku_obj.getPublished(
                        each_shopsku.split('*')[0].split('\\')[0].split('/')
                        [0])  # 按照店铺SKU来抓取刊登人
                    if pub:
                        break
                if pub:
                    break
            datedict['Published'] = pub

        datedict['market_time'] = None

        # 这里是商品状态结果集
        statuslist = t_online_info_objs.get_goodsstatus_by_productid(
            params['ProductID'])
        a1 = 0
        if '1' in statuslist:
            a1 = 1
        a2 = 0
        if '2' in statuslist:
            a2 = 1
        a3 = 0
        if '3' in statuslist:
            a3 = 1
        a4 = 0
        if '4' in statuslist:
            a4 = 1
        datedict['GoodsFlag'] = a1 * 1000 + a2 * 100 + a3 * 10 + a4

        # 店铺SKU状态结果集
        sstatuslist = t_online_info_objs.get_shopskustatus_by_productid(
            params['ProductID'])
        b1 = 0
        if 'Enabled' in sstatuslist:
            b1 = 1
        b2 = 0
        if 'Disabled' in sstatuslist:
            b2 = 1
        datedict['ShopsFlag'] = b1 * 10 + b2

        # 绑定状态结果集
        datedict['BindingFlag'] = 1  # 默认全部绑定
        # anum = obj[-1] # 变体数量
        # unum = t_online_info_objs.get_binding_by_productid(params['ProductID'])
        # if int(anum) == int(unum):
        #     datedict['BindingFlag'] = 3
        # elif int(anum) > 0 and int(unum) == 0:
        #     datedict['BindingFlag'] = 1
        # elif int(anum) > 0 and int(unum) != 0:
        #     datedict['BindingFlag'] = 2
        # print datedict

        datedict['BeforeReviewState'] = obj['BeforeReviewState']  # 上一个wish查看状态

        datedict['Rating'] = 0  # 链接的评分
        if float(datedict['OfSales']) > 0:
            rResult = t_online_info_wish_obj.get_product_id_rating(
                datedict['ProductID'])
            old_rating = rResult.get('rating', 0)

            Gresult = get_rating(datedict['ProductID'])
            new_rating = Gresult.get('rating', 0)

            if new_rating == 0 and datedict[
                    'ReviewState'] == 'rejected':  # 被拒绝的连接
                datedict['Rating'] = old_rating
            elif new_rating != 0:
                datedict['Rating'] = new_rating

        datedict['ADShow'] = 0  # 是否有广告   0 没有  1  有
        adResult = t_wish_pb_campaignproductstats_obj.j_ad(
            datedict['ProductID'])
        if adResult['errorcode'] == 1:
            datedict['ADShow'] = 1

        # 周销量趋势 -1:下降 0:平稳 1:上升
        datedict['SalesTrend'] = get_salestrend(datedict['ProductID'],
                                                t_report_orders1days_objs)

        datedict['FBW_Flag'] = obj['FBW_Flag']  # fbw 标记

        print "datedict['ProductID']=============%s" % datedict['ProductID']

        t_online_info_wish_obj.refreshwishdata(datedict)