123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199 |
- # -*- 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.views import View
- from Model.models import UnicomComboOrderInfo, UnicomCombo, Order_Model
- 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-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:
- now_time = int(time.time())
- 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)
- params = {'iccid': item['iccid']}
- result = unicom_api.query_device_status(**params)
- res_dict = unicom_api.get_text_dict(result)
- # 状态不等于1(激活)时进行激活 1:激活;2:停用
- if res_dict['data']['status'] != 1:
- re_data = {"iccid": item['iccid'], "status": 1}
- unicom_api.update_device_state(**re_data)
- UnicomComboOrderInfo.objects.filter(id=item['id']) \
- .update(status=1, updated_time=now_time, year=year, month=month,
- flow_total_usage=flow_total_usage)
- else:
- UnicomComboOrderInfo.objects.filter(id=item['id']) \
- .update(status=1, updated_time=now_time, year=year, month=month,
- flow_total_usage=flow_total_usage)
- logger.info('激活成功,订单编号:{}'.format(order_id))
- return response.json(0)
- except Exception as e:
- print(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).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)
- 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
- # result = Decimal(surplus_flow).quantize(Decimal('0.00'))
- 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:
- re_data = {"iccid": iccid, "status": 2}
- unicom_api.update_device_state(**re_data)
- 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:
- """
- try:
- now_time = int(time.time())
- combo_order_qs = UnicomComboOrderInfo.objects.filter(expire_time__gt=now_time, status=0,
- iccid=iccid).order_by(
- 'created_time')
- if not combo_order_qs.exists():
- return False
- combo_order = combo_order_qs.first()
- 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:
- print(e)
- return False
|