AgentOrderController.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : AgentOrderController.py
  4. @Time : 2024/3/14 10:53
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import threading
  10. import time
  11. from datetime import datetime, timedelta
  12. from decimal import Decimal, ROUND_DOWN
  13. from django.http import QueryDict
  14. from django.views import View
  15. from AgentModel.models import AgentDevice, AgentCloudServicePackage, AgentCustomerPackage, AgentDeviceOrder, \
  16. AgentDeviceOrderInstallment, AgentAccount
  17. from Ansjer.config import LOGGER
  18. from Model.models import Order_Model, Store_Meal, UnicomCombo
  19. from Object.ResponseObject import ResponseObject
  20. from Object.TokenObject import TokenObject
  21. from Service.CommonService import CommonService
  22. class AgentOrderView(View):
  23. def get(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request.GET, request, operation)
  27. def post(self, request, *args, **kwargs):
  28. request.encoding = 'utf-8'
  29. operation = kwargs.get('operation')
  30. return self.validation(request.POST, request, operation)
  31. def delete(self, request, *args, **kwargs):
  32. request.encoding = 'utf-8'
  33. operation = kwargs.get('operation')
  34. delete = QueryDict(request.body)
  35. if not delete:
  36. delete = request.GET
  37. return self.validation(delete, request, operation)
  38. def put(self, request, *args, **kwargs):
  39. request.encoding = 'utf-8'
  40. operation = kwargs.get('operation')
  41. put = QueryDict(request.body)
  42. return self.validation(put, request, operation)
  43. def validation(self, request_dict, request, operation):
  44. response = ResponseObject()
  45. tko = TokenObject(
  46. request.META.get('HTTP_AUTHORIZATION'),
  47. returntpye='pc')
  48. if operation == 'addOrder': # 添加代理商订单
  49. order_id = request_dict.get('order_id', None)
  50. uid = request_dict.get('uid', None)
  51. order_type = request_dict.get('order_type', None)
  52. package_id = request_dict.get('package_id', None)
  53. self.check_agent_service_package(order_id, uid, int(package_id))
  54. return response.json(0)
  55. @classmethod
  56. def check_agent_service_package(cls, order_id, uid, package_id):
  57. """
  58. 检查是否代理服务套餐
  59. @param package_id: 套餐id
  60. @param order_id: 订单ID
  61. @param uid: UID
  62. @return: True | False
  63. """
  64. try:
  65. serial_number = CommonService.get_serial_number_by_uid(uid)
  66. a_device_qs = AgentDevice.objects.filter(serial_number=serial_number) \
  67. .values('ac_id', 'type', 'status')
  68. LOGGER.info(f'******check_agent_service_package检查是否代理*****orderId:{order_id}')
  69. if not a_device_qs.exists():
  70. return False
  71. LOGGER.info(f'******check_agent_service_package当前设备属于代理商*****serial_number:{serial_number}')
  72. asy = threading.Thread(target=cls.save_agent_package,
  73. args=(order_id, serial_number, a_device_qs[0]['ac_id'], package_id))
  74. asy.start()
  75. return True
  76. except Exception as e:
  77. LOGGER.info('*****AgentOrderView.check_agent_service_package:errLine:{}, errMsg:{}'
  78. .format(e.__traceback__.tb_lineno, repr(e)))
  79. return False
  80. @classmethod
  81. def save_agent_package(cls, order_id, serial_number, ac_id, package_id):
  82. """
  83. 保存代理套餐
  84. """
  85. try:
  86. order_qs = Order_Model.objects.filter(orderID=order_id, status=1).values('price', 'payTime', 'order_type')
  87. if not order_qs.exists():
  88. LOGGER.info(f'******save_agent_package当前代理客户未添加此套餐******ac_id:{ac_id},package_id:{package_id}')
  89. return
  90. order_type = order_qs[0]['order_type']
  91. package_type = 2 if order_type in [2, 3, 5] else 1 # 判断订单信息是云存还是4G
  92. package_id = int(package_id)
  93. agent_package_qs = AgentCloudServicePackage.objects.filter(type=package_type, package_id=package_id,
  94. status=1)
  95. if not agent_package_qs.exists():
  96. LOGGER.info(f'******save_agent_package当前套餐未设置代理******order_id:{order_id},serial_number:{serial_number}')
  97. return
  98. agent_package = agent_package_qs.first() # 代理云服务套餐
  99. LOGGER.info(f'******save_agent_package代理套餐******service_name:{agent_package_qs.first().service_name}')
  100. acp_qs = AgentCustomerPackage.objects.filter(ac_id=ac_id, cs_id=agent_package.id).values('id')
  101. if not acp_qs.exists():
  102. LOGGER.info(f'******save_agent_package当前代理客户未添加此套餐******ac_id:{ac_id},package_id:{package_id}')
  103. return
  104. # 组装数据
  105. now_time = int(time.time())
  106. pay_price = Decimal(order_qs[0]['price']).quantize(Decimal('0.00'))
  107. profit = cls.calculate_order_profit(agent_package, pay_price)
  108. dict_data = {'ac_id': ac_id, 'serial_number': serial_number, 'csp_id': agent_package.id,
  109. 'order_id': order_id, 'status': 1, 'profit_amount': pay_price, 'profit': profit,
  110. 'pay_time': order_qs[0]['payTime'], 'created_time': now_time, 'updated_time': now_time}
  111. agent_order_obj = AgentDeviceOrder.objects.create(**dict_data)
  112. # 保存分期结算记录
  113. cls.save_order_installment(agent_order_obj.id, package_type, package_id, profit, ac_id)
  114. LOGGER.info(f'******save_agent_package代理订单存表结束:{dict_data}')
  115. except Exception as e:
  116. LOGGER.info('*****AgentOrderView.save_agent_package:errLine:{}, errMsg:{}'
  117. .format(e.__traceback__.tb_lineno, repr(e)))
  118. @classmethod
  119. def calculate_order_profit(cls, agent_package, price):
  120. """
  121. 计算利润
  122. @param agent_package: 套餐配置
  123. @param price: 支付价格
  124. @return: 利润
  125. """
  126. profit = 0
  127. price = Decimal(price).quantize(Decimal('0.00'))
  128. if agent_package.profit_type == 1:
  129. profit = agent_package.profit
  130. elif agent_package.profit_type == 2:
  131. profit_value = Decimal(agent_package.profit).quantize(Decimal('0.00'))
  132. cost = Decimal(agent_package.cost).quantize(Decimal('0.00'))
  133. profit = (price - cost) * (profit_value / 100)
  134. profit = profit.quantize(Decimal('0.00'))
  135. return profit
  136. @classmethod
  137. def get_settlement_interval(cls, package_type, package_id):
  138. try:
  139. if package_type == 1: # 云存
  140. store_qs = Store_Meal.objects.filter(id=package_id).values('day', 'bucket_id', 'expire',
  141. 'icloud_store_meal_id')
  142. if not store_qs.exists():
  143. return []
  144. # 根据套餐周期计算往后每个月26号作为结算时间
  145. return cls.get_future_timestamps(store_qs[0]['expire'])
  146. elif package_type == 2: # 4G
  147. combo4g_qs = UnicomCombo.objects.filter(id=package_id).values('expiration_days', 'expiration_type')
  148. if not combo4g_qs.exists():
  149. return []
  150. # 目前4G套餐都是基于按天类型创建
  151. if combo4g_qs[0]['expiration_type'] == 0 and combo4g_qs[0]['expiration_days'] > 0:
  152. months = int(combo4g_qs[0]['expiration_days'] / 30)
  153. # 根据套餐周期计算往后每个月26号作为结算时间
  154. return cls.get_future_timestamps(months)
  155. except Exception as e:
  156. LOGGER.info('*****AgentOrderView.get_settlement_interval:errLine:{}, errMsg:{}'
  157. .format(e.__traceback__.tb_lineno, repr(e)))
  158. return []
  159. @staticmethod
  160. def get_future_timestamps(months):
  161. """
  162. 生成未来若干个月的第一个月的26号11点的timestamp列表。
  163. 参数:
  164. months -- 未来需要生成timestamp的月份数量
  165. 返回值:
  166. timestamps -- 包含未来months个月第一个月的26号11点的timestamp的列表
  167. """
  168. current_time = datetime.now() # 获取当前时间,注意这会是系统当前时区的时间
  169. current_month = current_time.month
  170. current_year = current_time.year
  171. timestamps = []
  172. for _ in range(months):
  173. # 如果当前月已经是需要生成的月份,则年份和月份不变
  174. if current_month == 1 and _ == 0:
  175. next_year = current_year
  176. next_month = current_month + 1
  177. else:
  178. # 计算下一个月的年和月
  179. if current_month == 12:
  180. next_month = 1
  181. next_year = current_year + 1
  182. else:
  183. next_month = current_month + 1
  184. next_year = current_year
  185. # 生成下个月的26号11点的时间点
  186. next_date = datetime(next_year, next_month, 26, 11, 0, 0)
  187. # 如果生成的日期超过了当月的实际天数(比如2月没有26号),则需要回退到当月的最后一天
  188. last_day_of_month = (datetime(next_year, next_month, 1) + timedelta(days=31)).replace(day=1) - timedelta(
  189. days=1)
  190. if next_date > last_day_of_month:
  191. next_date = last_day_of_month.replace(hour=11, minute=0, second=0, microsecond=0)
  192. timestamps.append(int(next_date.timestamp()))
  193. # 更新当前月份和年份为下一次循环使用
  194. current_month = next_month
  195. current_year = next_year
  196. return timestamps
  197. @staticmethod
  198. def distribute_commission(commission, periods):
  199. # 转换佣金和期数为Decimal类型,并设置精度
  200. commission = Decimal(str(commission)).quantize(Decimal('0.01'))
  201. periods = Decimal(periods)
  202. # 每期基础金额(向下取整到最接近的0.01)
  203. base_amount = (commission / periods).quantize(Decimal('0.01'), rounding=ROUND_DOWN)
  204. # 初始化每期分配的金额列表
  205. distributed_amounts = [base_amount] * int(periods)
  206. # 计算按照基础金额分配后的总和
  207. total_distributed = sum(distributed_amounts)
  208. # 计算剩余需要分配的金额
  209. remainder = commission - total_distributed
  210. # 分配剩余金额
  211. if remainder > Decimal('0'):
  212. # 从第一期开始分配剩余金额
  213. for i in range(len(distributed_amounts)):
  214. if remainder >= Decimal('0.01'):
  215. distributed_amounts[i] += Decimal('0.01')
  216. remainder -= Decimal('0.01')
  217. else:
  218. # 如果剩余金额不足0.01,则将其全部加到当前期
  219. distributed_amounts[i] += remainder
  220. break
  221. return distributed_amounts
  222. @classmethod
  223. def save_order_installment(cls, agent_order_id, package_type, package_id, profit, ac_id=None):
  224. """
  225. 保存代理订单分期信息
  226. :param cls: 类方法的约定参数
  227. :param agent_order_id: 代理订单ID
  228. :param package_type: 套餐类型
  229. :param package_id: 套餐ID
  230. :param profit: 利润总额
  231. :return: 无返回值
  232. :param ac_id: 代理客户ID
  233. """
  234. try:
  235. # 根据包裹类型和ID获取结算时间间隔列表
  236. time_list = cls.get_settlement_interval(package_type, package_id)
  237. period_number = len(time_list) # 计算分期总数
  238. # 输入合理性检查
  239. if period_number == 0 or profit <= 0:
  240. LOGGER.info(f'Invalid input parameters: period_number={period_number}, profit={profit}')
  241. return
  242. n_time = int(datetime.now().timestamp()) # 获取当前时间戳
  243. # 利润总额按分期数平均分配
  244. amount_list = cls.distribute_commission(profit, period_number)
  245. installment_list = []
  246. # 遍历分期数,生成分期记录列表
  247. for time_point in range(period_number):
  248. installment_list.append(AgentDeviceOrderInstallment(ado_id=agent_order_id,
  249. period_number=period_number,
  250. ac_id=ac_id,
  251. amount=amount_list[time_point],
  252. due_date=time_list[time_point],
  253. status=1,
  254. created_time=n_time,
  255. updated_time=n_time))
  256. # 分批处理大量数据,避免数据库压力过大
  257. batch_size = 100
  258. for i in range(0, len(installment_list), batch_size):
  259. AgentDeviceOrderInstallment.objects.bulk_create(
  260. installment_list[i:i + batch_size]
  261. )
  262. # 记录创建完成的日志
  263. LOGGER.info(f'*****AgentOrderView.save_OrderInstallment分期结算记录创建完成:{len(installment_list)} records')
  264. except Exception as e:
  265. # 记录异常信息
  266. LOGGER.error('*****AgentOrderView.save_OrderInstallment:errLine:{}, errMsg:{}'
  267. .format(e.__traceback__.tb_lineno, repr(e)))
  268. @staticmethod
  269. def update_periodic_settlement():
  270. """
  271. 更新周期结算信息
  272. 返回值:
  273. - 无返回值
  274. """
  275. try:
  276. # 根据条件查询需要更新结算信息的订单分期记录
  277. adoi_qs = AgentDeviceOrderInstallment.objects.filter(status=1, due_date__lte=int(time.time()))
  278. if not adoi_qs:
  279. # 如果没有找到符合条件的记录,直接返回
  280. return
  281. ids = []
  282. a_account_list = []
  283. adoi_set = set()
  284. n_time = int(time.time())
  285. for item in adoi_qs:
  286. # 准备分期记录的id列表和账户记录列表
  287. ids.append(item.id)
  288. adoi_set.add(item.ado_id)
  289. a_account_list.append(AgentAccount(ac_id=item.ac_id, amount=item.amount,
  290. remark=f'周期结算',
  291. status=1, created_time=n_time,
  292. updated_time=n_time))
  293. batch_size = 100
  294. # 分批更新分期记录状态
  295. for i in range(0, len(ids), batch_size):
  296. AgentDeviceOrderInstallment.objects.filter(id__in=ids[i:i + batch_size]) \
  297. .update(status=2, settlement_time=n_time, updated_time=n_time)
  298. # 分批创建账户记录
  299. for i in range(0, len(a_account_list), batch_size):
  300. AgentAccount.objects.bulk_create(a_account_list[i:i + batch_size])
  301. # 检查是否所有分期都已结算,如果是,则更新订单状态为已结算
  302. for ado in adoi_set:
  303. adoi_qs = AgentDeviceOrderInstallment.objects.filter(ado_id=ado, status=1)
  304. if not adoi_qs.exists():
  305. AgentDeviceOrder.objects.filter(id=ado, status=1) \
  306. .update(status=2, settlement_time=n_time, updated_time=n_time)
  307. except Exception as e:
  308. # 记录异常信息
  309. LOGGER.error(
  310. f'*****AgentOrderView.update_periodic_settlement:errLine:{e.__traceback__.tb_lineno}, errMsg:{str(e)}')