def check_and_generate_codes(cls, check_counts=50000, item_counts=20000): total_num = InviteCode.objects.filter(is_used=False).count() if total_num < check_counts: letters = 'abcdefghijkmnpqrstuvwxyz' digits = '23456789' insert_list = [] generate_list = [ salt for salt in list( set([ ''.join(random.sample(letters + digits, 6)) for i in range(item_counts) ])) ] num = 0 for code in generate_list: try: InviteCode.objects.get(code=code) except InviteCode.DoesNotExist: insert_list.append(InviteCode(code=code)) num += 1 InviteCode.objects.bulk_create(insert_list) # 发送提醒短信 from wanglibao_sms.tasks import send_messages message = u'原始邀请码少于{}条,系统已重新生成{}条'.format(check_counts, num) phones_list = ['15038038823', '18612250386'] messages_list = [message] send_messages.apply_async(kwargs={ "phones": phones_list, "messages": messages_list }) logging.debug( 'code inserted has been done, total items: {}'.format(num))
def settle(cls, product): if product.ordered_amount != product.total_amount: raise P2PException( u'产品已申购额度(%s)不等于总额度(%s)' % (str(product.ordered_amount), str(product.total_amount))) if product.status != u'满标已审核': raise P2PException(u'产品状态(%s)不是(满标已审核)' % product.status) phones = [] messages_list = [] user_ids = [] with transaction.atomic(): for equity in product.equities.all(): equity_keeper = EquityKeeper(equity.user, equity.product) equity_keeper.settle(savepoint=False) user_ids.append(equity.user.id) phones.append(equity.user.wanglibaouserprofile.phone) name = equity.user.wanglibaouserprofile.name messages_list.append( messages.product_settled(name, equity, product, timezone.now())) product.status = u'还款中' product.save() send_messages.apply_async(kwargs={ "phones": phones, "messages": messages_list, }) user_ids = {}.fromkeys(user_ids).keys() matches = re.search(u'日计息', product.pay_method) if matches and matches.group(): pname = u"%s,期限%s天" % (product.name, product.period) else: pname = u"%s,期限%s个月" % (product.name, product.period) title, content = messages.msg_bid_success(pname, timezone.now()) inside_message.send_batch.apply_async( kwargs={ "users": user_ids, "title": title, "content": content, "mtype": "loaned" }) cache_backend = redis_backend() # 更新该标的redis缓存 cache_backend.update_detail_cache(product.id) # 将标信息从满标的redis列表中挪到还款中的redis列表 cache_backend.update_list_cache('p2p_products_full', 'p2p_products_repayment', product)
def reward_user_5(user, introduced_by, reward_type, got_amount, product, only_show): reward = Reward.objects.filter(is_used=False, type=reward_type).first() text_content = u"【网利宝】您在邀请好友送收益的活动中,获得%s元收益,收益已经发放至您的网利宝账户。请注意查收。回复TD退订4008-588-066【网利宝】" % got_amount if only_show is not True: send_messages.apply_async( kwargs={ "phones": [user.wanglibaouserprofile.phone], "messages": [text_content] }) if only_show is not True: earning = Earning() earning.amount = got_amount earning.type = 'I' earning.product = product order = OrderHelper.place_order(introduced_by, Order.ACTIVITY, u"邀请送收益活动赠送", earning=model_to_dict(earning)) earning.order = order keeper = MarginKeeper(introduced_by, order.pk) # 赠送活动描述 desc = u'%s,邀请好友首次理财活动中,活赠%s元' % ( introduced_by.wanglibaouserprofile.name, got_amount) earning.margin_record = keeper.deposit(got_amount, description=desc) earning.user = introduced_by earning.save() message_content = u"您在邀请好友送收益的活动中,您的好友%s在活动期间完成首次投资,根据活动规则,您获得%s元收益。<br/>\ <a href = 'https://www.wanglibao.com/accounts/home/'>查看账户余额</a><br/>\ 感谢您对我们的支持与关注。<br/>\ 网利宝" % (safe_phone_str( user.wanglibaouserprofile.phone), got_amount) if only_show is not True: RewardRecord.objects.create(user=introduced_by, reward=reward, description=message_content) inside_message.send_one.apply_async( kwargs={ "user_id": introduced_by.id, "title": u"邀请送收益活动", "content": message_content, "mtype": "activity" }) else: print message_content print introduced_by.wanglibaouserprofile.name print safe_phone_str(user.wanglibaouserprofile.phone) print text_content
def post(self, request): uuid = request.POST.get('uuid', '') error_message = request.POST.get('error_message', '') #try: # payinfo = PayInfo.objects.get(uuid=uuid, type='W') #except PayInfo.DoesNotExist: # return HttpResponse({ # u"没有找到 %s 该记录" % uuid # }) payinfo = PayInfo.objects.filter(uuid=uuid, type='W').first() if not payinfo: return HttpResponse({u"没有找到 %s 该记录" % uuid}) if payinfo.status == PayInfo.FAIL or payinfo.status == PayInfo.SUCCESS: logger.info( "The withdraw status [%s] already process , ignore it" % uuid) return HttpResponse({u"该%s 请求已经处理过,请勿重复处理" % uuid}) marginKeeper = MarginKeeper(payinfo.user) # 提现审核失败回滚时需要将扣除的各手续费返还 total_amount = payinfo.amount + payinfo.fee + payinfo.management_fee marginKeeper.withdraw_rollback(total_amount, error_message, uninvested=payinfo.management_amount) payinfo.status = PayInfo.FAIL payinfo.error_message = error_message payinfo.confirm_time = None payinfo.save() # 短信通知添加用户名 name = payinfo.user.wanglibaouserprofile.name or u'用户' send_messages.apply_async( kwargs={ "phones": [payinfo.user.wanglibaouserprofile.phone], "messages": [messages.withdraw_failed(name, error_message)] }) title, content = messages.msg_withdraw_fail(timezone.now(), payinfo.amount) inside_message.send_one.apply_async( kwargs={ "user_id": payinfo.user.id, "title": title, "content": content, "mtype": "withdraw" }) return HttpResponse({u"该 %s 请求已经处理完毕" % uuid})
def fail(cls, product): if product.status == u'流标': raise P2PException('Product already failed') cls.logger.info(u"Product [%d] [%s] not able to reach 100%%" % (product.id, product.name)) user_ids = [] phones = [] messages_list = [] with transaction.atomic(): for equity in product.equities.all(): equity_keeper = EquityKeeper(equity.user, equity.product) equity_keeper.rollback(savepoint=False) user_ids.append(equity.user.id) phones.append(equity.user.wanglibaouserprofile.phone) messages_list.append( messages.product_failed( equity.user.wanglibaouserprofile.name, product)) ProductKeeper(product).fail() try: from .tasks import coop_product_push coop_product_push.apply_async(kwargs={'product_id': product.id}, queue='celery02') except: pass user_ids = {}.fromkeys(user_ids).keys() if phones: send_messages.apply_async(kwargs={ "phones": phones, "messages": messages_list, }) matches = re.search(u'日计息', product.pay_method) if matches and matches.group(): pname = u"%s,期限%s天" % (product.name, product.period) else: pname = u"%s,期限%s个月" % (product.name, product.period) title, content = messages.msg_bid_fail(pname) inside_message.send_batch.apply_async( kwargs={ "users": user_ids, "title": title, "content": content, "mtype": "bids" })
def send_manual_message(sender, instance, **kwargs): if instance.type == u'手动' and instance.status == u'发送中': #from celery.execute import send_task from wanglibao_sms.tasks import send_messages if instance.channel == u'慢道': channel = 1 else: channel = 2 #send_task("wanglibao_sms.tasks.send_messages", kwargs={ # 'phones': instance.phones.split(' '), # 'messages': [instance.contents], # 'channel': channel #}) send_messages.apply_async( kwargs={ 'phones': instance.phones.split(' '), 'messages': [instance.contents], 'channel': channel }) instance.status = u'成功' instance.save()
def reward_user_yi_nian_xunlei(user_id, reward_type, amount, only_show): user = User.objects.get(pk=user_id) reward = Reward.objects.filter(is_used=False, type=reward_type).first() if only_show is not True: print user.wanglibaouserprofile.phone print user.wanglibaouserprofile.name reward.is_used = True reward.save() message_content = u"您在“满额就送”活动期间,累计投资%s元,根据活动规则,您获得一年迅雷白金会员奖励。<br/>\ 激活码:%s,有效期至2015年12月31日。<br/>\ <a href = 'http://pay.vip.xunlei.com/baijin.html'>立即兑换</a><br/>\ 感谢您对我们的支持与关注。<br/>\ 网利宝" % (amount, reward.content) if only_show is not True: inside_message.send_one.apply_async( kwargs={ "user_id": user_id, "title": u"满额送活动", "content": message_content, "mtype": "activity" }) text_content = u"【网利宝】您在“满额就送”活动期间,获得一年迅雷白金会员奖励。激活码:%s,有效期至2015年12月31日。回复TD退订4008-588-066【网利宝】" % reward.content if only_show is not True: send_messages.apply_async( kwargs={ "phones": [user.wanglibaouserprofile.phone], "messages": [text_content] }) RewardRecord.objects.create(user=user, reward=reward, description=message_content) else: print message_content print text_content print user.wanglibaouserprofile.phone
def reward_user_jd_1000(user_id, reward_type, amount, only_show): user = User.objects.get(pk=user_id) reward = Reward.objects.filter(is_used=False, type=reward_type).first() if only_show is not True and reward is None: print user.wanglibaouserprofile.phone print user.wanglibaouserprofile.name return reward.is_used = True reward.save() message_content = u"您在“满额就送”活动期间,累计投资%s元,根据活动规则,您获得1000元京东礼品卡。<br/>\ 京东卡密为:%s,有效期至2015年12月31日。<br/>\ <a href = 'http://www.jd.com'>立即使用</a><br/>\ 感谢您对我们的支持与关注。<br/>\ 网利宝" % (amount, reward.content) if only_show is not True: inside_message.send_one.apply_async( kwargs={ "user_id": user_id, "title": u"满额送活动", "content": message_content, "mtype": "activity" }) text_content = u"【网利宝】您在“满额就送”活动期间,获得1000元京东礼品卡。京东卡密为:%s,有效期至2015年12月31日。回复TD退订4008-588-066【网利宝】" % reward.content if only_show is not True: send_messages.apply_async( kwargs={ "phones": [user.wanglibaouserprofile.phone], "messages": [text_content] }) RewardRecord.objects.create(user=user, reward=reward, description=message_content) else: print message_content print text_content print user.wanglibaouserprofile.phone
def send_commission_income_message_sms(): """ 包含主站的全民淘金和新平台的全民淘金 :return: """ today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=1) start = timezone.datetime(yesterday.year, yesterday.month, yesterday.day, 20, 0, 0, tzinfo=timezone.utc) end = timezone.datetime(today.year, today.month, today.day, 20, 0, 0, tzinfo=timezone.utc) incomes = Income.objects.filter(created_at__gte=start, created_at__lt=end) php_incomes = PhpIncome.objects.filter(created_at__gte=start, created_at__lt=end) python_users = set([income.user for income in incomes]) php_users = set([income.user for income in php_incomes]) # all_users = python_users.union(php_users) # 所有主动邀请了投资的用户集合 same_users = python_users.intersection(php_users) # 同时在python和php都有佣金收入的用户 php_only_users = php_users.difference(python_users) # 只在php有佣金收入的用户 python_incomes = incomes.values('user').annotate( Count('invite', distinct=True)).annotate(Sum('earning')) # 这个在老平台的基础上去处理php的用户佣金的计算方法, 肯定会慢好多, 看情况是否要进行紧急优化 if python_incomes: phones_list = [] messages_list = [] for income in python_incomes: user_info = User.objects.filter(id=income.get('user'))\ .select_related('user__wanglibaouserprofile').values('wanglibaouserprofile__phone') phones_list.append(user_info[0].get('wanglibaouserprofile__phone')) user = User.objects.get(id=income.get('user')) earning = income.get('earning__sum') invite_count = income.get('invite__count') if user in same_users: earning += php_incomes.filter(user=user).aggregate( Sum('earning'))['earning__sum'] or 0 invite_count += php_incomes.filter(user=user).\ values('user').annotate(Count('invite', distinct=True))[0]['invite__count'] messages_list.append( messages.sms_income(user.wanglibaouserprofile.name, invite_count, earning)) # 站内信和短信内容都加上 月利宝的全民淘金 # 发送站内信 title, content = messages.msg_give_income(invite_count, earning) inside_message.send_one.apply_async( kwargs={ "user_id": income.get('user'), "title": title, "content": content, "mtype": "invite" }) # 批量发送短信 send_messages.apply_async(kwargs={ "phones": phones_list, "messages": messages_list }) if php_only_users: phones_list = [] messages_list = [] php_incomes_only = php_incomes.filter(user__in=php_only_users).\ values('user').annotate(Count('invite', distinct=True)).annotate(Sum('earning')) for income in php_incomes_only: user_info = User.objects.filter(id=income.get('user'))\ .select_related('user__wanglibaouserprofile').values('wanglibaouserprofile__phone') phones_list.append(user_info[0].get('wanglibaouserprofile__phone')) user = User.objects.get(id=income.get('user')) messages_list.append( messages.sms_income(user.wanglibaouserprofile.name, income.get('invite__count'), income.get('earning__sum'))) # 发送站内信 title, content = messages.msg_give_income( income.get('invite__count'), income.get('earning__sum')) inside_message.send_one.apply_async( kwargs={ "user_id": income.get('user'), "title": title, "content": content, "mtype": "invite" }) # 批量发送短信 send_messages.apply_async(kwargs={ "phones": phones_list, "messages": messages_list })
def withdraw_submit_ok(user_id, user_name, phone, amount, bank_name, order_id, device): user = User.objects.filter(id=user_id).first() # 短信通知添加用户名 try: # 支持通过字典传递完整的device信息或是通过str直接传device_type if isinstance(device, dict): device_type = device['device_type'] elif isinstance(device, str) or isinstance(device, unicode): assert device in ['pc', 'ios', 'android'] device_type = device else: raise except: device_type = u'pc' logger.exception("=withdraw_ok= Failed to get device_type") send_messages.apply_async( kwargs={ 'phones': [phone], # 'messages': [messages.withdraw_submitted(amount, timezone.now())] 'messages': [messages.withdraw_submitted(user_name)] }) title, content = messages.msg_withdraw(timezone.now(), amount) inside_message.send_one.apply_async( kwargs={ "user_id": user.id, "title": title, "content": content, "mtype": "withdraw" }) weixin_user = WeixinUser.objects.filter(user=user).first() if weixin_user: # 亲爱的{},您的提现申请已受理,1-3个工作日内将处理完毕,请耐心等待。 # {{first.DATA}} 取现金额:{{keyword1.DATA}} 到账银行:{{keyword2.DATA}} 预计到账时间:{{keyword3.DATA}} {{remark.DATA}} now = datetime.datetime.now() withdraw_ok_time = "%s前处理完毕" % ( now + datetime.timedelta(days=3)).strftime('%Y年%m月%d日') sentTemplate.apply_async( kwargs={ "kwargs": json.dumps({ "openid": weixin_user.openid, "template_id": WITH_DRAW_SUBMITTED_TEMPLATE_ID, "first": u"亲爱的%s,您的提现申请已受理" % user_name, "keyword1": "%s 元" % str(amount), "keyword2": bank_name, "keyword3": withdraw_ok_time, # "url":settings.CALLBACK_HOST + '/weixin/activity_ggl/', }) }, queue='celery02') try: utils.log_clientinfo(device, "withdraw", user_id, order_id, amount) except Exception: pass # 往数据中心发送提现信息数据 if settings.SEND_PHP_ON_OR_OFF: send_withdraw_data.apply_async(kwargs={ "user_id": user_id, "amount": amount, "order_id": order_id, "device_type": device_type, }, queue='celery02')
def deposit_ok(user_id, amount, device, order_id): # fix@chenweibi, add order_id try: try: # 支持通过字典传递完整的device信息或是通过str直接传device_type if isinstance(device, dict): device_type = device['device_type'] elif isinstance(device, str) or isinstance(device, unicode): assert device in ['pc', 'ios', 'android'] device_type = device else: raise except: device_type = u'pc' logger.exception("=deposit_ok= Failed to get device_type") title, content = messages.msg_pay_ok(amount) inside_message.send_one.apply_async(kwargs={ "user_id": user_id, "title": title, "content": content, "mtype": "pay" }) user = User.objects.get(id=user_id) user_profile = user.wanglibaouserprofile # activity_backends.check_activity(user, 'recharge', device_type, # amount, **{'order_id': order_id}) check_activity_task.apply_async(kwargs={ "user_id": user.id, "trigger_node": 'recharge', "device_type": device_type, "amount": amount, "order_id": order_id, }, queue='celery02') try: # Add by hb on 2015-12-18 : add return value flag = utils.log_clientinfo(device, "deposit", user_id, order_id, amount) if not flag: raise Exception("Failed to log_clientinfo") except Exception, ex: logger.exception("=20151218= [%s] [%s] [%s] [%s] [%s]" % (ex, device, user_id, order_id, amount)) pass send_messages.apply_async( kwargs={ 'phones': [user_profile.phone], 'messages': [messages.deposit_succeed(user_profile.name, amount)] }) weixin_user = WeixinUser.objects.filter(user=user).first() # 亲爱的满先生,您的充值已成功 # {{first.DATA}} 充值时间:{{keyword1.DATA}} 充值金额:{{keyword2.DATA}} 可用余额:{{keyword3.DATA}} {{remark.DATA}} if weixin_user: deposit_ok_time = datetime.datetime.now().strftime( '%Y年%m月%d日 %H:%M:%S') margin = Margin.objects.filter(user=user).first() sentTemplate.apply_async(kwargs={ "kwargs": json.dumps({ "openid": weixin_user.openid, "template_id": DEPOSIT_SUCCESS_TEMPLATE_ID, "first": u"亲爱的%s,您的充值已成功" % user_profile.name, "keyword1": deposit_ok_time, "keyword2": "%s 元" % str(amount), "keyword3": "%s 元" % str(margin.margin), }) }, queue='celery02') logger.info('=deposit_ok= Success: [%s], [%s], [%s]' % (user_profile.phone, order_id, amount))
join_record.remain_chance = 0 join_record.save() except Exception: reward.is_used = False reward.save() raise Exception(u"发奖异常,奖品回库") else: send_msg = u'尊敬的用户,恭喜您在参与影像投资节活动中获得优惠机会,优惠码为:%s,'\ u'请凭借此信息至相关门店享受优惠,相关奖励请咨询八月婚纱照相馆及鼎极写真摄影,'\ u'感谢您的参与!【网利科技】' % (reward.content) send_messages.apply_async( kwargs={ "phones": [ user.wanglibaouserprofile.phone, ], "messages": [ send_msg, ], }) inside_message.send_one.apply_async( kwargs={ "user_id": user.id, "title": u"影像投资节优惠码", "content": send_msg, "mtype": "activity" }) logger.info('影像投资节优惠码发送成功,user_id:%s; order_id:%s; reward_id:%s' % (user.id, order_id, reward.id))
u"experience repayment error, amortization id : %s , message: %s" % (amo.id, e.message)) # 发站内信,利息大于6元 if amo_tmp.interest > 6 and is_commit: user_profile = amo_tmp.user.wanglibaouserprofile # 短信 phone_list.append(user_profile.phone) message_list.append( messages.experience_amortize(user_profile.name, amo_tmp.interest)) # 站内信 title, content = messages.experience_amortize_msg( user_profile.name, amo_tmp.product.name, amo_tmp.product.period, timezone.now(), amo_tmp.interest) inside_message.send_one.apply_async( kwargs={ "user_id": amo_tmp.user.id, "title": title, "content": content, "mtype": "amortize" }) # 发短信 send_messages.apply_async(kwargs={ "phones": phone_list, "messages": message_list })
def post(self, request): action = request.POST.get('action') uuids_param = request.POST.get('transaction_uuids', '') uuids = re.findall(r'[\w\-_]+', uuids_param) payinfos = PayInfo.objects.filter(uuid__in=uuids, type='W').order_by('create_time') # These are the uuids exists in db for real uuids_param = ",".join([payinfo.uuid for payinfo in payinfos]) if action == 'preview' or action is None: return self.render_to_response({ 'payinfos': payinfos, 'total_amount': payinfos.aggregate(Sum("amount"))['amount__sum'], 'transaction_uuids': uuids_param }) elif action == 'confirm': for payinfo in payinfos: with transaction.atomic(): if payinfo.status != PayInfo.ACCEPTED and payinfo.status != PayInfo.PROCESSING: logger.info( "The withdraw status [%s] not in %s or %s, ignore it" % (payinfo.status, PayInfo.ACCEPTED, PayInfo.PROCESSING)) continue amount = payinfo.amount fee = payinfo.fee management_fee = payinfo.management_fee management_amount = payinfo.management_amount marginKeeper = MarginKeeper(payinfo.user) total_amount = amount + fee + management_fee marginKeeper.withdraw_ack(total_amount, uninvested=management_amount) payinfo.status = PayInfo.SUCCESS payinfo.confirm_time = timezone.now() payinfo.save() # 给提现记录表中的信息同步进行确认,同时将提现的费用充值到网利宝的公司提现账户 if fee > 0 or management_fee > 0: fee_total_amount = fee + management_fee withdraw_card = WithdrawCard.objects.filter( is_default=True).first() withdraw_card.amount += fee_total_amount withdraw_card.save() # 将提现信息单独记录到提现费用记录表中 withdraw_card = WithdrawCard.objects.filter( is_default=True).first() if withdraw_card: withdraw_card_record = WithdrawCardRecord() withdraw_card_record.type = PayInfo.WITHDRAW withdraw_card_record.amount = amount withdraw_card_record.fee = fee withdraw_card_record.management_fee = management_fee withdraw_card_record.management_amount = management_amount withdraw_card_record.withdrawcard = withdraw_card withdraw_card_record.payinfo = payinfo withdraw_card_record.user = payinfo.user withdraw_card_record.status = PayInfo.SUCCESS withdraw_card_record.message = u'用户提现费用存入' withdraw_card_record.save() # 取款确认时要检测该次提现是否是真正的在每个月的免费次数之内,如果是还需要将已扣除的费用返还给用户(仅限手续费) give_back = False if fee > 0: fee_misc = WithdrawFee() fee_config = fee_misc.get_withdraw_fee_config() withdraw_count = fee_misc.get_withdraw_success_count( payinfo.user) free_times = fee_config['fee']['free_times_per_month'] if withdraw_count <= free_times: give_back = True if give_back: # 1.给用户返还手续费 marginKeeper.deposit( fee, description=u'返还提现免费次数之内的手续费:{}元'.format(fee), catalog=u"返还手续费") # 2.从网利宝提现账户中减去手续费 withdraw_card = WithdrawCard.objects.filter( is_default=True).first() withdraw_card.amount -= fee withdraw_card.save() # 将提现信息单独记录到提现费用记录表中 withdraw_card_record = WithdrawCardRecord() withdraw_card_record.type = PayInfo.WITHDRAW withdraw_card_record.amount = fee withdraw_card_record.fee = fee withdraw_card_record.management_fee = 0 withdraw_card_record.management_amount = 0 withdraw_card_record.withdrawcard = withdraw_card withdraw_card_record.payinfo = payinfo withdraw_card_record.user = payinfo.user withdraw_card_record.status = PayInfo.SUCCESS withdraw_card_record.message = u'用户提现费用返还' withdraw_card_record.save() # 发站内信 title, content = messages.msg_withdraw_success( timezone.now(), payinfo.amount) inside_message.send_one.apply_async( kwargs={ "user_id": payinfo.user_id, "title": title, "content": content, "mtype": "withdraw" }) send_messages.apply_async( kwargs={ "phones": [payinfo.user.wanglibaouserprofile.phone], "messages": [ messages.withdraw_confirmed( payinfo.user.wanglibaouserprofile.name, amount) ] }) return HttpResponse({u"所有的取款请求已经处理完毕 %s" % uuids_param})
def amortize(self, amortization, savepoint=True): with transaction.atomic(savepoint=savepoint): if amortization.settled: raise P2PException('amortization %s already settled.' % amortization) sub_amortizations = amortization.subs.all() description = unicode(amortization) catalog = u'分期还款' product = amortization.product matches = re.search(u'日计息', product.pay_method) if matches and matches.group(): pname = u"%s,期限%s天" % (product.name, product.period) else: pname = u"%s,期限%s个月" % (product.name, product.period) phone_list = list() message_list = list() settled_sub_amos = list() for sub_amo in sub_amortizations: user_margin_keeper = MarginKeeper(sub_amo.user) user_margin_keeper.amortize(sub_amo.principal, sub_amo.interest, sub_amo.penal_interest, sub_amo.coupon_interest, savepoint=False, description=description) sub_amo.settled = True sub_amo.settlement_time = timezone.now() sub_amo.save() amo_amount = sub_amo.principal + sub_amo.interest + sub_amo.penal_interest + sub_amo.coupon_interest # 加入重复回款的用户还需要扣回的金额及扣款操作 try: repeat_user = RepeatPaymentUser.objects.select_for_update()\ .filter(user_id=sub_amo.user.id, amount__gt=0).first() if repeat_user: repeat_amount = repeat_user.amount # if repeat_amount > 0: # 判断是否每天从回款中扣款 is_every_day = True if not repeat_user.is_every_day: product_ids = repeat_user.product_ids.split(',') product_ids = [ int(p_id) for p_id in product_ids if p_id.strip() != '' ] # 判断当期还款的产品id是否在用户新购标的id中, 不在说明该标不用扣款 if product.id not in product_ids: is_every_day = False if is_every_day: # 判断剩余应扣金额是否大于等于本期回款本息之合, 大于等于,则扣本息,否则扣剩余应扣金额 if repeat_amount >= amo_amount: reduce_amount = amo_amount reduce_amount_current = repeat_amount - amo_amount # 剩余应扣金额-本次扣除的本息之合 else: reduce_amount = repeat_amount reduce_amount_current = 0 print( "repeat_amount: %s, amo_amount: %s, type1:%s, type2:%s" % (repeat_amount, amo_amount, type(repeat_amount), type(amo_amount))) # 减账户余额 user_margin_keeper.reduce_margin( reduce_amount, u'系统重复回款扣回%s元' % reduce_amount) # 更新剩余应扣金额 repeat_user.amount = reduce_amount_current repeat_user.save() # 记录扣款流水 repeat_record = RepeatPaymentUserRecords( user_id=sub_amo.user.id, name=sub_amo.user.wanglibaouserprofile.name, phone=sub_amo.user.wanglibaouserprofile.phone, amount=reduce_amount, amount_current=reduce_amount_current, description=description) repeat_record.save() except Exception: logger.exception('err') logger.error("用户扣款失败,用户id:[%s], 回款本息合计:[%s]" % (sub_amo.user, amo_amount)) pass try: phone_list.append(sub_amo.user.wanglibaouserprofile.phone) message_list.append( messages.product_amortize( sub_amo.user.wanglibaouserprofile.name, amortization.product, # sub_amo.settlement_time, amo_amount)) title, content = messages.msg_bid_amortize( pname, timezone.now(), amo_amount) inside_message.send_one.apply_async( kwargs={ "user_id": sub_amo.user.id, "title": title, "content": content, "mtype": "amortize" }) except: logger.debug("") self.__tracer(catalog, sub_amo.user, sub_amo.principal, sub_amo.interest, sub_amo.penal_interest, amortization, description, sub_amo.coupon_interest) # 标的每一期还款完成后,检测该用户还款的本金是否有符合活动的规则,有的话触发活动规则 try: if sub_amo.principal > 0: # activity_backends.check_activity(sub_amo.user, 'repaid', 'pc', sub_amo.principal, product.id) check_activity_task.apply_async(kwargs={ "user_id": sub_amo.user.id, "trigger_node": 'repaid', "device_type": 'pc', "amount": sub_amo.principal, "product_id": product.id, }, queue='celery02') except Exception: logger.debug( "check activity on repaid, user: {}, principal: {}, product_id: {}" .format(sub_amo.user.id, sub_amo.principal, product.id)) try: weixin_user = WeixinUser.objects.filter( user=sub_amo.user).first() if weixin_user and weixin_user.subscribe: now = datetime.now().strftime('%Y年%m月%d日 %H:%M:%S') sentTemplate.apply_async(kwargs={ "kwargs": json.dumps({ "openid": weixin_user.openid, "template_id": PRODUCT_AMORTIZATION_TEMPLATE_ID, "keyword1": product.name, "keyword2": "%s 元" % str(amo_amount), "keyword3": now, }) }, queue='celery02') except Exception, e: logger.debug( ">>>> weixin msg send err, user_id:[%s], [%s] " % sub_amo.user.id, e) pass # 添加还款用户到渠道通知列表 @chenwb try: settled_sub_amos.append({ 'id': sub_amo.id, 'user': sub_amo.user.id, 'product': product.id, 'term': sub_amo.term, 'settled': sub_amo.settled, 'term_date': sub_amo.term_date.strftime('%Y-%m-%d %H:%M:%S'), 'settlement_time': sub_amo.settlement_time.strftime('%Y-%m-%d %H:%M:%S'), 'principal': float(sub_amo.principal), 'interest': float(sub_amo.interest), 'penal_interest': float(sub_amo.penal_interest), 'coupon_interest': float(sub_amo.coupon_interest), 'description': sub_amo.description, }) except: pass amortization.settled = True amortization.save() catalog = u'还款入账' send_messages.apply_async(kwargs={ "phones": phone_list, "messages": message_list }) self.__tracer(catalog, None, amortization.principal, amortization.interest, amortization.penal_interest, amortization) # 向渠道中心发送还款用户列表通知 @chenwb # Comment by hb on 2016-05-13 try: if settled_sub_amos: from .tasks import coop_amortizations_push coop_amortizations_push.apply_async(kwargs={ 'amortizations': settled_sub_amos, 'product_id': product.id, 'amo_act': 'amortize' }, queue='celery02') except: pass