UnicomComboTaskController.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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(year, month, 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. 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. month_usage_flow = unicom_api.get_flow_usage_total(year, month, iccid)
  126. logger.info('--->{}-{},iccid:{};套餐总值:{},激活时当月用量值:{},月已用量:{}'
  127. .format(year, month, iccid, flow_total, usage_flow, month_usage_flow))
  128. is_expire = False
  129. if item['year'] == year and item['month'] == month:
  130. if month_usage_flow > 0:
  131. # 初始套餐已使用流量 + 套餐总流量
  132. flow = usage_flow + flow_total
  133. if month_usage_flow >= flow:
  134. is_expire = True
  135. usage = (month_usage_flow - usage_flow) if month_usage_flow > usage_flow else 0
  136. cls.flow_warning_push(u_device_info_qs.user_id, u_device_info_qs.serial_no, item['id'], flow_total,
  137. usage)
  138. else:
  139. activate_year = item['year']
  140. activate_month = item['month']
  141. # 上月使用流量
  142. last_usage_flow = unicom_api.get_flow_usage_total(activate_year, activate_month, iccid)
  143. # 上月套餐实际使用量
  144. actual_usage_flow = last_usage_flow - usage_flow
  145. # 剩余
  146. surplus_flow = flow_total - actual_usage_flow
  147. if month_usage_flow > 0:
  148. if month_usage_flow >= surplus_flow:
  149. is_expire = True
  150. usage = (month_usage_flow + last_usage_flow - usage_flow) \
  151. if (month_usage_flow + last_usage_flow) > usage_flow else 0
  152. cls.flow_warning_push(u_device_info_qs.user_id, u_device_info_qs.serial_no, item['id'], flow_total,
  153. usage)
  154. # 检查是否有当月未使用套餐 没有则停卡
  155. if is_expire:
  156. UnicomComboOrderInfo.objects.filter(id=item['id']).update(status=2, updated_time=now_time)
  157. activate_status = cls.query_unused_combo_and_activate(iccid, year, month,
  158. month_usage_flow)
  159. if not activate_status:
  160. # 停用
  161. unicom_api.change_device_to_disable(iccid)
  162. return response.json(0)
  163. except Exception as e:
  164. logger.info('出错了~检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  165. return response.json(177, repr(e))
  166. @staticmethod
  167. def flow_warning_push(app_user_id, serial_no, combo_order_id, flow_total, flow_usage):
  168. """
  169. 监控流量使用大于85%and小于96%进行消息推送提醒
  170. @param app_user_id: app用户id
  171. @param serial_no: 序列号
  172. @param combo_order_id: 当前套餐订单id
  173. @param flow_total: 流量总量
  174. @param flow_usage: 已使用流量
  175. @return:
  176. """
  177. logger = logging.getLogger('info')
  178. try:
  179. if not app_user_id:
  180. return False
  181. if 0 < flow_total and 0 < flow_usage < flow_total:
  182. res = flow_usage / flow_total * 100
  183. if 85 < res <= 95:
  184. flow_push = UnicomFlowPush.objects.filter(serial_no=serial_no, combo_order_id=combo_order_id)
  185. if not flow_push.exists():
  186. now_time = int(time.time())
  187. push_data = {'combo_order_id': str(combo_order_id), 'serial_no': serial_no,
  188. 'flow_total_usage': flow_usage, 'flow_total': flow_total, 'status': 0,
  189. 'updated_time': now_time,
  190. 'created_time': now_time, 'user_id': app_user_id}
  191. UnicomFlowPush.objects.create(**push_data)
  192. return True
  193. except Exception as e:
  194. logger.info('出错了~异常流量监控,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  195. @staticmethod
  196. def query_unused_combo_and_activate(iccid, year, month, usage_flow):
  197. """
  198. 查询未使用套餐并激活
  199. @param iccid:
  200. @param year:
  201. @param month:
  202. @param usage_flow:
  203. @return:
  204. """
  205. logger = logging.getLogger('info')
  206. try:
  207. now_time = int(time.time())
  208. combo_order_qs = UnicomComboOrderInfo.objects \
  209. .filter(expire_time__gt=now_time, activation_time__lte=now_time, status=0, iccid=iccid) \
  210. .order_by('created_time')
  211. if not combo_order_qs.exists():
  212. return False
  213. combo_order = combo_order_qs.first()
  214. if not combo_order.order_id:
  215. return False
  216. order_qs = Order_Model.objects.filter(orderID=combo_order.order_id, status=1)
  217. if not order_qs.exists():
  218. return False
  219. upd_data = {
  220. 'status': 1,
  221. 'year': year,
  222. 'month': month,
  223. 'flow_total_usage': str(usage_flow),
  224. 'updated_time': now_time,
  225. }
  226. UnicomComboOrderInfo.objects.filter(id=combo_order.id).update(**upd_data)
  227. return True
  228. except Exception as e:
  229. logger.info('出错了~检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  230. return False
  231. @classmethod
  232. def check_flow_expire(cls, response):
  233. """
  234. 检查流量到期停卡操作
  235. @param response:
  236. @return:
  237. """
  238. logger = logging.getLogger('info')
  239. logger.info('--->进入监控流量到期停卡或激活叠加包')
  240. now_time = int(time.time())
  241. combo_order_qs = UnicomComboOrderInfo.objects.filter(~Q(status=2), expire_time__lte=now_time,
  242. is_del=False).values()
  243. today = datetime.datetime.today()
  244. year = today.year
  245. month = today.month
  246. if not combo_order_qs.exists():
  247. return response.json(0)
  248. iccid_list = []
  249. with transaction.atomic():
  250. for item in combo_order_qs:
  251. try:
  252. icc_id = item['iccid']
  253. um_device_qs = UnicomDeviceInfo.objects.filter(iccid=icc_id)
  254. if not um_device_qs.exists():
  255. continue
  256. UnicomComboOrderInfo.objects.filter(id=item['id']).update(status=2)
  257. iccid_list.append(icc_id)
  258. logger.info('--->当前流量套餐已过期,iccid:{}'.format(icc_id))
  259. except Exception as e:
  260. logger.info('出错了~监控流量到期异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  261. continue
  262. # set无序不重复元素集
  263. iccid_list = list(set(iccid_list))
  264. unicom_api = UnicomObjeect()
  265. for item in iccid_list:
  266. activate_combo_qs = UnicomComboOrderInfo.objects.filter(iccid=item, status=1, expire_time__gt=now_time,
  267. is_del=False).values()
  268. if activate_combo_qs.exists():
  269. continue
  270. usage_flow = unicom_api.get_flow_usage_total(year, month, item)
  271. result = cls.query_unused_combo_and_activate(item, year, month, usage_flow)
  272. if not result:
  273. # 停用设备
  274. unicom_api.change_device_to_disable(item)
  275. else:
  276. unicom_api.change_device_to_activate(item)
  277. return response.json(0)