UnicomComboTaskController.py 13 KB

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