UnicomComboTaskController.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UnicomComboTaskController.py
  4. @Time : 2022/6/30 16:23
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import datetime
  10. import logging
  11. import time
  12. from django.db import transaction
  13. from django.views import View
  14. from Model.models import UnicomComboOrderInfo, UnicomCombo, Order_Model
  15. from Object.ResponseObject import ResponseObject
  16. from Object.UnicomObject import UnicomObjeect
  17. class UnicomComboTaskView(View):
  18. def get(self, request, *args, **kwargs):
  19. request.encoding = 'utf-8'
  20. operation = kwargs.get('operation')
  21. return self.validation(request.GET, request, operation)
  22. def post(self, request, *args, **kwargs):
  23. request.encoding = 'utf-8'
  24. operation = kwargs.get('operation')
  25. return self.validation(request.POST, request, operation)
  26. def validation(self, request_dict, request, operation):
  27. response = ResponseObject()
  28. print(request)
  29. if operation == 'check-activate':
  30. return self.check_activate_combo(request_dict, response)
  31. elif operation == 'check-flow':
  32. return self.check_flow_usage(response)
  33. elif operation == 'check-expire':
  34. today = datetime.datetime.today()
  35. year = today.year
  36. month = today.month
  37. self.query_unused_combo_and_activate(request_dict.get('iccid'), year, month, '666')
  38. return response.json(0)
  39. @classmethod
  40. def check_activate_combo(cls, request_dict, response):
  41. """
  42. 定时检查是否有次月激活套餐
  43. @param request_dict:
  44. @param response:
  45. @return:
  46. """
  47. logger = logging.getLogger('info')
  48. print(request_dict)
  49. logger.info('定时检查是否有次月激活联通套餐')
  50. now_time = int(time.time())
  51. combo_order_info_qs = UnicomComboOrderInfo.objects.filter(status=0, next_month_activate=True,
  52. activation_time__lte=now_time,
  53. expire_time__gte=now_time, is_del=0).values()
  54. if not combo_order_info_qs.exists():
  55. return response.json(0)
  56. try:
  57. now_time = int(time.time())
  58. today = datetime.datetime.today()
  59. year = today.year
  60. month = today.month
  61. with transaction.atomic():
  62. unicom_api = UnicomObjeect()
  63. for item in combo_order_info_qs:
  64. if item['order_id']:
  65. order_id = item['order_id']
  66. order_qs = Order_Model.objects.filter(orderID=order_id, status=1)
  67. if not order_qs.exists():
  68. continue
  69. combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1, iccid=item['iccid'])
  70. # 当前已有套餐正在使用则跳出当前循环
  71. if combo_order_qs.exists():
  72. continue
  73. combo_id = item['combo_id']
  74. combo_qs = UnicomCombo.objects.filter(id=combo_id).values()
  75. if not combo_qs.exists():
  76. continue
  77. flow_total_usage = unicom_api.get_flow_usage_total(year, month, item['iccid'])
  78. flow_total_usage = str(flow_total_usage)
  79. params = {'iccid': item['iccid']}
  80. result = unicom_api.query_device_status(**params)
  81. res_dict = unicom_api.get_text_dict(result)
  82. # 状态不等于1(激活)时进行激活 1:激活;2:停用
  83. if res_dict['data']['status'] != 1:
  84. re_data = {"iccid": item['iccid'], "status": 1}
  85. unicom_api.update_device_state(**re_data)
  86. UnicomComboOrderInfo.objects.filter(id=item['id']) \
  87. .update(status=1, updated_time=now_time, year=year, month=month,
  88. flow_total_usage=flow_total_usage)
  89. else:
  90. UnicomComboOrderInfo.objects.filter(id=item['id']) \
  91. .update(status=1, updated_time=now_time, year=year, month=month,
  92. flow_total_usage=flow_total_usage)
  93. logger.info('激活成功,订单编号:{}'.format(order_id))
  94. return response.json(0)
  95. except Exception as e:
  96. print(e)
  97. return response.json(177, repr(e))
  98. @classmethod
  99. def check_flow_usage(cls, response):
  100. """
  101. 检查流量使用情况
  102. @return:
  103. """
  104. logger = logging.getLogger('info')
  105. logger.info('进入检查流量使用情况')
  106. try:
  107. combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1).values()
  108. if not combo_order_qs.exists():
  109. return response.json(0)
  110. today = datetime.datetime.today()
  111. year = today.year
  112. month = today.month
  113. unicom_api = UnicomObjeect()
  114. now_time = int(time.time())
  115. for item in combo_order_qs:
  116. iccid = item['iccid']
  117. usage_flow = float(item['flow_total_usage']) if item['flow_total_usage'] else 0.0
  118. combo_id = item['combo_id']
  119. combo_qs = UnicomCombo.objects.filter(id=combo_id).values()
  120. if combo_qs.exists():
  121. combo_qs = combo_qs.first()
  122. flow_total = combo_qs['flow_total']
  123. # 查询当前月用量历史
  124. month_usage_flow = unicom_api.get_flow_usage_total(year, month, iccid)
  125. is_expire = False
  126. if item['year'] == year and item['month'] == month:
  127. if month_usage_flow > 0:
  128. # 初始套餐已使用流量 + 套餐总流量
  129. flow = usage_flow + flow_total
  130. if month_usage_flow >= flow:
  131. is_expire = True
  132. else:
  133. activate_year = item['year']
  134. activate_month = item['month']
  135. # 上月使用流量
  136. last_usage_flow = unicom_api.get_flow_usage_total(activate_year, activate_month, iccid)
  137. # 上月套餐实际使用量
  138. actual_usage_flow = last_usage_flow - usage_flow
  139. # 剩余
  140. surplus_flow = flow_total - actual_usage_flow
  141. # result = Decimal(surplus_flow).quantize(Decimal('0.00'))
  142. if month_usage_flow > 0:
  143. if month_usage_flow >= surplus_flow:
  144. is_expire = True
  145. # 检查是否有当月未使用套餐 没有则停卡
  146. if is_expire:
  147. UnicomComboOrderInfo.objects.filter(id=item['id']).update(status=2, updated_time=now_time)
  148. activate_status = cls.query_unused_combo_and_activate(iccid, year, month,
  149. month_usage_flow)
  150. if not activate_status:
  151. re_data = {"iccid": iccid, "status": 2}
  152. unicom_api.update_device_state(**re_data)
  153. return response.json(0)
  154. except Exception as e:
  155. logger.info('网关推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  156. return response.json(177, repr(e))
  157. @staticmethod
  158. def query_unused_combo_and_activate(iccid, year, month, usage_flow):
  159. """
  160. 查询未使用套餐并激活
  161. @param iccid:
  162. @param year:
  163. @param month:
  164. @param usage_flow:
  165. @return:
  166. """
  167. try:
  168. now_time = int(time.time())
  169. combo_order_qs = UnicomComboOrderInfo.objects.filter(expire_time__gt=now_time, status=0,
  170. iccid=iccid).order_by(
  171. 'created_time')
  172. if not combo_order_qs.exists():
  173. return False
  174. combo_order = combo_order_qs.first()
  175. upd_data = {
  176. 'status': 1,
  177. 'year': year,
  178. 'month': month,
  179. 'flow_total_usage': str(usage_flow),
  180. 'updated_time': now_time,
  181. }
  182. UnicomComboOrderInfo.objects.filter(id=combo_order.id).update(**upd_data)
  183. return True
  184. except Exception as e:
  185. print(e)
  186. return False