Example #1
0
 def post(self):
     wb = Wuba('find.allprotype')
     response = yield wb()
     self.set_header('Content-Type', 'application/json; charset=UTF-8')
     wb.parse_response(response.body)
     parent_id = int(self.get_argument('id', '0'))
     result = []
     if wb.is_ok():
         for node in wb.message.data:
             if node.parentId == parent_id:
                 result.append({
                     'id': node.prodTypeId,
                     'name': node.name,
                     'isParent': False
                 })
         self.write(json_dumps(result))
     else:
         self.write('[]')
Example #2
0
    def post(self):
        """推送商品"""
        arg = lambda k: self.get_argument(k).encode('utf-8')
        goods_id = self.get_argument('goods_id')

        dg = alloc_distributor_goods(self.db, goods_id, options.shop_id_wuba)
        params = dict([(name, self.get_argument(name).encode('utf-8')) for name in self.request.arguments])

        params.pop("goods_id")
        params.pop("_xsrf")
        params['groupbuyId'] = dg.goods_link_id
        prod_model_json = dict(prodmodcatename=arg('prodName'), prodprice=arg('prodPrice'),
                               groupprice=arg('groupPrice'), prodcode='', count=arg('saleMaxNum'))

        cityIds = self.request.arguments['cityIds']
        ids = []
        for cityId in cityIds:
            ids.append(int(cityId))

        params['cityIds'] = str(ids)

        if options.app_mode == 'dev':
            params['prodImg'] = 'http://www.itlearner.com/google_commonweal_ad/images/sun/300px.jpg'
        params['prodModelJson'] = '{%s}' % json_dumps(prod_model_json)
        #商家信息参数
        shop_ids = list(arg('shop_ids').split(","))
        # 将团购信息参数中的特定key值转移出来,构建商家信息参数
        partner_keys = {"partnerId", "title", "shortTitle", "telephone", "webUrl", "busline", "mapImg",
                        "mapServiceId", "mapUrl", "latitude", "longitude", "address", "circleId"}
        partners = []
        for shop_id in shop_ids:
            partner = {}
            for key in partner_keys:
                partner[key] = params.pop(key + "_" + shop_id)
            partners.append(partner)

        request_params = {'groupbuyInfo': params, 'partners': partners}
        wb = Wuba('addgroupbuy')
        response = yield wb.fetch(**request_params)
        wb.parse_response(response.body)

        if wb.is_ok():
            off_sale_at = datetime.strptime(params['endTime'], '%Y-%m-%d %H:%M:%S')
            expire_at = ceiling(datetime.strptime(params['deadline'], '%Y-%m-%d %H:%M:%S'), today=True)
            self.db.execute('update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), '
                            'offsale_at = %s, expire_at = %s, distributor_goods_id = %s '
                            'where goods_id=%s and distributor_shop_id=%s and goods_link_id=%s',
                            self.current_user.name, off_sale_at, expire_at,
                            wb.message.data.groupbuyId58, goods_id, options.shop_id_wuba, dg.goods_link_id)

            self.render('goods/distributor/wuba/result.html', ok=True, title='上传成功',
                        explain='<a href="http://t.58.com/sh/%s" target="_blank">去58查看商品</a><br/><a href="/goods/distributor?shop=wb">'
                                '继续上传58商品</a>' % wb.message.data.groupbuyId58)
        else:
            self.render('goods/distributor/wuba/result.html', ok=False, title='上传出错', explain=wb.message.msg)
Example #3
0
def sync_stock():
    sql = """
        select g.id, gds.distributor_shop_id, gds.distributor_goods_id, gds.goods_link_id, g.stock, ds.taobao_api_info,
        ds.distributor_id
        from goods g, distributor_shop ds, goods_distributor_shop gds where g.id = gds.goods_id
        and gds.distributor_shop_id = ds.id
        and g.generate_type = 'IMPORT' and gds.deleted = '0'
            and gds.distributor_shop_id in (%s, %s, %s, %s) """

    params = [options.shop_id_taobao, options.shop_id_tmall, options.shop_id_jingdong,  options.shop_id_wuba]
    sync_list = db.query(sql, *params)

    for item in sync_list:
        if not item.distributor_goods_id or item.distributor_goods_id == '0':
            logging.error('商品找不到对应的外部id.商品id: %s', item.id)
            continue

        if item.distributor_shop_id in (options.shop_id_taobao, options.shop_id_tmall):
            if not item.taobao_api_info:
                logging.error('商品没有对应的taobao_api_info.商品id: %s', item.id)
                continue

            app_info = json.loads(item.taobao_api_info, object_hook=json_hook)
            # 获取店铺类型
            request = Taobao('taobao.item.quantity.update')
            request.set_app_info(app_info.app_key, app_info.app_secret_key)
            request.set_session(app_info.session)

            args = {
                'num_iid': item.distributor_goods_id,
                'quantity': item.stock,
                'type': 1
            }
            response = yield request(**args)
            request.parse_response(response.body)

            if request.is_ok():
                logging.info('商品id: %s在 %s上更新库存成功,更新为%s', item.id,
                             {options.shop_id_tmall: '天猫', options.shop_id_taobao: '淘宝'}.get(item.distributor_shop_id),
                             item.stock)
            else:
                logging.info('商品id: %s在 %s上更新库存失败', item.id,
                             {options.shop_id_tmall: '天猫', options.shop_id_taobao: '淘宝'}.get(item.distributor_shop_id))

        elif item.distributor_id == options.distributor_id_jingdong:
            args = {
                'vender_team_id': item.goods_link_id,
                'jd_team_id': item.distributor_goods_id,
                'max_number': item.stock
            }

            shop = db.get('select taobao_seller_id, taobao_api_info from distributor_shop where id=%s',
                          item.distributor_shop_id)
            api_info = json.loads(shop.taobao_api_info, object_hook=json_hook)

            jd_push = Jingdong('updateMaxNumber', str(shop.taobao_seller_id), api_info.vender_key, api_info.secret_key)

            response = yield jd_push.fetch(**args)
            jd_push.parse_response(response.body)

            if jd_push.is_ok():
                logging.info('商品id: %s在京东上更新库存成功,更新为%s', item.id, item.stock)
            else:
                logging.info('商品id: %s在京东上更新库存失败', item.id)

        elif item.distributor_shop_id == options.shop_id_wuba:
            args = {
                'groupbuyId': item.goods_link_id,
                'num': item.stock
            }

            wuba = Wuba('changeinventory')
            response = yield wuba.fetch(**args)
            wuba.parse_response(response.body)

            if wuba.is_ok():
                logging.info('商品id: %s在58上更新库存成功,更新为%s', item.id, item.stock)
            else:
                logging.info('商品id: %s在58上更新库存失败', item.id)

        else:
            pass
Example #4
0
    def post(self):
        form = Form(self.request.arguments, list_schema)

        start = form.start_date.value
        end = form.end_date.value
        if not start or not end:
            self.render('finance/statement.html', form=form, error='请输入查询日期')
            return
        start_date = datetime.strptime(start, '%Y-%m-%d')
        end_date = datetime.strptime(end, '%Y-%m-%d')
        durations = (end_date - start_date).days
        if durations > 60:
            self.render('finance/statement.html',
                        form=form,
                        error='最大支持60天查询,建议缩小查询区间,提高数据生成速度')
            return

        result = []
        goods_link_ids = []
        # 包含首尾
        for i in range(durations + 1):
            attempts = 0
            # 一个请求重试3次
            while attempts < 3:
                wb = Wuba('queryjiesuan')
                d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d')
                request_params = {'jiesuantime': d}
                response = yield wb(**request_params)
                wb.parse_response(response.body)
                if wb.is_ok():
                    if wb.message.data.jiesuanDetails:
                        for item in wb.message.data.jiesuanDetails:
                            item.update({'jiesuandate': d})
                            result.append(item)
                            goods_link_ids.append(str(item.get('groupid3')))
                    break
                else:
                    attempts += 1
                if attempts == 3:
                    result.append({
                        'jiesuandate': d,
                        'orderid58': '当日查询结果异常,建议单独重新查询',
                        'groupprice': '',
                        'commission': '',
                        'jiesuanmoney': '',
                        'usetime': ''
                    })
        if result and goods_link_ids:
            # 下载
            title = [
                u'结算日期', u'外部订单号', u'验证/发货日期', u'商品名称', u'业务发生金额', u'佣金',
                u'实际结算金额'
            ]
            self.set_header('Content-type', 'application/excel')
            self.set_header(
                'Content-Disposition', u'attachment; filename=' + u'58对账单' +
                start + u'到' + end + u'.xls')
            wuba_excel = Workbook(encoding='utf-8')
            write_wuba_excel = wuba_excel.add_sheet('0')

            for index, content in enumerate(title):
                write_wuba_excel.write(0, index, content)

            range_list = [
                'jiesuandate', 'orderid58', 'usetime', 'goods_name',
                'groupprice', 'commission', 'jiesuanmoney'
            ]
            goods_names = self.db.query(
                'select goods_link_id glid, short_name name '
                'from goods g, goods_distributor_shop gds '
                'where g.id=gds.goods_id and gds.goods_link_id in '
                '(' + ','.join(set(goods_link_ids)) + ')')

            name_dict = PropDict([(i.glid, i.name) for i in goods_names])

            for i, item in enumerate(result):
                for j, content in enumerate(range_list):
                    v = item.get(content, '')
                    v = v if v else ''
                    if content == 'usetime':
                        v = str(v)
                    elif content == 'commission':
                        if not v:
                            v = 0
                    elif content == 'orderid58':
                        v = str(v)
                    elif content == 'goods_name':
                        v = name_dict.get(item.get('groupid3'))

                    write_wuba_excel.write(i + 1, j, v)

            stream = StringIO.StringIO()
            wuba_excel.save(stream)
            self.write(stream.getvalue())
        else:
            self.render('finance/statement.html', form=form, error='该期间没有结算数据')
Example #5
0
    def post(self):
        """编辑团购和商户信息"""
        product_id = self.get_argument('product_id')
        product = self.db.get('select * from goods_distributor_shop where id = %s', product_id)
        params = dict([(name, self.get_argument(name).encode('utf-8')) for name in self.request.arguments])

        params.pop("product_id")
        params.pop("method")
        params.pop("_xsrf")
        method = self.get_argument("method")

        if 'endTime' in self.request.arguments:
            end_time = params['endTime']
        request_params = getattr(self, method)(params, str(product.goods_link_id))
        wb = Wuba(method)
        response = yield wb.fetch(**request_params)
        wb.parse_response(response.body)

        if wb.is_ok():
            #券延期成功之后再延期团购结束日期
            if method == 'delay':
                params.pop("deadline")
                request_params = {'groupbuyId': product.goods_link_id, 'endTime': end_time}
                wb = Wuba('editgroupbuyinfo')
                response = yield wb.fetch(**request_params)
                wb.parse_response(response.body)
                if wb.is_ok():
                    logging.info("延长团购结束日期成功!商品ID=%s", product_id)

            self.render('goods/distributor/wuba/result.html', ok=True, title='编辑成功',
                        explain='<a href="/goods/distributor?shop_id=%s">继续上传58商品</a>' % options.shop_id_wuba)
        else:
            self.render('goods/distributor/wuba/result.html', ok=False, title='修改出错', explain=wb.message.msg)