Beispiel #1
0
def add_free(userid, goods_code=None, service_code='card_actv'):
    '''
    给userid开通免费体验
    '''
    goods = get_goods(goods_code, service_code)
    if not goods.get('free'):
        raise ParamError('该服务暂不支持免费体验')
    free = goods['free']

    try:
        now = int(time.time())
        expire_time = str_timestamp(time.strftime(DATE_FMT),
                                    DATE_FMT) + (free + 1) * 24 * 3600 - 1
        recharge_id = getid()
        with get_connection_exception('qf_mchnt') as db:
            db.insert(
                'recharge', {
                    'id': recharge_id,
                    'userid': userid,
                    'ctime': now,
                    'utime': now,
                    'goods_code': goods['code'],
                    'status': 1,
                    'expire_time': expire_time
                })
        return recharge_id
    except:
        log.warn('create activity error: %s' % traceback.format_exc())
        raise DBError('开通免费体验失败')
Beispiel #2
0
    def _create_order(self, d):
        # 订单信息
        fields = ('userid', 'goods_code', 'txamt', 'total_amt', 'price_code',
                  'promo_code', 'goods_name')
        order = {i: d[i] for i in fields}
        order['id'] = getid()
        order['out_sn'] = 0
        order['ext'] = order['promo_code'][:2]
        order['promo_code'] = order['promo_code'][2:]
        order['status'] = ORDER_STATUS['undo']
        order['ctime'] = order['utime'] = int(time.time())
        # 插入paying_order
        with get_connection_exception('qf_mchnt') as db:
            db.insert('paying_order', order)

        # 返回值
        r = {}
        r['goods_name'] = d['goods_name']
        r['txamt'] = d['txamt']
        r['txcurrcd'] = 'CNY'
        r['txdtm'] = time.strftime(DATETIME_FMT)
        r['out_trade_no'] = order['id']
        r['udid'] = 'mchnt_api'
        r['appcode'] = config.QT2_APP_CODE
        r['sign'] = RechargeUtil.make_sign(r)
        return r
Beispiel #3
0
    def POST(self):

        params = {
            k.strip(): str(v).strip()
            for k, v in self.req.inputjson().items()
        }
        name = params.get("name", '')
        contact_mobile = params.get("contact_mobile", '')
        city = params.get("city", '')
        company = params.get('company', '')
        coop_type = params.get("coop_type", '1')  # 合作方式

        medium = params.get("medium", "")
        campaign = params.get("campaign", "")
        source = params.get("source", "")
        content = params.get("content", "")
        term = params.get("term", "")

        if not name or not contact_mobile or not city or not coop_type:
            raise ParamError("参数不能为空")
        try:
            coop_type = int(coop_type)
            if coop_type not in INTENT_COOP_TYPE:
                raise ParamError("coop_type参数错误")
        except:
            raise ParamError("coop_type参数错误")

        if not re.match(MOBILE_PATTERN, contact_mobile):
            raise ParamError("手机格式错误")

        curr_time = time.strftime(DTM_FMT)
        if self.db.select("intent_coopman",
                          where={"contact_mobile": contact_mobile},
                          fields="id"):
            raise ParamError("此手机号已提交过")
        else:
            pri_id = getid()
            try:
                self.db.insert("intent_coopman",
                               values={
                                   "id": pri_id,
                                   "name": name,
                                   "contact_mobile": contact_mobile,
                                   "city": city,
                                   "coop_type": coop_type,
                                   "source": source,
                                   "medium": medium,
                                   "campaign": campaign,
                                   "content": content,
                                   "term": term,
                                   "company": company,
                                   "ctime": curr_time
                               })
                return self.write(success(data={}))
            except:
                log.warning(traceback.format_exc())
                raise DBError("操作失败")
Beispiel #4
0
    def POST(self):
        data = self.validator.data
        data['ctime'] = data['utime'] = int(time.time())
        data['id'] = getid()
        data['userid'] = self.user.userid
        data['state'] = 1
        if not data['mobile']:
            user = apcli.user_by_id(data['userid']) or {}
            data['mobile'] = user.get('mobile') or ''

        with get_connection('qf_mchnt') as db:
            db.insert('bk_apply', data)

        return self.write(success({}))
Beispiel #5
0
    def _update_v1():
        '''
        老版本更新
        '''
        with get_connection('qf_mchnt') as db:
            # 获取当前的信息
            upwhere = {
                'goods_code': order['goods_code'],
                'userid': order['userid']
            }
            try:
                info = db.select_one('recharge', where=upwhere)
            except:
                info = None

            # 更新当前级别的信息
            try:
                price = RechargeUtil.get_price(order['goods_code'],
                                               order['price_code'])
                st = datetime.date.today()
                if info:
                    exptm = info['expire_time']
                    if str(exptm) > time.strftime(DATETIME_FMT):
                        st = datetime.date(year=exptm.year,
                                           month=exptm.month,
                                           day=exptm.day)
                add_conf = {price['alidity']['unit']: price['alidity']['key']}
                end = str_to_tstamp(
                    str(future(st, **add_conf)) + ' 23:59:59', DATETIME_FMT)
                # 若不存在,则直接插入
                if info:
                    updata = {
                        'expire_time': end,
                        'utime': int(time.time()),
                        'status': 2
                    }
                    db.update('recharge', updata, upwhere)
                else:
                    indata = {}
                    indata['id'] = getid()
                    indata['userid'] = order['userid']
                    indata['goods_code'] = order['goods_code']
                    indata['status'] = 2
                    indata['expire_time'] = end + config.PAYING_GOODS[
                        'free'] * 24 * 3600
                    indata['ctime'] = indata['utime'] = int(time.time())
                    db.insert('recharge', indata)
            except:
                log.warn('更新消费者有效期失败:%s' % traceback.format_exc())
Beispiel #6
0
    def POST(self):
        d = {k:v.strip() for k, v in self.req.input().iteritems()}
        order = {field:d.get(field, '') for field in ('goods_code', 'price_code', 'promo_code')}
        order['userid'] = int(self.user.userid)
        ext = {}
        ext['promo_code'] = order['promo_code']

        # 获取信息
        info = RechargeUtil.check_recharge_info(**order)
        goods = info['goods']
        promo_amt = info.get('promo_amt', 0)
        ext['promo_amt'] = promo_amt

        # 折算金额
        cur_amt, _ = RechargeUtil.get_cur_payinfo(order['userid'], order['goods_code'])
        ext['cur_amt'] = cur_amt

        order['total_amt'] = goods['price']['amt']
        order['goods_name'] = goods['price']['goods_name']
        order['txamt'] = max(order['total_amt'] - cur_amt - promo_amt, 1)

        # 订单其他信息
        order['id'] = getid()
        order['out_sn'] = 0
        order['ext'] = json.dumps(ext)
        order['promo_code'] = order['promo_code'][2:]
        order['status'] = ORDER_STATUS['undo']
        order['ctime'] = order['utime'] = int(time.time())
        # 插入paying_order
        with get_connection_exception('qf_mchnt') as db:
            db.insert('paying_order', order)

        # 返回值
        r = {}
        r['goods_name'] = order['goods_name']
        r['txamt'] = order['txamt']
        r['txcurrcd'] = 'CNY'
        r['txdtm'] = time.strftime(DATETIME_FMT)
        r['out_trade_no'] = order['id']
        r['udid'] = 'mchnt_api'
        r['appcode'] = config.QT2_APP_CODE
        r['sign'] = RechargeUtil.make_sign(r)

        return self.write(success(r))
Beispiel #7
0
def coupon_effect():
    '''红包活动'''
    with get_connection('qf_marketing') as db:
        fields = ('id, mchnt_id, type, title, total_amt, used_num, used_amt,'
                  'rule, start_time, expire_time, create_time, obtain_xx_id')
        actvs = db.select(table='activity',
                          where={
                              'src':
                              'QPOS',
                              'mchnt_id': ('!=', 0),
                              'type': ('in', CouponDefine.HJ_ACTVS),
                              'status':
                              CouponDefine.ACTV_STATUS_ENABLE,
                              'expire_time':
                              ('between',
                               (TD_TIMESTAMP - 24 * 3600, TD_TIMESTAMP - 1)),
                          },
                          fields=fields) or []

        close_actvs = db.select(
            table='activity',
            where={
                'src':
                'QPOS',
                'mchnt_id': ('!=', 0),
                'type': ('in', CouponDefine.HJ_ACTVS),
                'status':
                CouponDefine.ACTV_STATUS_CLOSED,
                'update_time':
                ('between', (TD_TIMESTAMP - 24 * 3600, TD_TIMESTAMP - 1)),
            },
            fields=fields) or []
        actvs = actvs + close_actvs
        if not actvs: return

        # 刺激消费,红包核销数,实际花销
        actids = [i['id'] for i in actvs]
        rrecords = db.select(table='record',
                             where={
                                 'activity_id': ('in', actids),
                                 'type':
                                 ('in', (CouponDefine.RD_STATUS_USE,
                                         CouponDefine.RD_STATUS_UNDO,
                                         CouponDefine.RD_STATUS_DESTROY)),
                             },
                             fields='amt, activity_id, total_amt, type') or []
        effects = {}
        for record in rrecords:
            aid = record['activity_id']
            atype = record['type']
            if aid not in effects:
                effects[aid] = defaultdict(int)
            # 核销的红包
            if atype == CouponDefine.RD_STATUS_USE:
                effects[aid]['t_amt'] += record['total_amt']
                effects[aid]['cnt'] += 1
                effects[aid]['t_coupon_amt'] += record['amt']
            # 撤销,还原的红包
            else:
                effects[aid]['t_amt'] -= record['total_amt']
                effects[aid]['cnt'] -= 1
                effects[aid]['t_coupon_amt'] -= record['amt']

    # 整理数据
    result, now = [], int(time.time())
    push_data = []
    for actv in actvs:
        teffect = effects.get(actv['id'], {})
        actv['t_coupon_amt'] = teffect.get('t_coupon_amt', 0)  # 实际花销
        actv['cnt'] = teffect.get('cnt', 0)  # 红包核销数

        effect = {
            'datas': actv,
            'effect': {
                'total_amt': teffect.get('t_amt', 0),
            }
        }

        # 如果数据有数据
        datas = get_data(actv['id'])
        if datas:
            effect['rank'] = datas
            effect['effect']['c_cnt'] = datas['c_cnt']
        else:
            effect['effect']['c_cnt'] = 0

        if actv['type'] == CouponDefine.ACTV_TYPE_PAYMENT:
            # 消费返红包
            if not actv['obtain_xx_id']:
                actv_type = 3  # 消费返红包
            # 分享红包
            else:
                actv_type = 30  # 消费分享红包
        else:
            actv_type = 31  # 分发红包

        # 结案报告数据
        effect_id = getid()
        result.append({
            'id':
            effect_id,
            'userid':
            actv['mchnt_id'],
            'type':
            actv_type,
            'ctime':
            now,
            'content':
            json.dumps(effect, default=json_default_trans),
        })

        # 推送数据
        push_data.append({
            'id': effect_id,
            'actv_name': actv['title'],
            'userid': actv['mchnt_id'],
            'type': actv_type,
            'actv_id': actv['id']
        })

    push_msgs(result, push_data)
Beispiel #8
0
def card_effect():
    '''集点活动'''
    def get_content(actv):
        '''获取报告'''
        effect = {}
        effect['datas'] = actv
        effect['effect'] = {}

        # 参与人数, 刺激消费, 会员复购数
        custs, total_amt, rebuy = [], 0, 0
        with get_connection('qf_mchnt') as db:
            # 参与人数
            custs = db.select(table='member_pt',
                              where={'activity_id': actv['id']},
                              fields='customer_id')
            custs = [i['customer_id'] for i in custs or []]
            if custs:
                # 刺激消费
                tt = db.select(table='pt_record',
                               where={'activity_id': actv['id']},
                               fields='type, sum(total_amt) as ttamt',
                               other='group by type') or []
                tt_dict = {i['type']: i['ttamt'] for i in tt}
                total_amt = tt_dict.get(1, 0) - tt_dict.get(2, 0)

                # 会员复购数
                rebuy = db.select_one(table='member',
                                      where={
                                          'userid': actv['userid'],
                                          'customer_id': ('in', custs),
                                          'ctime': ('<', actv['ctime'])
                                      },
                                      fields='count(1) as num')['num']
        effect['datas']['customer_num'] = len(custs)
        effect['effect']['total_amt'] = int(total_amt)
        effect['effect']['rebuy'] = rebuy
        # 实际花销 (礼品兑换数*礼品单价)
        effect['datas'][
            'total_txamt'] = actv['exchange_num'] * actv['goods_amt']

        # 数据组排位信息
        datas = get_data(actv['id'])
        if datas:
            effect['rank'] = datas

        return effect

    actvs = None
    with get_connection('qf_mchnt') as db:
        actvs = db.select(table='card_actv',
                          where={
                              'expire_time':
                              ('between', (TD_TIMESTAMP - 24 * 3600,
                                           TD_TIMESTAMP - 1)),
                          })
    if not actvs: return

    result, now = [], int(time.time())
    push_data = []
    for actv in actvs:
        t = {}
        t['id'] = getid()
        t['userid'] = actv['userid']
        t['type'] = 1  # 结案报告类型
        t['ctime'] = now
        t['content'] = json.dumps(get_content(actv),
                                  default=json_default_trans)
        result.append(t)

        push_data.append({
            'id': t['id'],
            'userid': actv['userid'],
            'type': 1,
            'actv_name': u'兑换{}的集点活动'.format(actv['goods_name']),
            'actv_id': actv['id'],
        })
    push_msgs(result, push_data)
Beispiel #9
0
def sale_effect():
    '''特卖活动'''
    sales = None
    where = {
        'audit_status': ('in', (SpecialDefine.AUDIT_STATUS_PLACED,
                                SpecialDefine.AUDIT_STATUS_SUCCESS)),
        'status':
        ('in', (SpecialDefine.STATUS_PLACED, SpecialDefine.STATUS_NORMAL,
                SpecialDefine.STATUS_TEST)),
        'redeem_end_date':
        YTD,
        'atype':
        SpecialDefine.ATYPE_SALE,
    }
    fields = ('qf_uid, id, price, origin_price, title, buyable_start_date,'
              'create_time, quantity, daily_quantity, redeem_end_date')
    with get_connection('qmm_wx') as db:
        sales = db.select('market_activity', where=where, fields=fields)
    if not sales: return None

    # 获取兑换数量
    tsales = SpecialApi.get_actv_sales([i['id'] for i in sales])

    # 曝光数
    query_infos = SpecialApi.get_actv_pv([i['id'] for i in sales])

    result, now = [], int(time.time())
    push_data = []
    for sale in sales:
        # 兑换数量
        sale['buy_count'] = int(tsales.get(i['id']) or 0)

        # 购买数量
        sale['sales_count'] = 0
        sale['total_count'] = sale['daily_quantity'] or sale['quantity']  # 总数量
        if sale['daily_quantity']:
            sale['sales_count'] = sale['total_count'] - sale['quantity']
        sale['sales_count'] = max(sale['buy_count'], sale['sales_count'])
        sale['total_cheap_amt'] = sale['sales_count'] * (sale['origin_price'] -
                                                         sale['price'])

        effect = {
            'datas': sale,
            'effect': {
                'total_query':
                sum([t['count'] for t in query_infos.get(sale['id'])]),
                'total_amt':
                sale['price'] * sale['buy_count']
            }
        }

        # 结案数据
        effect_id = getid()
        result.append({
            'id': effect_id,
            'userid': sale['qf_uid'],
            'type': 2,  # 结案报告类型
            'ctime': now,
            'content': json.dumps(effect, default=json_default_trans)
        })

        # 推送数据
        push_data.append({
            'id': effect_id,
            'userid': sale['qf_uid'],
            'actv_name': sale['title'],
            'actv_id': sale['id'],
            'type': 2
        })
    push_msgs(result, push_data)
Beispiel #10
0
    def _update():
        '''
         最新版本
        '''
        # 获取当前服务
        cur_goods = err = None
        for goods in config.GOODS:
            if goods['code'] == goods_code:
                if goods.get('is_gratis'):
                    err = '服务是免费'
                    break
                cur_goods = goods
                break
        else:
            err = '未找到服务'
        if cur_goods['price']['code'] != order['price_code']:
            err = '服务没有该价格'
        if err:
            log.debug(err)
            return

        with get_connection('qf_mchnt') as db:
            # 获取当前的信息
            upwhere = {
                'goods_code': order['goods_code'],
                'userid': order['userid']
            }
            try:
                info = db.select_one('recharge', where=upwhere)
            except:
                info = None

            # 更新当前级别的信息
            try:
                st = datetime.date.today()
                if info:
                    exptm = info['expire_time']
                    if str(exptm) > time.strftime(DATETIME_FMT):
                        st = datetime.date(year=exptm.year,
                                           month=exptm.month,
                                           day=exptm.day)
                add_conf = {
                    cur_goods['price']['alidity']['unit']:
                    cur_goods['price']['alidity']['key']
                }
                end = str_to_tstamp(
                    str(future(st, **add_conf)) + ' 23:59:59', DATETIME_FMT)
                # 若不存在,则直接插入
                if info:
                    updata = {
                        'expire_time': end,
                        'utime': int(time.time()),
                        'status': 2
                    }
                    db.update('recharge', updata, upwhere)
                else:
                    indata = {}
                    indata['id'] = getid()
                    indata['userid'] = order['userid']
                    indata['goods_code'] = order['goods_code']
                    indata['status'] = 2
                    indata['expire_time'] = end + cur_goods.get('free',
                                                                0) * 24 * 3600
                    indata['ctime'] = indata['utime'] = int(time.time())
                    db.insert('recharge', indata)
            except:
                log.warn('更新消费者有效期失败:%s' % traceback.format_exc())

            # 更新低级别的服务
            low_codes = {
                goods['code']
                for goods in config.GOODS if not goods.get('is_gratis')
                and goods['vip'] < cur_goods['vip']
            }
            if low_codes:
                content = '{}购买了{}高级服务,将所有低级服务折算'.format(
                    time.strftime(DATETIME_FMT), order['goods_code'])
                now = int(time.time())
                db.update(table='recharge',
                          where={
                              'goods_code': ('in', low_codes),
                              'userid': order['userid'],
                              'expire_time': ('>', now),
                          },
                          values={
                              'content': content,
                              'expire_time': now,
                              'utime': now
                          })