Exemplo n.º 1
0
 def exchange_redpackets(self, ids=None, customer=None):
     reds = ReadPacket.objects.filter(id__in=ids,
                                      customer=customer,
                                      status=ReadPacket.NOT_EXCHANGE)
     sum_value = reds.aggregate(s_v=Sum('value')).get('s_v') or 0
     reds_count = reds.count()  # 红包条数
     if reds_count <= 0:  # 如果红包个数小于0则直接返回
         return 2, 0, 0
     coupon_10_count = int(sum_value / 10)  # 十元优惠券条数
     leave_mony = sum_value - coupon_10_count * 10  # 发完十元后还剩下多少钱
     if leave_mony > 0:
         coupon_5_count = 1 if leave_mony / 5 < 1 else 2  # 剩下的红包金额除以5 大于1则发送2张5元优惠券 否则发放1张优惠券
     else:
         coupon_5_count = 0
     code = ''
     for i in range(coupon_10_count):
         cou, code, msg = create_user_coupon(customer_id=int(customer),
                                             coupon_template_id=21)
     for j in range(coupon_5_count):
         cou, code, msg = create_user_coupon(customer_id=int(customer),
                                             coupon_template_id=20)
     if code == 0 or code == 0:
         reds.update(status=ReadPacket.EXCHANGE)  # 更新红包到兑换状态
     coupon_value = coupon_10_count * 10 + coupon_5_count * 5
     return code, coupon_10_count + coupon_5_count, coupon_value
Exemplo n.º 2
0
    def award_confirm(self):
        self.award_status = True
        self.save()

        from flashsale.coupon.apis.v1.usercoupon import create_user_coupon
        from flashsale.pay import constants
        create_user_coupon(
            customer_id=int(self.customer_id),
            coupon_template_id=constants.COUPON_ID_FOR_20160223_AWARD)
Exemplo n.º 3
0
    def pick_active_share_coupon(self, request):
        content = request.POST
        uniq_id = content.get("uniq_id") or ''
        ufrom = content.get("ufrom") or ''
        customer = get_customer(request)
        if customer is None:
            return Response({"code": 9, "msg": "用户不存在", "coupon_id": ''})
        if not uniq_id:
            return Response({"code": 10, "msg": "参数错误", "coupon_id": ''})
        coupon_share = self.queryset.filter(uniq_id=uniq_id).first()
        if coupon_share is None:
            return Response({"code": 8, "msg": "领取完了哦", "coupon_id": ''})
        else:
            if not coupon_share.release_count < coupon_share.limit_share_count:  # 领取次数必须小于最大领取限制
                return Response({"code": 8, "msg": "领取完了", "coupon_id": ''})
        if not ufrom:
            logger.warn('customer:{0}, param ufrom is None'.format(
                customer.id))

        # not need anymore, 20170217
        return Response({"code": 11, "msg": '红包停止发放', "coupon_id": ''})
        template_id = coupon_share.template_id
        coupon, code, msg = create_user_coupon(customer_id=customer.id,
                                               coupon_template_id=template_id,
                                               order_share_id=coupon_share.id,
                                               ufrom=ufrom)
        if code != 0:
            return Response({"code": code, "msg": msg, "coupon_id": ''})
        else:
            return Response({"code": code, "msg": msg, "coupon_id": coupon.id})
Exemplo n.º 4
0
    def refund_order(self, request, pk, *args, **kwargs):
        data = request.data
        saleorder_id = data.get('saleorder_id')
        refund_num = data.get('refund_num')
        lack_order = self.get_object()
        if not saleorder_id.isdigit() or not refund_num.isdigit():
            return Response({'code': 1, 'info': u'订单编号及数量不对'})

        sale_order = SaleOrder.objects.filter(id=saleorder_id).first()
        if not sale_order or \
                not lack_order.get_refundable() or \
                        int(sale_order.sku_id) != int(lack_order.sku_id) or \
                not sale_order.get_refundable():
            return Response({'code': 2, 'info': u'自动退款条件不满足'})

        user_id = request.user.id
        refund_num = int(refund_num)
        refund_fee = round((sale_order.payment / (sale_order.num or 0)) * refund_num, 2)
        sale_trade = sale_order.sale_trade
        refund_channel = sale_trade.channel

        try:
            with transaction.atomic():
                refund = create_refund_order(
                    user_id, saleorder_id, 0, refund_num, refund_fee, refund_channel,
                    desc=u'订单缺货自动退款,补发10优惠券', good_status=SaleRefund.SELLER_OUT_STOCK,
                    modify=None, proof_pic=None, is_lackrefund=True, lackorder_id=lack_order.id
                )
            if not refund.is_refundapproved:
                # 发优惠券
                create_user_coupon(customer_id=sale_trade.buyer_id,
                                   coupon_template_id=LACK_REFUND_COUPON_TEMPLATE_ID,
                                   trade_id=sale_trade.id)
                # 退款
                refund.refund_approve()
                lack_order.refund_num += refund_num
                lack_order.is_refund = True
                lack_order.save(update_fields=['refund_num', 'is_refund'])
                # TODO app推送
        except Exception, exc:
            logger.error('lackrefund-error:%s' % exc.message, exc_info=True)
            return Response({'code': 1, 'info': exc.message})
Exemplo n.º 5
0
def release_tmp_share_coupon(customer):
    """
    查看临时优惠券中的优惠券是否存在未发的发放
    """
    if not customer:
        return True
    tmp_coupons = TmpShareCoupon.objects.filter(mobile=customer.mobile,
                                                status=False)
    st = is_old_customer(customer.id)
    for tmp_coupon in tmp_coupons:
        share = OrderShareCoupon.objects.filter(
            uniq_id=tmp_coupon.share_coupon_id).first()
        if not share:
            continue
        tpl = share.template
        if not tpl:
            continue
        try:
            if tpl.coupon_type == CouponTemplate.TYPE_ORDER_SHARE:
                # 存在订单分享优惠券
                has_order_share_coupon = UserCoupon.objects.filter(
                    customer_id=customer.id,
                    coupon_type=UserCoupon.TYPE_ORDER_SHARE).exists()
                template_id = constants.LIMIT_ORDER_SHARE_COUPON_TEMPLATE if st or has_order_share_coupon else tpl.id
                create_user_coupon(customer_id=customer.id,
                                   coupon_template_id=template_id,
                                   order_share_id=share.id,
                                   coupon_value=tmp_coupon.value,
                                   ufrom=u'tmp')
            elif tpl.coupon_type == CouponTemplate.TYPE_ACTIVE_SHARE:
                create_user_coupon(customer_id=customer.id,
                                   coupon_template_id=tpl.id,
                                   order_share_id=share.id,
                                   ufrom=u'tmp')
            tmp_coupon.status = True
            tmp_coupon.save(update_fields=['status'])  # 更新状态到已经领取
        except Exception as exc:
            logger.error(u'release_tmp_share_coupon for customer %s -%s' %
                         (customer.id, exc))
            continue
    return True
Exemplo n.º 6
0
    def pick_order_share_coupon(self, request):
        content = request.POST
        uniq_id = content.get("uniq_id") or ''
        ufrom = content.get("ufrom") or ''
        customer = get_customer(request)
        default_return = collections.defaultdict(code=0, msg='', coupon={})
        if customer is None:
            default_return.update({"code": 9, "msg": "用户不存在"})
            return Response(default_return)
        if not uniq_id:
            default_return.update({"code": 10, "msg": "参数错误"})
            return Response(default_return)
        coupon_share = self.queryset.filter(uniq_id=uniq_id).first()
        if coupon_share is None:
            default_return.update({"code": 8, "msg": "领取完了哦"})
            return Response(default_return)
        else:

            urelase_tmp_count = TmpShareCoupon.objects.filter(
                share_coupon_id=uniq_id, status=False).count()  # 临时未 领取
            if not (coupon_share.release_count + urelase_tmp_count
                    ) < coupon_share.limit_share_count:  # 领取次数必须小于最大领取限制
                default_return.update({"code": 8, "msg": "领取完了"})
                return Response(default_return)
        if not ufrom:
            logger.warn('customer:{0}, param ufrom is None'.format(
                customer.id))

        # not need anymore, 20170217
        return Response({"code": 11, "msg": '红包停止发放'})
        # 判断当前用户是否有 历史订单
        st = is_old_customer(customer.id)
        # 如果有订单的用户 再次领取的分享优惠券为指定的其他优惠券
        template_id = constants.LIMIT_ORDER_SHARE_COUPON_TEMPLATE if st else coupon_share.template_id
        coupon, code, msg = create_user_coupon(customer_id=customer.id,
                                               coupon_template_id=template_id,
                                               order_share_id=coupon_share.id,
                                               ufrom=ufrom)
        if code != 0:
            default_return.update({"code": code, "msg": msg})
            return Response(default_return)
        else:
            default_return.update({"code": code, "msg": msg})
            serializer = serializers.UserCouponSerialize(coupon)
            return Response({
                "code": code,
                "msg": msg,
                "coupon": serializer.data
            })
Exemplo n.º 7
0
    def post(self, request, event_id, *args, **kwargs):
        content = request.POST
        template_id = content.get("template_id", 0)
        customer = Customer.objects.get(user=request.user)
        customer_id = customer.id
        from flashsale.coupon.apis.v1.usercoupon import create_user_coupon
        cou, code, msg = create_user_coupon(
            customer_id=customer.id, coupon_template_id=int(template_id))

        if code == 0:
            winner = AwardWinner.objects.get(customer_id=customer_id,
                                             event_id=event_id)
            winner.status = 1
            winner.save()

        response = Response({"code": code, "res": msg})
        response["Access-Control-Allow-Origin"] = "*"
        return response
Exemplo n.º 8
0
 def create(self, request, *args, **kwargs):
     """ 根据参数生成不同类型的优惠券,多张优惠券逗号分隔 """
     content = request.POST
     template_ids = content.get("template_id") or ''
     if not template_ids:  # 参数有误
         return Response({"code": 7, "res": "优惠券不存在", "coupons": ""})
     try:
         template_ids = [int(i) for i in template_ids.split(',')]
         customer = Customer.objects.get(user=request.user)
         if template_ids:  # 根据模板id发放
             code = 7
             msg = u'没有发放'
             coupon_ids = []
             for template_id in template_ids:
                 try:
                     coupon, code, msg = create_user_coupon(
                         customer_id=customer.id,
                         coupon_template_id=template_id,
                         ufrom='wx')
                     if coupon:  # 添加返回的coupon
                         coupon_ids.append(coupon.id)
                 except:
                     continue
             queryset = self.queryset.filter(id__in=coupon_ids)
             serializer = self.get_serializer(queryset, many=True)
             if code == 0:
                 # 推送消息提醒
                 task_release_coupon_push.s(customer.id).delay()
             return Response({
                 "code": code,
                 "res": msg,
                 "coupons": serializer.data
             })
     except Customer.DoesNotExist:
         return Response({"code": 8, "res": "需登陆后领取", "coupons": ""})
     except TypeError:
         return Response({"code": 7, "res": "优惠券不存在", "coupons": ""})
     else:
         return Response({"code": 7, "res": "优惠券不存在", "coupons": ""})
Exemplo n.º 9
0
def refund_coupon(sale_refund, amount_flow=None, im_execute=True):
    # type : (SaleRefund, Optional[Dict[str, *Ant]], bool) -> bool
    """补邮费优惠券给用户
    """
    from flashsale.coupon.apis.v1.usercoupon import create_user_coupon

    if amount_flow and amount_flow != sale_refund.amount_flow:
        sale_refund.amount_flow = amount_flow
        sale_refund.save(update_fields=['amount_flow'])
    if not im_execute:
        return im_execute
    try:
        if isinstance(sale_refund.amount_flow, dict):
            refund_coupon_info = sale_refund.amount_flow.get('refund_coupon')
            if refund_coupon_info:
                coupon_template_id = refund_coupon_info.get('template_id')
                send_status = refund_coupon_info.get('send_status')
                if coupon_template_id and not send_status:
                    cou, code, msg = create_user_coupon(
                        sale_refund.buyer_id,
                        coupon_template_id,
                        trade_id=sale_refund.trade_id)
                    if code == 0:
                        refund_coupon_info.update({
                            'send_status': True,
                            'coupon_id': cou.id,
                            'coupon_value': cou.value
                        })
                        sale_refund.amount_flow.update(
                            {'refund_coupon': refund_coupon_info})
                        sale_refund.save(update_fields=['amount_flow'])
                        return True
    except Exception as e:
        logger.error({
            'action': u'refund_coupon %s' % sale_refund.id,
            'message': e.message
        })
        return False
    return False