Browse Source

优化联通设备表,新增用户激活赠送初始流量

zhangdongming 3 years ago
parent
commit
edaa087e7d
3 changed files with 131 additions and 3 deletions
  1. 94 1
      Controller/UnicomCombo/UnicomComboController.py
  2. 6 1
      Model/models.py
  3. 31 1
      Object/UnicomObject.py

+ 94 - 1
Controller/UnicomCombo/UnicomComboController.py

@@ -6,6 +6,7 @@
 @Email   : zhangdongming@asj6.wecom.work
 @Software: PyCharm
 """
+import datetime
 import json
 import logging
 import time
@@ -15,13 +16,14 @@ from django.http import HttpResponse, JsonResponse
 from django.views.generic.base import View
 
 from Model.models import UnicomDeviceInfo, UnicomCombo, Pay_Type, Order_Model, Store_Meal, AiStoreMeal, \
-    UnicomComboOrderInfo
+    UnicomComboOrderInfo, UnicomComboExperienceHistory
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Object.UnicomObject import UnicomObjeect
 from Object.utils import LocalDateTimeUtil
 from Object.utils.PayUtil import PayService
 from Service.CommonService import CommonService
+from Object.RedisObject import RedisObject
 
 
 class UnicomComboView(View):
@@ -52,6 +54,8 @@ class UnicomComboView(View):
         elif operation == 'device-bind':
             response = ResponseObject('cn')
             return self.device_add(request_dict, response)
+        elif operation == 'device-status':
+            return self.update_device_status(request_dict, ResponseObject(lang='cn'))
         else:
             token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
             lang = request_dict.get('lang', token.lang)
@@ -123,6 +127,87 @@ class UnicomComboView(View):
             print(e)
             return response.json(177, repr(e))
 
+    @classmethod
+    def update_device_status(cls, request_dict, response):
+        """
+        修改设备状态
+        @param request_dict:
+        @param response:
+        @return:
+        """
+        iccid = request_dict.get('iccid', None)
+        if not iccid:
+            return response.json(444)
+        if cls.user_activate_flow(iccid):
+            return response.json(0)
+        return response.json(177)
+
+    @classmethod
+    def user_activate_flow(cls, iccid):
+        """
+        用户激活初始化流量套餐
+        @param iccid:
+        @return:
+        """
+        logger = logging.getLogger('info')
+        try:
+            flow_key = 'asj:unicom:flow:{}'
+            now_time = int(time.time())
+            today = datetime.datetime.today()
+            year = today.year
+            month = today.month
+            unicom_device_info_qs = UnicomDeviceInfo.objects.filter(iccid=iccid)
+            if not unicom_device_info_qs.exists():
+                return False
+            unicom_device_info_qs = unicom_device_info_qs.first()
+            if unicom_device_info_qs.status != 1:
+                logger.info('用户激活iccid={},业务系统状态为{}'.format(iccid, unicom_device_info_qs.status))
+                return False
+            # 联通业务逻辑
+            unicom_api = UnicomObjeect()
+            re_data = {'iccid': iccid}
+            result = unicom_api.query_device_status(**re_data)
+            res_dict = unicom_api.get_text_dict(result)
+            # 状态不等于1(激活)时进行激活 1:激活;2:停用
+            if res_dict['data']['status'] != 1:
+                re_data = {"iccid": iccid, "status": 1}
+                unicom_api.update_device_state(**re_data)
+            # 查看是否体验过免费套餐
+            experience_history_qs = UnicomComboExperienceHistory.objects.filter(iccid=iccid)
+            if not experience_history_qs.exists():
+                logger.info('用户首次激活iccid={}'.format(iccid))
+                combo_qs = UnicomCombo.objects.filter(combo_type=1, status=0, is_show=1, is_del=False) \
+                    .values('id', 'expiration_type', 'expiration_days', 'combo_type')
+                if combo_qs.exists():
+                    combo_qs = combo_qs.first()
+                    # 保存体验记录
+                    experience_history_vo = {'iccid': iccid, 'experience_type': 0, 'do_time': now_time}
+                    UnicomComboExperienceHistory.objects.create(**experience_history_vo)
+                    # 保存套餐激活信息
+                    cls.create_combo_order_info('', 0, iccid, combo_qs['id'])
+            usage_data = {'iccid': iccid}
+            usage_history = unicom_api.unicom_flow_usage_cache(flow_key.format(iccid), (60 * 10 + 3), **usage_data)
+            # 使用流量总历史
+            flow_total = 0
+            # 当月实际总使用流量
+            flow_total_usage = 0
+            if usage_history and usage_history['success']:
+                device_usage_history_list = usage_history['data']['deviceUsageHistory']
+                if device_usage_history_list:
+                    for item in device_usage_history_list:
+                        flow_total += float(item['flowTotalUsage'])
+                        if item['year'] == year and item['month'] == month:
+                            flow_total_usage = item['flowTotalUsage']
+            # 修改业务联通卡设备激活信息
+            UnicomDeviceInfo.objects.filter(iccid=iccid).update(status=1, updated_time=now_time, year=year, month=month,
+                                                                flow_total_usage=str(flow_total_usage),
+                                                                before_usage_history=str(flow_total))
+
+            return True
+        except Exception as e:
+            print(e)
+            return False
+
     @classmethod
     def save_unicom_combo(cls, request_dict, response):
         """
@@ -376,6 +461,14 @@ class UnicomComboView(View):
 
     @classmethod
     def create_combo_order_info(cls, order_id, activate_type, iccid, combo_id):
+        """
+        创建套餐生效记录
+        @param order_id: 订单id
+        @param activate_type: 激活类型
+        @param iccid: 联通20位iccid
+        @param combo_id: 套餐id
+        @return: True Or False
+        """
         logger = logging.getLogger('info')
         logger.info('创建联通订单套餐信息,订单id{}'.format(order_id))
         try:

+ 6 - 1
Model/models.py

@@ -2659,6 +2659,8 @@ class UnicomCombo(models.Model):
     package_id = models.CharField(default='', max_length=32, verbose_name=u'联通套餐id')
     combo_name = models.CharField(default='', max_length=32, verbose_name=u'套餐名称')
     status = models.SmallIntegerField(default=0, verbose_name='状态{0:开启,1:停用}')
+    # 套餐类型 0:商用,1:初始化赠送
+    combo_type = models.SmallIntegerField(default=0, verbose_name='套餐类型')
     flow_total = models.IntegerField(default=0, blank=True, verbose_name=u'流量总量值 单位(MB)')
     expiration_days = models.IntegerField(default=0, blank=True, verbose_name=u'有效期天数')
     expiration_type = models.SmallIntegerField(default=0, verbose_name=u'有效期类型,0=天,1=月,2=年')
@@ -2702,6 +2704,9 @@ class UnicomDeviceInfo(models.Model):
     id = models.AutoField(primary_key=True, verbose_name=u'自增标记Id')
     iccid = models.CharField(default='', max_length=32, verbose_name=u'完整的20位纯数字ICCID')
     status = models.SmallIntegerField(default=0, verbose_name=u'状态{0:可测试,1:测试完成,2:已使用}')
+    year = models.IntegerField(default=0, verbose_name=u'激活年')
+    month = models.IntegerField(default=0, verbose_name=u'激活月')
+    flow_total_usage = models.CharField(blank=True, default='', max_length=32, verbose_name=u'激活当月实际用量历史')
     before_usage_history = models.CharField(blank=True, default='', max_length=32, verbose_name=u'激活前用量历史')
     serial_no = models.CharField(default='', max_length=32, verbose_name=u'设备序列号')
     user_id = models.CharField(blank=True, max_length=32, verbose_name=u'用户id')
@@ -2759,7 +2764,7 @@ class UnicomComboExperienceHistory(models.Model):
     id = models.AutoField(primary_key=True)
     # 0: 免费体验, 1: 激活码
     experience_type = models.SmallIntegerField(default=0, verbose_name='体验类型')
-    serial_no = models.CharField(max_length=32, default='', verbose_name='设备序列号')
+    iccid = models.CharField(max_length=32, default='', verbose_name='联通20位ICCID')
     do_time = models.IntegerField(default=0, verbose_name='激活时间')
 
     class Meta:

+ 31 - 1
Object/UnicomObject.py

@@ -7,6 +7,7 @@
 @Software: PyCharm
 """
 import base64
+import datetime
 import json
 from decimal import Decimal
 
@@ -15,6 +16,7 @@ from Crypto.Cipher import AES
 
 from Ansjer.config import unicomAppUrl, unicomAppId, unicomAppSecret, unicomTenantId, \
     unicomEncodeKey, unicomIvKey, unicomUserName, unicomPassword, unicomPushKey
+from Object.RedisObject import RedisObject
 from Object.utils import SM3Util
 from Object.utils.SymmetricCryptoUtil import AESencrypt
 
@@ -227,8 +229,36 @@ class UnicomObjeect:
             return json.loads(result.text)
         return None
 
+    @staticmethod
+    def unicom_flow_usage_cache(key, expire=0, **usage_data):
+        """
+        流量用量历史优先查询缓存
+        @param key: 缓存key
+        @param expire: 失效时间
+        @param usage_data: 查询参数
+        @return: 返回结果dict
+        """
+        redis = RedisObject()
+        usage_history = redis.get_data(key)
+        if usage_history:
+            usage_history = json.loads(usage_history)
+        else:
+            usage_history = UnicomObjeect().query_device_usage_history(**usage_data)
+            usage_history = UnicomObjeect().get_text_dict(usage_history)
+            redis.set_data(key=key, val=json.dumps(usage_history.values()), expire=expire)
+        return usage_history
+
 
 if __name__ == '__main__':
+
+    today = datetime.datetime.today()
+    year = today.year
+    month = today.month
+    print(year)
+    print(month)
+    print(type(year))
+    if not '':
+        print('为空')
     price = '12.13'
     print(float(price))
     discount = '6'
@@ -240,7 +270,7 @@ if __name__ == '__main__':
     print(unicom_api.createSign(**data))
     # result = unicom_api.generate_token()
     # result = unicom_api.refresh_token('5d0c0f30-99bd-4f17-9614-3524495b05d4')
-    params = {'iccid': '89860620170009628001'}
+    params = {'iccid': '89860621330065433774'}
     response = unicom_api.verify_device(**params)
     # response = unicom_api.query_device_status(**params)
     # response = unicom_api.update_device_state(**params)