counts_views.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. from rest_framework.views import APIView
  2. from rest_framework.response import Response
  3. from smartfarming.models.ascend import MongoBase, MongoLandInfo, MongoPlantInfo, MongoAreaJob, LandPlanInfo, CountryModel, PlanWeekend
  4. from smartfarming.models.user import DeviceUser
  5. from smartfarming.models.device import MongoDevice
  6. from smartfarming.models.worm_forecast import MongoCBDphoto
  7. from smartfarming.serializers.ascend_serializers import (
  8. LandPlanInfoSerializers
  9. )
  10. from django.core.paginator import Paginator
  11. import time
  12. import datetime
  13. from django.db.models import Q, Sum, Count
  14. from django.conf import settings
  15. class LandPlanInfoAPIView(APIView):
  16. def post(self, request):
  17. # 种植采收列表及统计信息
  18. request_data = request.data
  19. plan = request_data.get("plan")
  20. year = request_data.get("year")
  21. page_num = int(request_data.get("pagenum")) if request_data.get("pagenum") else 1
  22. page_size = int(request_data.get("pagesize")) if request_data.get("pagesize") else 10
  23. start_timestamp, end_timestatmp = 0, 0
  24. if year:
  25. start_timestamp = datetime.datetime(int(year), 1,1,0,0).timestamp()
  26. end_timestatmp = datetime.datetime(int(year), 12,31,23,59).timestamp()
  27. plan_ids_head = []
  28. if plan :
  29. plan_ids_head = MongoPlantInfo.objects.filter(plantname__icontains=plan).values_list("id", flat=True)
  30. if plan_ids_head and year:
  31. queryset = LandPlanInfo.objects.filter(Q(plan_id__in = plan_ids_head) & Q(addtime__gte=start_timestamp, addtime__lte=end_timestatmp)).exclude(recovery_time=0).filter(is_delete=1).order_by("-addtime")
  32. elif year:
  33. queryset = LandPlanInfo.objects.filter(addtime__gte=start_timestamp, addtime__lte=end_timestatmp).filter(is_delete=1).exclude(recovery_time=0).order_by("-addtime")
  34. elif plan_ids_head:
  35. queryset = LandPlanInfo.objects.filter(plan_id__in = plan_ids_head).filter(is_delete=1).exclude(recovery_time=0).order_by("-addtime")
  36. else:
  37. queryset = LandPlanInfo.objects.filter(is_delete=1).exclude(recovery_time=0).order_by("-addtime")
  38. total_obj = queryset.count()
  39. paginator = Paginator(queryset, page_size)
  40. page_obj = paginator.get_page(page_num)
  41. serializers = LandPlanInfoSerializers(page_obj, many=True)
  42. # 折线图
  43. year_value = LandPlanInfo.objects.all().exclude(recovery_time=0).values_list("addtime", flat=True).order_by("-addtime")
  44. years = []
  45. for year in year_value:
  46. y = datetime.datetime.fromtimestamp(year).year
  47. if y not in years:
  48. years.append(y)
  49. years.reverse()
  50. # 获取最近5年的作物ID
  51. end = datetime.datetime(int(years[-1]) -5, 12,31,23,59).timestamp()
  52. start = datetime.datetime(int(years[-1]), 12,31,23,59).timestamp()
  53. plan_ids = LandPlanInfo.objects.filter(addtime__gte=end, addtime__lte=start).exclude(recovery_time=0).distinct().values_list("plan_id", flat=True).order_by("plan_id")
  54. counts = []
  55. # 组织具体数据
  56. for i in years:
  57. start_timestamp = datetime.datetime(i, 1,1,0,0).timestamp()
  58. end_timestatmp = datetime.datetime(i, 12,31,23,59).timestamp()
  59. plan_totals = LandPlanInfo.objects.filter(
  60. addtime__gte=start_timestamp,
  61. addtime__lte=end_timestatmp).exclude(recovery_time=0).values("plan_id").annotate(total=Sum("recovery_kg")).order_by("plan_id").values_list("plan_id", "total")
  62. inners = {}
  63. for k in plan_totals:
  64. inners[str(k[0])] = k[1]
  65. pid =[]
  66. for j in plan_ids:
  67. pid.append(inners.get(str(j), 0))
  68. counts.append(pid)
  69. transpose_matrix = [[row[i] for row in counts] for i in range(len(counts[0]))]
  70. plannames = []
  71. # 组织农作物
  72. for p in plan_ids:
  73. plan_obj = MongoPlantInfo.objects.filter(id=p)
  74. if plan_obj:
  75. planname = plan_obj.first().plantname +"-"+ plan_obj.first().planttype
  76. else:
  77. planname = ""
  78. plannames.append(planname)
  79. return Response({
  80. "code": 0,
  81. "msg": "success",
  82. "data": serializers.data,
  83. "count": total_obj,
  84. "charts": {
  85. "years": years,
  86. "data": transpose_matrix,
  87. "plan": plannames
  88. }
  89. })
  90. class PlanNameAPIView(APIView):
  91. def post(self, request):
  92. try:
  93. # 作物名字
  94. plan_ids = LandPlanInfo.objects.filter(is_delete=1).exclude(recovery_time=0).values_list("plan_id", flat=True).order_by("-addtime")
  95. plans = MongoPlantInfo.objects.filter(is_delete=1, id__in=plan_ids).values_list("plantname", flat=True).distinct()
  96. return Response({"code": 0, "msg": "success", "data": plans})
  97. except Exception as e:
  98. return Response({"code": 0, "msg": "success", "data": []})
  99. class PlanAreaAPIView(APIView):
  100. def post(self, request):
  101. # 种植面积与作物个数统计
  102. land_plan_ids = LandPlanInfo.objects.filter(status="采收").filter(recovery_kg=0).values("land_id", "plan_id")
  103. plan_land = []
  104. plans = []
  105. plan_area = 0
  106. for i in land_plan_ids:
  107. landarea = MongoLandInfo.objects.get(id=i.get("land_id")).landarea
  108. plant = MongoPlantInfo.objects.get(id=i.get("plan_id"))
  109. plantname = f"{plant.plantname}({plant.planttype})"
  110. plan_land.append(
  111. {
  112. "name": plantname,
  113. "value": round(float(landarea), 2)
  114. }
  115. )
  116. plans.append(plantname) if plantname not in plans else None
  117. plan_area += round(float(landarea), 2)
  118. return Response({"code": 0, "msg": "success", "data": {"lands_area": round(plan_area, 2), "plans_count": len(plans), "p_list": plan_land}})
  119. class DeviceCountAPIView(APIView):
  120. def post(self, request):
  121. # 统计设备在线或离线统计
  122. device_status = MongoDevice.objects.values("device_status").annotate(total=Count("id"))
  123. online = 0
  124. offline = 0
  125. for k in device_status:
  126. if k.get("device_status") == 1:
  127. online = k.get("total")
  128. if k.get("device_status") == 0:
  129. offline = k.get("total")
  130. # 设备分类
  131. device_type = MongoDevice.objects.values("device_type_id").annotate(total=Count("id"))
  132. config_dict = settings.CONFIG.get("device_type_zh")
  133. device_type = {config_dict.get(str(result["device_type_id"])): result["total"] for result in device_type}
  134. return Response({
  135. "code": 0,
  136. "msg": "success",
  137. "data": {
  138. "device_status": {"online": online, "offline": offline},
  139. "device_category": device_type
  140. }
  141. })
  142. class RecentPestCountAPIView(APIView):
  143. def post(self, request):
  144. # 统计最近一个月的害虫排名
  145. MongoCBDphoto