AgentOrderController.py 17 KB

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