AgentOrderController.py 17 KB

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