UnicomComboTaskController.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 decimal import Decimal
  13. from django.db import transaction
  14. from django.db.models import Q
  15. from django.views import View
  16. from Model.models import UnicomComboOrderInfo, UnicomCombo, Order_Model, UnicomDeviceInfo, UnicomFlowPush
  17. from Object.ResponseObject import ResponseObject
  18. from Object.UnicomObject import UnicomObjeect
  19. class UnicomComboTaskView(View):
  20. def get(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. operation = kwargs.get('operation')
  23. return self.validation(request.GET, request, operation)
  24. def post(self, request, *args, **kwargs):
  25. request.encoding = 'utf-8'
  26. operation = kwargs.get('operation')
  27. return self.validation(request.POST, request, operation)
  28. def validation(self, request_dict, request, operation):
  29. response = ResponseObject()
  30. print(request)
  31. if operation == 'check-activate':
  32. return self.check_activate_combo(request_dict, response)
  33. elif operation == 'check-flow':
  34. return self.check_flow_usage(response)
  35. elif operation == 'check-flow-expire':
  36. return self.check_flow_expire(response)
  37. elif operation == 'check-expire':
  38. today = datetime.datetime.today()
  39. year = today.year
  40. month = today.month
  41. self.query_unused_combo_and_activate(request_dict.get('iccid'), year, month, '666')
  42. return response.json(0)
  43. @classmethod
  44. def check_activate_combo(cls, request_dict, response):
  45. """
  46. 定时检查是否有次月激活套餐
  47. @param request_dict:
  48. @param response:
  49. @return:
  50. """
  51. logger = logging.getLogger('info')
  52. print(request_dict)
  53. logger.info('--->进入监控次月激活联通套餐')
  54. now_time = int(time.time())
  55. combo_order_info_qs = UnicomComboOrderInfo.objects.filter(status=0, next_month_activate=True,
  56. activation_time__lte=now_time,
  57. expire_time__gte=now_time, is_del=0).values()
  58. if not combo_order_info_qs.exists():
  59. return response.json(0)
  60. try:
  61. today = datetime.datetime.today()
  62. year = today.year
  63. month = today.month
  64. with transaction.atomic():
  65. unicom_api = UnicomObjeect()
  66. for item in combo_order_info_qs:
  67. if item['order_id']:
  68. order_id = item['order_id']
  69. order_qs = Order_Model.objects.filter(orderID=order_id, status=1)
  70. if not order_qs.exists():
  71. continue
  72. combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1, iccid=item['iccid'])
  73. # 当前已有套餐正在使用则跳出当前循环
  74. if combo_order_qs.exists():
  75. continue
  76. combo_id = item['combo_id']
  77. combo_qs = UnicomCombo.objects.filter(id=combo_id).values()
  78. if not combo_qs.exists():
  79. continue
  80. # 查询当月用量情况
  81. flow_total_usage = unicom_api.get_flow_usage_total(item['iccid'])
  82. flow_total_usage = Decimal(flow_total_usage).quantize(
  83. Decimal('0.00')) if flow_total_usage > 0 else 0
  84. flow_total_usage = str(flow_total_usage)
  85. iccid = item['iccid']
  86. # 检查激活iccid
  87. unicom_api.change_device_to_activate(iccid)
  88. cls.query_unused_combo_and_activate(iccid, year, month, flow_total_usage)
  89. logger.info('激活成功,订单编号:{}'.format(order_id))
  90. return response.json(0)
  91. except Exception as e:
  92. logger.info('出错了~次月激活套餐异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  93. return response.json(177, repr(e))
  94. @classmethod
  95. def check_flow_usage(cls, response):
  96. """
  97. 检查流量使用情况
  98. @return:
  99. """
  100. logger = logging.getLogger('info')
  101. logger.info('--->进入监控流量使用情况')
  102. try:
  103. unicom_api = UnicomObjeect()
  104. combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1, is_del=False, combo__is_unlimited=0).values()
  105. if not combo_order_qs.exists():
  106. return response.json(0)
  107. today = datetime.datetime.today()
  108. year = today.year
  109. month = today.month
  110. now_time = int(time.time())
  111. for item in combo_order_qs:
  112. iccid = item['iccid']
  113. u_device_info_qs = UnicomDeviceInfo.objects.filter(iccid=iccid)
  114. if not u_device_info_qs.exists():
  115. continue
  116. u_device_info_qs = u_device_info_qs.first()
  117. activate_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 not combo_qs.exists():
  121. continue
  122. combo_qs = combo_qs.first()
  123. flow_total = combo_qs['flow_total']
  124. # 队列已使用总流量总量
  125. flow_total_usage = unicom_api.get_flow_usage_total(iccid)
  126. logger.info('--->iccid:{};套餐总值:{},激活时队列已用总流量:{},当前最新套餐队列已使用流量量:{}'
  127. .format(iccid, flow_total, activate_usage_flow, flow_total_usage))
  128. is_expire = False
  129. flow = activate_usage_flow + flow_total
  130. if flow_total_usage > 0:
  131. # 初始套餐已使用流量 + 套餐总流量
  132. if flow_total_usage >= flow:
  133. is_expire = True
  134. usage = (flow_total_usage - activate_usage_flow) if flow_total_usage > activate_usage_flow else 0
  135. cls.flow_warning_push(u_device_info_qs.user_id, u_device_info_qs.serial_no, item['id'], flow_total,
  136. usage)
  137. # 检查是否有当月未使用套餐 没有则停卡
  138. if is_expire:
  139. flow_exceed = flow_total_usage - flow
  140. UnicomComboOrderInfo.objects.filter(id=item['id']) \
  141. .update(status=2, updated_time=now_time, flow_exceed=flow_exceed)
  142. activate_status = cls.query_unused_combo_and_activate(iccid, year, month,
  143. flow_total_usage)
  144. if not activate_status:
  145. # 停用
  146. unicom_api.change_device_to_disable(iccid)
  147. return response.json(0)
  148. except Exception as e:
  149. logger.info('出错了~检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  150. return response.json(177, repr(e))
  151. @staticmethod
  152. def flow_warning_push(app_user_id, serial_no, combo_order_id, flow_total, flow_usage):
  153. """
  154. 监控流量使用大于85%and小于96%进行消息推送提醒
  155. @param app_user_id: app用户id
  156. @param serial_no: 序列号
  157. @param combo_order_id: 当前套餐订单id
  158. @param flow_total: 套餐流量总量
  159. @param flow_usage: 套餐已使用流量
  160. @return:
  161. """
  162. logger = logging.getLogger('info')
  163. try:
  164. if not app_user_id:
  165. return False
  166. now_time = int(time.time())
  167. push_data = {'combo_order_id': str(combo_order_id), 'serial_no': serial_no,
  168. 'flow_total_usage': flow_usage, 'flow_total': flow_total, 'status': 0,
  169. 'updated_time': now_time,
  170. 'created_time': now_time, 'user_id': app_user_id}
  171. if 0 < flow_total and 0 < flow_usage < flow_total:
  172. res = flow_usage / flow_total * 100
  173. if 85 < res <= 95:
  174. flow_push = UnicomFlowPush.objects.filter(serial_no=serial_no, combo_order_id=combo_order_id)
  175. if not flow_push.exists():
  176. UnicomFlowPush.objects.create(**push_data)
  177. elif flow_usage >= flow_total:
  178. push_data['flow_total_usage'] = flow_total
  179. push_data['type'] = 1
  180. UnicomFlowPush.objects.create(**push_data)
  181. return True
  182. except Exception as e:
  183. logger.info('出错了~异常流量监控,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  184. @staticmethod
  185. def query_unused_combo_and_activate(iccid, year, month, usage_flow):
  186. """
  187. 查询未使用套餐并激活
  188. @param iccid:
  189. @param year:
  190. @param month:
  191. @param usage_flow:
  192. @return:
  193. """
  194. logger = logging.getLogger('info')
  195. try:
  196. now_time = int(time.time())
  197. combo_order_qs = UnicomComboOrderInfo.objects \
  198. .filter(expire_time__gt=now_time, activation_time__lte=now_time, status=0, iccid=iccid) \
  199. .order_by('created_time')
  200. if not combo_order_qs.exists():
  201. return False
  202. combo_order = combo_order_qs.first()
  203. if not combo_order.order_id:
  204. return False
  205. order_qs = Order_Model.objects.filter(orderID=combo_order.order_id, status=1)
  206. if not order_qs.exists():
  207. return False
  208. upd_data = {
  209. 'status': 1,
  210. 'year': year,
  211. 'month': month,
  212. 'flow_total_usage': str(usage_flow),
  213. 'updated_time': now_time,
  214. }
  215. UnicomComboOrderInfo.objects.filter(id=combo_order.id).update(**upd_data)
  216. return True
  217. except Exception as e:
  218. logger.info('出错了~检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  219. return False
  220. @classmethod
  221. def check_flow_expire(cls, response):
  222. """
  223. 检查流量到期停卡操作
  224. @param response:
  225. @return:
  226. """
  227. logger = logging.getLogger('info')
  228. logger.info('--->进入监控流量到期停卡或激活叠加包')
  229. now_time = int(time.time())
  230. combo_order_qs = UnicomComboOrderInfo.objects.filter(~Q(status=2), expire_time__lte=now_time,
  231. is_del=False).values()
  232. today = datetime.datetime.today()
  233. year = today.year
  234. month = today.month
  235. if not combo_order_qs.exists():
  236. return response.json(0)
  237. iccid_list = []
  238. with transaction.atomic():
  239. for item in combo_order_qs:
  240. try:
  241. icc_id = item['iccid']
  242. um_device_qs = UnicomDeviceInfo.objects.filter(iccid=icc_id)
  243. if not um_device_qs.exists():
  244. continue
  245. UnicomComboOrderInfo.objects.filter(id=item['id']).update(status=2)
  246. iccid_list.append(icc_id)
  247. logger.info('--->当前流量套餐已过期,iccid:{}'.format(icc_id))
  248. except Exception as e:
  249. logger.info('出错了~监控流量到期异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  250. continue
  251. # set无序不重复元素集
  252. iccid_list = list(set(iccid_list))
  253. unicom_api = UnicomObjeect()
  254. for item in iccid_list:
  255. activate_combo_qs = UnicomComboOrderInfo.objects.filter(iccid=item, status=1, expire_time__gt=now_time,
  256. is_del=False).values()
  257. if activate_combo_qs.exists():
  258. continue
  259. usage_flow = unicom_api.get_flow_usage_total(item)
  260. result = cls.query_unused_combo_and_activate(item, year, month, usage_flow)
  261. if not result:
  262. # 停用设备
  263. unicom_api.change_device_to_disable(item)
  264. else:
  265. unicom_api.change_device_to_activate(item)
  266. return response.json(0)