def api_put(request): """ 响应PUT """ member_id = request.member.id record_id = request.POST['belong_to'] eventParticipance = app_models.eventParticipance.objects.filter( belong_to=record_id, member_id=member_id) if eventParticipance.count() > 0: response = create_response(500) response.data = u"您已参加过该活动!" return response.get_response() else: data = request_util.get_fields_to_be_save(request) event_participance = app_models.eventParticipance(**data) event_participance.save() #调整参与数量 app_models.event.objects(id=record_id).update( **{"inc__participant_count": 1}) #活动奖励 prize = data.get('prize', None) error_msg = None if prize: prize_type = prize['type'] if prize_type == 'no_prize': pass #不进行奖励 elif prize_type == 'integral': if not request.member: pass #非会员,不进行积分奖励 else: value = int(prize['data']) integral_api.increase_member_integral( request.member, value, u'参与活动奖励积分') elif prize_type == 'coupon': if not request.member: pass #非会员,不进行优惠券发放 else: coupon_rule_id = int(prize['data']['id']) coupon, msg, _ = get_consume_coupon( request.webapp_owner_id, 'event', record_id, coupon_rule_id, request.member.id) if not coupon: error_msg = msg data = json.loads(event_participance.to_json()) data['id'] = data['_id']['$oid'] if error_msg: data['error_msg'] = error_msg response = create_response(200) response.data = data return response.get_response()
def api_put(request): """ 响应PUT """ data = request_util.get_fields_to_be_save(request) scratch_participance = app_models.ScratchParticipance(**data) scratch_participance.save() error_msg = None #调整参与数量 app_models.Scratch.objects(id=data['belong_to']).update( **{"inc__participant_count": 1}) #活动奖励 prize = data.get('prize', None) if prize: prize_type = prize['type'] if prize_type == 'no_prize': pass #不进行奖励 elif prize_type == 'integral': if not request.member: pass #非会员,不进行积分奖励 else: value = int(prize['data']) integral_api.increase_member_integral( request.member, value, u'参与活动奖励积分') elif prize_type == 'coupon': if not request.member: pass #非会员,不进行优惠券发放 else: coupon_rule_id = int(prize['data']['id']) # coupon, msg = mall_api.consume_coupon(request.webapp_owner_id, coupon_rule_id, request.member.id) coupon, msg, _ = get_consume_coupon( request.webapp_owner_id, 'scratch', data['belong_to'], coupon_rule_id, request.member.id) if not coupon: error_msg = msg data = json.loads(scratch_participance.to_json()) data['id'] = data['_id']['$oid'] if error_msg: data['error_msg'] = error_msg response = create_response(200) response.data = data return response.get_response()
def api_put(request): """ 响应PUT 算法:奖池抽奖球数量=奖品总数量+奖品总数量/中奖概率 如,中奖率:15%,奖品总数:500个,则奖池抽奖球个数为:500/15%=3333=3333 """ post = request.POST response = create_response(500) record_id = post.get('id', None) code = post.get('ex_code', None) now_datetime = datetime.today() member = request.member member_id = member.id webapp_user_id = request.webapp_user.id if not record_id: response.errMsg = u'抽奖活动信息出错' return response.get_response() exlottery = app_models.Exlottery.objects.get(id=record_id) if not exlottery: response.errMsg = u'不存在该活动或已删除' return response.get_response() #检查码有没有被使用过 can_play_count = 0 exlottery_participance = app_models.ExlotteryParticipance.objects(code=code, belong_to=record_id, member_id=member_id) if exlottery_participance.count() == 1: # 如果绑定,验证抽奖码有没有抽奖 if exlottery_participance.first().status == app_models.NOT_USED: can_play_count = 1 # 如果当前可玩次数为0,则直接返回 if can_play_count <= 0: response = create_response(500) response.errMsg = u'该抽奖码已经被使用过~' return response.get_response() #首先检查活动状态 status_text = exlottery.status_text if status_text != u'进行中': response = create_response(500) response.errMsg = u'参与抽奖失败,请刷新页面重试~' return response.get_response() chance = exlottery.chance / 100.0 #中奖率 participants_count = exlottery.participant_count #所有参与的人数 winner_count = exlottery.winner_count #中奖人数 #根据抽奖限制,对比抽奖时间 allow_repeat = True if exlottery.allow_repeat == 'true' else False # expend = exlottery.expend # delivery = exlottery.delivery # if not member or member.integral < expend: # response = create_response(500) # response.errMsg = u'积分不足' # return response.get_response() #构造奖项池 prize_tank = [] exlottery_prize_dict = exlottery.prize for _, item in exlottery_prize_dict.items(): prize_count = int(item['prize_count']) for i in range(prize_count): prize_item = { 'title': item['title'], 'prize_count': prize_count, 'prize_type': item['prize_type'], 'prize_data': item['prize_data'] } prize_tank.append(prize_item) curr_tank_size = len(prize_tank) cache_key = 'apps_exlottery_%s_noprizecount' % record_id cache_count = GET_CACHE(cache_key) if cache_count or cache_count == 0: null_prize = int(cache_count) else: null_prize = int(curr_tank_size / chance) - curr_tank_size prize_tank.extend([None for _ in range(null_prize)]) if len(prize_tank) <= 0: response = create_response(500) response.errMsg = u'奖品已抽光' return response.get_response() member_has_record = app_models.ExlottoryRecord.objects(belong_to=record_id, member_id=member_id, prize_type__in=['integral','coupon','entity']) #如果不能重复中奖,则判断是否之前抽中过 if not allow_repeat and member_has_record: response = create_response(500) response.errMsg = u'您已经抽到奖品了,不能重复中奖~' return response.get_response() #扣除抽奖消耗的积分 # member.consume_integral(expend, u'参与抽奖,消耗积分') #奖励抽奖赠送积分 # member.consume_integral(-delivery, u'参与抽奖,获得参与积分') #判定是否中奖 exlottery_prize_type = "no_prize" exlottery_prize_data = '' #收集完所有奖项的数据,打乱奖池list顺序 random.shuffle(prize_tank) #随机抽奖 exlottery_prize = random.choice(prize_tank) #1、奖品数为0时,不中奖 #2、根据是否可以重复抽奖和抽到的优惠券规则判断 SET_CACHE(cache_key, null_prize) if not exlottery_prize: result = u'谢谢参与' SET_CACHE(cache_key, null_prize - 1) else: exlottery_prize_type = exlottery_prize['prize_type'] temp_prize_title = result = exlottery_prize['title'] #如果抽到的是优惠券,则获取该优惠券的配置 if exlottery_prize_type == 'coupon': #优惠券 exlottery_prize_data = exlottery_prize['prize_data']['id'] coupon, msg, _ = get_consume_coupon(exlottery.owner_id, 'exlottery',str(exlottery.id), exlottery_prize_data, member_id) if not coupon: result = u'谢谢参与' exlottery_prize_type = 'no_prize' else: prize_value = exlottery_prize['prize_data']['name'] exlottery_prize_dict[temp_prize_title]['prize_count'] = int(exlottery_prize_dict[temp_prize_title]['prize_count']) - 1 elif exlottery_prize_type == 'integral': #积分 member.consume_integral(-int(exlottery_prize['prize_data']), u'参与抽奖,抽中积分奖项') exlottery_prize_data = exlottery_prize['prize_data'] prize_value = u'%s积分' % exlottery_prize_data exlottery_prize_dict[temp_prize_title]['prize_count'] = int(exlottery_prize_dict[temp_prize_title]['prize_count']) - 1 else: prize_value = exlottery_prize['prize_data'] exlottery_prize_dict[temp_prize_title]['prize_count'] = int(exlottery_prize_dict[temp_prize_title]['prize_count']) - 1 #更新奖品所剩数量 exlottery.update(set__prize=exlottery_prize_dict) exlottery.reload() #写日志 prize_value = result if result == u'谢谢参与' else prize_value log_data = { "member_id": member_id if member else 0, "belong_to": record_id, "exlottery_name": exlottery.name, "prize_type": exlottery_prize_type, "prize_title": result, "prize_name": str(prize_value), "prize_data": str(exlottery_prize_data), "status": False if exlottery_prize_type=='entity' else True, "created_at": now_datetime, "code": code } exlottery_record = app_models.ExlottoryRecord(**log_data) exlottery_record.save() #更新码的使用时间 exlottery_code = app_models.ExlotteryCode.objects(belong_to=record_id, code=code).first() exlottery_code.update(set__use_time=exlottery_record.created_at) #抽奖后,更新数据 has_prize = False if result == u'谢谢参与' else True exlottery_participance.update(set__status=app_models.HAS_USED) exlottery_participance.first().reload() #调整参与数量和中奖人数 newRecord = {} if has_prize: app_models.Exlottery.objects(id=record_id).update(inc__winner_count=1) newRecord = { 'created_at': now_datetime.strftime('%Y-%m-%d'), 'prize_name': prize_value, 'prize_title': result } app_models.Exlottery.objects(id=record_id).update(inc__participant_count=1) response = create_response(200) response.data = { 'result': result, 'newRecord': newRecord, "prize_name": prize_value, 'prize_type': exlottery_prize_type, 'can_play_count': 0, # 'remained_integral': member_models.objects.get(id=member_id).integral } return response.get_response()
def do_signment(self, exsign, grade_id): return_data = { 'status_code': RETURN_STATUS_CODE['SUCCESS'], } now_date = datetime.datetime.now() #用户签到操作 user_update_data = { 'set__latest_date': now_date, 'inc__total_count': 1 } latest_date = self.latest_date #判断是否已签到 if latest_date and latest_date.strftime( '%Y-%m-%d') == now_date.strftime( '%Y-%m-%d') and self.serial_count != 0: return_data['status_code'] = RETURN_STATUS_CODE['ALREADY'] return_data['errMsg'] = u'今日已签到' return return_data #判断是否连续签到,否则重置为1 if latest_date and latest_date.strftime('%Y-%m-%d') == ( now_date - datetime.timedelta(days=1)).strftime('%Y-%m-%d'): user_update_data['inc__serial_count'] = 1 curr_serial_count = temp_curr_serial_count = int( self.serial_count) + 1 else: user_update_data['set__serial_count'] = 1 temp_curr_serial_count = 0 curr_serial_count = 1 #如果当前连续签到大于等于最高连续签到,则更新最高连续签到 if temp_curr_serial_count > int(self.top_serial_count): user_update_data['set__top_serial_count'] = temp_curr_serial_count #更新prize curr_prize_integral = daily_integral = serial_integral = next_serial_integral = next_serial_count = 0 curr_prize_coupon_id = daily_coupon_id = serial_coupon_id = next_serial_coupon_id = '' curr_prize_coupon_name = daily_coupon_name = serial_coupon_name = next_serial_coupon_name = '' next_serial_coupon = [] daily_coupon = [] serial_coupon = [] curr_prize_coupon = [] #首先获取奖项配置 prize_settings = exsign.prize_settings bingo = 0 flag = False for name in sorted(map(lambda x: (int(x), x), prize_settings.keys())): setting = prize_settings[name[1]] name = int(name[0]) if flag or name > curr_serial_count: next_serial_count = name for price_type, value in setting.items(): if price_type == 'integral': next_serial_integral = value elif price_type == 'coupon': for v in value: if int(v['grade_id']) == grade_id: next_serial_coupon.append({ "id": v["id"], "name": v["name"], "grade_id": v["grade_id"] }) elif int(v['grade_id']) == 0: next_serial_coupon.append({ "id": v["id"], "name": v["name"], "grade_id": v["grade_id"] }) break if name == 0: #每日奖励和达到连续签到要求的奖励 for price_type, value in setting.items(): if price_type == 'integral': daily_integral = int(value) elif price_type == 'coupon': for v in value: if int(v['grade_id']) == grade_id: daily_coupon.append({ "id": v["id"], "name": v["name"], "grade_id": v["grade_id"] }) elif int(v['grade_id']) == 0: daily_coupon.append({ "id": v["id"], "name": v["name"], "grade_id": v["grade_id"] }) if name == curr_serial_count: #达到连续签到要求的奖励 bingo = curr_serial_count flag = True for price_type, value in setting.items(): if price_type == 'integral': serial_integral = int(value) elif price_type == 'coupon': for v in value: if int(v['grade_id']) == grade_id: serial_coupon.append({ "id": v["id"], "name": v["name"], "grade_id": v["grade_id"] }) elif int(v['grade_id']) == 0: serial_coupon.append({ "id": v["id"], "name": v["name"], "grade_id": v["grade_id"] }) user_prize = self.prize temp_coupon_list = user_prize['coupon'].split(',') temp_coupon_list = [] if temp_coupon_list == [ '' ] else temp_coupon_list #防止出现[''].append(x)再用join时出现前置逗号的问题 #若命中连续签到,则不奖励每日签到 if bingo == curr_serial_count: user_prize['integral'] = int( user_prize['integral']) + serial_integral if serial_coupon: for s in serial_coupon: temp_coupon_list.append(s["name"]) curr_prize_coupon = serial_coupon curr_prize_integral = serial_integral else: user_prize['integral'] = int( user_prize['integral']) + daily_integral if daily_coupon: for d in daily_coupon: temp_coupon_list.append(d["name"]) curr_prize_coupon = daily_coupon curr_prize_integral = daily_integral user_prize['coupon'] = ','.join(temp_coupon_list) user_update_data['set__prize'] = user_prize # self.update(**user_update_data) sync_result = self.modify( { '__raw__': { '$or': [{ 'latest_date': None }, { 'latest_date': { '$lt': datetime.datetime(now_date.year, now_date.month, now_date.day, 0, 0) } }] } }, **user_update_data) if not sync_result: return_data['status_code'] = RETURN_STATUS_CODE['ALREADY'] return_data['errMsg'] = u'每天只能签到一次' return return_data self.reload() #更新签到参与人数 exsign.update(inc__participant_count=1) #发放奖励 积分&优惠券 member = member_models.Member.objects.get(id=self.member_id) member.consume_integral(-int(curr_prize_integral), u'参与签到,积分奖项') if curr_prize_coupon: from apps.request_util import get_consume_coupon for c in curr_prize_coupon: coupon, msg, coupon_count = get_consume_coupon( exsign.owner_id, 'exsign', str(exsign.id), c['id'], self.member_id) c["count"] = coupon_count return_data['curr_prize_integral'] = curr_prize_integral return_data['curr_prize_coupon'] = curr_prize_coupon return_data['daily_integral'] = daily_integral return_data['daily_coupon'] = daily_coupon return_data['next_serial_count'] = next_serial_count return_data['next_serial_integral'] = next_serial_integral return_data['next_serial_coupon'] = next_serial_coupon return_data['serial_count'] = int(self.serial_count) return return_data
def api_put(request): """ 响应PUT 算法:奖池抽奖球数量=奖品总数量+奖品总数量/中奖概率 如,中奖率:15%,奖品总数:500个,则奖池抽奖球个数为:500/15%=3333=3333 """ post = request.POST response = create_response(500) record_id = post.get('id', None) data = {} now_datetime = datetime.today() if not record_id: response.errMsg = u'抽奖活动信息出错' return response.get_response() egg = app_models.Egg.objects.get(id=record_id) if not egg: response.errMsg = u'不存在该活动或已删除' return response.get_response() #首先检查活动状态 status_text = egg.status_text if status_text != u'进行中': response = create_response(500) response.errMsg = u'参与抽奖失败,请刷新页面重试~' return response.get_response() chance = egg.chance / 100.0 #中奖率 participants_count = egg.participant_count #所有参与的人数 winner_count = egg.winner_count #中奖人数 limitation = egg.limitation_times #抽奖限制 #根据抽奖限制,对比抽奖时间 allow_repeat = True if egg.allow_repeat == 'true' else False expend = egg.expend delivery = egg.delivery delivery_setting = egg.delivery_setting webapp_user_id = request.webapp_user.id member = request.member if not member or member.integral < expend: response = create_response(500) response.errMsg = u'积分不足' return response.get_response() #构造奖项池 prize_tank = [] egg_prize_dict = egg.prize for _, item in egg_prize_dict.items(): prize_count = int(item['prize_count']) for i in range(prize_count): prize_item = { 'title': item['title'], 'prize_count': prize_count, 'prize_type': item['prize_type'], 'prize_data': item['prize_data'] } prize_tank.append(prize_item) curr_tank_size = len(prize_tank) cache_key = 'apps_egg_%s_noprizecount' % record_id cache_count = GET_CACHE(cache_key) if cache_count or cache_count == 0: null_prize = int(cache_count) else: null_prize = int(curr_tank_size / chance) - curr_tank_size prize_tank.extend([None for _ in range(null_prize)]) if len(prize_tank) <= 0: response = create_response(500) response.errMsg = u'奖品已抽光' return response.get_response() member_id = member.id data['member_id'] = member_id data['webapp_user_id'] = webapp_user_id egg_participances = app_models.EggParticipance.objects( belong_to=record_id, member_id=member_id) if egg_participances.count() != 0: egg_participance = egg_participances.first() else: #如果当前用户没有参与过该活动,则创建新记录 data['belong_to'] = record_id data['egg_date'] = now_datetime - dt.timedelta( seconds=2) #第一次参与抽奖初始抽奖时间向前2秒以免在下面的逻辑中被判定为过于频繁 data['can_play_count'] = limitation #根据抽奖活动限制,初始化可参与次数 egg_participance = app_models.EggParticipance(**data) egg_participance.save() #如果当前可玩次数为0,则直接返回 #如果限制抽奖次数,则进行判断目前是否抽奖次数已经使用完 if int(limitation) != -1: if egg_participance.can_play_count <= 0: response = create_response(500) response.errMsg = u'您今天的砸金蛋机会已经用完~' return response.get_response() if not allow_repeat and egg_participance.has_prize: response = create_response(500) response.errMsg = u'您已经抽到奖品了,不能重复中奖~' return response.get_response() if int(limitation) != -1: # 临时解决高并发问题 ----start # permisson = False # index_list = ['one', 'two'] if limitation == 2 else ['one'] # for index in index_list: # try: # data = {} # data['member_id'] = member_id # data['belong_to'] = record_id # data['date_control'] = now_datetime.strftime('%Y-%m-%d') # data['can_play_count_control_%s'%index] = now_datetime.strftime('%Y-%m-%d') # control = app_models.eggControl(**data) # control.save() # permisson = True # break # except: # pass # if not permisson: # response = create_response(500) # response.errMsg = u'您今天的抽奖机会已经用完~' # return response.get_response() # 临时解决高并发问题 ----end #根据抽奖次数限制,更新可抽奖次数 # egg_participance.update(dec__can_play_count=1) sync_result = egg_participance.modify(query={ 'egg_date__lt': now_datetime - dt.timedelta(seconds=1), 'can_play_count__gte': 1 }, dec__can_play_count=1, set__egg_date=now_datetime) if not sync_result: response = create_response(500) response.errMsg = u'操作过于频繁!' return response.get_response() else: sync_result = egg_participance.modify( query={'egg_date__lt': now_datetime - dt.timedelta(seconds=1)}, set__egg_date=now_datetime) if not sync_result: response = create_response(500) response.errMsg = u'操作过于频繁!' return response.get_response() #扣除抽奖消耗的积分 member.consume_integral(expend, u'参与砸金蛋,消耗积分') #判定是否中奖 egg_prize_type = "no_prize" egg_prize_data = '' #收集完所有奖项的数据,打乱奖池list顺序 random.shuffle(prize_tank) #随机抽奖 egg_prize = random.choice(prize_tank) #1、奖品数为0时,不中奖 #2、根据是否可以重复抽奖和抽到的优惠券规则判断 SET_CACHE(cache_key, null_prize) if not egg_prize: result = u'谢谢参与' SET_CACHE(cache_key, null_prize - 1) else: egg_prize_type = egg_prize['prize_type'] temp_prize_title = result = egg_prize['title'] #如果抽到的是优惠券,则获取该优惠券的配置 if egg_prize_type == 'coupon': #优惠券 egg_prize_data = egg_prize['prize_data']['id'] coupon, msg, _ = get_consume_coupon(egg.owner_id, 'egg', str(egg.id), egg_prize_data, member_id) if not coupon: result = u'谢谢参与' egg_prize_type = 'no_prize' else: prize_value = egg_prize['prize_data']['name'] egg_prize_dict[temp_prize_title]['prize_count'] = int( egg_prize_dict[temp_prize_title]['prize_count']) - 1 elif egg_prize_type == 'integral': #积分 member.consume_integral(-int(egg_prize['prize_data']), u'参与砸金蛋,抽中积分奖项') egg_prize_data = egg_prize['prize_data'] prize_value = u'%s积分' % egg_prize_data egg_prize_dict[temp_prize_title]['prize_count'] = int( egg_prize_dict[temp_prize_title]['prize_count']) - 1 else: prize_value = egg_prize['prize_data'] egg_prize_dict[temp_prize_title]['prize_count'] = int( egg_prize_dict[temp_prize_title]['prize_count']) - 1 #更新奖品所剩数量 egg.update(set__prize=egg_prize_dict) egg.reload() #写日志 prize_value = result if result == u'谢谢参与' else prize_value log_data = { "member_id": member_id if member else 0, "belong_to": record_id, "egg_name": egg.name, "prize_type": egg_prize_type, "prize_title": result, "prize_name": str(prize_value), "prize_data": str(egg_prize_data), "status": False if egg_prize_type == 'entity' else True, "created_at": now_datetime } app_models.EggRecord(**log_data).save() #抽奖后,更新数据 has_prize = False if result == u'谢谢参与' else True #根据送积分规则,查询当前用户是否已中奖 if delivery_setting == 'false': member.consume_integral(-delivery, u'参与砸金蛋,获得参与积分') elif not egg_participance.has_prize and not has_prize: member.consume_integral(-delivery, u'参与砸金蛋,获得参与积分') if has_prize: egg_participance.update(**{ "set__has_prize": has_prize, "inc__total_count": 1 }) else: egg_participance.update(inc__total_count=1) # #修复参与过抽奖的用户隔一天后再抽就能无限制抽奖的bug -----start # egg_participance.update(set__egg_date=now_datetime) # #修复参与过抽奖的用户隔一天后再抽就能无限制抽奖的bug -----end egg_participance.reload() #调整参与数量和中奖人数 newRecord = {} if has_prize: app_models.Egg.objects(id=record_id).update(inc__winner_count=1) newRecord = { 'created_at': now_datetime.strftime('%Y-%m-%d'), 'prize_name': prize_value, 'prize_title': result } app_models.Egg.objects(id=record_id).update(inc__participant_count=1) response = create_response(200) response.data = { 'result': result, 'newRecord': newRecord, "prize_name": prize_value, 'prize_type': egg_prize_type, 'can_play_count': egg_participance.can_play_count, 'remained_integral': member_models.objects.get(id=member_id).integral } return response.get_response()
def get_share_red_envelope(request): """ 领取分享红包 """ red_envelope_rule_id = request.GET.get('red_envelope_rule_id', 0) order_id = request.GET.get('order_id', 0) # 下单领取会带有order_id user_id = request.GET.get('webapp_owner_id', 0) is_share = request.GET.get('is_share', 0) material_id = 0 #除下单领取记录rule_id作为material_id # 订单 # if order_id: # order = Order.objects.get(id=order_id) #会员 member_id = -1 if request.member: member_id = request.member.id member = Member.objects.filter(id=member_id) #分享链接的会员id cookie_fmt = request.COOKIES.get('fmt', None) followed_member_id = 0 if cookie_fmt and cookie_fmt != 'None': followed_member_id = Member.objects.get(token=cookie_fmt).id is_share = False auth_appid = module_api.get_mp_info(user_id) qcode_img_url = '' shop_name = '' if auth_appid: qcode_img_url = auth_appid.qrcode_url if auth_appid.qrcode_url else '' shop_name = auth_appid.nick_name if auth_appid.nick_name else '' try: red_envelope_rule = RedEnvelopeRule.objects.get( id=red_envelope_rule_id, is_delete=False) except: c = RequestContext(request, {'is_deleted_data': True}) return render_to_response( 'shareRedEnvelope/webapp/share_red_envelope.html', c) coupon_rule_id = red_envelope_rule.coupon_rule_id coupon_rule = CouponRule.objects.get(id=coupon_rule_id) member_coupon_record_count = 0 if order_id: relation = RedEnvelopeToOrder.objects.filter( order_id=order_id, red_envelope_rule_id=red_envelope_rule_id) else: material_id = red_envelope_rule_id #除下单领取记录rule_id作为material_id if followed_member_id == member_id or not followed_member_id: relation = RedEnvelopeToOrder.objects.filter( red_envelope_rule_id=red_envelope_rule_id, member_id=member_id) else: member_get_red_envelope_records = GetRedEnvelopeRecord.objects.filter( member_id=followed_member_id, red_envelope_rule_id=red_envelope_rule_id) if member_get_red_envelope_records.count() > 0: relation = RedEnvelopeToOrder.objects.filter( id=member_get_red_envelope_records[0]. red_envelope_relation_id) else: relation = RedEnvelopeToOrder.objects.filter( red_envelope_rule_id=red_envelope_rule_id, member_id=followed_member_id) member_coupon_record_count = GetRedEnvelopeRecord.objects.filter( member_id=member_id, red_envelope_rule_id=red_envelope_rule_id).count() return_data = { 'red_envelope_rule': red_envelope_rule, 'shop_name': shop_name, 'page_title': "优惠大放送", 'share_page_title': "优惠大放送", 'share_page_desc': red_envelope_rule.share_title, 'share_img_url': red_envelope_rule.share_pic, 'share_to_timeline_use_desc': True, #分享到朋友圈的时候信息变成分享给朋友的描述 'is_share': is_share } if member: member = member[0] if relation.count() > 0 or member_coupon_record_count > 0: #分享获取红包 if member_coupon_record_count: records = GetRedEnvelopeRecord.objects.filter( member_id=member_id, red_envelope_rule_id=red_envelope_rule_id) p = RedEnvelopeParticipences.objects.get( coupon_id=records[0].coupon_id) #获取领取关系的记录 relation = RedEnvelopeToOrder.objects.filter( id=p.red_envelope_relation_id) friends = GetRedEnvelopeRecord.objects.filter( red_envelope_relation_id=records[0]. red_envelope_relation_id).order_by("-id")[:4] else: records = GetRedEnvelopeRecord.objects.filter( member_id=member_id, red_envelope_rule_id=red_envelope_rule_id) friends = GetRedEnvelopeRecord.objects.filter( red_envelope_relation_id=relation[0].id).order_by( "-id")[:4] for friend in friends: friend.member_name = friend.member.username friend.member_header_img = friend.member.user_icon member_red_envelope_relation = RedEnvelopeToOrder.objects.filter( member_id=member_id, red_envelope_rule_id=red_envelope_rule_id) red_envelope_relation_ids = [ record.red_envelope_relation_id for record in records ] if (records.count() > 0 and ((relation[0].id in red_envelope_relation_ids) or records.count() > member_red_envelope_relation.count()) or member_coupon_record_count): #会员已经领了 return_data['has_red_envelope'] = True return_data['coupon_rule'] = coupon_rule return_data['member'] = member if member.is_subscribed else "" return_data['qcode_img_url'] = qcode_img_url return_data['friends'] = friends else: if (red_envelope_rule.status and (red_envelope_rule.end_time > datetime.now() or red_envelope_rule.limit_time)): # coupon, msg = consume_coupon(request.webapp_owner_id, coupon_rule_id, member_id) coupon, msg, _ = get_consume_coupon( request.webapp_owner_id, 'red_envelope', str(red_envelope_rule.id), coupon_rule_id, member_id) if coupon: this_received_count = RedEnvelopeParticipences.objects.filter( owner_id=request.webapp_owner_id, red_envelope_rule_id=red_envelope_rule_id, red_envelope_relation_id=relation[0].id, member_id=member.id).count() if this_received_count > 0: pass else: GetRedEnvelopeRecord.objects.create( owner_id=request.webapp_owner_id, coupon_id=coupon.id, red_envelope_rule_id=red_envelope_rule_id, red_envelope_relation_id=relation[0].id, member=member, ) if followed_member_id: RedEnvelopeParticipences.objects.create( owner_id=request.webapp_owner_id, coupon_id=coupon.id, red_envelope_rule_id=red_envelope_rule_id, red_envelope_relation_id=relation[0].id, member_id=member.id, is_new=False if member.is_subscribed else True, introduced_by=followed_member_id) RedEnvelopeParticipences.objects.filter( owner_id=request.webapp_owner_id, red_envelope_rule_id=red_envelope_rule_id, red_envelope_relation_id=relation[0].id, member_id=followed_member_id).update( introduce_received_number=F( 'introduce_received_number') + 1) if member.is_subscribed: return_data['has_red_envelope'] = False return_data['coupon_rule'] = coupon_rule return_data['member'] = member return_data['friends'] = friends else: return_data['has_red_envelope'] = False return_data['coupon_rule'] = coupon_rule return_data['qcode_img_url'] = qcode_img_url return_data['friends'] = friends else: #用户订单获取 # if not order.webapp_user_id == member_id: # return HttpResponseRedirect("/workbench/jqm/preview/?module=mall&model=products&action=list&workspace_id=mall&project_id=0&webapp_owner_id=%s" % user_id) member.member_name = member.username_for_html if (red_envelope_rule.status and (red_envelope_rule.end_time > datetime.now() or red_envelope_rule.limit_time)): # coupon, msg = consume_coupon(request.webapp_owner_id, coupon_rule_id, member_id) coupon, msg, _ = get_consume_coupon(request.webapp_owner_id, 'red_envelope', str(red_envelope_rule.id), coupon_rule_id, member_id) if coupon: this_received_count = RedEnvelopeToOrder.objects.filter( owner_id=request.webapp_owner_id, order_id=order_id, material_id=material_id, member_id=member.id, red_envelope_rule_id=red_envelope_rule_id).count() if this_received_count > 0: pass else: relation = RedEnvelopeToOrder.objects.create( owner_id=request.webapp_owner_id, member_id=member_id, order_id=order_id, material_id=material_id, red_envelope_rule_id=red_envelope_rule_id, count=1) GetRedEnvelopeRecord.objects.create( owner_id=request.webapp_owner_id, coupon_id=coupon.id, red_envelope_rule_id=red_envelope_rule_id, red_envelope_relation_id=relation.id, member_id=member.id) RedEnvelopeParticipences.objects.create( owner_id=request.webapp_owner_id, coupon_id=coupon.id, red_envelope_rule_id=red_envelope_rule_id, red_envelope_relation_id=relation.id, member_id=member.id, is_new=False if member.is_subscribed else True) return_data['has_red_envelope'] = False return_data['coupon_rule'] = coupon_rule return_data[ 'member'] = member if member.is_subscribed else "" return_data['qcode_img_url'] = qcode_img_url else: return_data['coupon_rule'] = coupon_rule return_data['hide_non_member_cover'] = True, return_data['qcode_img_url'] = qcode_img_url request.META['should_remove_shared_url_session'] = True c = RequestContext(request, return_data) return render_to_response( 'shareRedEnvelope/webapp/share_red_envelope.html', c)
def api_put(request): """ 响应PUT """ member_id = request.member.id eventParticipance = app_models.surveyParticipance.objects.filter( belong_to=request.POST['belong_to'], member_id=member_id) if eventParticipance.count() > 0: response = create_response(500) response.data = u"您已参加过该活动!" return response.get_response() else: data = request_util.get_fields_to_be_save(request) survey_participance = app_models.surveyParticipance(**data) survey_participance.save() #调整参与数量 survey_record = app_models.survey.objects(id=data['belong_to']) survey_record.update(**{"inc__participant_count": 1}) add_tag_id = survey_record.first( ).tag_id if survey_record.first().tag_id != 0 else None #活动奖励 prize = data.get('prize', None) error_msg = None if prize: prize_type = prize['type'] if prize_type == 'no_prize': pass #不进行奖励 elif prize_type == 'integral': if not request.member: pass #非会员,不进行积分奖励 else: value = int(prize['data']) integral_api.increase_member_integral( request.member, value, u'参与活动奖励积分') elif prize_type == 'coupon': if not request.member: pass #非会员,不进行优惠券发放 else: coupon_rule_id = int(prize['data']['id']) coupon, msg, current_coupon_count = get_consume_coupon( request.webapp_owner_id, 'survey', data['belong_to'], coupon_rule_id, request.member.id) if not coupon: error_msg = msg #分配到某个分组 member = Member.objects.get(id=member_id) if member: isMember = member.is_subscribed if isMember and add_tag_id: MemberHasTag.add_tag_member_relation(member, [add_tag_id]) if MemberHasTag.objects.filter( member=member, member_tag__name="未分组").count() > 0: MemberHasTag.objects.filter( member=member, member_tag__name="未分组").delete() elif not isMember: survey_log = app_models.surveyParticipanceLog( belong_to=request.POST['belong_to'], member_id=member_id) survey_log.save() data = json.loads(survey_participance.to_json()) data['id'] = data['_id']['$oid'] if error_msg: data['error_msg'] = error_msg response = create_response(200) response.data = data return response.get_response()
def api_put(request): """ 响应PUT 算法:奖池抽奖球数量=奖品总数量+奖品总数量/中奖概率 如,中奖率:15%,奖品总数:500个,则奖池抽奖球个数为:500/15%=3333=3333 """ post = request.POST response = create_response(500) record_id = post.get('id', None) code = post.get('scan_code', None) name = post.get('name', None) phone = post.get('phone', None) now_datetime = datetime.today() is_user_input = post.get('is_user_input', '0') member = request.member member_id = member.id isMember = member.is_subscribed if not record_id: response.errMsg = u'抽奖活动信息出错' return response.get_response() scanlottery = app_models.Scanlottery.objects.get(id=record_id) if not scanlottery: response.errMsg = u'不存在该活动或已删除' return response.get_response() #检查码有没有被使用过 can_play_count = 0 scanlottery_record = app_models.ScanlotteryRecord.objects(code=code) if scanlottery_record.count() == 0: # 非会员不可参与 if isMember: can_play_count = 1 # 如果当前可玩次数为0,则直接返回 if can_play_count <= 0: response = create_response(500) response.errMsg = u'该码已经参与' return response.get_response() #首先检查活动状态 status_text = scanlottery.status_text if status_text != u'进行中': response = create_response(500) response.errMsg = u'参与抽奖失败,请刷新页面重试~' return response.get_response() chance = scanlottery.chance / 100.0 #中奖率 #构造奖项池 prize_tank = [] scanlottery_prize_dict = scanlottery.prize for _, item in scanlottery_prize_dict.items(): if is_user_input != '0': if item['title'] == '一等奖': continue prize_count = int(item['prize_count']) for i in range(prize_count): prize_item = { 'title': item['title'], 'prize_count': prize_count, 'prize_type': item['prize_type'], 'prize_data': item['prize_data'] } prize_tank.append(prize_item) curr_tank_size = len(prize_tank) cache_key = 'apps_scanlottery_%s_noprizecount' % record_id cache_count = GET_CACHE(cache_key) if cache_count or cache_count == 0: null_prize = int(cache_count) else: null_prize = int(curr_tank_size / chance) - curr_tank_size prize_tank.extend([None for _ in range(null_prize)]) if len(prize_tank) <= 0: response = create_response(500) response.errMsg = u'奖品已抽光' return response.get_response() #判定是否中奖 scanlottery_prize_type = "no_prize" scanlottery_prize_data = '' #收集完所有奖项的数据,打乱奖池list顺序 random.shuffle(prize_tank) #随机抽奖 scanlottery_prize = random.choice(prize_tank) #1、奖品数为0时,不中奖 #2、根据是否可以重复抽奖和抽到的优惠券规则判断 SET_CACHE(cache_key, null_prize) if not scanlottery_prize: result = u'谢谢参与' SET_CACHE(cache_key, null_prize - 1) else: scanlottery_prize_type = scanlottery_prize['prize_type'] temp_prize_title = result = scanlottery_prize['title'] #如果抽到的是优惠券,则获取该优惠券的配置 if scanlottery_prize_type == 'coupon': #优惠券 scanlottery_prize_data = scanlottery_prize['prize_data']['id'] coupon, msg, _ = get_consume_coupon(scanlottery.owner_id, 'exlottery',str(scanlottery.id), scanlottery_prize_data, member_id) if not coupon: result = u'谢谢参与' scanlottery_prize_type = 'no_prize' else: prize_value = scanlottery_prize['prize_data']['name'] scanlottery_prize_dict[temp_prize_title]['prize_count'] = int(scanlottery_prize_dict[temp_prize_title]['prize_count']) - 1 elif scanlottery_prize_type == 'integral': #积分 member.consume_integral(-int(scanlottery_prize['prize_data']), u'参与扫码抽奖,抽中积分奖项') scanlottery_prize_data = scanlottery_prize['prize_data'] prize_value = u'%s积分' % scanlottery_prize_data scanlottery_prize_dict[temp_prize_title]['prize_count'] = int(scanlottery_prize_dict[temp_prize_title]['prize_count']) - 1 else: prize_value = scanlottery_prize['prize_data'] scanlottery_prize_dict[temp_prize_title]['prize_count'] = int(scanlottery_prize_dict[temp_prize_title]['prize_count']) - 1 #更新奖品所剩数量 scanlottery.update(set__prize=scanlottery_prize_dict) scanlottery.reload() #写日志 prize_value = result if result == u'谢谢参与' else prize_value log_data = { "member_id": member_id if member else 0, "belong_to": record_id, "scanlottery_name": scanlottery.name, "prize_type": scanlottery_prize_type, "prize_title": result, "prize_name": str(prize_value), "prize_data": str(scanlottery_prize_data), "status": False if scanlottery_prize_type=='entity' else True, "created_at": now_datetime, "code": code, "tel": phone, "name": name, "participate_type": int(is_user_input) } scanlottery_record = app_models.ScanlotteryRecord(**log_data) scanlottery_record.save() #抽奖后,更新数据 has_prize = False if result == u'谢谢参与' else True #调整参与数量和中奖人数 newRecord = {} if has_prize: app_models.Scanlottery.objects(id=record_id).update(inc__winner_count=1) newRecord = { 'created_at': now_datetime.strftime('%Y-%m-%d'), 'prize_name': prize_value, 'prize_title': result } app_models.Scanlottery.objects(id=record_id).update(inc__participant_count=1) response = create_response(200) response.data = { 'result': result, 'newRecord': newRecord, "prize_name": prize_value, 'prize_type': scanlottery_prize_type, 'can_play_count': 0, } return response.get_response()