CouponController.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import time
  4. from django.db.models import F
  5. from django.http import HttpResponse
  6. from django.views.generic.base import View
  7. from Ansjer.config import LOGGER
  8. from Controller.CloudPhoto.CloudServiceController import CloudServiceController
  9. from Model.models import CouponModel, Device_User
  10. from Object.Enums.ConstantEnum import ConstantEnum
  11. from Object.ResponseObject import ResponseObject
  12. from Object.TokenObject import TokenObject
  13. from Service.CommonService import CommonService
  14. # 优惠券
  15. class CouponView(View):
  16. def get(self, request, *args, **kwargs):
  17. request.encoding = 'utf-8'
  18. operation = kwargs.get('operation')
  19. return self.validation(request.GET, request, operation)
  20. def post(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. operation = kwargs.get('operation')
  23. return self.validation(request.POST, request, operation)
  24. def validation(self, request_dict, request, operation):
  25. response = ResponseObject()
  26. if operation is None:
  27. return response.json(444, 'error path')
  28. if operation == 'generateCoupon': # 用户优惠券
  29. return self.generate_coupon(request_dict, response)
  30. else:
  31. token = request_dict.get('token', None)
  32. tko = TokenObject(token)
  33. response.lang = tko.lang
  34. if tko.code != 0:
  35. return response.json(tko.code)
  36. userID = tko.userID
  37. if operation == 'UserCoupon': # 用户优惠券
  38. return self.query_user_coupon(request_dict, userID, response)
  39. elif operation == 'createCoupon':
  40. self.generate_coupon_by_user(userID)
  41. return response.json(0)
  42. else:
  43. return response.json(414)
  44. def generate_coupon(self, request_dict, response):
  45. username = request_dict.get('username', None)
  46. num = request_dict.get('num', None)
  47. userID = Device_User.objects.filter(username=username).values('userID')[0]['userID']
  48. coupon_config_id = request_dict.get('coupon_config_id', 1)
  49. try:
  50. data = []
  51. # CouponConfigModel.objects.create(type=1, use_range=1, coupon_discount=8)
  52. # CouponLangObj = CouponLang.objects.create(
  53. # lang='cn',
  54. # instruction='用于自动续费套餐的首月',
  55. # quota='八',
  56. # unit='折',
  57. # remark='每台摄像机上只能用一次'
  58. # )
  59. # CouponConfigModel.objects.get(id=1).lang.add(CouponLangObj.id)
  60. now_time = int(time.time())
  61. CouponModel.objects.create(
  62. use_status=0,
  63. distribute_time=now_time,
  64. valid_time=now_time + 10000000,
  65. userID=userID,
  66. coupon_config_id=coupon_config_id,
  67. update_time=now_time,
  68. create_time=now_time
  69. )
  70. return HttpResponse('success')
  71. except Exception as e:
  72. return HttpResponse(
  73. "错误行数:{errLine}, 错误信息: {errmsg}".format(errLine=e.__traceback__.tb_lineno, errmsg=repr(e)))
  74. def query_user_coupon(self, request_dict, userID, response): # 用户优惠券列表
  75. now_time = int(time.time())
  76. lang = request_dict.get('lang', 'en')
  77. if lang not in ['en', 'cn']:
  78. lang = 'en'
  79. coupon_obj = CouponModel.objects.filter(
  80. userID=userID,
  81. use_status=0,
  82. distribute_time__lte=now_time,
  83. valid_time__gt=now_time,
  84. coupon_config__lang__lang=lang,
  85. ).annotate(
  86. coupon_id=F('id'),
  87. type=F('coupon_config__type'),
  88. coupon_discount=F('coupon_config__coupon_discount'),
  89. instruction=F('coupon_config__lang__instruction'),
  90. remark=F('coupon_config__lang__remark'),
  91. quota=F('coupon_config__lang__quota'),
  92. unit=F('coupon_config__lang__unit'),
  93. config_id=F('coupon_config_id')
  94. ).values(
  95. "coupon_id",
  96. "type",
  97. "coupon_discount",
  98. "valid_time",
  99. "instruction",
  100. "remark",
  101. "quota",
  102. "unit",
  103. "config_id"
  104. )
  105. for couponList in coupon_obj:
  106. couponList['valid_time'] = CommonService.timestamp_to_str(couponList['valid_time'])
  107. couponList['comboList'] = CloudServiceController.get_combo_list(0, couponList['config_id'])
  108. result = {
  109. 'count': coupon_obj.count(),
  110. 'couponList': list(coupon_obj),
  111. }
  112. return response.json(0, result)
  113. @staticmethod
  114. def generate_coupon_by_user(user_id):
  115. """
  116. 赠送优惠券圣诞节
  117. @param user_id: 用户ID
  118. @return: True | False
  119. """
  120. try:
  121. end_timestamp = ConstantEnum.PROMOTION_END_TIME.value
  122. now_time = int(time.time())
  123. if now_time >= end_timestamp:
  124. LOGGER.info('活动已结束,无法赠送优惠券')
  125. return False
  126. # 赠送三个优惠券
  127. for i in range(1, 4): # 赠送三个优惠券
  128. coupon_config_id = 21 if i < 3 else 22 # 21 9折 22 8折
  129. CouponModel.objects.create(
  130. use_status=0,
  131. distribute_time=now_time,
  132. valid_time=end_timestamp,
  133. userID=user_id,
  134. coupon_config_id=coupon_config_id,
  135. update_time=now_time,
  136. create_time=now_time
  137. )
  138. return True
  139. except Exception as e:
  140. # 记录异常信息
  141. LOGGER.error('赠送优惠券异常 user: {}: errLine: {}, errMsg: {}'.format(
  142. user_id, e.__traceback__.tb_lineno, repr(e)))
  143. return False