Browse Source

获取端口状态及时更新

zjl 1 year ago
parent
commit
ccf7e4ae75
4 changed files with 129 additions and 242 deletions
  1. 7 2
      apps/web/core/adapter/weifule_policy.py
  2. 14 52
      apps/web/dealer/views.py
  3. 27 188
      apps/web/device/views.py
  4. 81 0
      script/修复分账.py

+ 7 - 2
apps/web/core/adapter/weifule_policy.py

@@ -180,11 +180,16 @@ class POLICYBox(PolicyBase):
                 statusDict[str(ii + 1)] = {'status': Const.DEV_WORK_STATUS_IDLE}
 
         allPorts, usedPorts, usePorts = self.get_port_static_info(statusDict)
-        Device.update_dev_control_cache(self._device['devNo'],
-                                        {'allPorts': allPorts, 'usedPorts': usedPorts, 'usePorts': usePorts})
+        Device.update_dev_control_cache(
+            self._device['devNo'],
+            {'allPorts': allPorts, 'usedPorts': usedPorts, 'usePorts': usePorts}
+        )
 
         return statusDict
 
+    def dealer_get_port_status(self):
+        return self.get_port_status(True)
+
     def active_deactive_port(self, port, active):
         if active:
             raise ServiceException({'result': 2, 'description': u'该设备不支持直接打开端口'})

+ 14 - 52
apps/web/dealer/views.py

@@ -11042,56 +11042,21 @@ def deleteAddress(request):
 
 @error_tolerate(nil=DefaultJsonErrorResponse)
 @permission_required(ROLE.dealer, ROLE.subaccount)
-def getDevicePort(request):
-    # type: (WSGIRequest)->JsonResponse
-
-    def cmp_by_port(x, y):
-        if str(x['index']).isdigit() and str(y['index']).isdigit():
-            if int(x['index']) < int(y['index']):
-                return -1
-            elif int(x['index']) > int(y['index']):
-                return 1
-            return 0
-        else:
-            if x['index'] < y['index']:
-                return -1
-            elif x['index'] > y['index']:
-                return 1
-            return 0
-
-    def charge_pay_coin_unit(p, u):
-        """
-        给端口信息中的付费添加上单位
-        :param p:
-        :param u:
-        :return:
-        """
-        _coins = p.get("coins")
-        if not _coins:
-            return
-        p.update({"coins": "{}{}".format(_coins, u)})
+def getDevicePort(request):     # type: (WSGIRequest)->JsonResponse
 
     currentDealer = request.user
-
     dev = Device.get_dev_by_logicalCode(request.GET.get('logicalCode'))  # type: DeviceDict
 
-    group = dev.group  # type: GroupDict
-
-    if str(currentDealer.id) == group['ownerId']:
+    if str(currentDealer.id) == dev.ownerId:
         isManager = True
     else:
         isManager = False
 
     smartBox = dev.deviceAdapter
 
-    if hasattr(smartBox, 'dealer_get_device_port'):
-        portList = getattr(smartBox, 'dealer_get_device_port')()
-        return JsonResponse({"result": 1, "description": "", "payload": {"portList": portList}})
-
     try:
         # 先从设备上取信息,然后从缓存中取信息
         portDict = smartBox.dealer_get_port_status()
-        smartBox.async_update_portinfo_from_dev()
     except ServiceException as e:
         logger.exception(e)
         return JsonResponse({'result': 0, 'description': e.result.get('description'), 'payload': None})
@@ -11100,9 +11065,6 @@ def getDevicePort(request):
         return JsonResponse({"result": 0, "description": u"从设备上获取端口信息失败,请您重试", "payload": {}})
 
     portList = []
-
-    unit = smartBox.show_pay_unit
-
     statsMap = {
         str(Const.DEV_WORK_STATUS_IDLE): 'idle',
         str(Const.DEV_WORK_STATUS_WORKING): 'busy',
@@ -11121,35 +11083,35 @@ def getDevicePort(request):
             portList.append({'index': str(port), 'status': statsMap.get(str(vStatus), "idle")})
 
     busyPortInfoDict = smartBox.get_many_port_info(busyPortList)
-
     if busyPortInfoDict:
         for _info in busyPortInfoDict.values():
-            if 'status' in _info and _info['status'] == Const.DEV_WORK_STATUS_WORKING:
+            if _info['status'] == Const.DEV_WORK_STATUS_WORKING:
                 _info.update({'status': statsMap[str(_info['status'])]})
                 if 'needTime' in _info and str(_info['needTime']).isdigit():
-                    _info.update({'needTime': u'%s分钟' % _info['needTime']})
+                    info.update({'needTime': u'%s分钟' % _info['needTime']})
             else:
                 _info = {'status': 'idle', 'index': str(_info['index'])}
             portList.append(_info)
     else:
         ctrInfo = Device.get_dev_control_cache(dev.devNo)
-
         for port, valueDict in portDict.items():
             vStatus = valueDict.get('status', None)
             if vStatus == Const.DEV_WORK_STATUS_WORKING:
-                portDetail = smartBox.get_port_using_detail(port, ctrInfo)
+                portDetail = dev.deviceAdapter.get_port_using_detail(port, ctrInfo)
                 portDetail.update({"index": str(port), "status": 'busy'})
                 portList.append(portDetail)
 
-    portList.sort(key=lambda _port: int(_port['index']) if isinstance(_port['index'], str) and _port["index"].isdigit() else _port['index'])
-    map(charge_pay_coin_unit, portList, [unit for x in xrange(len(portList))])
+    # 排序
+    portList.sort(key=lambda x: int(x['index']) if isinstance(x['index'], str) and x["index"].isdigit() else x['index'])
 
-    if dev.support_power_graph and (
-            'showPG_in_port_detail' in dev.owner.features or dev.driverCode in [Const.DEVICE_TYPE_CODE_WEIFULE_ANJIAN]):
-        for item in portList:
-            item['showPG'] = True
+    # 添加单位以及功率曲线
+    showPG = dev.support_power_graph and 'showPG_in_port_detail' in dev.owner.features
+    unit = dev.deviceAdapter.show_pay_unit
+    for item in portList:
+        item['showPG'] = showPG
+        if 'coins' in item.keys():
+            item["coins"] = "{} {}".format(item['coins'], unit)
 
-    portList.sort(cmp=cmp_by_port)
     return JsonOkResponse(payload={"isManager": isManager, "portList": portList})
 
 

+ 27 - 188
apps/web/device/views.py

@@ -1898,96 +1898,16 @@ def saveLiveConfig(request):
 
     return JsonResponse({"result": 1, "description": ""})
 
-@error_tolerate(logger = logger, nil = JsonErrorResponse(u'操作失败'))
-@permission_required(ROLE.manager)
-def getDevicePort(request):
-    # type: (WSGIRequest)->JsonResponse
 
-    def cmp_by_port(x, y):
-        if (str(x['index']).isdigit() and str(y['index']).isdigit()):
-            if int(x['index']) < int(y['index']):
-                return -1
-            elif int(x['index']) > int(y['index']):
-                return 1
-            return 0
-        else:
-            if x['index'] < y['index']:
-                return -1
-            elif x['index'] > y['index']:
-                return 1
-            return 0
-
-    def charge_pay_coin_unit(p, u):
-        """
-        给端口信息中的付费添加上单位
-        :param p:
-        :param u:
-        :return:
-        """
-        _coins = p.get("coins")
-        if not _coins:
-            return
-        p.update({"coins": "{}{}".format(_coins, u)})
-
-    currentDealer = request.user
+@error_tolerate(logger=logger, nil=JsonErrorResponse(u'操作失败'))
+@permission_required(ROLE.manager)
+def getDevicePort(request):     # type: (WSGIRequest)->JsonResponse
 
     dev = Device.get_dev_by_logicalCode(request.GET.get('logicalCode'))  # type: DeviceDict
 
-    group = dev.group # type: GroupDict
-
-    devTypeCode = dev.devType['code']
-
-    smartBox  = dev.deviceAdapter
-
-    if hasattr(smartBox, 'dealer_get_device_port'):
-        portList = getattr(smartBox, 'dealer_get_device_port')()
-        return JsonResponse({"result": 1, "description": "", "payload": {"portList": portList}})
-
-    if devTypeCode in [Const.DEVICE_TYPE_CODE_GEZIGUI_485,
-                       Const.DEVICE_TYPE_CODE_CHARGE_ZHONGSHAN,Const.DEVICE_TYPE_CODE_CHARGE_WEIFULE_CAR,
-                       Const.DEVICE_TYPE_CODE_CAR_WEIFULE_CHARGING_DOUB,
-                       Const.DEVICE_TYPE_CODE_CAR_WEIFULE_21KW,
-                       Const.DEVICE_TYPE_CODE_CAR_WEIFILE_HOME_JFPG,
-                       Const.DEVICE_TYPE_CODE_CAR_WEIFILE_HOME_DOUB_JFPG,
-                       Const.DEVICE_TYPE_CODE_CHARGE_ZHONGSHAN_BILLASSERVICE]:
-        portList = smartBox.get_port_status_from_dev()
-        return JsonResponse({"result": 1, "description": "", "payload": {"portList": portList}})
-
-
-    if devTypeCode == Const.DEVICE_TYPE_CODE_WATER_DISPENSER:
-        ctrInfo = Device.get_dev_control_cache(dev.devNo)
-
-        if ctrInfo is None or ('1' not in ctrInfo and '2' not in ctrInfo):
-            portList = {}
-        else:
-            statusDict = {}
-            statusInfoDict = {}
-            for _ in range(1, 3):
-                tempPort = str(_)
-                if ctrInfo[tempPort].get('status', 0) == 0:
-                    statusDict[tempPort] = 'idle'
-                    statusInfoDict[tempPort] = ctrInfo[tempPort].get('statusErrorInfo', u'无')
-                elif ctrInfo[tempPort].get('status', 0) == 1:
-                    statusDict[tempPort] = 'busy'
-                    statusInfoDict[tempPort] = ctrInfo[tempPort].get('statusErrorInfo', u'无')
-                elif ctrInfo[tempPort].get('status', 0) == 3:
-                    statusDict[tempPort] = 'fault'
-                    statusInfoDict[tempPort] = ctrInfo[tempPort].get('statusErrorInfo', u'无')
-                else:
-                    statusDict[tempPort] = 'fault'
-                    statusInfoDict[tempPort] = ctrInfo[tempPort].get('statusErrorInfo', u'无')
-
-            portList = [
-                {'index': '1', 'status': statusDict['1'], 'statusErrorInfo': statusInfoDict.get('1', u'无')},
-                {'index': '2', 'status': statusDict['2'], 'statusErrorInfo': statusInfoDict.get('2', u'无')}
-            ]
-
-        return JsonResponse({"result": 1, "description": "", "payload": {"portList": portList}})
-
     try:
         # 先从设备上取信息,然后从缓存中取信息
-        portDict = smartBox.dealer_get_port_status()
-        smartBox.async_update_portinfo_from_dev()
+        portDict = dev.deviceAdapter.dealer_get_port_status()
     except ServiceException as e:
         logger.exception(e)
         return JsonResponse({'result': 0, 'description': e.result.get('description'), 'payload': None})
@@ -1997,71 +1917,14 @@ def getDevicePort(request):
 
     portList = []
 
-    unit = smartBox.show_pay_unit
-
-    statsMap = {str(Const.DEV_WORK_STATUS_IDLE): 'idle',
-                str(Const.DEV_WORK_STATUS_WORKING): 'busy',
-                str(Const.DEV_WORK_STATUS_FAULT): 'fault',
-                str(Const.DEV_WORK_STATUS_FORBIDDEN): 'ban',
-                str(Const.DEV_WORK_STATUS_CONNECTED): 'connected',
-                str(Const.DEV_WORK_STATUS_FINISHED): 'finished'}
-
-    # TODO zjl get_port_using_detail 这块太复杂 后续一定要整改!!! 目前先做if分支处理
-    if devTypeCode in [Const.DEVICE_TYPE_CODE_CHARGING_AQKJ, Const.DEVICE_TYPE_CODE_CHARGING_AQKJ_NEW]:
-        elecInfo = smartBox._query_elec()
-        for port, valueDict in portDict.items():
-            voltage = "{:.2f}".format(float(valueDict.get("voltage", "0")))
-            batteryImei = valueDict.get("batteryImei", "")
-            doorStatus = valueDict.get("doorStatus")
-            doorStatus = smartBox.translate_door_status_to_unicode(doorStatus)
-            tempStatus = statsMap.get(str(valueDict.get("status")))
-            elecPoint = valueDict.get("elec")
-
-            tempDict = {
-                "index": port,
-                "status": tempStatus,
-                "doorStatus": doorStatus,
-                "voltage": voltage,
-                "batteryImei": batteryImei if batteryImei else u"无电池",
-                "elecPoint": elecPoint
-            }
-            tempDict.update(elecInfo.get(port))
-            portList.append(tempDict)
-
-        portList.sort(cmp=cmp_by_port)
-        return JsonResponse({"result": 1, "description": "", "payload": {"portList": portList}})
-
-    if devTypeCode in [Const.DEVICE_TYPE_CODE_CABINET_NEW]:
-        doorStatus = smartBox._get_door_status()
-        for port, valueDict in portDict.items():
-            voltage = "{:.2f}".format(float(valueDict.get("voltage", "0")))
-
-            tempDict = {
-                "index": port,
-                "status": valueDict["status"],
-                "doorStatus": doorStatus.get(port, u"未知"),
-            }
-
-            valueDict.update(tempDict)
-            portList.append(valueDict)
-
-        portList.sort(
-            key=lambda x: int(x['index']) if isinstance(x['index'], str) and x["index"].isdigit() else x['index'])
-        return JsonResponse({"result": 1, "description": "", "payload": {"portList": portList}})
-
-    if devTypeCode in [Const.DEVICE_TYPE_CODE_CABINET]:
-        for port, valueDict in portDict.items():
-            tempStatus = statsMap.get(str(valueDict.get("status")))
-
-            tempDict = {
-                "index": port,
-                "status": tempStatus,
-            }
-            valueDict.update(tempDict)
-            portList.append(valueDict)
-
-        portList.sort(cmp=cmp_by_port)
-        return JsonResponse({"result": 1, "description": "", "payload": {"portList": portList}})
+    statsMap = {
+        str(Const.DEV_WORK_STATUS_IDLE): 'idle',
+        str(Const.DEV_WORK_STATUS_WORKING): 'busy',
+        str(Const.DEV_WORK_STATUS_FAULT): 'fault',
+        str(Const.DEV_WORK_STATUS_FORBIDDEN): 'ban',
+        str(Const.DEV_WORK_STATUS_CONNECTED): 'connected',
+        str(Const.DEV_WORK_STATUS_FINISHED): 'finished'
+    }
 
     busyPortList = []
     for port, valueDict in portDict.items():
@@ -2071,63 +1934,39 @@ def getDevicePort(request):
         else:
             portList.append({'index': str(port), 'status': statsMap.get(str(vStatus), "idle")})
 
-    busyPortInfoDict = smartBox.get_many_port_info(busyPortList)
-
-    if devTypeCode in [Const.DEVICE_TYPE_CODE_CHARGING_HAINIAO_DOUBLE]:
-        ctrInfo = Device.get_dev_control_cache(dev.devNo)
-        for port, valueDict in portDict.items():
-            vStatus = valueDict.get('status', None)
-            if vStatus == Const.DEV_WORK_STATUS_WORKING:
-                portDetail = smartBox.get_port_using_detail(port, ctrInfo)
-                if portDetail.get('timeUnit',None)==u'秒':
-                    portDetail.update({'needTime':str(portDetail['needTime'][:-2])+'秒'})
-                portDetail.update({"index": str(port), "status": 'busy'})
-                portList.append(portDetail)
-        portList.sort(
-            key=lambda x: int(x['index']) if isinstance(x['index'], str) and x["index"].isdigit() else x['index'])
-        map(charge_pay_coin_unit, portList, [unit for x in xrange(len(portList))])
-        for _ in portList:
-            if 'elec' in _:
-                _.pop('elec')
-        portList.sort(cmp=cmp_by_port)
-        return JsonOkResponse(payload={"isManager": False, "portList": portList})
+    busyPortInfoDict = dev.deviceAdapter.get_many_port_info(busyPortList)
 
     if busyPortInfoDict:
         for info in busyPortInfoDict.values():
             if info['status'] == Const.DEV_WORK_STATUS_WORKING:
-                info.update({'status':statsMap[str(info['status'])]})
-                if info.has_key('needTime') and str(info['needTime']).isdigit():
-                    info.update({'needTime':u'%s分钟' % info['needTime']})
+                info.update({'status': statsMap[str(info['status'])]})
+                if 'needTime' in info and str(info['needTime']).isdigit():
+                    info.update({'needTime': u'%s分钟' % info['needTime']})
             else:
-                info = {'status':'idle','index':str(info['index'])}
+                info = {'status': 'idle', 'index': str(info['index'])}
             portList.append(info)
     else:
         ctrInfo = Device.get_dev_control_cache(dev.devNo)
-
         for port, valueDict in portDict.items():
             vStatus = valueDict.get('status', None)
             if vStatus == Const.DEV_WORK_STATUS_WORKING:
-                portDetail = smartBox.get_port_using_detail(port, ctrInfo)
+                portDetail = dev.deviceAdapter.get_port_using_detail(port, ctrInfo)
                 portDetail.update({"index": str(port), "status": 'busy'})
                 portList.append(portDetail)
-
+    # 排序
     portList.sort(key=lambda x: int(x['index']) if isinstance(x['index'], str) and x["index"].isdigit() else x['index'])
-    map(charge_pay_coin_unit, portList, [unit for x in xrange(len(portList))])
 
-    # todo 删掉已充电量, 只保留订购电量 (微付乐的板子需要电量,不能去掉。按道理,这个是业务自己不返回elec,不能放在公共代码这里改)
-    if devTypeCode not in [Const.DEVICE_TYPE_CODE_CHANGING_WEIFULE, Const.DEVICE_TYPE_CODE_CHANGING_WEIFULE2,Const.DEVICE_TYPE_CODE_CHANGING_DIANCHUANCARCHARGING]:
-        for _ in portList:
-            if 'elec' in _:
-                _.pop('elec')
+    # 添加单位以及功率曲线
+    showPG = dev.support_power_graph and 'showPG_in_port_detail' in dev.owner.features
+    unit = dev.deviceAdapter.show_pay_unit
+    for item in portList:
+        item['showPG'] = showPG
+        if 'coins' in item.keys():
+            item["coins"] = "{} {}".format(item['coins'], unit)
 
-    if dev.support_power_graph and (
-            'showPG_in_port_detail' in dev.owner.features or dev.driverCode in [Const.DEVICE_TYPE_CODE_WEIFULE_ANJIAN]):
-        for item in portList:
-            item['showPG'] = True
-
-    portList.sort(cmp=cmp_by_port)
     return JsonOkResponse(payload={"isManager": False, "portList": portList})
 
+
 @permission_required(ROLE.manager)
 @error_tolerate(logger=logger, nil=JsonErrorResponse(u'系统错误,请稍后再试'))
 def getAlarmList(request):

+ 81 - 0
script/修复分账.py

@@ -0,0 +1,81 @@
+# coding=utf-8
+from apps.web.user.models import ConsumeRecord
+from apps.web.dealer.proxy import DealerGroupStats
+
+
+def get_orders():
+    import datetime
+    from apps.web.dealer.proxy import DealerGroupStats
+    from apps.web.user.models import ConsumeRecord
+
+    r_orders = list()
+    r_states = set()
+
+    orders = ConsumeRecord.objects.filter(
+        status="finished"
+    )
+
+    for order in orders:    # type: ConsumeRecord
+        if order.finishedTime:
+            continue
+
+        endTime = order.service.deviceEndTime
+        finishedTime = datetime.datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
+
+        date = datetime.datetime(
+            finishedTime.year,
+            finishedTime.month,
+            finishedTime.day
+        )
+        state = DealerGroupStats.update_group_stats(
+            group=order.group,
+            order=order,
+            date=date
+        )       # type: DealerGroupStats
+        if state:
+            order.link_state(state)
+            order.description = "REPAIRED"
+            order.finishedTime = finishedTime
+            order.save()
+
+            r_orders.append("{}\n".format(order.orderNo))
+            r_states.add("{}\n".format(str(state.id)))
+
+            print "success order = {}".format(order.orderNo)
+        else:
+            print "error order = {}".format(order.orderNo)
+
+    with open("r_orders.txt", "w") as f1:
+        f1.writelines(r_orders)
+
+    with open("r_states.txt", "w") as f2:
+        f2.writelines(r_states)
+
+
+def get_states():
+    from apps.web.dealer.proxy import DealerGroupStats
+    from apps.web.report.ledger import LedgerConsumeOrder
+
+    orders = ConsumeRecord.objects.filter(
+        description="REPAIRED"
+    )
+
+    states = set()
+    for order in orders:
+        states.add(str(order.dailyStats.id))
+
+    for stateId in states:
+        state = DealerGroupStats.objects.get(id=stateId)    # type: DealerGroupStats
+
+        if state.date == "2023-08-03":
+            continue
+
+        if state.is_ledgered:
+            print(stateId)
+
+        else:
+            LedgerConsumeOrder(state).execute()
+
+
+
+