Example #1
0
 def test_detail(self):
     # 创建已领取的优惠券
     self.factory.create_coupon(number=8,
                                rule=self.coupon_rule,
                                status=COUPON_STATUS['NOT_USED'])
     self.factory.create_coupon(number=2,
                                rule=self.coupon_rule,
                                status=COUPON_STATUS['USED'])
     detail = self.manager.detail()
     self.assertEqual(
         detail,
         dict(merchant=self.coupon_rule.merchant.name,
              merchant_location_lon=self.coupon_rule.merchant.location_lon,
              merchant_location_lat=self.coupon_rule.merchant.location_lat,
              discount=get_amount(self.coupon_rule.discount),
              min_charge=get_amount(self.coupon_rule.min_charge),
              valid_strategy=self.coupon_rule.valid_strategy,
              start_date=self.coupon_rule.start_date,
              end_date=self.coupon_rule.end_date,
              expiration_days=self.coupon_rule.expiration_days,
              stock=self.coupon_rule.stock,
              photo_url=self.coupon_rule.photo_url,
              datetime=self.coupon_rule.datetime.date(),
              obtain_num=10,
              used_num=2))
Example #2
0
 def to_representation(self, instance):
     """customize serializer.data"""
     ret = super(CouponRuleSerializer, self).to_representation(instance)
     ret = (json.loads(json.dumps(ret)))  # ret is immutable object, change it to dict
     ret['discount'] = get_amount(ret['discount'])
     ret['min_charge'] = get_amount(ret['min_charge'])
     return ret
Example #3
0
    def merchant_business_report(self, datetime_start, datetime_end) -> dict:
        """
        经营报表数据 (营业额, 收款单数, 引流支出, 引流收益)
        :return {
                    "turnover": 1000.1,
                    "payment": {
                        "use_coupon": 1,
                        "not_use_coupon": 10
                    },
                    "originator_earning": 10.01,
                    "originator_expenditure": 1
                }
        """
        not_refund_status = [
            PAYMENT_STATUS.FROZEN, PAYMENT_STATUS.REFUND_REQUESTED,
            PAYMENT_STATUS.REFUND_FAILED, PAYMENT_STATUS.FINISHED
        ]

        result = Payment.objects.filter(merchant=self.obj, ).exclude(
            status__in=(PAYMENT_STATUS.UNPAID, PAYMENT_STATUS.CANCELLED),
        ).filter(
            Q(datetime__gte=datetime_start),
            Q(datetime__lt=datetime_end),
        ).aggregate(
            # 所有账单总金额 - 优惠券总减免金额
            turnover=Sum('order_price',
                         filter=Q(status__in=not_refund_status)) - Coalesce(
                             Sum('coupon__discount',
                                 filter=Q(coupon__isnull=False,
                                          status__in=not_refund_status)), 0),
            originator_expenditure=Sum(
                'platform_share', filter=Q(status__in=not_refund_status)) +
            Sum('inviter_share', filter=Q(status__in=not_refund_status)) +
            Sum('originator_share', filter=Q(status__in=not_refund_status)),
            use_coupon=Count('pk', filter=Q(coupon__isnull=False)),
            not_use_coupon=Count('pk', filter=Q(coupon__isnull=True)))

        originator_earning = Transaction.objects.filter(
            account__merchant=self.obj, ).filter(
                Q(datetime__gte=datetime_start),
                Q(datetime__lt=datetime_end),
            ).aggregate(originator_earning=Sum(
                'amount',
                filter=Q(transaction_type=TRANSACTION_TYPE.MERCHANT_SHARE)), )

        result.update(originator_earning)
        result['turnover'] = get_amount(result['turnover'] or 0)
        result['originator_expenditure'] = get_amount(
            result['originator_expenditure'] or 0)
        result['originator_earning'] = get_amount(result['originator_earning']
                                                  or 0)
        result['payment'] = dict(use_coupon=result['use_coupon'],
                                 not_use_coupon=result['not_use_coupon'])
        del result['use_coupon']
        del result['not_use_coupon']

        return result
Example #4
0
    def send_refund_fail_message(self):
        payment = self.obj.payment
        paid_price = payment.order_price if not payment.coupon else payment.order_price - payment.coupon.discount

        message_sender = MerchantMessageSender(payment.merchant)
        message_sender.on_refund_fail(
            refund_amount='%.2f' % get_amount(paid_price),
            refund_datetime=timezone.now(),
            refund_serial_number=payment.serial_number)
Example #5
0
def send_pay_success_wechat_message(payment):
    """付款成功微信消息推送"""

    payment = PaymentManager(payment)

    message_sender = MerchantMessageSender(payment.merchant)
    message_sender.on_pay_success(
        merchant_receive='%.2f' % get_amount(payment.paid_price),
        payment_type='普通订单' if not payment.coupon else '优惠券订单',
        datetime=payment.datetime,
        pay_serial_number=payment.serial_number,
    )
Example #6
0
def render(field_data):
    """
    :param field_data: django field data
    :return: rendered data
    >>> render(datetime(2018, 1, 1, 0, 0, 0))
    >>> '2018-01-01 00:00'
    >>> render(30010)
    >>> 300.1
    """
    if isinstance(field_data, datetime):
        return field_data.strftime('%Y-%m-%d %H:%M')
    elif isinstance(field_data, int):
        return get_amount(field_data)
    else:
        return field_data
Example #7
0
        def list_every_day(queryset):
            lst = []
            day_p = date_start  # date pointer
            # date = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
            # turnover有2种情况:
            # data = [      2, 3,       6             ]
            # data = []
            for data in queryset:
                while day_p < data['date']:
                    lst.append(dict(date=day_p.strftime('%Y-%m-%d'), amount=0))
                    day_p = day_p + timedelta(days=1)
                lst.append(
                    dict(date=day_p.strftime('%Y-%m-%d'),
                         amount=get_amount(data['amount'] or 0)))
                day_p = day_p + timedelta(days=1)

            # 补全日期数据(7-10 or 0-10)
            while day_p < date_end:
                lst.append(dict(date=day_p.strftime('%Y-%m-%d'), amount=0))
                day_p = day_p + timedelta(days=1)

            return lst
Example #8
0
    def voice_text(self):
        pay_channel_name = PAY_CHANNELS.number_name_dict()[
            self.obj.pay_channel]  # '微信', '支付宝'
        price = get_amount(self.paid_price)

        return f'{pay_channel_name}到帐: {price}元。'
Example #9
0
    def test_get_amount(self):
        self.assertEqual(get_amount(0), 0)
        self.assertEqual(get_amount(1), 0.01)
        self.assertEqual(get_amount(30000), 300)
        self.assertEqual(get_amount(30030), 300.3)
        self.assertEqual(get_amount(30033), 300.33)

        self.assertEqual(get_amount('0'), 0)
        self.assertEqual(get_amount('1'), 0.01)
        self.assertEqual(get_amount('30000'), 300)
        self.assertEqual(get_amount('30030'), 300.3)
        self.assertEqual(get_amount('30033'), 300.33)

        self.assertEqual(get_amount('0.00'), 0)
        self.assertEqual(get_amount('1.0'), 0.01)
        self.assertEqual(get_amount('30000.00'), 300)
        self.assertEqual(get_amount('30030.00'), 300.3)
        self.assertEqual(get_amount('30033.00'), 300.33)
Example #10
0
    def account_alipay_withdraw_balance(self):
        """商户账户支付宝可提现金额"""
        amount = get_amount(self.obj.account.alipay_withdrawable_balance)

        # 不足支付宝最小可提现余额时, 可提现余额前端显示为0
        return amount
Example #11
0
 def account_alipay_balance(self):
     """商户账户支付宝余额"""
     return get_amount(self.obj.account.alipay_balance)
Example #12
0
    def account_wechat_withdraw_balance(self):
        """商户账户微信可提现金额"""
        amount = get_amount(self.obj.account.withdrawable_balance)

        # 不足微信最小可提现余额时, 可提现余额前端显示为0
        return amount
Example #13
0
 def account_wechat_balance(self):
     """商户账户微信余额"""
     return get_amount(self.obj.account.balance)
Example #14
0
    def test_update(self):
        self._create_coupon_rule()
        # 修改优惠券库存
        for stock in (0, 1, 300, 301):
            coupon_rule = self.coupon_rule
            old_update_datetime = coupon_rule.update_datetime

            url = reverse('coupon-detail', kwargs=dict(pk=self.coupon_rule.id))
            response = self.client.put(url,
                                       data=dict(stock=stock),
                                       Token=self.token,
                                       format='json')  # auth by token
            detail = response.json()
            self.assertEqual(
                detail,
                dict(
                    discount=get_amount(self.coupon_rule.discount),
                    min_charge=get_amount(self.coupon_rule.min_charge),
                    valid_strategy=self.coupon_rule.valid_strategy,
                    start_date=self.coupon_rule.start_date.strftime(
                        '%Y-%m-%d'),
                    end_date=self.coupon_rule.end_date.strftime('%Y-%m-%d'),
                    expiration_days=self.coupon_rule.expiration_days,
                    stock=stock,
                    photo_url=self.coupon_rule.photo_url,
                    note=self.coupon_rule.note,
                ))

            # 检查修改库存的coupon_rule
            coupon_rule.refresh_from_db()

            self.assertEqual(coupon_rule.discount,
                             set_amount(detail['discount']))
            self.assertEqual(coupon_rule.min_charge,
                             set_amount(detail['min_charge']))
            self.assertEqual(coupon_rule.valid_strategy,
                             detail['valid_strategy'])
            self.assertEqual(str(coupon_rule.start_date), detail['start_date'])
            self.assertEqual(str(coupon_rule.end_date), detail['end_date'])
            self.assertNotEqual(coupon_rule.update_datetime,
                                old_update_datetime)

        # 不存在的优惠券
        url = reverse('coupon-detail', kwargs=dict(pk='id_not_exist'))
        response = self.client.put(url, Token=self.token,
                                   format='json')  # auth by token
        resp_json = response.json()
        self.assertEqual(resp_json, {
            'detail': '未找到。',
            'error_code': 'not_found'
        })

        # 非商户创建的优惠券
        another_coupon_rule = self.factory.create_coupon_rule()
        url = reverse('coupon-detail', kwargs=dict(pk=another_coupon_rule.id))
        response = self.client.put(url, Token=self.token,
                                   format='json')  # auth by token
        resp_json = response.json()
        self.assertEqual(resp_json, {
            'detail': '未找到。',
            'error_code': 'not_found'
        })