Ver código fonte

物联网卡管理模块功能实现

yf_fyh 3 anos atrás
pai
commit
29e0db8b89
4 arquivos alterados com 184 adições e 12 exclusões
  1. 2 1
      .gitignore
  2. 1 1
      apps/IOTCard/models.py
  3. 181 10
      apps/IOTCard/views.py
  4. BIN
      requirements.txt

+ 2 - 1
.gitignore

@@ -4,4 +4,5 @@
 *.py[cod]
 __pycache__/
 migrations/
-.python-version
+.python-version
+*.xlsx

+ 1 - 1
apps/IOTCard/models.py

@@ -6,7 +6,7 @@ import django.utils.timezone as timezone
 class PlatSimInfo(models.Model):
     OPERATORS_CHOICE = [
         (1, "合宙"),
-        (2, "企朋"),  # 企朋和SIMBOSS是同一单位
+        (2, "SIMBoss"),  # 企朋和SIMBOSS是同一单位
         (3, "未知")
     ]
     TYPE_CHOICE = [

+ 181 - 10
apps/IOTCard/views.py

@@ -1,11 +1,18 @@
 from rest_framework import status
 from rest_framework import viewsets
 from rest_framework.response import Response
+from django.http import HttpResponse
 from rest_framework.decorators import action
 from rest_framework.serializers import ValidationError
 
 import requests
+import uuid
 import json
+import os
+import datetime
+from io import BytesIO
+import pandas as pd
+from django.utils.encoding import escape_uri_path
 
 from .serializers import PlatSimInfoSerializer
 from .models import PlatSimInfo
@@ -14,6 +21,13 @@ from utils.utils import get_equip_list, Get_SIM_info
 
 
 # Create your views here.
+def time_dif(checkdatetime):
+    # 获取传入时间和当前时间差
+    nowdatetime = datetime.datetime.now()
+    checkdatetime = datetime.datetime.strptime(checkdatetime,"%Y-%m-%d %H:%M:%S")
+    
+    timedif = nowdatetime - checkdatetime
+    return timedif.days
 
 
 class PlatformIOTCardViewSet(viewsets.ModelViewSet):
@@ -21,14 +35,6 @@ class PlatformIOTCardViewSet(viewsets.ModelViewSet):
     pagination_class = CustomPagination
     queryset = PlatSimInfo.objects.all().order_by("expiry_date")
 
-    @action(methods=['get'], detail=False, url_path='get_device_type', url_name='get_device_type')
-    def get_device_type(self, request, *args, **kwargs):
-        queryset = PlatSimInfo.objects.raw("SELECT id,device_type FROM plat_sim_info GROUP BY device_type;")
-        data = []
-        for i in queryset:
-            data.append(i.device_type)
-        return Response(data)
-
     def list(self, request, *args, **kwargs):
         device_type = request.query_params.get("device_type")
         deviceId = request.query_params.get("deviceId")
@@ -62,7 +68,7 @@ class PlatformIOTCardViewSet(viewsets.ModelViewSet):
             raise ValidationError("该物联网卡号已存在,请核查!")
 
         if self.get_queryset().filter(deviceId=device_id, input_type=2).exists():
-            raise ValidationError("该设备已存在手动录入物联网卡,请核查!")
+            raise ValidationError("该设备已存在手动录入类型,请核查!")
 
         device_info_list = get_equip_list(
             d_id=device_id,
@@ -113,6 +119,7 @@ class PlatformIOTCardViewSet(viewsets.ModelViewSet):
         self.perform_create(serializer)
         headers = self.get_success_headers(serializer.data)
         return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
+
     def update(self, request, pk, *args, **kwargs):
         req = request.data.get("req")
         instance = self.get_object()
@@ -165,4 +172,168 @@ class PlatformIOTCardViewSet(viewsets.ModelViewSet):
         serializer = self.get_serializer(instance, data=update_data, partial=True)
         serializer.is_valid(raise_exception=True)
         self.perform_update(serializer)
-        return Response(serializer.data)
+        return Response(serializer.data)
+
+    @action(methods=['get'], detail=False, url_path='get_device_type', url_name='get_device_type')
+    def get_device_type(self, request, *args, **kwargs):
+        queryset = PlatSimInfo.objects.raw("SELECT id,device_type FROM plat_sim_info GROUP BY device_type;")
+        data = []
+        for i in queryset:
+            data.append(i.device_type)
+        return Response(data)
+    
+    @action(methods=['get'], detail=False, url_path='down_excel', url_name='down_excel')
+    def down_excel(self, request, *args, **kwargs):
+        filename = request.query_params.get("filename")
+        if filename == "发货表示例模板.xlsx":
+            save_data = dict(设备ID=[])
+        elif filename == "合宙续存流量卡筛选模板.xlsx":
+            save_data = dict(ICCID=[],续费价格=[],当月消耗流量=[])
+        elif filename == "SIMBoss续存流量卡筛选模板.xlsx":
+            save_data = dict(ICCID=[],筛查月份1=[],筛查月份2=[],筛查月份3=[],筛查月份4=[],筛查月份5=[],
+            筛查月份6=[],筛查月份7=[],筛查月份8=[],筛查月份9=[])
+        else:
+            now_dir = os.path.dirname(__file__)
+            file_path = os.path.join(now_dir,"excel_folder",filename)
+            if os.path.exists(file_path) == False:
+                raise ValidationError("文件不存在,请确认文件名")
+            else:
+                with open(file_path, 'rb') as f:
+                    data = f.read()
+            response = HttpResponse(data, content_type="application/vnd.ms-excel")
+            response['Content-Disposition'] = 'attachment;filename={}'.format(escape_uri_path(filename))
+            os.remove(file_path)
+            return response
+        df = pd.DataFrame(data=save_data)
+        output = BytesIO()
+        df.to_excel(output, index=False)
+        output.seek(0)
+        response = HttpResponse(content_type='application/vnd.ms-excel')
+        response['Content-Disposition'] = 'attachment;filename={}'.format(escape_uri_path(filename))
+        response.write(output.getvalue())
+        return response
+
+    @action(methods=['post'], detail=False, url_path='delivery_card_filter', url_name='delivery_card_filter')
+    def card_delivery_filter(self, request, *args, **kwargs):
+        file = request.FILES.get('file')
+        file_dataframe = pd.read_excel(file)
+        save_data = dict(deviceid=[],fulldeviceid=[],device_type=[],is_recharge=[],backword=[])
+
+        for deviceId in file_dataframe["设备ID"]:
+            if isinstance(deviceId,int):
+                deviceId = str(int(deviceId))
+            else:
+                deviceId = deviceId.strip()
+            sim_queryset = self.get_queryset().filter(deviceId__endswith=deviceId,input_type=1)
+            if sim_queryset.count() == 0:
+                fulldeviceid = "未知"
+                device_type = "未知"
+                is_recharge = "未知"
+                backword = "根据表内设备号未找到记录"
+            elif sim_queryset.count() == 1:
+                sim_obj = sim_queryset.first()
+                fulldeviceid = sim_obj.deviceId
+                device_type = sim_obj.device_type
+                if sim_obj.expiry_date == "未知":
+                    is_recharge = "未知"
+                else:
+                    time_difference = time_dif(sim_obj.expiry_date)
+                    if time_difference >= -180:
+                        is_recharge = "是"
+                    else:
+                        is_recharge = "否"
+                backword = "{}".format(sim_obj.simId)
+                if sim_obj.device_type=="孢子仪" or sim_obj.device_type=="测报灯":
+                    sim2_queryset = self.get_queryset().filter(deviceId=fulldeviceid,input_type=2).order_by("-id")
+                    if sim2_queryset:
+                        sim2_obj = sim2_queryset[0]
+                        if sim2_obj.expiry_date == "未知":
+                            is_recharge = "卡1" + is_recharge + ",卡2未知"
+                        else:
+                            time_difference = time_dif(sim2_obj.expiry_date)
+                            if time_difference >= -180:
+                                is_recharge = "卡1" + is_recharge + ",卡2是"
+                            else:
+                                is_recharge = "卡1" + is_recharge + ",卡2否"
+                        backword = "卡1:{};卡2:{}".format(sim_obj.simId,sim2_obj.simId)
+                    else:
+                        print("卡二不存在")
+                
+            else:
+                fulldeviceid = "未知"
+                device_type = "未知"
+                is_recharge = "未知"
+                backword = "根据表内设备号存在多条记录"
+            save_data["deviceid"].append(deviceId)
+            save_data["fulldeviceid"].append(fulldeviceid)
+            save_data["is_recharge"].append(is_recharge)
+            save_data["device_type"].append(device_type)
+            save_data["backword"].append(backword)
+            
+        df = pd.DataFrame(data=save_data)
+        save_filename = str(uuid.uuid4())+".xlsx"
+        now_dir = os.path.dirname(__file__)
+        save_path = os.path.join(now_dir,"excel_folder",save_filename)
+        df.to_excel(save_path,index=False,header=["设备ID","完整设备号(自行判断)","设备类型","是否需要充值","说明备注"])
+        return Response(save_filename)
+    @action(methods=['post'], detail=False, url_path='xucun_card_filter', url_name='xucun_card_filter')
+    def xucun_card_filter(self, request, *args, **kwargs):
+        simtype = request.data.get("simtype")
+        renew_file = request.FILES.get("file")
+        file_dataframe = pd.read_excel(renew_file)
+        if simtype == "1":  # 合宙卡
+            save_data = dict(ICCID=[], 续费价格=[], 是否需要充值=[],备注=[])
+            sim_list = list(file_dataframe["ICCID"])
+            price_list = list(file_dataframe["续费价格"])
+            usage_list = list(file_dataframe["当月消耗流量"])
+            for index, usage in enumerate(usage_list):
+                save_data["ICCID"].append(str(sim_list[index]))
+                save_data["续费价格"].append(str(price_list[index]))
+                try:
+                    usage_value = float(usage)
+                except:
+                    usage_value = ""
+                if usage_value == 0 or usage_value == "":
+                    card_queryset = self.get_queryset().filter(simId=str(sim_list[index]))
+                    if card_queryset.exists():
+                        card_obj = card_queryset.first()
+                        deviceId = card_obj.deviceId
+                        device_info_list = get_equip_list(d_id=deviceId,isfullId=1)
+                        if device_info_list:
+                            device_info = device_info_list[0]
+                            uptime = device_info["uptime"]
+                        else:
+                            uptime = "1970-01-01 00:00:00"
+                        time_diff_days = time_dif(uptime)
+                        if time_diff_days > 270:
+                            save_data["是否需要充值"].append("否")
+                            save_data["备注"].append("对应设备号:{}".format(deviceId))
+                        else:
+                            save_data["是否需要充值"].append("是")
+                            save_data["备注"].append("对应设备号:{}".format(deviceId))
+                    else:
+                        save_data["是否需要充值"].append("未知")
+                        save_data["备注"].append("未找到该卡记录,请确认是否未录入平台")
+                else:
+                    save_data["是否需要充值"].append("是")
+                    save_data["备注"].append("当月存在流量使用")
+        else:   # SIMboss
+            save_data = dict(ICCID=[],是否需要充值=[])
+            for index, sim in enumerate(file_dataframe["ICCID"]):
+                save_data["ICCID"].append(str(sim))
+                status = 0
+                for i in range(9):
+                    if float(file_dataframe["筛查月份{}".format(str(i+1))][index]) > 1:
+                        status = 1
+                        break
+                if status == 1:
+                    save_data["是否需要充值"].append("是")
+                else:
+                    save_data["是否需要充值"].append("否")
+
+        df = pd.DataFrame(data=save_data)
+        save_filename = str(uuid.uuid4())+".xlsx"
+        now_dir = os.path.dirname(__file__)
+        save_path = os.path.join(now_dir,"excel_folder",save_filename)
+        df.to_excel(save_path,index=False)
+        return Response(save_filename)

BIN
requirements.txt