OperatingCostsDataController.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UserDataController.py
  4. @Time : 2024年6月7日09:27:28
  5. @Author : peng
  6. @Email : peng
  7. @Software: PyCharm
  8. """
  9. from django.db.models import Q, Sum
  10. from django.views.generic.base import View
  11. import datetime
  12. import requests
  13. from Model.models import OperatingCosts, Order_Model, CountryModel, UID_Bucket
  14. from Service.CommonService import CommonService
  15. from Ansjer.config import CONFIG_EUR, CONFIG_INFO, CONFIG_CN, CONFIG_US
  16. from dateutil.relativedelta import relativedelta
  17. # 运营成本数据
  18. class OperatingCostsDataView(View):
  19. def get(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. operation = kwargs.get('operation')
  22. return self.validation(request.GET, request, operation)
  23. def post(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request.POST, request, operation)
  27. def validation(self, request_dict, request, operation):
  28. token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
  29. if token_code != 0:
  30. return response.json(token_code)
  31. if operation == 'getOperatingCosts': # 查询订单成本利润
  32. return self.get_operating_costs(request, request_dict, response)
  33. else:
  34. return response.json(414)
  35. @classmethod
  36. def get_operating_costs(cls, request, request_dict, response):
  37. """
  38. 查询订单成本利润
  39. @param request:请求参数
  40. @param request_dict:请求参数
  41. @request_dict startTime:开始时间
  42. @request_dict endTime:结束时间
  43. @param response:响应对象
  44. @return:
  45. """
  46. start_time = request_dict.get('startTime', None)
  47. end_time = request_dict.get('endTime', None)
  48. page = request_dict.get('page', 1)
  49. line = request_dict.get('line', 10)
  50. if not all([page, line]):
  51. return response.json(444, {'error param': 'page or line'})
  52. page = int(page)
  53. line = int(line)
  54. try:
  55. if start_time and end_time:
  56. operating_costs_qs = OperatingCosts.objects.filter(Q(time__gte=start_time), Q(time__lte=end_time))
  57. else:
  58. operating_costs_qs = OperatingCosts.objects.all()
  59. count = operating_costs_qs.count()
  60. order_list = list(operating_costs_qs.values_list('order_id', flat=True).order_by('-time'))[:page * line]
  61. operating_qs = operating_costs_qs.values('order_id', 'uid', 'day_average_price', 'month_average_price',
  62. 'purchase_quantity', 'actual_storage', 'actual_api',
  63. 'monthly_income', 'settlement_days', 'remaining_usage_time',
  64. 'end_time', 'created_time', 'start_time', 'time').order_by(
  65. '-time')[(page - 1) * line:page * line]
  66. all_order_qs = Order_Model.objects.filter(orderID__in=order_list)
  67. country_qs = CountryModel.objects.values('id', 'country_name')
  68. country_dict = {}
  69. for item in country_qs:
  70. country_dict[item['id']] = item['country_name']
  71. res = []
  72. storage_univalence = 0.023 / 30
  73. api_univalence = 0.005 / 1000
  74. for item in operating_qs:
  75. order_qs = all_order_qs.filter(orderID=item['order_id']).values('price', 'order_type', 'fee',
  76. 'userID__region_country',
  77. 'rank__expire', 'payType')
  78. if not order_qs.exists():
  79. continue
  80. country_name = country_dict.get(order_qs[0]['userID__region_country'], '未知国家')
  81. region = '国内' if CONFIG_INFO == CONFIG_CN else '国外'
  82. if order_qs[0]['order_type'] in [0, 1]:
  83. order_type = '云存'
  84. storage_cost = round(
  85. float(item['actual_storage']) / 1024 * storage_univalence * item['settlement_days'], 2)
  86. api_cost = round(int(item['actual_api']) * api_univalence, 2)
  87. if CONFIG_INFO == CONFIG_CN: # 国内要换算汇率
  88. storage_cost = storage_cost * 7
  89. api_cost = api_cost * 7
  90. if float(item['monthly_income']) == 0.0:
  91. profit = 0
  92. profit_margin = 0
  93. else:
  94. profit = round(float(item['monthly_income']) - storage_cost - api_cost, 2) # 利润=月结算金额-月成本
  95. profit_margin = round(profit / float(item['month_average_price']), 2) # 利润率=利润/每月收入分摊
  96. expire = str(order_qs[0]['rank__expire']) + '个月'
  97. else:
  98. order_type = '4G流量'
  99. storage_cost = 0
  100. api_cost = 0
  101. if order_qs[0]['payType'] in [2, 3]:
  102. fee = float(order_qs[0]['price']) * 0.0054
  103. else:
  104. fee = float(order_qs[0]['fee']) if order_qs[0]['fee'] else 0
  105. res.append({
  106. 'order_id': item['order_id'],
  107. 'uid': item['uid'],
  108. 'region': region,
  109. 'country_name': country_name,
  110. 'order_type': order_type,
  111. 'expire': expire,
  112. 'price': order_qs[0]['price'],
  113. 'fee': fee,
  114. 'real_income': round(float(order_qs[0]['price']) - fee, 2),
  115. 'day_average_price': item['day_average_price'],
  116. 'month_average_price': item['month_average_price'],
  117. 'purchase_quantity': item['purchase_quantity'],
  118. 'start_time': item['start_time'],
  119. 'end_time': item['end_time'],
  120. 'settlement_time': item['created_time'],
  121. 'settlement_days': item['settlement_days'],
  122. 'monthly_income': item['monthly_income'],
  123. 'remaining_usage_time': item['remaining_usage_time'],
  124. 'actual_storage': item['actual_storage'],
  125. 'actual_api': item['actual_api'],
  126. 'storage_cost': storage_cost,
  127. 'api_cost': api_cost,
  128. 'profit': profit,
  129. 'profit_margin': profit_margin,
  130. 'time': item['time']
  131. })
  132. return response.json(0, {'count': count,
  133. 'res': res})
  134. except Exception as e:
  135. print('error')
  136. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))