UnicomComboTaskController.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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 threading
  12. import time
  13. from decimal import Decimal
  14. from django.db import transaction
  15. from django.db.models import Q
  16. from django.views import View
  17. from Model.models import UnicomComboOrderInfo, UnicomCombo, Order_Model, UnicomDeviceInfo, UnicomFlowPush, \
  18. IotCardUsageHistory
  19. from Object.RedisObject import RedisObject
  20. from Object.ResponseObject import ResponseObject
  21. from Object.UnicomObject import UnicomObjeect
  22. logger = logging.getLogger('info')
  23. class UnicomComboTaskView(View):
  24. def get(self, request, *args, **kwargs):
  25. request.encoding = 'utf-8'
  26. operation = kwargs.get('operation')
  27. return self.validation(request.GET, request, operation)
  28. def post(self, request, *args, **kwargs):
  29. request.encoding = 'utf-8'
  30. operation = kwargs.get('operation')
  31. return self.validation(request.POST, request, operation)
  32. def validation(self, request_dict, request, operation):
  33. response = ResponseObject()
  34. print(request)
  35. if operation == 'check-activate':
  36. return self.check_activate_combo(request_dict, response)
  37. elif operation == 'check-flow':
  38. return self.check_flow_usage(response)
  39. elif operation == 'check-flow-expire':
  40. return self.check_flow_expire(response)
  41. elif operation == 'check-expire':
  42. today = datetime.datetime.today()
  43. year = today.year
  44. month = today.month
  45. self.query_unused_combo_and_activate(request_dict.get('iccid'), year, month, '666')
  46. return response.json(0)
  47. elif operation == 'updateFlowUsed': # 更新流量使用
  48. self.unicom_flow_used(request_dict, response)
  49. return response.json(0)
  50. elif operation == 'queryFlowUsedHistory':
  51. return self.query_flow_used_history(response)
  52. elif operation == 'queryFlowCache':
  53. return self.query_flow_cache(response)
  54. elif operation == 'getDeviceUsageHistory':
  55. return self.get_device_usage_history(response)
  56. elif operation == 'updateCardCycleFlow':
  57. return self.update_device_cycle_flow(response)
  58. else:
  59. return response.json(414)
  60. @classmethod
  61. def check_activate_combo(cls, request_dict, response):
  62. """
  63. 定时检查是否有次月激活套餐
  64. @param request_dict:
  65. @param response:
  66. @return:
  67. """
  68. print(request_dict)
  69. logger.info('--->进入监控次月激活联通套餐')
  70. now_time = int(time.time())
  71. combo_order_info_qs = UnicomComboOrderInfo.objects.filter(status=0, next_month_activate=True,
  72. activation_time__lte=now_time,
  73. expire_time__gte=now_time, is_del=0).values()
  74. if not combo_order_info_qs.exists():
  75. return response.json(0)
  76. try:
  77. today = datetime.datetime.today()
  78. year = today.year
  79. month = today.month
  80. with transaction.atomic():
  81. unicom_api = UnicomObjeect()
  82. for item in combo_order_info_qs:
  83. if item['order_id']:
  84. order_id = item['order_id']
  85. order_qs = Order_Model.objects.filter(orderID=order_id, status=1)
  86. if not order_qs.exists():
  87. continue
  88. combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1, iccid=item['iccid'])
  89. # 当前已有套餐正在使用则跳出当前循环
  90. if combo_order_qs.exists():
  91. continue
  92. combo_id = item['combo_id']
  93. combo_qs = UnicomCombo.objects.filter(id=combo_id).values()
  94. if not combo_qs.exists():
  95. continue
  96. # 查询当月用量情况
  97. flow_total_usage = unicom_api.get_flow_usage_total(item['iccid'])
  98. flow_total_usage = Decimal(flow_total_usage).quantize(
  99. Decimal('0.00')) if flow_total_usage > 0 else 0
  100. flow_total_usage = str(flow_total_usage)
  101. iccid = item['iccid']
  102. # 检查激活iccid
  103. unicom_api.change_device_to_activate(iccid)
  104. cls.query_unused_combo_and_activate(iccid, year, month, flow_total_usage)
  105. logger.info('激活成功,订单编号:{}'.format(order_id))
  106. return response.json(0)
  107. except Exception as e:
  108. logger.info('出错了~次月激活套餐异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  109. return response.json(177, repr(e))
  110. @classmethod
  111. def check_flow_usage(cls, response):
  112. """
  113. 检查流量使用情况
  114. @return:
  115. """
  116. logger.info('--->进入监控流量使用情况')
  117. try:
  118. combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1, is_del=False, combo__is_unlimited=0).values()
  119. if not combo_order_qs.exists():
  120. return response.json(0)
  121. asy = threading.Thread(target=UnicomComboTaskView.async_monitoring_flow, args=(combo_order_qs,))
  122. asy.start()
  123. return response.json(0)
  124. except Exception as e:
  125. logger.info('出错了~检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  126. return response.json(177, repr(e))
  127. @classmethod
  128. def async_monitoring_flow(cls, combo_order_qs):
  129. """
  130. 异步检测流量使用详情
  131. """
  132. try:
  133. unicom_api = UnicomObjeect()
  134. today = datetime.datetime.today()
  135. year = today.year
  136. month = today.month
  137. now_time = int(time.time())
  138. for item in combo_order_qs:
  139. iccid = item['iccid']
  140. u_device_info_qs = UnicomDeviceInfo.objects.filter(iccid=iccid)
  141. if not u_device_info_qs.exists():
  142. continue
  143. u_device_info_qs = u_device_info_qs.first()
  144. activate_usage_flow = float(item['flow_total_usage']) if item['flow_total_usage'] else 0.0
  145. combo_id = item['combo_id']
  146. combo_qs = UnicomCombo.objects.filter(id=combo_id).values()
  147. if not combo_qs.exists():
  148. continue
  149. combo_qs = combo_qs.first()
  150. flow_total = combo_qs['flow_total']
  151. # 队列已使用总流量总量
  152. flow_total_usage = unicom_api.get_flow_usage_total(iccid)
  153. flow_total_usage = float(flow_total_usage)
  154. is_expire = False
  155. flow = activate_usage_flow + flow_total
  156. if flow_total_usage > 0:
  157. # 初始套餐已使用流量 + 套餐总流量
  158. if flow_total_usage >= flow:
  159. is_expire = True
  160. usage = (flow_total_usage - activate_usage_flow) if flow_total_usage > activate_usage_flow else 0
  161. cls.flow_warning_push(u_device_info_qs.user_id, u_device_info_qs.serial_no, item['id'], flow_total,
  162. usage)
  163. # 检查是否有当月未使用套餐 没有则停卡
  164. if is_expire:
  165. flow_exceed = flow_total_usage - flow
  166. UnicomComboOrderInfo.objects.filter(id=item['id']) \
  167. .update(status=2, updated_time=now_time, flow_exceed=flow_exceed)
  168. activate_status = cls.query_unused_combo_and_activate(iccid, year, month,
  169. flow_total_usage)
  170. logger.info('-->当前卡{}流量已用完,是否有生效套餐:{}'.format(iccid, activate_status))
  171. if not activate_status:
  172. # 停用
  173. unicom_api.change_device_to_disable(iccid)
  174. except Exception as e:
  175. logger.info('异步~检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  176. @staticmethod
  177. def flow_warning_push(app_user_id, serial_no, combo_order_id, flow_total, flow_usage):
  178. """
  179. 监控流量使用大于85%and小于96%进行消息推送提醒
  180. @param app_user_id: app用户id
  181. @param serial_no: 序列号
  182. @param combo_order_id: 当前套餐订单id
  183. @param flow_total: 套餐流量总量
  184. @param flow_usage: 套餐已使用流量
  185. @return:
  186. """
  187. try:
  188. if not app_user_id:
  189. return False
  190. now_time = int(time.time())
  191. push_data = {'combo_order_id': str(combo_order_id), 'serial_no': serial_no,
  192. 'flow_total_usage': flow_usage, 'flow_total': flow_total, 'status': 0,
  193. 'updated_time': now_time,
  194. 'created_time': now_time, 'user_id': app_user_id}
  195. if 0 < flow_total and 0 < flow_usage < flow_total:
  196. res = flow_usage / flow_total * 100
  197. if 85 < res <= 95:
  198. flow_push = UnicomFlowPush.objects.filter(serial_no=serial_no, combo_order_id=combo_order_id)
  199. if not flow_push.exists():
  200. UnicomFlowPush.objects.create(**push_data)
  201. elif flow_usage >= flow_total:
  202. push_data['flow_total_usage'] = flow_total
  203. push_data['type'] = 1
  204. UnicomFlowPush.objects.create(**push_data)
  205. return True
  206. except Exception as e:
  207. logger.info('出错了~异常流量监控,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  208. @staticmethod
  209. def query_unused_combo_and_activate(iccid, year, month, usage_flow):
  210. """
  211. 查询未使用套餐并激活
  212. @param iccid:
  213. @param year:
  214. @param month:
  215. @param usage_flow:
  216. @return:
  217. """
  218. try:
  219. now_time = int(time.time())
  220. combo_order_qs = UnicomComboOrderInfo.objects \
  221. .filter(expire_time__gt=now_time, activation_time__lte=now_time, status=0, iccid=iccid) \
  222. .order_by('created_time')
  223. if not combo_order_qs.exists():
  224. return False
  225. combo_order = combo_order_qs.first()
  226. if not combo_order.order_id:
  227. return False
  228. order_qs = Order_Model.objects.filter(orderID=combo_order.order_id, status=1)
  229. if not order_qs.exists():
  230. return False
  231. upd_data = {
  232. 'status': 1,
  233. 'year': year,
  234. 'month': month,
  235. 'flow_total_usage': str(usage_flow),
  236. 'activation_time': now_time,
  237. 'updated_time': now_time,
  238. }
  239. UnicomComboOrderInfo.objects.filter(id=combo_order.id).update(**upd_data)
  240. asy = threading.Thread(target=UnicomComboTaskView.async_combo_sys_msg_push,
  241. args=(iccid, combo_order.id, 3))
  242. asy.start()
  243. return True
  244. except Exception as e:
  245. logger.info('出错了~激活套餐,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  246. return False
  247. @classmethod
  248. def check_flow_expire(cls, response):
  249. """
  250. 检查流量到期停卡操作
  251. @param response:
  252. @return:
  253. """
  254. logger.info('check_flow_expire进入监控流量到期停卡或激活叠加包')
  255. now_time = int(time.time())
  256. combo_order_qs = UnicomComboOrderInfo.objects.filter(~Q(status=2), expire_time__lte=now_time,
  257. is_del=False).values()
  258. if not combo_order_qs.exists():
  259. return response.json(0)
  260. asy = threading.Thread(target=UnicomComboTaskView.async_deactivate_expire_package,
  261. args=(combo_order_qs, now_time))
  262. asy.start()
  263. return response.json(0)
  264. @staticmethod
  265. def async_deactivate_expire_package(combo_order_qs, now_time):
  266. """
  267. 异步停用过期套餐
  268. @param combo_order_qs: 过期套餐querySet
  269. @param now_time 当前实际
  270. """
  271. today = datetime.datetime.today()
  272. year = today.year
  273. month = today.month
  274. iccid_list = []
  275. for item in combo_order_qs:
  276. try:
  277. icc_id = item['iccid']
  278. um_device_qs = UnicomDeviceInfo.objects.filter(iccid=icc_id)
  279. if not um_device_qs.exists():
  280. continue
  281. UnicomComboOrderInfo.objects.filter(id=item['id']).update(status=2, updated_time=now_time)
  282. iccid_list.append(icc_id)
  283. logger.info('修改套餐已失效成功,iccid:{}'.format(icc_id))
  284. except Exception as e:
  285. logger.info('async_deactivate_expire_package套餐过期修改失效异常,{}'
  286. 'errLine:{}, errMsg:{}'.format(item['iccid'], e.__traceback__.tb_lineno, repr(e)))
  287. continue
  288. # set无序不重复元素集
  289. iccid_list = list(set(iccid_list))
  290. unicom_api = UnicomObjeect()
  291. for item in iccid_list:
  292. try:
  293. activate_combo_qs = UnicomComboOrderInfo.objects.filter(iccid=item, status=1, expire_time__gt=now_time,
  294. is_del=False).values()
  295. if activate_combo_qs.exists():
  296. continue
  297. usage_flow = unicom_api.get_flow_usage_total(item)
  298. # 查询是否有未使用套餐,有则进行激活 否 则调用API停卡
  299. result = UnicomComboTaskView().query_unused_combo_and_activate(item, year, month, usage_flow)
  300. if not result: # 没有可用套餐进行停卡
  301. # 停用设备
  302. unicom_api.change_device_to_disable(item)
  303. logger.info('调用停卡API successful,iccid:{}'.format(item))
  304. combo_order_info_qs = UnicomComboOrderInfo.objects.filter(iccid=item, status=2) \
  305. .values('id').order_by('-updated_time')
  306. combo_order = combo_order_info_qs.first()
  307. asy = threading.Thread(target=UnicomComboTaskView.async_combo_sys_msg_push,
  308. args=(item, combo_order['id'], 4))
  309. asy.start()
  310. else:
  311. unicom_api.change_device_to_activate(item)
  312. except Exception as e:
  313. logger.info('async_deactivate_expire_package套餐过期停卡异常,{}'
  314. 'errLine:{}, errMsg:{}'.format(item, e.__traceback__.tb_lineno, repr(e)))
  315. continue
  316. @staticmethod
  317. def async_combo_sys_msg_push(iccid, combo_order_id, push_type):
  318. """
  319. 异步保存消息推送 激活|过期
  320. @param iccid:
  321. @param combo_order_id:
  322. @param push_type:
  323. @return:
  324. """
  325. try:
  326. now_time = int(time.time())
  327. ud_info_qs = UnicomDeviceInfo.objects.filter(iccid=iccid).values('serial_no', 'user_id')
  328. push_data = {'combo_order_id': str(combo_order_id), 'serial_no': ud_info_qs.first()['serial_no'],
  329. 'status': 0, 'type': push_type,
  330. 'updated_time': now_time,
  331. 'created_time': now_time, 'user_id': ud_info_qs.first()['user_id']}
  332. UnicomFlowPush.objects.create(**push_data)
  333. except Exception as e:
  334. logger.info('-->出错了~,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  335. @staticmethod
  336. def unicom_flow_used(request_dict, response):
  337. """
  338. 查询设备每张卡流量使用情况
  339. @param request_dict:
  340. @param response:
  341. @return:
  342. """
  343. page_size = int(request_dict.get('pageSize', 1))
  344. device_count = UnicomDeviceInfo.objects.filter(card_type=0).count()
  345. total_pages = device_count // page_size + (device_count % page_size > 0) # 计算总页数
  346. for page_number in range(1, total_pages + 1):
  347. u_device_qs = UnicomDeviceInfo.objects.filter(card_type=0).values('id', 'iccid', 'sim_used_flow').order_by(
  348. '-created_time')[(page_number - 1) * page_size:page_number * page_size]
  349. asy = threading.Thread(target=UnicomComboTaskView.thread_collect_flow_used, args=(u_device_qs,))
  350. asy.start()
  351. return response.json(0)
  352. @staticmethod
  353. def thread_collect_flow_used(u_device_qs):
  354. for item in u_device_qs:
  355. try:
  356. unicom_api = UnicomObjeect()
  357. n_time = int(time.time())
  358. # 队列已使用总流量总量
  359. flow_total_usage = unicom_api.get_flow_usage_total(item['iccid'])
  360. UnicomDeviceInfo.objects.filter(id=item['id']).update(updated_time=n_time,
  361. sim_used_flow=flow_total_usage)
  362. except Exception as e:
  363. print(repr(e))
  364. continue
  365. @classmethod
  366. def query_flow_used_history(cls, response):
  367. # 获取符合条件的卡片对象查询集,并按创建时间升序排序
  368. card_qs = UnicomDeviceInfo.objects.filter(card_type=0).values('iccid').order_by('created_time')
  369. if not card_qs.exists():
  370. return response.json(0)
  371. asy = threading.Thread(target=UnicomComboTaskView.async_bulk_create_usage_history, args=(card_qs,))
  372. asy.start()
  373. return response.json(0)
  374. @staticmethod
  375. def async_bulk_create_usage_history(qs):
  376. """
  377. 异步批量创建流量用量历史记录
  378. """
  379. redis_obj = RedisObject()
  380. current_time = int(time.time()) # 获取当前时间戳
  381. for item in qs:
  382. iccid = item['iccid']
  383. key = 'monthly_flow_' + iccid
  384. flow_dict = redis_obj.get_all_hash_data(key) # 获取Redis中指定键的哈希表数据
  385. iot_card_list = [] # 创建一个空的列表,用于批量创建IotCardUsageHistory对象
  386. for k, v in flow_dict.items():
  387. try:
  388. cycle = datetime.datetime.strptime(str(k.decode()), '%Y-%m') # 将字符串日期解析为datetime类型
  389. flow = float(v)
  390. iot_card_list.append(IotCardUsageHistory(
  391. iccid=iccid,
  392. card_type=1,
  393. cycle=int(cycle.strftime('%Y%m')), # 将日期转换为整数形式,如202201
  394. flow_total_usage=flow,
  395. created_time=current_time,
  396. updated_time=current_time
  397. ))
  398. except Exception as e:
  399. print(repr(e))
  400. continue
  401. # 批量创建IotCardUsageHistory对象
  402. if iot_card_list:
  403. IotCardUsageHistory.objects.bulk_create(iot_card_list)
  404. @classmethod
  405. def query_flow_cache(cls, response):
  406. """
  407. 查询流量缓存永久的将设置过期时间为10分钟
  408. """
  409. redis = RedisObject()
  410. try:
  411. res = redis.get_keys('ASJ:UNICOM:FLOW:*')
  412. keys = [key.decode() for key in res]
  413. # 进行进一步的处理或打印
  414. for key in keys:
  415. ttl = redis.get_ttl(key)
  416. if ttl == -1:
  417. logger.info('iccidFlow:{}'.format(key))
  418. redis.CONN.expire(key, 60 * 10)
  419. return response.json(0)
  420. except Exception as e:
  421. logger.info('出错了~次月激活套餐异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  422. return response.json(177, repr(e))
  423. @staticmethod
  424. def get_device_usage_history(response):
  425. """
  426. 查询联通设备历史用量
  427. """
  428. card_qs = UnicomDeviceInfo.objects.filter(card_type=0).values('iccid')
  429. if not card_qs.exists():
  430. return response.json(0)
  431. asy = threading.Thread(target=UnicomComboTaskView.async_update_device_usage_history, args=(card_qs,))
  432. asy.start()
  433. return response.json(0)
  434. @staticmethod
  435. def async_update_device_usage_history(qs):
  436. """
  437. 异步更新设备用量历史
  438. @param qs: 联通iccid集合
  439. """
  440. try:
  441. u_service = UnicomObjeect()
  442. iot_card_list = []
  443. now_time = int(time.time())
  444. # 获取当前时间
  445. current_date = datetime.datetime.now()
  446. # 计算上个月的时间
  447. last_month_date = current_date - datetime.timedelta(days=current_date.day)
  448. # 例格式化日期为 "202307"
  449. formatted_date = last_month_date.strftime('%Y%m')
  450. for item in qs:
  451. params = {'iccid': item['iccid']}
  452. result = u_service.query_device_usage_history(**params)
  453. res_dict = u_service.get_text_dict(result)
  454. if res_dict['code'] == 0 and res_dict['data']:
  455. for cycle in res_dict['data']:
  456. if cycle['flowTotalUsage'] <= 0 or cycle['cycle'] != int(formatted_date):
  457. continue
  458. iot_card_list.append(IotCardUsageHistory(
  459. iccid=item['iccid'],
  460. card_type=1,
  461. cycle=cycle['cycle'],
  462. flow_total_usage=cycle['flowTotalUsage'],
  463. created_time=now_time,
  464. updated_time=now_time
  465. ))
  466. if not iot_card_list:
  467. return None
  468. IotCardUsageHistory.objects.bulk_create(iot_card_list)
  469. except Exception as e:
  470. logger.info('查询账期流量异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  471. return None
  472. @staticmethod
  473. def update_device_cycle_flow(response):
  474. """
  475. 更新设备账期流量接口
  476. """
  477. card_qs = UnicomDeviceInfo.objects.filter(card_type=0, status=2).values('iccid')
  478. if not card_qs.exists():
  479. return response.json(0)
  480. logger.info('总数:{}'.format(card_qs.count()))
  481. asy = threading.Thread(target=UnicomComboTaskView.async_update_device_cycle_flow, args=(card_qs,))
  482. asy.start()
  483. return response.json(0)
  484. @staticmethod
  485. def async_update_device_cycle_flow(qs):
  486. """
  487. 异步更新设备账期流量
  488. """
  489. try:
  490. logger.info('进入异步更新设备卡账期流量~~~~')
  491. unicom_api = UnicomObjeect()
  492. for item in qs:
  493. try:
  494. unicom_api.get_flow_usage_total(item['iccid'])
  495. except Exception as e:
  496. print(repr(e))
  497. continue
  498. except Exception as e:
  499. logger.info('更新账期流量异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  500. return None