def ToCalculateADS(productid, shopname, dbconn):
    try:
        t_online_info_obj = t_online_info(shopname, dbconn)
        rResult = t_online_info_obj.getonlinestatusbyproductid(productid)
        assert rResult['errorcode'] == 0, rResult['errortext']
        if rResult['Status'] == 'Enabled' and rResult[
                'ReviewState'] == 'approved':
            return '1'
        else:
            return '0'
    except Exception, e:
        rResult = {'errorcode': -1, 'errortext': '%s:%s' % (Exception, e)}
Example #2
0
    def getSince(self, data):
        t_online_info_obj = t_online_info(
            self.t_api_scheduleImp.auth_info['ShopName'],
            self.t_api_scheduleImp.cnxn)
        Max_ProductLastUpdated = t_online_info_obj.getMax_ProductLastUpdated2()
        get_wish_product_order_updatetime_obj = get_wish_product_order_updatetime(
            self.t_api_scheduleImp.cnxn,
            self.t_api_scheduleImp.auth_info['ShopName'])
        end = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S')
        if Max_ProductLastUpdated == '1970-01-01':
            #没找到那就是
            start = None
        else:
            #[最大时间+1s,现在)
            start = strtimeaddseconds(Max_ProductLastUpdated, -600)

            data['since'] = start
            self.OneCmdRecoreDict['cmdtext'] = '[ %s , %s )' % (start, end)
        get_wish_product_order_updatetime_obj.update_time_or_insert(
            start, end, 'Product')
Example #3
0
    def GetShopSKUInfo(self):
        if self.OneCmdRecoreDict[
                'TransactionID'] is None or self.OneCmdRecoreDict[
                    'TransactionID'].strip() == '':
            Params_dict = eval(self.OneCmdRecoreDict['Params'].replace(
                "`", "'"))
            #import requests
            #url_create = "https://merchant.wish.com/api/v2/product/create-download-job"
            data = {
                'access_token':
                self.t_api_scheduleImp.auth_info['access_token'],
                'format': 'json',
            }
            self.getSince(data)
            print 'data=%s' % data
            dict_ret = requests.post(Params_dict['url_create'],
                                     params=data,
                                     timeout=10)

            print dict_ret.__dict__
            print '---------------\n'
            #dict_ret =eval(ret)
            print 'dict_ret=%s' % dict_ret
            print '---------------\n'
            _content = eval(dict_ret._content)
            #刷新一下token  1015 :问令牌过期   4000:权存取 1016:失效
            if _content['code'] == 1015 or _content[
                    'code'] == 1016:  # or _content['code']== 4000   or _content['code']== 1017  or _content['code']== 1018  or _content['code']== 9000   :
                # self.RefreshToken()

                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.OneCmdRecoreDict['TransactionID'] = ''
                self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                    self.OneCmdRecoreDict)
                self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)
                return
            if dict_ret.status_code == 200 and _content['code'] == 0:
                self.OneCmdRecoreDict['Status'] = '1'
                self.OneCmdRecoreDict['ProcessingStatus'] = 'SUBMIT'
                self.OneCmdRecoreDict[
                    'ActualBeginTime'] = datetime.datetime.now()
                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.OneCmdRecoreDict['TransactionID'] = '{`job_id`:`%s`}' % (
                    _content['data']['job_id'])
                self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                    self.OneCmdRecoreDict)
                self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)
            else:  #报错
                #self.OneCmdRecoreDict['Status'] = '-2'
                #self.OneCmdRecoreDict['ProcessingStatus'] = dict_ret.status_code
                self.OneCmdRecoreDict['Status'] = dict_ret.status_code
                self.OneCmdRecoreDict['ProcessingStatus'] = _content['code']
                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)

        else:
            TransactionID_dict = eval(
                self.OneCmdRecoreDict['TransactionID'].replace("`", "'"))
            print 'TransactionID_dict=%s' % TransactionID_dict

            Params_dict = eval(self.OneCmdRecoreDict['Params'].replace(
                "`", "'"))
            print self.OneCmdRecoreDict['Params']

            data = {
                'access_token':
                self.t_api_scheduleImp.auth_info['access_token'],
                'format': 'json',
                'job_id': TransactionID_dict['job_id'],
            }
            dict_ret = requests.post(Params_dict['url_status'],
                                     params=data,
                                     timeout=10)

            #dict_ret =eval(ret)
            #print json.dumps(dict_ret, indent=1)
            print '---------------\n'
            print 'dict_ret=%s' % dict_ret
            print '---------------\n'
            print dict_ret.__dict__
            print '---------------\n'
            print dict_ret._content
            _content = eval(dict_ret._content)
            #刷新一下token  1015 :问令牌过期   4000:权存取
            if _content['code'] == 1015 or _content[
                    'code'] == 1016:  #or _content['code']== 4000  or _content['code']== 1016 or _content['code']== 1017  or _content['code']== 1018  or _content['code']== 9000   :
                # self.RefreshToken()

                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.OneCmdRecoreDict['TransactionID'] = ''
                self.OneCmdRecoreDict['ProcessingStatus'] = _content['code']
                self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                    self.OneCmdRecoreDict)
                self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)
                return
            if dict_ret.status_code == 200 and _content['code'] == 0:
                if _content['data']['status'] == 'FINISHED':
                    if _content['data']['total_count'] > 0 and _content[
                            'data'].has_key('download_link'):
                        #下载数据
                        download_link = _content['data'][
                            'download_link'].replace('\\', '')
                        print 'download_link=%s' % download_link
                        req = urllib2.Request(download_link)
                        csv_bytes = urllib2.urlopen(req,
                                                    timeout=600).read().decode(
                                                        'ascii', 'ignore')
                        csv_reader = csv.reader(StringIO(csv_bytes))
                        t_online_info_obj = t_online_info(
                            self.t_api_scheduleImp.auth_info['ShopName'],
                            self.t_api_scheduleImp.cnxn)
                        t_online_info_obj.insertWish(csv_reader)

                    self.OneCmdRecoreDict['Status'] = '2'
                    self.OneCmdRecoreDict['ProcessingStatus'] = _content[
                        'data']['status']
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)
                elif _content['data']['status'] == 'PENDING' or _content[
                        'data']['status'] == 'RUNNING':
                    self.OneCmdRecoreDict['Status'] = '1'
                    self.OneCmdRecoreDict['ProcessingStatus'] = _content[
                        'data']['status']
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                        self.OneCmdRecoreDict)
                    self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)

                else:
                    self.OneCmdRecoreDict['Status'] = '-2'
                    self.OneCmdRecoreDict['ProcessingStatus'] = _content[
                        'data']['status']
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)
            else:  #报错
                self.OneCmdRecoreDict['Status'] = dict_ret.status_code
                self.OneCmdRecoreDict['ProcessingStatus'] = _content['code']
                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)
Example #4
0
class ShopOnlineInfo():
    def __init__(self, t_api_scheduleImp, OneCmdRecoreDict, flag, db_conn):
        self.t_api_scheduleImp = t_api_scheduleImp
        self.OneCmdRecoreDict = OneCmdRecoreDict
        self.flag = flag
        self.db_conn = db_conn

    def do(self):
        result = {}
        if self.OneCmdRecoreDict['CMDID'] == 'UpdateInventory':
            self.UpdateInventory()
            result['CMDID'] = 'UpdateInventory'

        elif self.OneCmdRecoreDict['CMDID'] == 'GetShopSKUInfo':
            result = self.GetShopSKUInfoV2()
            result['CMDID'] = 'GetShopSKUInfo'

        elif self.OneCmdRecoreDict['CMDID'] == 'GetListOrders':
            result = self.GetListOrders2()
            result['CMDID'] = 'GetListOrders'

        else:
            result['CMDID'] = 'Other'
            pass
        return result

    def UpdateInventory(self):
        pass

    def GetShopSKUInfo(self):
        if self.OneCmdRecoreDict[
                'TransactionID'] is None or self.OneCmdRecoreDict[
                    'TransactionID'].strip() == '':
            Params_dict = eval(self.OneCmdRecoreDict['Params'].replace(
                "`", "'"))
            #import requests
            #url_create = "https://merchant.wish.com/api/v2/product/create-download-job"
            data = {
                'access_token':
                self.t_api_scheduleImp.auth_info['access_token'],
                'format': 'json',
            }
            self.getSince(data)
            print 'data=%s' % data
            dict_ret = requests.post(Params_dict['url_create'],
                                     params=data,
                                     timeout=10)

            print dict_ret.__dict__
            print '---------------\n'
            #dict_ret =eval(ret)
            print 'dict_ret=%s' % dict_ret
            print '---------------\n'
            _content = eval(dict_ret._content)
            #刷新一下token  1015 :问令牌过期   4000:权存取 1016:失效
            if _content['code'] == 1015 or _content[
                    'code'] == 1016:  # or _content['code']== 4000   or _content['code']== 1017  or _content['code']== 1018  or _content['code']== 9000   :
                # self.RefreshToken()

                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.OneCmdRecoreDict['TransactionID'] = ''
                self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                    self.OneCmdRecoreDict)
                self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)
                return
            if dict_ret.status_code == 200 and _content['code'] == 0:
                self.OneCmdRecoreDict['Status'] = '1'
                self.OneCmdRecoreDict['ProcessingStatus'] = 'SUBMIT'
                self.OneCmdRecoreDict[
                    'ActualBeginTime'] = datetime.datetime.now()
                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.OneCmdRecoreDict['TransactionID'] = '{`job_id`:`%s`}' % (
                    _content['data']['job_id'])
                self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                    self.OneCmdRecoreDict)
                self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)
            else:  #报错
                #self.OneCmdRecoreDict['Status'] = '-2'
                #self.OneCmdRecoreDict['ProcessingStatus'] = dict_ret.status_code
                self.OneCmdRecoreDict['Status'] = dict_ret.status_code
                self.OneCmdRecoreDict['ProcessingStatus'] = _content['code']
                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)

        else:
            TransactionID_dict = eval(
                self.OneCmdRecoreDict['TransactionID'].replace("`", "'"))
            print 'TransactionID_dict=%s' % TransactionID_dict

            Params_dict = eval(self.OneCmdRecoreDict['Params'].replace(
                "`", "'"))
            print self.OneCmdRecoreDict['Params']

            data = {
                'access_token':
                self.t_api_scheduleImp.auth_info['access_token'],
                'format': 'json',
                'job_id': TransactionID_dict['job_id'],
            }
            dict_ret = requests.post(Params_dict['url_status'],
                                     params=data,
                                     timeout=10)

            #dict_ret =eval(ret)
            #print json.dumps(dict_ret, indent=1)
            print '---------------\n'
            print 'dict_ret=%s' % dict_ret
            print '---------------\n'
            print dict_ret.__dict__
            print '---------------\n'
            print dict_ret._content
            _content = eval(dict_ret._content)
            #刷新一下token  1015 :问令牌过期   4000:权存取
            if _content['code'] == 1015 or _content[
                    'code'] == 1016:  #or _content['code']== 4000  or _content['code']== 1016 or _content['code']== 1017  or _content['code']== 1018  or _content['code']== 9000   :
                # self.RefreshToken()

                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.OneCmdRecoreDict['TransactionID'] = ''
                self.OneCmdRecoreDict['ProcessingStatus'] = _content['code']
                self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                    self.OneCmdRecoreDict)
                self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)
                return
            if dict_ret.status_code == 200 and _content['code'] == 0:
                if _content['data']['status'] == 'FINISHED':
                    if _content['data']['total_count'] > 0 and _content[
                            'data'].has_key('download_link'):
                        #下载数据
                        download_link = _content['data'][
                            'download_link'].replace('\\', '')
                        print 'download_link=%s' % download_link
                        req = urllib2.Request(download_link)
                        csv_bytes = urllib2.urlopen(req,
                                                    timeout=600).read().decode(
                                                        'ascii', 'ignore')
                        csv_reader = csv.reader(StringIO(csv_bytes))
                        t_online_info_obj = t_online_info(
                            self.t_api_scheduleImp.auth_info['ShopName'],
                            self.t_api_scheduleImp.cnxn)
                        t_online_info_obj.insertWish(csv_reader)

                    self.OneCmdRecoreDict['Status'] = '2'
                    self.OneCmdRecoreDict['ProcessingStatus'] = _content[
                        'data']['status']
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)
                elif _content['data']['status'] == 'PENDING' or _content[
                        'data']['status'] == 'RUNNING':
                    self.OneCmdRecoreDict['Status'] = '1'
                    self.OneCmdRecoreDict['ProcessingStatus'] = _content[
                        'data']['status']
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                        self.OneCmdRecoreDict)
                    self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)

                else:
                    self.OneCmdRecoreDict['Status'] = '-2'
                    self.OneCmdRecoreDict['ProcessingStatus'] = _content[
                        'data']['status']
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)
            else:  #报错
                self.OneCmdRecoreDict['Status'] = dict_ret.status_code
                self.OneCmdRecoreDict['ProcessingStatus'] = _content['code']
                self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now(
                )
                self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)

    def GetShopSKUInfoV2(self):
        refreshdict = {'ShopName': '', 'ProductID': [], 'record': {}}
        record = {}
        pageurl = ''
        datalist = []

        shopstatus = None
        while True:
            if pageurl == '':
                url_List_all_Products = "https://merchant.wish.com/api/v2/product/multi-get"
                data = {
                    'access_token':
                    self.t_api_scheduleImp.auth_info['access_token'],
                    'format':
                    'json',
                    'limit':
                    '250',
                    'show_rejected':
                    'true',
                }
                if self.flag == 1:
                    record = self.getSinceV2(data, 'Product')
                print 'data=%s' % data
                dict_ret = requests.get(url_List_all_Products,
                                        params=data,
                                        timeout=30)
                print '---------------', pageurl
                _content = eval(dict_ret._content)

                if dict_ret.status_code == 200 and _content['code'] == 0:
                    # datalist.append(_content['data'])
                    datalist = datalist + _content['data']

                    t_store_configuration_file_obj = t_store_configuration_file(
                        self.db_conn)
                    t_store_configuration_file_obj.update_shopStatus(
                        '0', self.t_api_scheduleImp.auth_info['ShopName'])

                    t_online_info_wish_obj = t_online_info_wish(self.db_conn)
                    t_online_info_wish_obj.UpdateWishSNameByShopName(
                        self.t_api_scheduleImp.auth_info['ShopName'], '0')

                    if _content.has_key(
                            'paging') and _content['paging'].has_key('next'):
                        pageurl = _content['paging']['next'].replace('\\', '')
                    else:
                        self.t_api_scheduleImp.cnxn.commit()
                        self.OneCmdRecoreDict['Status'] = '2'
                        self.OneCmdRecoreDict[
                            'ActualEndTime'] = datetime.datetime.now()
                        self.t_api_scheduleImp.moveOneCmd(
                            self.OneCmdRecoreDict)
                        break
                else:
                    shopstatus = self.j_result_code(_content)
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.OneCmdRecoreDict['TransactionID'] = ''
                    self.t_api_scheduleImp.refreshScheduleTimeAndTimedelta(
                        self.OneCmdRecoreDict)
                    self.t_api_scheduleImp.updateOneCmd(self.OneCmdRecoreDict)
                    break
            else:
                print '---------------', pageurl
                paging_bytes = None
                try:
                    paging_req = urllib2.Request(pageurl)
                    paging_bytes = urllib2.urlopen(paging_req,
                                                   timeout=60).read()
                except Exception, ex:
                    datalist = []
                    record = {}
                    self.OneCmdRecoreDict['Status'] = 'Exception'
                    self.OneCmdRecoreDict[
                        'ActualEndTime'] = datetime.datetime.now()
                    self.OneCmdRecoreDict[
                        'errorinfo'] = '%s  F_EXE_API_WISH except Exception= %s ex=%s  __LINE__=%s' % (
                            time.strftime('%Y-%m-%d %H:%M:%S',
                                          time.localtime(time.time())),
                            Exception, ex, sys._getframe().f_lineno)
                    self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)
                    break

                if paging_bytes is not None:
                    paging_bytes_dict = eval(paging_bytes)
                    # datalist.append(paging_bytes_dict['data'])
                    datalist = datalist + paging_bytes_dict['data']

                    if paging_bytes_dict.has_key(
                            'paging') and paging_bytes_dict['paging'].has_key(
                                'next'):
                        if len(paging_bytes_dict['paging']['next']) <= 10:
                            break
                        else:
                            pageurl = paging_bytes_dict['paging'][
                                'next'].replace('\\', '')
                    else:
                        break
                else:
                    break
        # t_store_configuration_file_obj.update_shopStatus(shopstatus, self.t_api_scheduleImp.auth_info['ShopName'])
        if datalist:
            t_online_info_obj = t_online_info(
                self.t_api_scheduleImp.auth_info['ShopName'],
                self.t_api_scheduleImp.cnxn, self.t_api_scheduleImp.redis_conn)
            refreshdict = t_online_info_obj.insertWishV2(datalist)

            self.t_api_scheduleImp.cnxn.commit()
            self.OneCmdRecoreDict['Status'] = '2'
            self.OneCmdRecoreDict['ActualEndTime'] = datetime.datetime.now()
            self.t_api_scheduleImp.moveOneCmd(self.OneCmdRecoreDict)
        refreshdict['record'] = record
        return refreshdict
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())
def OnTheShelf_OR_LowerFrame_BY_ShopSKU(shopsku, shopname, flag, flagname=''):
    myresult = {'Code': 0, 'messages': ''}
    try:
        upstatus = 'over'  # 日志
        uptext = None

        t_wish_store_oplogs_obj = t_wish_store_oplogs(connection)
        t_store_configuration_file_obj = t_store_configuration_file(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'  # 店铺状态
            classshopsku_obj = classshopsku(redis_conn=redis_coon,
                                            shopname=shopname)
            cwishapi_obj = cwishapi()
            t_online_info_obj = t_online_info(shopname, connection)

            auth_info = verb_token(shopname, connection)
            assert auth_info['errorcode'] == 1, auth_info['errortext']

            data = {}
            data['access_token'] = auth_info.get('access_token', '')
            data['ShopSKU'] = shopsku

            proinfo = t_online_info_obj.get_listingid_by_shopname_shopsku(
                shopsku)
            assert proinfo[
                'errorcode'] == 0, 'EDGetProductIDSuccess:%s' % proinfo[
                    'errortext']

            if flag == 'enshopsku':  # ShopSKU上架
                sstatus = 'Enabled'
                result = cwishapi_obj.update_to_enable(data, timeout=30)
            else:
                sstatus = 'Disabled'
                result = cwishapi_obj.update_to_disable(data, timeout=30)

            _content = eval(result._content)

            if result.status_code == 200 and _content['code'] == 0:
                uResult = t_online_info_obj.update_status_by_shopsku(
                    sstatus, shopsku)  # 更新shopsku状态数据
                assert uResult[
                    'errorcode'] == 0, 'EDSuccess:%s' % uResult['errortext']

                classshopsku_obj.setStatus(shopsku, sstatus)  # 修改redis数据

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

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

                upstatus = 'error'  # 日志
                uptext = business_Terms(_content)
                myresult['messages'] = u'%s:上下架操作失败!%s' % (
                    shopsku, business_Terms(_content))

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

            adResult = t_online_info_wish_obj.UpdateWishStatusAD(
                proinfo['productid'], toResult)
            assert adResult['errorcode'] == 1, adResult['errortext']

            myresult['_content'] = _content
        else:
            upstatus = 'error'
            snstatus = '-1'  # listing 店铺状态标记
            uptext = u'店铺状态被标记为异常'
            myresult['_content'] = uptext
            myresult['messages'] = u'%s:上下架操作失败!%s' % (shopsku, uptext)

        uPResult = t_wish_store_oplogs_obj.updateStatusP(
            flagname, shopsku, upstatus, uptext)
        assert uPResult['errorcode'] == 0, uPResult['errortext']

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

        myresult['Code'] = 1
    except Exception, e:
        myresult['Code'] = -1
        myresult['messages'] = '%s:%s:%s' % (shopsku, Exception, e)
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)
Example #8
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)