Эх сурвалжийг харах

Merge branch 'test' of http://192.168.136.99:3000/servers/ASJServer into linhaohong

guanhailong 1 жил өмнө
parent
commit
3b8181c5ca

+ 17 - 12
AdminController/ServeManagementController.py

@@ -1210,7 +1210,8 @@ class serveManagement(View):
                 return response.json(0, [])
                 return response.json(0, [])
             count = order_qs.count()
             count = order_qs.count()
             order_qs = order_qs.values("id", "order_id", "username", "pay_type", "status", "trade_no", "agreement_id",
             order_qs = order_qs.values("id", "order_id", "username", "pay_type", "status", "trade_no", "agreement_id",
-                                       "price", "pay_time").order_by('-pay_time')[(page - 1) * line:page * line]
+                                       "price", "pay_time", "meal_name").order_by('-pay_time')[
+                       (page - 1) * line:page * line]
             return response.json(0, {'list': list(order_qs), 'total': count})
             return response.json(0, {'list': list(order_qs), 'total': count})
         except Exception as e:
         except Exception as e:
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
@@ -1223,20 +1224,24 @@ class serveManagement(View):
         if not abnormal_order.exists():
         if not abnormal_order.exists():
             return response.json(173)
             return response.json(173)
         try:
         try:
-            abnormal_order_qs = abnormal_order.values('trade_no', 'pay_time')
+            abnormal_order_qs = abnormal_order.values('trade_no', 'pay_time', 'pay_type')
             trade_no = abnormal_order_qs[0]['trade_no']
             trade_no = abnormal_order_qs[0]['trade_no']
             pay_time = abnormal_order_qs[0]['pay_time']
             pay_time = abnormal_order_qs[0]['pay_time']
-            order_qs = Order_Model.objects.filter(trade_no=trade_no)
-            if order_qs.exists():
-                order_qs.update(payTime=pay_time)
-                abnormal_order.update(status=1)
-                return response.json(0)
-            params = {'trade_no': trade_no, 'pay_time': pay_time}
-            eur_response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
-            if eur_response.status_code == 200:
-                result = eur_response.json()
-                if result['result_code'] == 0 and result['result']['is_exist']:
+            pay_type = abnormal_order_qs[0]['pay_type']
+            if pay_type in [0, 1]:  # 处理paypal订单
+                order_qs = Order_Model.objects.filter(trade_no=trade_no)
+                if order_qs.exists():
+                    order_qs.update(payTime=pay_time)
                     abnormal_order.update(status=1)
                     abnormal_order.update(status=1)
+                    return response.json(0)
+                params = {'trade_no': trade_no, 'pay_time': pay_time}
+                eur_response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
+                if eur_response.status_code == 200:
+                    result = eur_response.json()
+                    if result['result_code'] == 0 and result['result']['is_exist']:
+                        abnormal_order.update(status=1)
+            elif pay_type == 3:  # 处理微信订单
+                pass
             return response.json(0)
             return response.json(0)
         except Exception as e:
         except Exception as e:
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))

+ 7 - 5
AdminController/UnicomManageController.py

@@ -89,7 +89,7 @@ class UnicomManageControllerView(View):
                 return self.get_exchange_code_page(request_dict, response)
                 return self.get_exchange_code_page(request_dict, response)
             elif operation == 'updateExchangeCode':  # 修改兑换码
             elif operation == 'updateExchangeCode':  # 修改兑换码
                 return self.update_exchange_code(request_dict, response)
                 return self.update_exchange_code(request_dict, response)
-            elif operation == 'resetCardPackage':
+            elif operation == 'resetCardPackage':  # 单卡重置流量
                 return self.reset_card_package(request, request_dict, response, tko.user)
                 return self.reset_card_package(request, request_dict, response, tko.user)
             elif operation == 'getPackageDetails':
             elif operation == 'getPackageDetails':
                 return self.get_package_details(request_dict, response)
                 return self.get_package_details(request_dict, response)
@@ -1077,9 +1077,9 @@ class UnicomManageControllerView(View):
                     continue
                     continue
 
 
                 iccid = device_info_qs.first().iccid
                 iccid = device_info_qs.first().iccid
-                # 根据序列号重置出厂流量套餐
+                # 根据序列号查询是否有出厂绑定无限流量套餐
                 serial_package_qs = SerialNumberPackage.objects.filter(~Q(status=1), serial_number=serial_number)
                 serial_package_qs = SerialNumberPackage.objects.filter(~Q(status=1), serial_number=serial_number)
-                if serial_package_qs.exists():
+                if serial_package_qs.exists():  # 有并且不等于1
                     serial_package_qs.update(status=1, updated_time=now_time, updated_by=user)
                     serial_package_qs.update(status=1, updated_time=now_time, updated_by=user)
 
 
                 if device_info_qs.first().card_type == 1:  # 五兴电信
                 if device_info_qs.first().card_type == 1:  # 五兴电信
@@ -1099,7 +1099,7 @@ class UnicomManageControllerView(View):
                 if sys_msg_qs.exists():  # 删除有关系统消息数据
                 if sys_msg_qs.exists():  # 删除有关系统消息数据
                     sys_msg_qs.delete()
                     sys_msg_qs.delete()
                 # 将4G用户信息状态改为已完成测试状态
                 # 将4G用户信息状态改为已完成测试状态
-                device_info_qs.update(status=1, updated_time=now_time, user_id='')
+                device_info_qs.update(status=2, updated_time=now_time, user_id='')
 
 
                 combo_order_qs = UnicomComboOrderInfo.objects.filter(iccid=iccid)
                 combo_order_qs = UnicomComboOrderInfo.objects.filter(iccid=iccid)
                 if combo_order_qs.exists():
                 if combo_order_qs.exists():
@@ -1108,7 +1108,9 @@ class UnicomManageControllerView(View):
                 combo_experience_history_qs = UnicomComboExperienceHistory.objects.filter(iccid=iccid)
                 combo_experience_history_qs = UnicomComboExperienceHistory.objects.filter(iccid=iccid)
                 if combo_experience_history_qs.exists():
                 if combo_experience_history_qs.exists():
                     combo_experience_history_qs.delete()
                     combo_experience_history_qs.delete()
-                UnicomObjeect().change_device_to_disable(iccid)  # 重置流量停用设备
+                # UnicomObjeect().change_device_to_disable(iccid)  # 重置流量停用设备
+                result = UnicomComboView().activate_test_flow_package(serial_number)
+                LOGGER.info(f'{serial_number}重置流量{result}')
                 # 记录日志,清除缓存
                 # 记录日志,清除缓存
                 ip = CommonService.get_ip_address(request)
                 ip = CommonService.get_ip_address(request)
                 describe = '重置4G流量序列号{},iccid:{}'.format(serial_number, iccid)
                 describe = '重置4G流量序列号{},iccid:{}'.format(serial_number, iccid)

+ 11 - 6
Controller/CloudStorage.py

@@ -209,7 +209,7 @@ class CloudStorageView(View):
         if experience_context_qs.exists():
         if experience_context_qs.exists():
             if not is_ai:  # 返回云存套餐
             if not is_ai:  # 返回云存套餐
                 store_qs = store_qs.filter(~Q(pay_type='10'), Q(pixel_level=pixel_level), Q(is_ai=0))  # 筛选像素等级
                 store_qs = store_qs.filter(~Q(pay_type='10'), Q(pixel_level=pixel_level), Q(is_ai=0))  # 筛选像素等级
-            else:          # 返回云存+AI套餐
+            else:  # 返回云存+AI套餐
                 is_ai = uid_set_qs[0]['is_ai']
                 is_ai = uid_set_qs[0]['is_ai']
                 is_ai = 1 if is_ai != 2 and CONFIG_INFO != CONFIG_CN else 0  # 国内不支持AI服务
                 is_ai = 1 if is_ai != 2 and CONFIG_INFO != CONFIG_CN else 0  # 国内不支持AI服务
                 if not is_ai:
                 if not is_ai:
@@ -1125,16 +1125,19 @@ class CloudStorageView(View):
                     if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time:  # 套餐使用中并且相同套餐叠加过期时间
                     if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time:  # 套餐使用中并且相同套餐叠加过期时间
                         Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, order_id=order_id,
                         Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, order_id=order_id,
                                                        expire=expire, is_ai=is_ai, bucket_id=bucket_id)
                                                        expire=expire, is_ai=is_ai, bucket_id=bucket_id)
-                        UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
+                        update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
                         use_flag = False
                         use_flag = False
                     else:
                     else:
-                        UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel, bucket_id=bucket_id,
-                                                                           endTime=end_time, updateTime=now_time,
-                                                                           use_status=1)
+                        update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(channel=channel,
+                                                                                           bucket_id=bucket_id,
+                                                                                           endTime=end_time,
+                                                                                           updateTime=now_time,
+                                                                                           use_status=1)
                 else:
                 else:
                     uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
                     uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
                                                            endTime=end_time, addTime=now_time, updateTime=now_time,
                                                            endTime=end_time, addTime=now_time, updateTime=now_time,
                                                            use_status=1)
                                                            use_status=1)
+                    update_status = True
                     uid_bucket_id = uid_bucket.id
                     uid_bucket_id = uid_bucket.id
 
 
                 device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
                 device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
@@ -1148,7 +1151,9 @@ class CloudStorageView(View):
                 # 核销coupon
                 # 核销coupon
                 if order_list[0]['coupon_id']:
                 if order_list[0]['coupon_id']:
                     CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=now_time)
                     CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=now_time)
-
+                logger.info(
+                    'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(uid, uid_bucket_id, update_status,
+                                                                                  order_id))
                 order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
                 order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
                                 promotion_rule_id=promotion_rule_id)
                                 promotion_rule_id=promotion_rule_id)
                 date_time = time.strftime("%Y-%m-%d", time.localtime())
                 date_time = time.strftime("%Y-%m-%d", time.localtime())

+ 112 - 5
Controller/Cron/CronTaskController.py

@@ -8,10 +8,13 @@
 # @File    : CronTaskController.py
 # @File    : CronTaskController.py
 # @Software: PyCharm
 # @Software: PyCharm
 import datetime
 import datetime
+import io
 import threading
 import threading
 import time
 import time
+import zipfile
 
 
 import requests
 import requests
+import csv
 from django.db import connection, connections, transaction
 from django.db import connection, connections, transaction
 from django.db.models import Q, Sum, Count
 from django.db.models import Q, Sum, Count
 from django.views import View
 from django.views import View
@@ -30,6 +33,8 @@ from Object.utils.PayPalUtil import PayPalService
 from Service.CommonService import CommonService
 from Service.CommonService import CommonService
 from Service.VodHlsService import SplitVodHlsObject
 from Service.VodHlsService import SplitVodHlsObject
 from Object.UnicomObject import UnicomObjeect
 from Object.UnicomObject import UnicomObjeect
+from Object.WechatPayObject import WechatPayObject
+from Object.AliPayObject import AliPayObject
 
 
 
 
 class CronDelDataView(View):
 class CronDelDataView(View):
@@ -1397,6 +1402,10 @@ class CronComparedDataView(View):
         response = ResponseObject()
         response = ResponseObject()
         if operation == 'PaypalOrder':  # 定时对比paypal订单
         if operation == 'PaypalOrder':  # 定时对比paypal订单
             return self.compared_paypal_order(response)
             return self.compared_paypal_order(response)
+        elif operation == 'WechatOrder':  # 定时对比微信订单
+            return self.compared_wechat_order(response)
+        elif operation == 'AlipayOrder':  # 定时对比阿里订单
+            return self.compared_alipay_order(response)
         else:
         else:
             return response.json(404)
             return response.json(404)
 
 
@@ -1416,7 +1425,7 @@ class CronComparedDataView(View):
                 ('transaction_status', 'S')
                 ('transaction_status', 'S')
             )
             )
             order_list = PayPalService(PAYPAL_CRD['client_id'], PAYPAL_CRD['client_secret']).get_transactions(data)
             order_list = PayPalService(PAYPAL_CRD['client_id'], PAYPAL_CRD['client_secret']).get_transactions(data)
-            thread = threading.Thread(target=CronComparedDataView.thread_compared_order,
+            thread = threading.Thread(target=CronComparedDataView.thread_compared_pyapal_order,
                                       args=(order_list['transaction_details'],))
                                       args=(order_list['transaction_details'],))
             thread.start()
             thread.start()
             return response.json(0)
             return response.json(0)
@@ -1426,7 +1435,7 @@ class CronComparedDataView(View):
             return response.json(500)
             return response.json(500)
 
 
     @staticmethod
     @staticmethod
-    def thread_compared_order(order_list):
+    def thread_compared_pyapal_order(order_list):
         now_time = int(time.time())
         now_time = int(time.time())
         for item in order_list:
         for item in order_list:
             trade_no = item['transaction_info']['transaction_id']
             trade_no = item['transaction_info']['transaction_id']
@@ -1434,7 +1443,7 @@ class CronComparedDataView(View):
                 trade_no = item['transaction_info']['paypal_reference_id']
                 trade_no = item['transaction_info']['paypal_reference_id']
             order_qs = Order_Model.objects.filter(trade_no=trade_no, payType=1)
             order_qs = Order_Model.objects.filter(trade_no=trade_no, payType=1)
             if not order_qs.exists():
             if not order_qs.exists():
-                order_id = item['transaction_info'].get('transaction_subject', '')
+                transaction_subject = item['transaction_info'].get('transaction_subject', '')
                 agreement_id = item['transaction_info'].get('paypal_reference_id', '')
                 agreement_id = item['transaction_info'].get('paypal_reference_id', '')
                 pay_time = datetime.datetime.strptime(item['transaction_info']['transaction_initiation_date'],
                 pay_time = datetime.datetime.strptime(item['transaction_info']['transaction_initiation_date'],
                                                       "%Y-%m-%dT%H:%M:%S%z").timestamp()
                                                       "%Y-%m-%dT%H:%M:%S%z").timestamp()
@@ -1446,11 +1455,13 @@ class CronComparedDataView(View):
                     'price': item['transaction_info']['transaction_amount']['value'],
                     'price': item['transaction_info']['transaction_amount']['value'],
                     'pay_type': 1,
                     'pay_type': 1,
                     'upd_time': now_time,
                     'upd_time': now_time,
-                    'status': 0
+                    'status': 0,
+                    'meal_name': transaction_subject
                 }
                 }
                 if agreement_id:
                 if agreement_id:
                     order_dict['pay_type'] = 0
                     order_dict['pay_type'] = 0
-                    order_dict['order_id'] = order_id
+                    order_dict['meal_name'] = 'paypal_cycle'
+                    order_dict['order_id'] = transaction_subject
                 params = {'trade_no': trade_no}
                 params = {'trade_no': trade_no}
                 response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
                 response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
                 if response.status_code != 200:
                 if response.status_code != 200:
@@ -1461,3 +1472,99 @@ class CronComparedDataView(View):
                 if result['result_code'] != 0 or not result['result']['is_exist']:
                 if result['result_code'] != 0 or not result['result']['is_exist']:
                     # 如果响应结果为空,记录在数据库
                     # 如果响应结果为空,记录在数据库
                     AbnormalOrder.objects.create(**order_dict)
                     AbnormalOrder.objects.create(**order_dict)
+
+    @staticmethod
+    def compared_wechat_order(response):
+        today = datetime.datetime.today()
+        start_date = today - datetime.timedelta(days=1)
+        start_date = start_date.strftime("%Y%m%d")
+        try:
+            order_list = WechatPayObject().download_bill(start_date)
+            thread = threading.Thread(target=CronComparedDataView.thread_compared_wechat_order,
+                                      args=(order_list,))
+            thread.start()
+            return response.json(0)
+        except Exception as e:
+            LOGGER.info('CronComparedDataView.compared_wechat_order, errLine:{}, errMsg:{}'.format(
+                e.__traceback__.tb_lineno, repr(e)))
+            return response.json(500)
+
+    @staticmethod
+    def thread_compared_wechat_order(order_list):
+        now_time = int(time.time())
+        for order in order_list:
+            if order['交易类型'] != '`APP':
+                continue
+            order_id = order['商户订单号'].replace('`', '')
+            order_qs = Order_Model.objects.filter(orderID=order_id)
+            if not order_qs.exists():
+                order_dict = {
+                    'trade_no': order['微信订单号'].replace('`', ''),
+                    'order_id': order_id,
+                    'pay_type': 3,
+                    'price': order['订单金额'].replace('`', ''),
+                    'pay_time': int(datetime.datetime.strptime(order['\ufeff交易时间'], "`%Y-%m-%d %H:%M:%S").timestamp()),
+                    'upd_time': now_time,
+                    'meal_name': order['商品名称'].replace('`', ''),
+                }
+                AbnormalOrder.objects.create(**order_dict)
+
+    @staticmethod
+    def compared_alipay_order(response):
+        today = datetime.datetime.today()
+        start_date = today - datetime.timedelta(days=1)
+        start_date = start_date.strftime("%Y-%m-%d")
+        try:
+            ali_pay_obj = AliPayObject()
+            alipay = ali_pay_obj.conf()
+            result = alipay.server_api(
+                api_name='alipay.data.dataservice.bill.downloadurl.query',
+                biz_content={'bill_type': 'trade',
+                             'bill_date': start_date,
+                             }
+            )
+            res = requests.get(result['bill_download_url'])
+            zip_file = res.content
+            zip_data = io.BytesIO(zip_file)
+            data = []
+            with zipfile.ZipFile(zip_data, 'r') as zip_ref:
+                for file in zip_ref.namelist():
+                    if '汇总' not in file.encode('cp437').decode('gbk'):
+                        with zip_ref.open(file) as f:
+                            reader = csv.reader(io.TextIOWrapper(f, 'gbk'))
+                            for row in reader:
+                                data.append(row)
+            key_list = data[4]
+            orders = data[5:-4]
+            order_list = []
+            for item in orders:
+                order_list.append(dict(zip(key_list, item)))
+            thread = threading.Thread(target=CronComparedDataView.thread_compared_alipay_order,
+                                      args=(order_list,))
+            thread.start()
+            return response.json(0)
+        except Exception as e:
+            LOGGER.info('CronComparedDataView.compared_alipay_order, errLine:{}, errMsg:{}'.format(
+                e.__traceback__.tb_lineno, repr(e)))
+            return response.json(500)
+
+    @staticmethod
+    def thread_compared_alipay_order(order_list):
+        now_time = int(time.time())
+        for order in order_list:
+            order_id = order['商户订单号'].replace('\t', '')
+            if len(order_id) != 20:
+                continue
+            order_qs = Order_Model.objects.filter(orderID=order_id)
+            if not order_qs.exists():
+                order_dict = {
+                    'trade_no': order['支付宝交易号'].replace('\t', ''),
+                    'order_id': order_id,
+                    'pay_type': 2,
+                    'price': order['订单金额(元)'].replace('\t', ''),
+                    'pay_time': int(datetime.datetime.strptime(order['完成时间'], "%Y-%m-%d %H:%M:%S").timestamp()),
+                    'upd_time': now_time,
+                    'meal_name': order['商品名称'].replace('\t', ''),
+                    'username': order['对方账户'].replace('\t', ''),
+                }
+                AbnormalOrder.objects.create(**order_dict)

+ 11 - 3
Controller/DeviceConfirmRegion.py

@@ -8,6 +8,7 @@ from Model.models import CountryModel, RegionModel, P2PIpModel, DeviceDomainMode
 from Object.ResponseObject import ResponseObject
 from Object.ResponseObject import ResponseObject
 from Service.CommonService import CommonService
 from Service.CommonService import CommonService
 from Object.IPWeatherObject import IPQuery
 from Object.IPWeatherObject import IPQuery
+from Ansjer.config import LOGGER
 
 
 
 
 class ConfirmRegion(View):
 class ConfirmRegion(View):
@@ -60,8 +61,10 @@ class ConfirmRegion(View):
                 'push_api_url': push_api,
                 'push_api_url': push_api,
                 'push_region': push_region
                 'push_region': push_region
             }
             }
+            LOGGER.info('获取域名:ip:{},响应数据:{}'.format(ip, res))
             return response.json(0, res)
             return response.json(0, res)
         except Exception as e:
         except Exception as e:
+            LOGGER.info('获取域名异常:error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
 
 
@@ -74,16 +77,19 @@ class ConfirmRegionV2(View):
     @staticmethod
     @staticmethod
     def get(request, *args, **kwargs):
     def get(request, *args, **kwargs):
         response = ResponseObject()
         response = ResponseObject()
+
+        # 获取ip
+        request.encoding = 'utf-8'
+        ip = CommonService.get_ip_address(request)
+
         serial_number = request.GET.get('serial_number', None)
         serial_number = request.GET.get('serial_number', None)
         if not serial_number:
         if not serial_number:
+            LOGGER.info('V2获取域名缺少序列号:ip:{}'.format(ip))
             return response.json(444)
             return response.json(444)
         try:
         try:
             data_dict = {'serial_number': serial_number}
             data_dict = {'serial_number': serial_number}
             device_domain_region_qs = DeviceDomainRegionModel.objects.filter(serial_number=serial_number)
             device_domain_region_qs = DeviceDomainRegionModel.objects.filter(serial_number=serial_number)
 
 
-            # 获取ip
-            request.encoding = 'utf-8'
-            ip = CommonService.get_ip_address(request)
             data_dict['ip'] = ip
             data_dict['ip'] = ip
 
 
             # 获取国家编码
             # 获取国家编码
@@ -126,8 +132,10 @@ class ConfirmRegionV2(View):
                 'region_id': region_id,
                 'region_id': region_id,
                 'push_region': push_region
                 'push_region': push_region
             }
             }
+            LOGGER.info('V2获取域名:序列号:{},ip:{},响应数据:{}'.format(serial_number, ip, res))
             return response.json(0, res)
             return response.json(0, res)
         except Exception as e:
         except Exception as e:
+            LOGGER.info('V2获取域名异常:error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
             return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
 
 

+ 6 - 3
Controller/PaymentCycle.py

@@ -237,16 +237,17 @@ class PaypalCycleNotify(View):
                     if ubq['use_status'] == 1 and ubq['endTime'] > nowTime:  # 套餐使用中并且未过期,加入未使用的关联套餐表
                     if ubq['use_status'] == 1 and ubq['endTime'] > nowTime:  # 套餐使用中并且未过期,加入未使用的关联套餐表
                         Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, is_ai=is_ai,
                         Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, is_ai=is_ai,
                                                        order_id=orderID, expire=expire, bucket_id=bucketId)
                                                        order_id=orderID, expire=expire, bucket_id=bucketId)
-                        UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
+                        update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
                         use_flag = False
                         use_flag = False
                     else:  # 云存服务已过期则重新开通云存服务
                     else:  # 云存服务已过期则重新开通云存服务
-                        UID_Bucket.objects.filter(id=uid_bucket_id).update(uid=UID, channel=channel, bucket_id=bucketId,
+                        update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(uid=UID, channel=channel, bucket_id=bucketId,
                                                                            endTime=endTime, updateTime=nowTime)
                                                                            endTime=endTime, updateTime=nowTime)
 
 
                 else:
                 else:
                     ub_cqs = UID_Bucket.objects.create \
                     ub_cqs = UID_Bucket.objects.create \
                         (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
                         (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
                          updateTime=nowTime, use_status=1)
                          updateTime=nowTime, use_status=1)
+                    update_status = True
                     uid_bucket_id = ub_cqs.id
                     uid_bucket_id = ub_cqs.id
                 dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
                 dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
                 if dvq.exists():
                 if dvq.exists():
@@ -275,7 +276,9 @@ class PaypalCycleNotify(View):
                 # 核销coupon
                 # 核销coupon
                 if order_list[0]['coupon_id']:
                 if order_list[0]['coupon_id']:
                     CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=nowTime)
                     CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=nowTime)
-
+                logger.info(
+                    'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(UID, uid_bucket_id, update_status,
+                                                                                  orderID))
                 order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
                 order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
                                 promotion_rule_id=promotion_rule_id, agreement_id=agreement_id)
                                 promotion_rule_id=promotion_rule_id, agreement_id=agreement_id)
                 # 如果存在序列号,消息提示用序列号
                 # 如果存在序列号,消息提示用序列号

+ 84 - 73
Controller/SerialNumberController.py

@@ -235,8 +235,8 @@ class SerialNumberView(View):
                 res = self.get_uid_info_by_serial(company_serial.id)
                 res = self.get_uid_info_by_serial(company_serial.id)
                 return response.json(0, res)
                 return response.json(0, res)
             elif company_serial.status == 3:  # 已占用
             elif company_serial.status == 3:  # 已占用
-                res = self.log_and_send_email(request, company_serial.id, serial_number, now_time)
-                if not res:
+                sync_success = self.sync_serial_data_and_log(request, company_serial.id, serial_number, now_time)
+                if not sync_success:
                     return response.json(10042)
                     return response.json(10042)
                 return response.json(0, self.get_uid_info_by_serial(company_serial.id))
                 return response.json(0, self.get_uid_info_by_serial(company_serial.id))
         except Exception as e:
         except Exception as e:
@@ -351,94 +351,105 @@ class SerialNumberView(View):
                 LOGGER.info('发送提醒邮件异常: error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
                 LOGGER.info('发送提醒邮件异常: error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
     @staticmethod
     @staticmethod
-    def log_and_send_email(request, company_serial_id, serial, now_time):
+    def sync_serial_data_and_log(request, company_serial_id, serial, now_time):
         """
         """
-        记录序列号占用操作日志及发送邮件通知,(美服、欧服已占用序列号将执行数据同步)
+        同步序列号数据和记录日志
         @param company_serial_id: 企业关联序列号 ID
         @param company_serial_id: 企业关联序列号 ID
         @param request: 请求
         @param request: 请求
         @param serial: 序列号
         @param serial: 序列号
         @param now_time: 当前时间
         @param now_time: 当前时间
+        @return : bool
         """
         """
-        send_email = S3Email()
+        ip = CommonService.get_ip_address(request)
+        operation = '{}序列号占用,'.format(serial)
+        log = {
+            'ip': ip,
+            'user_id': 1,
+            'status': 200,
+            'time': now_time,
+            'url': 'serialNumber/attachUID',
+        }
+        sync_result = False
+        # 测试服和国内服不同步
+        if CONFIG_INFO == 'test' or CONFIG_INFO == 'cn':
+            return sync_result
         try:
         try:
-            if CONFIG_INFO == 'cn' or CONFIG_INFO == 'test':
-                return {}
             # 判断当前序列号是否绑定UID
             # 判断当前序列号是否绑定UID
             uid_serial_qs = UIDCompanySerialModel.objects.filter(company_serial_id=company_serial_id)
             uid_serial_qs = UIDCompanySerialModel.objects.filter(company_serial_id=company_serial_id)
             if uid_serial_qs.exists():
             if uid_serial_qs.exists():
-                email_content = '{}序列号已占用当前数据库已绑定UID: {}'.format(CONFIG_INFO, serial)
-                send_email.faEmail(email_content, 'servers@ansjer.com')
-                return {}
-            if CONFIG_INFO == 'eur':  # 查美服
-                response = requests.get("https://www.dvema.com/serialNumber/get-status",
-                                        params={'serial_number': serial}, timeout=15)
-            else:  # 查国服
-                response = requests.get("https://www.zositechc.cn/serialNumber/get-status",
-                                        params={'serial_number': serial}, timeout=15)
-            ip = CommonService.get_ip_address(request)
-            operation = '{}序列号占用:{}'.format(CONFIG_INFO, serial)
-            log = {
-                'ip': ip,
-                'user_id': 1,
-                'status': 200,
-                'time': now_time,
-                'operation': operation,
-                'url': 'serialNumber/attachUID',
-            }
-            if not response.status_code == 200:
-                operation += '查询其它服UID数据异常响应状态:{}'.format(response.status_code)
+                operation += ',已绑定UID,不同步数据'
+                log['operation'] = operation
+                LogModel.objects.create(**log)
+                return sync_result
+
+            region = 'us'
+            # 欧洲服同步美洲服,美洲服同步国内服数据
+            if CONFIG_INFO == 'eur':
+                url = 'https://www.dvema.com/'
+            else:
+                region = 'cn'
+                url = 'https://www.zositechc.cn/'
+
+            url += 'serialNumber/get-status'
+            response = requests.get(url=url, params={'serial_number': serial}, timeout=15)
+
+            if response.status_code != 200:
+                operation += '查询{}服UID数据响应状态码异常:{}'.format(region, response.status_code)
                 log['operation'] = operation
                 log['operation'] = operation
                 LogModel.objects.create(**log)
                 LogModel.objects.create(**log)
-                return {}
+                return sync_result
+
             results = json.loads(response.text)
             results = json.loads(response.text)
-            if not results['result_code'] == 0:
-                operation += '其它服绑定UID数据result_code: {}'.format(results['result_code'])
+            if results['result_code'] != 0:
+                operation += '查询{}服UID数据result_code异常:{}'.format(region, results['result_code'])
                 log['operation'] = operation
                 log['operation'] = operation
                 LogModel.objects.create(**log)
                 LogModel.objects.create(**log)
-                return {}
-            # 解析从其它服获取的UID数据
+                return sync_result
+
+            # 其它服没有绑定uid
             uid_info = results['result']['uidInfo']
             uid_info = results['result']['uidInfo']
-            if uid_info:
-                if uid_info['p2p_type'] == 1:  # 尚云UID不进行同步只进行 邮寄警报
-                    # 邮件通知
-                    email_content = '国内uid同步国外服类型为尚云不操作: {}'.format(serial)
-                    send_email.faEmail(email_content, 'servers@ansjer.com')
-                else:
-                    # 同步UID数据
-                    uid_id = ''
-                    uid_qs = UIDModel.objects.filter(uid=uid_info['uid'])
-                    if uid_qs.exists():
-                        if uid_qs.first().status == 2:  # 判断uid是否被使用
-                            email_content = '{}序列号已占用且{}已被使用:{}'.format(CONFIG_INFO, uid_info['uid'], serial)
-                            send_email.faEmail(email_content, 'servers@ansjer.com')
-                            return {}
-                        else:
-                            uid_qs.update(status=2, update_time=now_time)
-                            uid_id = uid_qs.first().id
-                    if not uid_id:
-                        uid_id = UIDModel.objects.create(**uid_info).id
-                    # 企业序列号关联 uid
-                    UIDCompanySerialModel.objects.create(uid_id=uid_id, company_serial_id=company_serial_id,
-                                                         add_time=now_time, update_time=now_time)
-                    # 成功后 修改企业序列号状态为2(已分配)
-                    CompanySerialModel.objects.filter(id=company_serial_id) \
-                        .update(status=2, update_time=now_time)
-                    SerialNumberView.sync_iot_core_data(serial)
-                    email_content = '{}序列号已占用已将其它服UID数据同步完成: {}'.format(CONFIG_INFO, serial)
-                    send_email.faEmail(email_content, 'servers@ansjer.com')
-                    operation += '同步成功'
+            if not uid_info:
+                operation += '{}服没有绑定UID'.format(region)
+                log['operation'] = operation
+                LogModel.objects.create(**log)
+                return sync_result
+            # 同步uid数据
+            if uid_info['p2p_type'] == 1:
+                operation += '尚云UID不同步数据'
+            else:
+                uid_qs = UIDModel.objects.filter(uid=uid_info['uid'])
+                if not uid_qs.exists():
+                    uid_id = UIDModel.objects.create(**uid_info).id
+                if uid_qs.first().status == 2:  # 判断uid是否被使用
+                    operation += 'uid{}已被使用'.format(uid_info['uid'])
                     log['operation'] = operation
                     log['operation'] = operation
                     LogModel.objects.create(**log)
                     LogModel.objects.create(**log)
-                    return 'success'
-            email_content = '{}序列号已占用其它服没有绑定UID: {}'.format(CONFIG_INFO, serial)
-            send_email.faEmail(email_content, 'servers@ansjer.com')
-            return {}
+                    return sync_result
+                else:
+                    uid_qs.update(status=2, update_time=now_time)
+                    uid_id = uid_qs.first().id
+
+                # 企业序列号关联 uid
+                UIDCompanySerialModel.objects.create(
+                    uid_id=uid_id, company_serial_id=company_serial_id, add_time=now_time, update_time=now_time)
+                # 修改企业序列号状态为2(绑定uid)
+                CompanySerialModel.objects.filter(id=company_serial_id) \
+                    .update(status=2, update_time=now_time)
+                sync_iot_result = SerialNumberView.sync_iot_core_data(serial)
+
+                operation += '同步{}服uid数据成功,同步iot数据结果:{}'.format(region, sync_iot_result)
+                sync_result = True
+
+            # 记录日志
+            log['operation'] = operation
+            LogModel.objects.create(**log)
+            return sync_result
+
         except Exception as e:
         except Exception as e:
-            email_content = '序列号占用同步数据异常: {},errLine:{}, errMsg:{}' \
-                .format(serial, e.__traceback__.tb_lineno, repr(e))
-            send_email.faEmail(email_content, 'servers@ansjer.com')
-            send_email.faEmail(email_content, 'antony@ansjer.com')
-            return {}
+            operation += '同步数据异常,error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e))
+            log['operation'] = operation
+            LogModel.objects.create(**log)
+            return sync_result
 
 
     def do_get_uid(self, request_dict, response):
     def do_get_uid(self, request_dict, response):
         serial_number = request_dict.get('serial_number', None)
         serial_number = request_dict.get('serial_number', None)
@@ -611,8 +622,8 @@ class SerialNumberView(View):
                 res = self.get_uid_info_by_serial(company_serial.id)
                 res = self.get_uid_info_by_serial(company_serial.id)
                 return response.json(0, res)
                 return response.json(0, res)
             elif company_serial.status == 3:  # 已占用
             elif company_serial.status == 3:  # 已占用
-                res = self.log_and_send_email(request, company_serial.id, serial_number, now_time)
-                if not res:
+                sync_success = self.sync_serial_data_and_log(request, company_serial.id, serial_number, now_time)
+                if not sync_success:
                     return response.json(10042)
                     return response.json(10042)
                 return response.json(0, self.get_uid_info_by_serial(company_serial.id))
                 return response.json(0, self.get_uid_info_by_serial(company_serial.id))
         except Exception as e:
         except Exception as e:

+ 39 - 0
Controller/UnicomCombo/UnicomComboController.py

@@ -1101,3 +1101,42 @@ class UnicomComboView(View):
         except Exception as e:
         except Exception as e:
             LOGGER.info('{}判断是否4G设备异常,errLine:{}, errMsg:{}'.format(serial_number, e.__traceback__.tb_lineno, repr(e)))
             LOGGER.info('{}判断是否4G设备异常,errLine:{}, errMsg:{}'.format(serial_number, e.__traceback__.tb_lineno, repr(e)))
             return False
             return False
+
+    @classmethod
+    def update_package_order(cls, request_dict, response):
+        iccid = request_dict.get('iccid', None)
+        result = cls.update_flow_package_order_by_iccid(iccid)
+        print(result)
+        return response.json(0)
+
+    @classmethod
+    def update_flow_package_order_by_iccid(cls, iccid):
+        """
+        延长无限流量套餐
+        """
+        try:
+            LOGGER.info(f'更新流量套餐包有效期:iccid={iccid}')
+            package_info_qs = UnicomComboOrderInfo.objects.filter(iccid=iccid) \
+                .filter(~Q(combo__combo_type=4), ~Q(status=2)).order_by('created_time')
+            if not package_info_qs.exists():
+                return False
+            if package_info_qs.count() > 1:
+                a_time = 0
+                is_unlimited = 0
+                for item in package_info_qs:
+                    if is_unlimited == 1 and item.combo.is_unlimited == 1:
+                        activate_time = a_time - (3600 * 12)
+                        expire_time = LocalDateTimeUtil.get_after_days_timestamp(a_time, item.combo.expiration_days)
+                        UnicomComboOrderInfo.objects.filter(id=item.id) \
+                            .update(activation_time=activate_time, expire_time=expire_time,
+                                    updated_time=int(time.time()))
+                        LOGGER.info(f'有更新:iccid={iccid}')
+                    is_unlimited = item.combo.is_unlimited
+                    a_time = item.expire_time
+            return True
+
+        except Exception as e:
+            LOGGER.info(
+                '{}update_flow_package_order_by_iccid,errLine:{}, errMsg:{}'.format(iccid, e.__traceback__.tb_lineno,
+                                                                                    repr(e)))
+            return False

+ 2 - 0
Controller/UnicomCombo/WXTechController.py

@@ -315,6 +315,8 @@ class WXTechControllerView(View):
                                                      user_id, combo_id)
                                                      user_id, combo_id)
                 if result:
                 if result:
                     exchange_code_qs.update(status=True, updated_time=int(time.time()))
                     exchange_code_qs.update(status=True, updated_time=int(time.time()))
+                    # 校验是否两个重叠无限流量套餐 修改套餐数据
+                    UnicomComboView().update_flow_package_order_by_iccid(iccid)
                     cls.save_log(ip, 10065, '兑换成功{},{}'.format(serial_number, code))
                     cls.save_log(ip, 10065, '兑换成功{},{}'.format(serial_number, code))
                     return response.json(10065)
                     return response.json(10065)
             elif card_type == 1:  # 五兴电信无限流量兑换码
             elif card_type == 1:  # 五兴电信无限流量兑换码

+ 1 - 0
Model/models.py

@@ -4404,6 +4404,7 @@ class AbnormalOrder(models.Model):
     pay_time = models.IntegerField(verbose_name='支付成功时间', default=0)
     pay_time = models.IntegerField(verbose_name='支付成功时间', default=0)
     upd_time = models.IntegerField(verbose_name='更新时间', default=0)
     upd_time = models.IntegerField(verbose_name='更新时间', default=0)
     status = models.SmallIntegerField(default=0, verbose_name='处理结果')  # 0:未处理,1:已处理
     status = models.SmallIntegerField(default=0, verbose_name='处理结果')  # 0:未处理,1:已处理
+    meal_name = models.CharField(default='', blank=True, max_length=32, verbose_name='套餐名')
 
 
     class Meta:
     class Meta:
         db_table = 'abnormal_order'
         db_table = 'abnormal_order'

+ 22 - 1
Object/WechatPayObject.py

@@ -1,3 +1,4 @@
+import datetime
 import hashlib
 import hashlib
 import time
 import time
 from urllib.parse import quote
 from urllib.parse import quote
@@ -23,6 +24,7 @@ class WechatPayObject:
         self.APIKEY = 'ZHansjeransjeransjer680301000000'
         self.APIKEY = 'ZHansjeransjeransjer680301000000'
         self.url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'  # 微信请求url
         self.url = 'https://api.mch.weixin.qq.com/pay/unifiedorder'  # 微信请求url
         self.refund_url = 'https://api.mch.weixin.qq.com/secapi/pay/refund'   # 退款url
         self.refund_url = 'https://api.mch.weixin.qq.com/secapi/pay/refund'   # 退款url
+        self.downloadbill_url = 'https://api.mch.weixin.qq.com/pay/downloadbill'
         self.error = None
         self.error = None
         self.params = None
         self.params = None
 
 
@@ -225,4 +227,23 @@ class WechatPayObject:
         if response['xml']['return_code'] == 'SUCCESS':
         if response['xml']['return_code'] == 'SUCCESS':
             return True
             return True
         else:
         else:
-            return False
+            return False
+
+    def download_bill(self, date):
+        params = {
+            'appid': self.APPID,  # 公众账号ID
+            'mch_id': self.MCHID,  # 商户号
+            'nonce_str': self.getNonceStr(),  # 随机字符串
+            'bill_date': date,  # 对账单日期
+            'bill_type': 'ALL',  # 账单类型
+        }
+        string_sign = "&".join(['{}={}'.format(k, params[k]) for k in sorted(params)] + ['key={}'.format(self.APIKEY)])
+        params['sign'] = hashlib.md5(string_sign.encode('utf8')).hexdigest().upper()   # MD5签名
+        xml = "<xml>{}</xml>".format("".join(['<{k}>{v}</{k}>'.format(k=k, v=v) for k, v in params.items()]))   # 数据拼接成xml格式
+        r = requests.post(url=self.downloadbill_url, headers={'Content-Type': 'text/xml'}, data=xml.encode('utf-8'))
+        order_text_list = r.text.split('\r\n')
+        key_list = order_text_list[0].split(',')
+        order_list = []
+        for item in order_text_list[1:-3]:
+            order_list.append(dict(zip(key_list, item.split(','))))
+        return order_list

+ 7 - 2
Service/EquipmentInfoService.py

@@ -528,9 +528,14 @@ class EquipmentInfoService:
                 'device_user_id': user_id,
                 'device_user_id': user_id,
                 'event_time__range': (start_time, end_time),
                 'event_time__range': (start_time, end_time),
             }
             }
-            event_type_kwargs = {}
+            event_type_kwargs = {
+                'device_user_id': user_id,
+                'event_time__range': (start_time, end_time),
+            }
             if uid_list:
             if uid_list:
                 kwargs['device_uid__in'] = uid_list
                 kwargs['device_uid__in'] = uid_list
+                event_type_kwargs['device_uid__in'] = uid_list
+            event_type_list = []
             if event_type:
             if event_type:
                 # 多类型查询
                 # 多类型查询
                 event_type_list = cls.get_comb_event_type(event_type)
                 event_type_list = cls.get_comb_event_type(event_type)
@@ -543,7 +548,7 @@ class EquipmentInfoService:
                 elif tags:
                 elif tags:
                     kwargs['event_tag__regex'] = tags
                     kwargs['event_tag__regex'] = tags
 
 
-            if not event_type_kwargs:
+            if not event_type_list:
                 # 新增tab_val字段记录表的标识:表编号+10
                 # 新增tab_val字段记录表的标识:表编号+10
                 equipment_info_1 = EquipmentInfo1.objects.filter(**kwargs).annotate(tab_val=Value('11', output_field=CharField()))
                 equipment_info_1 = EquipmentInfo1.objects.filter(**kwargs).annotate(tab_val=Value('11', output_field=CharField()))
                 equipment_info_2 = EquipmentInfo2.objects.filter(**kwargs).annotate(tab_val=Value('12', output_field=CharField()))
                 equipment_info_2 = EquipmentInfo2.objects.filter(**kwargs).annotate(tab_val=Value('12', output_field=CharField()))