示例#1
0
    def post(self, sp_id):
        params = PropDict([(name, self.get_argument(name).encode('utf-8'))
                           for name in self.request.arguments])
        token = hashlib.md5(options.cookie_secret + sp_id).hexdigest()
        if not verify_wx_request(params, token):
            logging.info('weixin msg verification failed')
            return
        else:
            logging.info('weixin request body: %s',
                         self.request.body.replace('\n', ''))
            body = ET.fromstring(self.request.body)
            msg_type = body.findtext('./MsgType')
            sent_from = body.findtext('./FromUserName')
            mem = self.db.get(
                'select * from member where wx_id=%s and sp_id=%s', sent_from,
                sp_id)
            if not mem:
                # 用户不存在,创建
                mem_id = create_member(self.db, sp_id, sent_from)
                mem = self.db.get('select * from member where id=%s', mem_id)
            properties = self.db.query(
                'select * from supplier_property where sp_id=%s', sp_id)
            sp_props = PropDict([(i.name, i.value) for i in properties])

            # 根据对应的消息类型处理消息
            getattr(self, msg_type)(sp_id, body, mem, sp_props)
示例#2
0
 def get(self):
     sp_id = self.current_user.supplier_id
     cover = self.db.get(
         'select * from supplier_property where sp_id=%s and name="wx_site_cover"',
         sp_id)
     if cover:
         cover = json.loads(cover.value, object_hook=json_hook)
         cover = PropDict(cover)
     else:
         cover = PropDict()
     self.render('wx/site/cover_edit.html', cover=cover, img_url=img_url)
示例#3
0
def refund_coupon(db, coupon_sn, operator, remark):
    """
    退款操作
    无论成功与否,都返回Dict: 如{"ok":False, "coupon_sn": 12341234, "msg":"券号不存在" }
    :param db:torndb.Connection
    :param coupon_sn:str
    :param operator:str
    :param remark:str
    :return: Dict
    """

    coupon = db.get(
        'select *, c.id as cid from item i, item_coupon c where c.sn=%s and i.id=c.item_id',
        coupon_sn)
    # 检查券号是否存在
    if not coupon:
        return PropDict({'ok': False, 'coupon_sn': coupon_sn, 'msg': '券号不存在'})
    # 不是未消费不能退款
    if not const.status.BUY == coupon.status:
        return PropDict({
            'ok': False,
            'coupon_sn': coupon_sn,
            'msg': '券已消费或已退款'
        })
    goods = db.get('select * from goods where id=%s', coupon.goods_id)
    # 导入券不能退款
    if 'IMPORT' == goods.generate_type:
        return PropDict({
            'ok': False,
            'coupon_sn': coupon_sn,
            'msg': '导入券不能退款'
        })

    # 更新券状态
    db.execute(
        'update item i join item_coupon c set i.refund_value=%s, i.refund_at=NOW(), '
        'status=3 where i.id=c.item_id and c.sn=%s', coupon.payment,
        coupon_sn.encode('utf-8'))
    # 更新库存
    db.execute(
        'update goods set sales_count=sales_count-1, stock=stock+1 where id=%s',
        goods.id)
    # 记录日志
    db.execute(
        'insert into journal (created_at, type, created_by, message, iid)'
        'values (NOW(), 2, %s, %s, %s)', operator,
        '券 %s 未消费退款,理由:%s' % (coupon_sn, remark), coupon.cid)

    logging.info('券 %s 未消费退款成功,理由:%s, 对应商品:%s' %
                 (coupon_sn, remark, goods.short_name))
    return PropDict({'ok': True, 'coupon_sn': coupon_sn, 'msg': '退款成功'})
示例#4
0
 def get(self, sp_id):
     params = PropDict([(name, self.get_argument(name).encode('utf-8'))
                        for name in self.request.arguments])
     logging.info('Weixin heartbeat request: %s', json_dumps(params))
     token = hashlib.md5(options.cookie_secret + sp_id).hexdigest()
     if verify_wx_request(params, token):
         self.write(params.echostr)
示例#5
0
    def post(self):
        params = PropDict([
            (name,
             self.request.arguments[name][0].decode('GBK').encode('utf-8'))
            for name in self.request.arguments
        ])
        logging.info('taobao coupon order request: %s', json_dumps(params))
        seller_id = params.taobao_sid

        shop = self.db.get(
            'select * from distributor_shop where deleted =0 and taobao_seller_id=%s',
            seller_id)
        if not shop:
            logging.error('distributor_shop not found. seller_id:%s',
                          seller_id)
            return self.write('{"code":501}')
        shop.taobao_api_info = json.loads(shop.taobao_api_info,
                                          object_hook=json_hook)

        if coupon_sign_params(
                params, shop.taobao_api_info.coupon_service_key.encode(
                    'utf-8')) != params.sign:
            logging.error(
                'taobao sign failed: %s %s',
                coupon_sign_params(
                    params,
                    shop.taobao_api_info.coupon_service_key.encode('utf-8')),
                params.sign)
            return self.write('{"code":502}')

        order = self.db.get(
            'select * from distributor_order where distributor_shop_id=%s and order_no=%s',
            shop.id, params.order_id)

        getattr(self, params.method)(params, order)
示例#6
0
 def find_order_info(self):
     for key in self.params.goods_keys:
         if self.message.data.dealtitle.encode('utf-8').find(key) >= 0:
             return PropDict(goods_id=self.params.goods_keys[key],
                             coupon_sn=str(self.message.data.code),
                             distributor_shop_id=self.params.distributor_shop_id)
     return None
示例#7
0
def cal_money(db, agent_id, start_day, end_day):
    sale_info = db.query(
        """
        select count(1) `count`, sum(amount) amount
        from external_money em, supplier s
        where em.uid=s.id and em.type=1 and em.source=3
        and s.agent_id=%s and em.created_at >=%s and em.created_at < %s
    """, agent_id, start_day, end_day)

    if sale_info.count < 50:
        price = 2880
    elif sale_info.count < 100:
        price = 2580
    else:
        price = 1980

    result = PropDict({
        'price':
        price,
        'count':
        sale_info.count,
        'base_amount':
        Decimal(BASE_PRICE - price) * sale_info.count,
        'premium_amount':
        max(sale_info.amount - Decimal(BASE_PRICE) * sale_info.count,
            Decimal(0)),
        'month_info':
        start_day.strftime('%Y年%m月')
    })
    result['total_amount'] = result[
        'base_amount'] + result['premium_amount'] * Decimal('0.7')
    return result
示例#8
0
 def is_ok(self):
     if self.method == 'verify':
         ok = self.message.data.isSuccess
         if not ok:
             self.error = PropDict(
                 coupon_sn=mix_str(self.message.data.siteCode),
                 msg=mix_str(self.message.data.message).replace('糯米', ''))
         return ok
示例#9
0
 def get(self):
     user = self.current_user
     if 'wx_mem_cover' in user.sp_props:
         cover = json.loads(user.sp_props.wx_mem_cover,
                            object_hook=json_hook)
     else:
         cover = PropDict()
     self.render('wx/member/cover_edit.html', cover=cover, img_url=img_url)
示例#10
0
 def is_ok(self):
     if self.method == 'verify':
         ok = self.message.status == 1
         if not ok:
             self.error = PropDict(
                 coupon_sn=mix_str(self.message.data.code),
                 msg=(mix_str(self.message.data.errmsg))
             )
         return ok
示例#11
0
def order_status(tid, app_info):
    order_status = Taobao('taobao.trade.get')
    order_status.set_app_info(app_info.app_key, app_info.app_secret_key)
    order_status.set_session(app_info.session)
    response = yield order_status(tid=tid, fields='status')
    logging.info("response.body:%s", response.body)
    order_status.parse_response(response.body)
    if order_status.is_ok():
        logging.info('order_status.message.trade.status :%s,%s',
                     order_status.message.trade.status)
        if order_status.message.trade.status == 'WAIT_SELLER_SEND_GOODS':
            raise tornado.gen.Return(PropDict(ok=True, status='SEND'))
        elif order_status.message.trade.status == 'TRADE_CLOSED':
            raise tornado.gen.Return(PropDict(ok=False, status='REFUND'))
        else:
            raise tornado.gen.Return(PropDict(ok=False, status='OTHER'))
    else:
        raise tornado.gen.Return(PropDict(ok=False, status='OTHER'))
示例#12
0
    def get(self):
        cover = self.db.get('select * from supplier_property where name = "wx_mall_cover" and sp_id = %s',
                            self.current_user.supplier_id)
        if cover:
            cover = json.loads(cover.value, object_hook=json_hook)
        else:
            cover = PropDict()

        self.render('wx/mall/cover.html', cover=cover, img_url=img_url)
示例#13
0
 def find_order_info(self):
     logging.info('nuomi self.message: %s', self.message)
     for key in self.params.goods_keys:
         if self.message.data.dealName.encode('utf-8').find(key) >= 0:
             return PropDict(
                 goods_id=self.params.goods_keys[key],
                 coupon_sn=mix_str(self.message.data.siteCode),
                 distributor_shop_id=self.params.distributor_shop_id)
     return None
示例#14
0
 def is_ok(self):
     if self.method == 'verify':
         result = self.message.msg.serialNumList
         for i in result:
             if i.result.code != 200:
                 self.error.append(
                     PropDict(coupon_sn=mix_str(i.serialNum),
                              msg=mix_str(i.result.msg.message)))
         return any([i.result.code == 200 for i in result])
示例#15
0
def local_check(db, coupon_sn, shop_id):
    """
    :type db torndb.Connection
    """
    coupon = db.get(
        'select i.sp_id, i.status, c.expire_at, c.mobile, g.all_shop, i.goods_id from item i, '
        'item_coupon c,goods g where c.sn=%s and i.id=c.item_id and g.id=i.goods_id ',
        coupon_sn)
    if not coupon:
        return PropDict(ok=False, coupon_sn=coupon_sn, msg='券号不存在')

    shop = db.get('select s.* from supplier_shop s where id=%s', shop_id)

    if coupon.sp_id != shop.supplier_id:
        return PropDict(ok=False, coupon_sn=coupon_sn, msg='券号不存在')
    if coupon.status != const.status.BUY:
        return PropDict(ok=False, coupon_sn=coupon_sn, msg='该券已使用或已退款')
    if coupon.expire_at < datetime.now():
        return PropDict(ok=False, coupon_sn=coupon_sn, msg='该券已过期')
    #检查是不是属于该店的券
    #全部店铺直接验证,指定门店则判断是否和选择的门店是否一致
    if coupon.all_shop == '0':
        shops = db.query(
            'select gss.supplier_shop_id id from goods_supplier_shop gss,goods g '
            'where g.id=gss.goods_id and g.id=%s', coupon.goods_id)
        if int(shop_id) not in [i.id for i in shops]:
            return PropDict(ok=False, coupon_sn=coupon_sn, msg='该券不能在此门店使用!')

    return PropDict(ok=True, coupon_sn=coupon_sn, coupon=coupon)
示例#16
0
def local_verify(db, coupon_sn, shop_id, operator, verified_at=None):
    if not verified_at:
        verified_at = datetime.now()

    coupon = db.get(
        'select i.*, c.*, i.id as iid, c.id as cid '
        'from item i, item_coupon c where c.sn=%s and i.id=c.item_id',
        coupon_sn)
    if not coupon:
        return PropDict(ok=False, coupon_sn=coupon_sn, msg='券号不存在')

    shop = db.get('select * from supplier_shop where id=%s', shop_id)

    db.execute(
        'update item set status=2, used_at=%s, sp_shop_id=%s '
        'where id=%s', verified_at, shop_id, coupon.iid)

    # 查找商户及门店的账户
    supplier_shop_account_id = db.get(
        'select account_id from supplier_shop where id=%s', shop_id).account_id

    # 记录商户门店账务明细
    remark = '券消费:%s, 验证门店:%s, 商品:%s, 售价:%s, 付款:%s' \
             % (coupon_sn.encode('utf-8'), shop.name, coupon.goods_name, coupon.sales_price, coupon.payment)
    db.execute(
        'insert into account_sequence(type, account_id, item_id, amount, remark, created_at, status, '
        'trade_type, trade_id) values (%s, %s, %s, %s, %s, %s, 1, 1, %s)',
        const.seq.USED, supplier_shop_account_id, coupon.iid,
        coupon.purchase_price, remark, verified_at, coupon.order_id)

    # 记录日志
    db.execute(
        'insert into journal (created_at, type, created_by, message, iid) values (%s, 2, %s, %s, %s)',
        verified_at, operator, remark, coupon.cid)
    return PropDict(ok=True,
                    coupon_sn=coupon_sn,
                    shop_name=shop.name,
                    msg='验证成功')
示例#17
0
 def current_user(self):
     uid = self.get_secure_cookie('_spu')
     if uid and uid.isdigit():
         user = self.db.get(
             'select su.*, s.short_name supplier_short_name, s.properties sp_properties, '
             's.account_id sp_account_id, s.separate_account '
             'from supplier_user su,supplier s where su.supplier_id = s.id and su.id = %s '
             'and su.deleted = 0', uid)
         sp_props = self.db.query(
             'select * from supplier_property where sp_id=%s',
             user.supplier_id)
         user['sp_props'] = PropDict([(sp_prop.name, sp_prop.value)
                                      for sp_prop in sp_props])
         return user
示例#18
0
 def find_order_info(self):
     results = []
     for i in self.message.msg.serialNumList:
         # 只有code 是200 的才有receiptList
         if i.result.code == 200:
             for receipt in i.result.msg.receiptList:
                 for key in self.params.goods_keys:
                     if receipt.dealSMSName.encode('utf-8').find(key) >= 0:
                         results.append(
                             PropDict(goods_id=self.params.goods_keys[key],
                                      coupon_sn=receipt.serialNum.replace(
                                          ' ', ''),
                                      distributor_shop_id=self.params.
                                      distributor_shop_id))
     return results
示例#19
0
 def __init__(self, arguments, schema):
     self.arguments = PropDict()
     self.errors = {}
     self.schema = schema
     for name in schema.schema:
         key = str(name)
         if key in arguments:
             value = arguments[key][0] if type(
                 arguments[key]) == list else arguments[key]
             self.arguments[key] = EmptyDict({'value': value})
         elif (key + '[]') in arguments:
             self.arguments[key] = EmptyDict(
                 {'value': arguments[key + '[]']})
         else:
             self.arguments[key] = EmptyDict()
示例#20
0
    def get(self, mem_id):
        sp_id = self.current_user.supplier_id
        mem = self.db.get('select * from member where sp_id=%s and id=%s', sp_id, mem_id)
        if not mem:
            self.redirect(self.reverse_url('member.list'))
            return
        # 查询消费订单记录
        page = PropDict({'rows': []})
        if mem.mobile:
            # todo 考虑不给商家看未消费的
            sql = """select i.*, ss.name sname, ds.name dname
            from item i, orders o, supplier_shop ss, distributor_shop ds
            where  o.mobile=%s and i.order_id=o.id and i.sp_shop_id=ss.id and i.distr_shop_id=ds.id and i.status=2
            order by i.used_at desc"""
            page = Paginator(self, sql, [mem.mobile])

        self.render('wx/member/detail.html', page=page, mem=mem)
示例#21
0
    def get(self):
        goods_id = self.get_argument('goods_id')
        category_id = self.get_argument('category_id')

        # 首先查询品牌和该分类下的所有额外属性
        brands_request = Yihaodian('yhd.category.brands.get')
        attribute_request = Yihaodian('yhd.category.attribute.get')
        brands_response, attribute_response = yield [
            brands_request(),
            attribute_request(categoryId=category_id)
        ]
        brands_request.parse_response(brands_response.body)
        attribute_request.parse_response(attribute_response.body)

        brands = [
            PropDict({
                'brandId': brand.findtext('./brandId'),
                'brandName': brand.findtext('./brandName')
            }) for brand in brands_request.message.findall(
                './brandInfoList/brandInfo')
        ]

        if attribute_request.is_ok():
            attributes = attribute_request.message.findall(
                './categoryAttributeInfoList/categoryAttributeInfo')
        else:
            attributes = []

        goods = self.db.get('select * from goods where id=%s', goods_id)

        goods_shops = self.db.query(
            'select ss.* from supplier_shop ss,goods g where ss.supplier_id=g.supplier_id and g.id=%s and ss.deleted=0 '
            'and (g.all_shop=1 or ss.id in (select supplier_shop_id from goods_supplier_shop where goods_id=%s))',
            goods_id, goods_id)

        self.render('goods/distributor/yihaodian/push.html',
                    category_id=category_id,
                    category_name=self.get_argument('category_name'),
                    brands=brands,
                    attributes=attributes,
                    goods=goods,
                    goods_shops=goods_shops)
示例#22
0
    def get(self):
        """销售业绩"""
        form = Form(self.request.arguments, list_schema)
        op_id = form.operator_id.value
        start = form.start_date.value
        end = form.end_date.value
        download = form.action.value if form.action.value else 'show'

        if not form.validate():
            return self.render('finance/profit.html',
                               form=form,
                               page=[],
                               name='输入正确参数查询',
                               total='',
                               amount='',
                               sale_amount='',
                               sum_commission='')

        operator = self.db.get('select * from operator where id=%s', op_id)
        if not operator:
            return self.render('finance/profit.html',
                               form=form,
                               page=[],
                               name='销售人员不存在',
                               total='',
                               amount='',
                               sale_amount='',
                               sum_commission='')

        sql = ''
        sum_sql = ''
        kind = ''
        kind0 = ''
        kind1 = ''
        sale_amount = 0
        params = [op_id]
        # 统计消费(验证)明细(不包含刷单)
        if form.kind.value == 1:
            sql = 'select goods_name, used_at as time, sales_price, purchase_price, payment as amount, ' \
                  '(payment-purchase_price) as profit, commission, order_no, order_id, distr_shop_id from item where sales_id=%s ' \
                  'and used_at is not null and cheat_at is null and status=2 '
            sum_sql = 'select sum(payment) amount, sum(commission) commission, sum(payment-purchase_price) as total ' \
                      'from item where sales_id=%s and used_at is not null and cheat_at is null and status=2 '
            sale_sql = 'select sum(payment) amount from item where sales_id=%s and created_at is not null '
            kind = '-消费利润汇总:'
            kind0 = '消费总金额:'
            kind1 = '渠道佣金:'

            if start:
                sql += 'and cast(used_at as Date)>=%s '
                sum_sql += 'and cast(used_at as Date)>=%s '
                sale_sql += 'and cast(created_at as Date)>=%s '
                params.append(start)
            if end:
                sql += 'and cast(used_at as Date)<=%s '
                sum_sql += 'and cast(used_at as Date)<=%s '
                sale_sql += 'and cast(created_at as Date)<=%s '
                params.append(end)
            sql += 'order by used_at desc'
            sale_amount = self.db.get(sale_sql, *params).amount
            sale_amount = (',销售总金额:' + str(sale_amount)) if sale_amount else ''
        # 统计"已消费"退款明细
        if form.kind.value == 2:
            sql = 'select goods_name, refund_at as time, sales_price, purchase_price, refund_value as amount, ' \
                  '(purchase_price-refund_value) as profit, commission, order_no, order_id, distr_shop_id from item where sales_id=%s ' \
                  'and refund_at is not null and used_at is not null '
            sum_sql = 'select sum(refund_value) amount,sum(commission) commission,sum(purchase_price-refund_value) as total ' \
                      'from item where sales_id=%s and refund_at is not null and used_at is not null '
            kind = '-已消费退款负利润汇总:'
            kind0 = '退款总金额:'
            kind1 = '渠道佣金:'

            if start:
                sql += 'and cast(refund_at as Date)>=%s '
                sum_sql += 'and cast(refund_at as Date)>=%s '
                params.append(start)
            if end:
                sql += 'and cast(refund_at as Date)<=%s '
                sum_sql += 'and cast(refund_at as Date)<=%s '
                params.append(end)
            sql += 'order by refund_at desc'
        # 统计刷单明细
        if form.kind.value == 3:
            sql = 'select goods_name, cheat_at as time, sales_price, purchase_price, sales_price as amount, ' \
                  '(cheat_value-purchase_price) as profit, commission, order_no, order_id, distr_shop_id from item where sales_id=%s ' \
                  'and cheat_at is not null '
            sum_sql = 'select sum(sales_price) amount,sum(commission) commission,sum(cheat_value-purchase_price) total ' \
                      'from item where sales_id=%s and cheat_at is not null '
            kind = '-刷单利润(手续费)汇总:'
            kind0 = '刷单总金额:'
            kind1 = '刷单佣金:'

            if start:
                sql += 'and cast(cheat_at as Date)>=%s '
                sum_sql += 'and cast(cheat_at as Date)>=%s '
                params.append(start)
            if end:
                sql += 'and cast(cheat_at as Date)<=%s '
                sum_sql += 'and cast(cheat_at as Date)<=%s '
                params.append(end)
            sql += 'order by cheat_at desc'

        if download == 'download':
            distr_shops = self.db.query(
                'select id, name from distributor_shop')
            distr_shops = PropDict([(i.id, i.name) for i in distr_shops])
            page = self.db.query(sql, *params)
            title = [
                u'交易时间', u'订单号', u'渠道', u'商品名称', u'售价', u'进价', u'实际金额', u'利润',
                u'佣金'
            ]
            self.set_header('Content-type', 'application/excel')
            self.set_header(
                'Content-Disposition', u'attachment; filename=' + u'销售业绩-' +
                operator.name.decode('utf-8') + u'.xls')
            order_excel = Workbook(encoding='utf-8')
            write_order_excel = order_excel.add_sheet('0')

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

            range_list = [
                'time', 'order_no', 'distr_shop_id', 'goods_name',
                'sales_price', 'purchase_price', 'amount', 'profit',
                'commission'
            ]

            for i, item in enumerate(page):
                for j, content in enumerate(range_list):
                    v = item.get(content, '')
                    v = v if v else 0
                    if content == 'time':
                        v = str(v)
                    if content == 'distr_shop_id':
                        v = distr_shops.get(item.get(content))
                    write_order_excel.write(i + 1, j, v)

            stream = StringIO.StringIO()
            order_excel.save(stream)
            self.write(stream.getvalue())
        else:
            page = Paginator(self, sql, params)
            summary = self.db.get(sum_sql, *params)
            sum_total = summary.total if summary.total else '0'
            sum_commission = summary.commission if summary.commission else '0'
            self.render("finance/profit.html",
                        form=form,
                        page=page,
                        name=operator.name,
                        total=kind + str(sum_total),
                        amount=kind0 + str(summary.amount),
                        sale_amount=sale_amount,
                        sum_commission=kind1 + str(sum_commission))
示例#23
0
# -*- coding: utf-8 -*-
from autumn.utils import PropDict

# account sequence type
seq = PropDict({
    'USED': 1,  # 券验证,实物发货(利润)
    'REFUND': 2,  # 退款
    'CHEAT_ORDER': 3,  # 刷单
    'PRE_PAYMENT': 4,  # 预付款
    'DEPOSIT': 5,  # 保证金
    'WX': 6  # 微信服务费
})

# item status type
status = PropDict({
    'BUY': 1,  # 购买(电子券未消费/实物未发货)
    'USED': 2,  # 电子券已消费/实物已发货
    'REFUND': 3,  # 退款/退货
    'WAIT_TO_SEND': 4,  # 实物待打包,待发货
    'UPLOADED': 5,  # 已上传
    'FROZEN': 6,  # 冻结
    'RETURNING': 7,  # 退货中
})
示例#24
0
    def get(self):
        """销售业绩"""
        form = Form(self.request.arguments, list_schema)
        op_id = form.operator_id.value
        start = form.start_date.value
        end = form.end_date.value
        download = form.action.value if form.action.value else 'show'

        if not form.validate():
            return self.render('finance/profit.html', form=form, page=[], name='输入正确参数查询', total='', amount='',
                               sale_amount='', sum_commission='')

        operator = self.db.get('select * from operator where id=%s', op_id)
        if not operator:
            return self.render('finance/profit.html', form=form, page=[], name='销售人员不存在', total='', amount='',
                               sale_amount='', sum_commission='')

        sql = ''
        sum_sql = ''
        kind = ''
        kind0 = ''
        kind1 = ''
        sale_amount = 0
        params = [op_id]
        # 统计消费(验证)明细(不包含刷单)
        if form.kind.value == 1:
            sql = 'select goods_name, used_at as time, sales_price, purchase_price, payment as amount, ' \
                  '(payment-purchase_price) as profit, commission, order_no, order_id, distr_shop_id from item where sales_id=%s ' \
                  'and used_at is not null and cheat_at is null and status=2 '
            sum_sql = 'select sum(payment) amount, sum(commission) commission, sum(payment-purchase_price) as total ' \
                      'from item where sales_id=%s and used_at is not null and cheat_at is null and status=2 '
            sale_sql = 'select sum(payment) amount from item where sales_id=%s and created_at is not null '
            kind = '-消费利润汇总:'
            kind0 = '消费总金额:'
            kind1 = '渠道佣金:'

            if start:
                sql += 'and cast(used_at as Date)>=%s '
                sum_sql += 'and cast(used_at as Date)>=%s '
                sale_sql += 'and cast(created_at as Date)>=%s '
                params.append(start)
            if end:
                sql += 'and cast(used_at as Date)<=%s '
                sum_sql += 'and cast(used_at as Date)<=%s '
                sale_sql += 'and cast(created_at as Date)<=%s '
                params.append(end)
            sql += 'order by used_at desc'
            sale_amount = self.db.get(sale_sql, *params).amount
            sale_amount = (',销售总金额:' + str(sale_amount)) if sale_amount else ''
        # 统计"已消费"退款明细
        if form.kind.value == 2:
            sql = 'select goods_name, refund_at as time, sales_price, purchase_price, refund_value as amount, ' \
                  '(purchase_price-refund_value) as profit, commission, order_no, order_id, distr_shop_id from item where sales_id=%s ' \
                  'and refund_at is not null and used_at is not null '
            sum_sql = 'select sum(refund_value) amount,sum(commission) commission,sum(purchase_price-refund_value) as total ' \
                      'from item where sales_id=%s and refund_at is not null and used_at is not null '
            kind = '-已消费退款负利润汇总:'
            kind0 = '退款总金额:'
            kind1 = '渠道佣金:'

            if start:
                sql += 'and cast(refund_at as Date)>=%s '
                sum_sql += 'and cast(refund_at as Date)>=%s '
                params.append(start)
            if end:
                sql += 'and cast(refund_at as Date)<=%s '
                sum_sql += 'and cast(refund_at as Date)<=%s '
                params.append(end)
            sql += 'order by refund_at desc'
        # 统计刷单明细
        if form.kind.value == 3:
            sql = 'select goods_name, cheat_at as time, sales_price, purchase_price, sales_price as amount, ' \
                  '(cheat_value-purchase_price) as profit, commission, order_no, order_id, distr_shop_id from item where sales_id=%s ' \
                  'and cheat_at is not null '
            sum_sql = 'select sum(sales_price) amount,sum(commission) commission,sum(cheat_value-purchase_price) total ' \
                      'from item where sales_id=%s and cheat_at is not null '
            kind = '-刷单利润(手续费)汇总:'
            kind0 = '刷单总金额:'
            kind1 = '刷单佣金:'

            if start:
                sql += 'and cast(cheat_at as Date)>=%s '
                sum_sql += 'and cast(cheat_at as Date)>=%s '
                params.append(start)
            if end:
                sql += 'and cast(cheat_at as Date)<=%s '
                sum_sql += 'and cast(cheat_at as Date)<=%s '
                params.append(end)
            sql += 'order by cheat_at desc'

        if download == 'download':
            distr_shops = self.db.query('select id, name from distributor_shop')
            distr_shops = PropDict([(i.id, i.name) for i in distr_shops])
            page = self.db.query(sql, *params)
            title = [u'交易时间', u'订单号', u'渠道', u'商品名称', u'售价', u'进价', u'实际金额', u'利润', u'佣金']
            self.set_header('Content-type', 'application/excel')
            self.set_header('Content-Disposition', u'attachment; filename=' +
                                                   u'销售业绩-'+operator.name.decode('utf-8')+u'.xls')
            order_excel = Workbook(encoding='utf-8')
            write_order_excel = order_excel.add_sheet('0')

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

            range_list = ['time', 'order_no', 'distr_shop_id', 'goods_name', 'sales_price', 'purchase_price', 'amount',
                          'profit', 'commission']

            for i, item in enumerate(page):
                for j, content in enumerate(range_list):
                    v = item.get(content, '')
                    v = v if v else 0
                    if content == 'time':
                        v = str(v)
                    if content == 'distr_shop_id':
                        v = distr_shops.get(item.get(content))
                    write_order_excel.write(i + 1, j, v)

            stream = StringIO.StringIO()
            order_excel.save(stream)
            self.write(stream.getvalue())
        else:
            page = Paginator(self, sql, params)
            summary = self.db.get(sum_sql, *params)
            sum_total = summary.total if summary.total else '0'
            sum_commission = summary.commission if summary.commission else '0'
            self.render("finance/profit.html", form=form, page=page, name=operator.name, total=kind + str(sum_total),
                        amount=kind0 + str(summary.amount), sale_amount=sale_amount,
                        sum_commission=kind1 + str(sum_commission))
示例#25
0
 def __init__(self, method, params):
     super(MeituanBrowser, self).__init__()
     self.method = method
     self.params = params
     self.error = PropDict()
示例#26
0
    def event(self, sp_id, msg, mem, sp_props):
        msg_time = datetime.fromtimestamp(int(msg.findtext('./CreateTime')))
        event = msg.findtext('./Event').lower()
        wx_id = mem.wx_id
        # 取消订阅,更新数据库
        if event == 'unsubscribe':
            logging.info('user %s un-sub', wx_id)
            self.db.execute('update member set wx_unfollow_at=%s where id=%s',
                            msg_time, mem.id)  # 更新取消时间
            self.write('')  # 退订,什么都不返回
            return
        if event == 'subscribe':
            logging.info('user %s subscribe', wx_id)
            # 查是否存在用户
            if mem:
                # 如果是认证的服务号,去抓取一下用户信息
                if sp_props.wx_type == 'service' and sp_props.wx_verified == '1':
                    app_id = sp_props.app_id
                    app_secret = sp_props.app_secret
                    info = Weixin(method='user/info',
                                  db=self.db,
                                  sp_id=sp_id,
                                  body='')
                    info.set_app_info(app_id, app_secret)
                    response = info.sync_fetch(openid=wx_id, lang='zh_CN')
                    info.parse_response(response)
                    if info.is_ok():
                        nickname = info.message.nickname
                        # 暂时数据库未升级至可以存储emoji字符,故使用以下代码,升级数据库后可删除
                        import re
                        try:
                            # UCS-4
                            highpoints = re.compile(u'[\U00010000-\U0010ffff]')
                        except re.error:
                            # UCS-2
                            highpoints = re.compile(
                                u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
                        nickname = highpoints.sub(u'', nickname)
                        sex = {0: '未知', 1: '男', 2: '女'}.get(info.message.sex)
                        follow_at = datetime.fromtimestamp(
                            info.message.subscribe_time)
                        head_img = info.message.headimgurl
                        self.db.execute(
                            'update member set wx_name = %s, gender = %s, last_active=NOW(), max_msg_id=0,'
                            'head_img = %s, wx_follow_at = %s, country = %s, province = %s, city = %s '
                            'where wx_id = %s and sp_id = %s', nickname, sex,
                            head_img, follow_at, info.message.country,
                            info.message.province, info.message.city, wx_id,
                            sp_id)
                        logging.info('user %s fetch info successfully', wx_id)
                    else:
                        self.db.execute(
                            'update member set wx_follow_at=%s, last_active=NOW(), '
                            'max_msg_id=0 where id=%s', msg_time, mem.id)
                        logging.info('user %s fetch info failed', wx_id)
                else:
                    self.db.execute(
                        'update member set wx_follow_at=%s, last_active=NOW(), '
                        'max_msg_id=0 where id=%s', msg_time, mem.id)

            # 推送新关注消息
            app_msg = self.db.get(
                'select wam.* '
                'from supplier_property sp join wx_app_msg wam on sp.value = wam.id '
                'where sp.sp_id = %s and name="wx_sub_msg" ', mem.sp_id)
            if app_msg:
                response = Template(wx_response['news']).generate(
                    to_user=mem.wx_id,
                    from_user=sp_props.wx_id,
                    time=int(time.time()),
                    items=[
                        PropDict(
                            title=app_msg.title,
                            description=app_msg.summary,
                            picurl=img_url(app_msg.cover),
                            url='http://%s.quanfx.com/app_msg/%s?wx_id=%s' %
                            (sp_id, app_msg.id, mem.wx_id))
                    ],
                )
                self.write(response)
                return
            else:
                self.write('')
                return
        if event == 'click':
            event_key = msg.findtext('./EventKey')
            action_type, action = event_key.split(':', 1)
            if action_type == 'website':
                cover = self.db.get(
                    'select * from supplier_property where sp_id=%s and name="wx_site_cover"',
                    sp_id)
                cover = json.loads(cover.value, object_hook=json_hook)
                response = Template(wx_response['news']).generate(
                    to_user=mem.wx_id,
                    from_user=sp_props.wx_id,
                    time=int(time.time()),
                    items=[
                        PropDict(title=cover.title,
                                 description=cover.desc,
                                 picurl=img_url(cover.pic),
                                 url='http://%s.quanfx.com/?wx_id=%s' %
                                 (sp_id, mem.wx_id))
                    ],
                )
                self.write(response)
                return
            elif action_type == 'app_msg':
                app_msg = self.db.get(
                    'select * from wx_app_msg where id=%s and deleted=0',
                    action)
                if app_msg:
                    response = Template(wx_response['news']).generate(
                        to_user=mem.wx_id,
                        from_user=sp_props.wx_id,
                        time=int(time.time()),
                        items=[
                            PropDict(
                                title=app_msg.title,
                                description=app_msg.summary,
                                picurl=img_url(app_msg.cover),
                                url='http://%s.quanfx.com/app_msg/%s?wx_id=%s'
                                % (sp_id, app_msg.id, mem.wx_id))
                        ],
                    )
                    self.write(response)
                    return
                else:
                    self.write('')
                    return
            elif action_type == 'app_msg_group':
                app_msg_group = self.db.get(
                    'select * from wx_app_msg_gp where deleted=0 and id=%s',
                    action)
                if app_msg_group:
                    app_msgs = self.db.query(
                        'select * from wx_app_msg where deleted=0 and id in ('
                        + app_msg_group.app_msgs + ')')
                    response = Template(wx_response['news']).generate(
                        to_user=mem.wx_id,
                        from_user=sp_props.wx_id,
                        time=int(time.time()),
                        items=[
                            PropDict(
                                title=app_msg.title,
                                description=app_msg.summary,
                                picurl=img_url(app_msg.cover),
                                url='http://%s.quanfx.com/app_msg/%s?wx_id=%s'
                                % (sp_id, app_msg.id, mem.wx_id))
                            for app_msg in app_msgs
                        ],
                    )
                    self.write(response)
                    return
                self.write('')
                return
            elif action_type == 'text':
                sms = self.db.get(
                    'select * from wx_menu where action like %s and sp_id = %s limit 1',
                    '%' + action + '%', sp_id)
                if sms:
                    response = Template(wx_response['text']).generate(
                        to_user=mem.wx_id,
                        from_user=sp_props.wx_id,
                        time=int(time.time()),
                        content=sms.action[12:])
                    self.write(response)
                    return
                self.write('')
                return
            elif action_type == 'member':
                # 取会员卡封面
                cover = self.db.get(
                    'select * from supplier_property where sp_id=%s and name="wx_mem_cover"',
                    sp_id)
                if not cover:
                    # 没有会员卡封面,取官网封面
                    cover = self.db.get(
                        'select * from supplier_property where sp_id=%s and name="wx_site_cover"',
                        sp_id)
                cover = json.loads(cover.value, object_hook=json_hook)
                response = Template(wx_response['news']).generate(
                    to_user=mem.wx_id,
                    from_user=sp_props.wx_id,
                    time=int(time.time()),
                    items=[
                        PropDict(title=cover.title,
                                 description=cover.desc,
                                 picurl=img_url(cover.pic),
                                 url='http://%s.quanfx.com/member?wx_id=%s' %
                                 (sp_id, mem.wx_id))
                    ],
                )
                self.write(response)
                return
            elif action_type == 'book':
                cover = self.db.get(
                    'select * from wx_booking_setting where sp_id=%s and id = %s',
                    sp_id, action)
                logging.info(cover)
                if cover:
                    info = json.loads(cover.info, object_hook=json_hook)
                    response = Template(wx_response['news']).generate(
                        to_user=mem.wx_id,
                        from_user=sp_props.wx_id,
                        time=int(time.time()),
                        items=[
                            PropDict(
                                title=info.title,
                                description=info.desc,
                                picurl=img_url(info.pic),
                                url='http://%s.quanfx.com/book/%s?wx_id=%s' %
                                (sp_id, cover.id, mem.wx_id))
                        ],
                    )
                    self.write(response)
                    return
                else:
                    self.write('')
                    return
            elif action_type == 'mall':
                cover = self.db.get(
                    'select * from supplier_property where sp_id=%s and name="wx_mall_cover"',
                    sp_id)
                if not cover:
                    # 没有商城封面,取官网封面
                    cover = self.db.get(
                        'select * from supplier_property where sp_id=%s and name="wx_site_cover"',
                        sp_id)
                cover = json.loads(cover.value, object_hook=json_hook)
                response = Template(wx_response['news']).generate(
                    to_user=mem.wx_id,
                    from_user=sp_props.wx_id,
                    time=int(time.time()),
                    items=[
                        PropDict(
                            title=cover.title,
                            description=cover.desc,
                            picurl=img_url(cover.pic),
                            url='http://%s.quanfx.com/mall/goods?wx_id=%s' %
                            (sp_id, mem.wx_id))
                    ],
                )
                self.write(response)
                return
            elif action_type == 'activity':
                cover = self.db.get(
                    'select * from supplier_property where sp_id = %s and name="wx_activity_cover"',
                    sp_id)
                if not cover:
                    # 没有商城封面,取官网封面
                    cover = self.db.get(
                        'select * from supplier_property where sp_id=%s and name="wx_site_cover"',
                        sp_id)
                cover = json.loads(cover.value, object_hook=json_hook)
                response = Template(wx_response['news']).generate(
                    to_user=mem.wx_id,
                    from_user=sp_props.wx_id,
                    time=int(time.time()),
                    items=[
                        PropDict(
                            title=cover.title,
                            description=cover.desc,
                            picurl=img_url(cover.pic),
                            url='http://%s.quanfx.com/activity/list?wx_id=%s' %
                            (sp_id, mem.wx_id))
                    ],
                )
                self.write(response)
                return
示例#27
0
    def text(self, sp_id, msg, mem, sp_props):
        """关键词应答"""
        content = msg.findtext('./Content')
        msg_time = datetime.fromtimestamp(int(msg.findtext('./CreateTime')))
        self.db.execute(
            'insert into wx_msg (created_at, sent_from, sent_to, content, wx_msg_id)'
            'values (%s, %s, %s, %s, %s)', msg_time, mem.id, sp_id, content,
            msg.findtext('./MsgId'))

        mapping = self.db.get(
            'select * from wx_keyword where sp_id = %s and deleted = 0 and key_type = 1 '
            'and keyword=%s order by id desc limit 1', sp_id, content)
        if not mapping:
            mapping = self.db.get(
                'select * from wx_keyword where sp_id = %s and deleted = 0 and key_type = 2 '
                'and keyword like %s order by id desc limit 1', sp_id,
                '%' + content + '%')
        if mapping:
            if mapping.response_type == 1:  # 文本
                response = Template(wx_response['text']).generate(
                    to_user=mem.wx_id,
                    from_user=sp_props.wx_id,
                    time=int(time.time()),
                    content=mapping.response,
                )
                self.write(response)
                return
            elif mapping.response_type == 2:  # 图文消息
                app_msg = self.db.get(
                    'select id, summary, title, cover from wx_app_msg where id=%s',
                    mapping.response)
                response = Template(wx_response['news']).generate(
                    to_user=mem.wx_id,
                    from_user=sp_props.wx_id,
                    time=int(time.time()),
                    items=[
                        PropDict(
                            title=app_msg.title,
                            description=app_msg.summary,
                            picurl=img_url(app_msg.cover),
                            url='http://%s.quanfx.com/app_msg/%s?wx_id=%s' %
                            (sp_id, app_msg.id, mem.wx_id))
                    ],
                )
                self.write(response)
                return
            elif mapping.response_type == 3:
                app_msg_group = self.db.get(
                    'select * from wx_app_msg_gp where deleted=0 and id=%s',
                    mapping.response)
                if app_msg_group:
                    app_msgs = self.db.query(
                        'select * from wx_app_msg where deleted=0 and id in ('
                        + app_msg_group.app_msgs + ')')
                    response = Template(wx_response['news']).generate(
                        to_user=mem.wx_id,
                        from_user=sp_props.wx_id,
                        time=int(time.time()),
                        items=[
                            PropDict(
                                title=app_msg.title,
                                description=app_msg.summary,
                                picurl=img_url(app_msg.cover),
                                url='http://%s.quanfx.com/app_msg/%s?wx_id=%s'
                                % (sp_id, app_msg.id, mem.wx_id))
                            for app_msg in app_msgs
                        ],
                    )
                    self.write(response)
                    return
                self.write('')
                return

        self.write('')
示例#28
0
    def get(self):
        form = Form(self.request.arguments, list_schema)
        if not form.summary_type.value:
            form.summary_type['value'] = 'goods_type'

        distr_shops = self.db.query(
            'select id, name from distributor_shop where deleted = 0 ')

        common_fields = """
            i.goods_name, i.goods_id,
            sum(case when i.created_at <=%s and i.created_at >=%s then 1 else 0 end) as sales_count,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.payment else 0 end) as sales_amount,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.purchase_price else 0 end) as cost,
            sum(case when i.created_at <=%s and i.created_at >=%s then i.payment-i.purchase_price else 0 end) as profit,
            sum(case when i.used_at <=%s and i.used_at >=%s then 1 else 0 end) as used,
            sum(case when i.used_at <=%s and i.used_at >=%s then i.payment else 0 end) as used_amount,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is not NULL then 1 else 0 end) as vrefund,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is not NULL then i.refund_value else 0 end) as vrefund_amount,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is NULL then 1 else 0 end) as refund,
            sum(case when i.refund_at <=%s and i.refund_at >=%s and used_at is NULL then i.refund_value else 0 end) as refund_amount,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then 1 else 0 end) as cheat,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then i.payment else 0 end) as cheat_amount,
            sum(case when i.cheat_at <=%s and i.cheat_at >=%s then i.cheat_value-i.purchase_price else 0 end) as cheat_profit
        """

        sql = ''
        sql_foot = ''
        if form.summary_type.value == 'goods_type':
            sql += 'select gc.name category_name, NULL as dsid, ' + common_fields
            sql += """ from item i, goods g, goods_category gct, goods_category gc
                    where i.goods_id = g.id and g.category_id=gct.id and gct.parent_id=gc.id
                  """
            sql_foot = 'group by i.goods_id order by gc.id '
        elif form.summary_type.value == 'distr_shop':
            sql += 'select ds.name distr_shop_name, ds.id dsid, ' + common_fields
            sql += """ from item i, distributor_shop ds where i.distr_shop_id=ds.id """
            sql_foot = 'group by ds.id, i.goods_id order by ds.id '

        sql += ' and (i.created_at <=%s and i.created_at >=%s or ' \
               ' i.used_at <=%s and i.used_at >=%s or ' \
               ' i.refund_at <=%s and i.refund_at >=%s or ' \
               ' i.cheat_at <=%s and i.cheat_at >=%s ) '

        params = []
        # 未指定截止日期,默认为今天
        if not form.end_date.value:
            end = ceiling(datetime.today(), today=True)
            form.end_date.value = end
        else:
            end = form.end_date.value
        # 未指定开始日期,默认为最近7天
        if not form.start_date.value:
            start = truncate(datetime.today() - timedelta(days=6))
            form.start_date.value = start
        else:
            start = form.start_date.value

        for i in range(17):
            params.append(end)
            params.append(start)

        # 指定商户
        if form.supplier.value:
            sql += ' and i.sp_id=%s '
            params.append(form.supplier.value)

        sql += sql_foot

        if form.action.value == 'download':
            distr_shops = self.db.query(
                'select id, name from distributor_shop')
            distr_shops = PropDict([(i.id, i.name) for i in distr_shops])
            page = self.db.query(sql, *params)
            title = [
                u'商品名称', u'销售数量', u'销售金额', u'成本', u'利润', u'已消费或发货', u'消费金额',
                u'未消费退款数量', u'未消费退款金额', u'已消费退款数量', u'已消费退款金额', u'刷单数量',
                u'刷单金额', u'刷单利润'
            ]
            range_list = [
                'goods_name', 'sales_count', 'sales_amount', 'cost', 'profit',
                'used', 'used_amount', 'refund', 'refund_amount', 'vrefund',
                'vrefund_amount', 'cheat', 'cheat_amount', 'cheat_profit'
            ]
            if form.summary_type.value == 'goods_type':
                title.append(u'大类')
                range_list.append('category_name')
            else:
                title.append(u'渠道')
                range_list.append('distr_shop_name')
            self.set_header('Content-type', 'application/excel')
            self.set_header(
                'Content-Disposition', u'attachment; filename=' + u'商品销售报表' +
                start + u'至' + end + u'.xls')
            order_excel = Workbook(encoding='utf-8')
            write_order_excel = order_excel.add_sheet('sheet0')

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

            for i, item in enumerate(page):
                for j, content in enumerate(range_list):
                    v = item.get(content, '')
                    v = v if v else 0
                    write_order_excel.write(i + 1, j, v)

            stream = StringIO.StringIO()
            order_excel.save(stream)
            self.write(stream.getvalue())
            pass
        else:
            # 查询
            page = Paginator(self, sql, params)
            self.render('finance/channel_goods_report.html',
                        form=form,
                        page=page,
                        distr_shops=distr_shops)
示例#29
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='该期间没有结算数据')
示例#30
0
    def get(self, act_id):
        user = self.current_user
        if user.level == 0:
            # 不是会员,先跳转到加入会员页面
            self.redirect(
                url_concat(self.reverse_url('member_join'),
                           {'wx_id': user.wx_id}))
        else:
            activity = self.db.get(
                'select * from wx_activity where id=%s and sp_id=%s and deleted=0 and is_active=1 '
                'and start_at < NOW() and expire_at > NOW() ', act_id,
                user.sp_id)
            if not activity:
                raise HTTPError(404)
            else:
                act_mem = self.db.get(
                    'select * from wx_activity_mem where act_id = %s and mem_id = %s',
                    act_id, user.id)
                act_pass = False if act_mem and (
                    act_mem.today_count >= activity.daily_try
                    or act_mem.count >= activity.max_try) else True
                day_remain_num = activity.daily_try if not act_mem else activity.daily_try - act_mem.today_count
                all_remain_num = activity.max_try if not act_mem else activity.max_try - act_mem.count
                if day_remain_num > all_remain_num:
                    day_remain_num = all_remain_num

                rewards = self.db.query(
                    'select id, type, name from wx_activity_rewards where act_id=%s '
                    'order by id asc', act_id)
                if activity.type == 1:
                    self.render('activity/scratch_off.html',
                                act_pass=act_pass,
                                activity=activity,
                                rewards=rewards,
                                day_remain_num=day_remain_num,
                                all_remain_num=all_remain_num)
                elif activity.type == 2:
                    win_rewards = [r for r in rewards]  # 用来记录奖项
                    rewards_num = len(rewards)
                    # 补起12个转盘格子
                    rewards.extend([
                        PropDict({
                            'type': '未中奖',
                            'id': -1
                        }) for i in range(12 - rewards_num)
                    ])
                    # 打乱顺序
                    shuffle(rewards)
                    # 添加转盘角度
                    default_degree = 17
                    for i in range(len(rewards)):
                        rewards[i].update({'deg': default_degree + i * 30})

                    self.render('activity/wheel.html',
                                activity=activity,
                                win_rewards=win_rewards,
                                rewards=rewards,
                                act_id=act_id,
                                json_dumps=json_dumps,
                                day_remain_num=day_remain_num,
                                all_remain_num=all_remain_num)
示例#31
0
    def post(self):
        self.set_header('Content-Type', 'application/json; charset=UTF-8')
        coupon_list = [i.strip() for i in self.get_argument('coupons', '').split(',') if i.strip()]
        if len(coupon_list) == 0:
            self.write({'ok': False, 'msg': u'请输入券号'})
            return
        shop_id = self.get_argument('shop_id', 0)
        #这一步是检查该操作员是否有权限验证券
        all_shops = self.db.query('select ss.* from supplier_shop ss, supplier_user su where ss.supplier_id=%s and '
                                  'ss.deleted=0 and su.id=%s and su.supplier_id=ss.supplier_id and '
                                  ' (su.shop_id=0 or ss.id=su.shop_id)',
                                  self.current_user.supplier_id, self.current_user.id)
        if int(shop_id) not in [i.id for i in all_shops]:
            self.write({'ok': False, 'msg': u'对不起,您无权执行此操作'})
            return

        is_our_coupon = False
        coupon_length = 0
        messages = PropDict()  # 用来存不同的手机号对应的券号
        #检测长度是否相同、是否是我们的券
        for coupon_sn in coupon_list:
            coupon = self.db.get('select id, sn, mobile from item_coupon where sn=%s', coupon_sn)
            if coupon:
                is_our_coupon = True
            if coupon_length == 0:
                coupon_length = len(coupon_sn)
            elif coupon_length != len(coupon_sn):
                coupon_length = -1
        if coupon_length == -1:
            self.write({'ok': False, 'msg': u'券号长度必须一致'})
            return

        result_list = []
        if is_our_coupon:
            # 我们自己的券
            for coupon_sn in coupon_list:
                #  本地检测
                check_result = local_check(self.db, coupon_sn, shop_id)
                if not check_result.ok:
                    ok, msg = (False, check_result.msg)
                else:
                    #  合作伙伴API验证
                    api_result = yield partner_api_verify(self.db, coupon_sn)
                    if not api_result.ok:
                        ok, msg = (False, api_result.msg)
                    else:
                        #  本地验证
                        verify_result = local_verify(self.db, coupon_sn, shop_id, self.current_user.name)
                        ok, msg = (verify_result.ok, verify_result.msg)
                        # 验证通过,记录需要发送确认短信的券
                        if ok:
                            if messages.get(str(check_result.coupon.mobile)):
                                # 手机号已存在,添加券号到对应手机号
                                messages.get(str(check_result.coupon.mobile)).append(str(coupon_sn))
                            else:
                                # 手机号不存在,新建K-V对
                                messages.update({str(check_result.coupon.mobile): [str(coupon_sn)]})

                result_list.append({'coupon_sn': coupon_sn, 'ok': ok, 'msg': msg})
        else:
            mobile = self.get_argument('mobile', '')
            # 检查手机号合法性
            mobile_ptn = re.compile('^1[\d+]{10}$')
            if not re.match(mobile_ptn, mobile):
                # 不合法手机号,不记录
                mobile = ''

            # 尝试外部验证
            results = yield partner_browser_verify(self.db, coupon_list, shop_id)
            for result in results:
                if result.ok:
                    goods_info = self.db.get('select g.* from goods g where id=%s', result.goods_id)
                    verify_infos = {'goods_id': result.goods_id, 'shop_id': shop_id}
                    #创建分销订单
                    distributor_order_id = self.db.execute(
                        'insert into distributor_order(order_no, message, distributor_shop_id, created_at) '
                        'values (%s, %s, %s, NOW())', result.coupon_sn, json_dumps(verify_infos), result.distributor_shop_id)
                    order_id, order_no = new_distributor_order(self.db, result.distributor_shop_id,
                                                               goods_info.sales_price, goods_info.sales_price, mobile)
                    #记录订单信息
                    new_order = new_distributor_item(
                        db=self.db,
                        order_id=order_id,
                        order_no=order_no,
                        sales_price=None,
                        count=1,
                        goods_info=goods_info,
                        mobile=mobile,
                        distributor_shop_id=result.distributor_shop_id,
                        distributor_goods_id='',
                        distributor_coupons=[{'coupon_sn': result.coupon_sn, 'coupon_pwd': result.coupon_pwd or ''}],
                        use_distributor_coupon=True
                    )
                    if new_order.ok:
                        #更新分销订单id
                        self.db.execute('update orders set distributor_order_id=%s where id = %s',
                                        distributor_order_id, order_id)
                        #更新订单id
                        self.db.execute('update distributor_order set order_id=%s where id=%s',
                                        order_id, distributor_order_id)
                        #更新该券验证的门店
                        self.db.execute('update item set sp_shop_id = %s where order_id=%s', shop_id, order_id)
                        self.redis.lpush(options.queue_coupon_local_verify, json_dumps({'coupon': result.coupon_sn,
                                         'shop_id': shop_id, 'retry': 0, 'used_at': datetime.now()}))
                result_list.append({'coupon_sn': result.coupon_sn, 'coupon_pwd': result.coupon_pwd or '',
                                    'ok': result.ok, 'msg': result.msg})

        # 如果有合法券号,发送确认短信
        if messages:
            shop_name = self.db.get('select name from supplier_shop where id=%s', shop_id).name
            for mobile, coupon_sns in messages.items():
                CouponConsumedMessage(self.redis, coupon_sns, shop_name, mobile).send()

        self.write({'ok': True, 'result': result_list})
示例#32
0
from ... import BaseHandler
from ... import require
import logging
import random
import string
from autumn.torn.paginator import Paginator
from autumn.utils import PropDict, json_dumps, mix_str
from voluptuous import Schema, All, Coerce, Length, Any, Range
from autumn.torn.form import Form, EmptyList, Decode, Datetime, EmptyNone, Unique, ListCoerce
from autumn.utils.dt import ceiling
import json
from autumn.goods import img_url
from autumn.utils import json_hook

act_dict = PropDict({1: "刮刮乐", 2: "大转盘"})


class List(BaseHandler):
    """微活动列表"""
    @require()
    def get(self):
        acts = self.db.query(
            'select * from wx_activity where sp_id = %s and deleted=0 order by id desc',
            self.current_user.supplier_id)
        self.render('wx/activity/list.html', acts=acts, act_dict=act_dict)


class Add(BaseHandler):
    """新增微活动"""
    @require()