# -*- encoding: utf-8 -*- """ @File : UnicomComboTaskController.py @Time : 2022/6/30 16:23 @Author : stephen @Email : zhangdongming@asj6.wecom.work @Software: PyCharm """ import datetime import logging import time from django.db import transaction from django.db.models import Q from django.views import View from Model.models import UnicomComboOrderInfo, UnicomCombo, Order_Model, UnicomDeviceInfo from Object.ResponseObject import ResponseObject from Object.UnicomObject import UnicomObjeect class UnicomComboTaskView(View): def get(self, request, *args, **kwargs): request.encoding = 'utf-8' operation = kwargs.get('operation') return self.validation(request.GET, request, operation) def post(self, request, *args, **kwargs): request.encoding = 'utf-8' operation = kwargs.get('operation') return self.validation(request.POST, request, operation) def validation(self, request_dict, request, operation): response = ResponseObject() print(request) if operation == 'check-activate': return self.check_activate_combo(request_dict, response) elif operation == 'check-flow': return self.check_flow_usage(response) elif operation == 'check-flow-expire': return self.check_flow_expire(response) elif operation == 'check-expire': today = datetime.datetime.today() year = today.year month = today.month self.query_unused_combo_and_activate(request_dict.get('iccid'), year, month, '666') return response.json(0) @classmethod def check_activate_combo(cls, request_dict, response): """ 定时检查是否有次月激活套餐 @param request_dict: @param response: @return: """ logger = logging.getLogger('info') print(request_dict) logger.info('--->进入监控次月激活联通套餐') now_time = int(time.time()) combo_order_info_qs = UnicomComboOrderInfo.objects.filter(status=0, next_month_activate=True, activation_time__lte=now_time, expire_time__gte=now_time, is_del=0).values() if not combo_order_info_qs.exists(): return response.json(0) try: today = datetime.datetime.today() year = today.year month = today.month with transaction.atomic(): unicom_api = UnicomObjeect() for item in combo_order_info_qs: if item['order_id']: order_id = item['order_id'] order_qs = Order_Model.objects.filter(orderID=order_id, status=1) if not order_qs.exists(): continue combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1, iccid=item['iccid']) # 当前已有套餐正在使用则跳出当前循环 if combo_order_qs.exists(): continue combo_id = item['combo_id'] combo_qs = UnicomCombo.objects.filter(id=combo_id).values() if not combo_qs.exists(): continue # 查询当月用量情况 flow_total_usage = unicom_api.get_flow_usage_total(year, month, item['iccid']) flow_total_usage = str(flow_total_usage) iccid = item['iccid'] # 检查激活iccid unicom_api.change_device_to_activate(iccid) cls.query_unused_combo_and_activate(iccid, year, month, flow_total_usage) logger.info('激活成功,订单编号:{}'.format(order_id)) return response.json(0) except Exception as e: logger.info('次月激活套餐异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e))) return response.json(177, repr(e)) @classmethod def check_flow_usage(cls, response): """ 检查流量使用情况 @return: """ logger = logging.getLogger('info') logger.info('--->进入监控流量使用情况') try: combo_order_qs = UnicomComboOrderInfo.objects.filter(status=1, is_del=False).values() if not combo_order_qs.exists(): return response.json(0) today = datetime.datetime.today() year = today.year month = today.month unicom_api = UnicomObjeect() now_time = int(time.time()) for item in combo_order_qs: iccid = item['iccid'] usage_flow = float(item['flow_total_usage']) if item['flow_total_usage'] else 0.0 combo_id = item['combo_id'] combo_qs = UnicomCombo.objects.filter(id=combo_id).values() if combo_qs.exists(): combo_qs = combo_qs.first() flow_total = combo_qs['flow_total'] # 查询当前月用量历史 month_usage_flow = unicom_api.get_flow_usage_total(year, month, iccid) logger.info('--->{}-{},iccid:{};套餐总值:{},激活时当月用量值:{},月已用量:{}' .format(year, month, iccid, flow_total, usage_flow, month_usage_flow)) is_expire = False if item['year'] == year and item['month'] == month: if month_usage_flow > 0: # 初始套餐已使用流量 + 套餐总流量 flow = usage_flow + flow_total if month_usage_flow >= flow: is_expire = True else: activate_year = item['year'] activate_month = item['month'] # 上月使用流量 last_usage_flow = unicom_api.get_flow_usage_total(activate_year, activate_month, iccid) # 上月套餐实际使用量 actual_usage_flow = last_usage_flow - usage_flow # 剩余 surplus_flow = flow_total - actual_usage_flow if month_usage_flow > 0: if month_usage_flow >= surplus_flow: is_expire = True # 检查是否有当月未使用套餐 没有则停卡 if is_expire: UnicomComboOrderInfo.objects.filter(id=item['id']).update(status=2, updated_time=now_time) activate_status = cls.query_unused_combo_and_activate(iccid, year, month, month_usage_flow) if not activate_status: # 停用 unicom_api.change_device_to_disable(iccid) return response.json(0) except Exception as e: logger.info('检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e))) return response.json(177, repr(e)) @staticmethod def query_unused_combo_and_activate(iccid, year, month, usage_flow): """ 查询未使用套餐并激活 @param iccid: @param year: @param month: @param usage_flow: @return: """ logger = logging.getLogger('info') try: now_time = int(time.time()) combo_order_qs = UnicomComboOrderInfo.objects \ .filter(expire_time__gt=now_time, activation_time__lte=now_time, status=0, iccid=iccid) \ .order_by('created_time') if not combo_order_qs.exists(): return False combo_order = combo_order_qs.first() if not combo_order.order_id: return False order_qs = Order_Model.objects.filter(orderID=combo_order.order_id, status=1) if not order_qs.exists(): return False upd_data = { 'status': 1, 'year': year, 'month': month, 'flow_total_usage': str(usage_flow), 'updated_time': now_time, } UnicomComboOrderInfo.objects.filter(id=combo_order.id).update(**upd_data) return True except Exception as e: logger.info('检测流量用量详情异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e))) return False @classmethod def check_flow_expire(cls, response): """ 检查流量到期停卡操作 @param response: @return: """ logger = logging.getLogger('info') logger.info('--->进入监控流量到期停卡或激活叠加包') now_time = int(time.time()) combo_order_qs = UnicomComboOrderInfo.objects.filter(~Q(status=2), expire_time__lte=now_time, is_del=False).values() today = datetime.datetime.today() year = today.year month = today.month if not combo_order_qs.exists(): return response.json(0) iccid_list = [] with transaction.atomic(): for item in combo_order_qs: try: icc_id = item['iccid'] um_device_qs = UnicomDeviceInfo.objects.filter(iccid=icc_id) if not um_device_qs.exists(): continue UnicomComboOrderInfo.objects.filter(id=item['id']).update(status=2) iccid_list.append(icc_id) logger.info('--->当前流量套餐已过期,iccid:{}'.format(icc_id)) except Exception as e: logger.info('监控流量到期异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e))) continue # set无序不重复元素集 iccid_list = list(set(iccid_list)) unicom_api = UnicomObjeect() for item in iccid_list: activate_combo_qs = UnicomComboOrderInfo.objects.filter(iccid=item, status=1, expire_time__gt=now_time, is_del=False).values() if activate_combo_qs.exists(): continue usage_flow = unicom_api.get_flow_usage_total(year, month, item) result = cls.query_unused_combo_and_activate(item, year, month, usage_flow) if not result: # 停用设备 unicom_api.change_device_to_disable(item) unicom_api.change_device_to_activate(item) return response.json(0)