AgentOrderController.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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.RedisObject import RedisObject
  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. if operation == 'settlementOrder': # 季度结算
  47. self.update_periodic_settlement()
  48. return response.json(0)
  49. tko = TokenObject(
  50. request.META.get('HTTP_AUTHORIZATION'),
  51. returntpye='pc')
  52. if operation == 'addOrder': # 添加代理商订单
  53. order_id = request_dict.get('order_id', None)
  54. uid = request_dict.get('uid', None)
  55. order_type = request_dict.get('order_type', None)
  56. package_id = request_dict.get('package_id', None)
  57. self.check_agent_service_package(order_id, uid, int(package_id))
  58. return response.json(0)
  59. else:
  60. return response.json(414)
  61. @classmethod
  62. def check_agent_service_package(cls, order_id, uid, package_id):
  63. """
  64. 检查是否代理服务套餐
  65. @param package_id: 套餐id
  66. @param order_id: 订单ID
  67. @param uid: UID
  68. @return: True | False
  69. """
  70. try:
  71. serial_number = CommonService.get_serial_number_by_uid(uid)
  72. a_device_qs = AgentDevice.objects.filter(serial_number=serial_number) \
  73. .values('ac_id', 'type', 'status')
  74. LOGGER.info(f'检查当前订单是否绑定代理*****orderID:{order_id},serialNumber:{serial_number}')
  75. if not a_device_qs.exists():
  76. return False
  77. LOGGER.info(f'当前设备属于代理商orderID:{order_id},serialNumber:{serial_number}')
  78. asy = threading.Thread(target=cls.save_agent_package,
  79. args=(order_id, serial_number, a_device_qs[0]['ac_id'], package_id))
  80. asy.start()
  81. return True
  82. except Exception as e:
  83. LOGGER.error('*****支付成功保存云服务代理订单异常orderID:{},errLine:{}, errMsg:{}'
  84. .format(order_id, e.__traceback__.tb_lineno, repr(e)))
  85. return False
  86. @classmethod
  87. def save_agent_package(cls, order_id, serial_number, ac_id, package_id):
  88. """
  89. 保存代理套餐
  90. """
  91. try:
  92. order_qs = Order_Model.objects.filter(orderID=order_id, status=1).values('price', 'payTime', 'order_type')
  93. if not order_qs.exists():
  94. LOGGER.info(
  95. f'******save_agent_package当前代理客户未添加此套餐******ac_id:{ac_id},package_id:{package_id}')
  96. return
  97. order_type = order_qs[0]['order_type']
  98. package_type = 2 if order_type in [2, 3, 5] else 1 # 判断订单信息是云存还是4G
  99. package_id = int(package_id)
  100. agent_package_qs = AgentCloudServicePackage.objects.filter(type=package_type, package_id=package_id,
  101. status=1)
  102. if not agent_package_qs.exists():
  103. LOGGER.info(
  104. f'******save_agent_package当前套餐未设置代理******order_id:{order_id},serial_number:{serial_number}')
  105. return
  106. agent_package = agent_package_qs.first() # 代理云服务套餐
  107. LOGGER.info(f'******save_agent_package代理套餐******service_name:{agent_package_qs.first().service_name}')
  108. acp_qs = AgentCustomerPackage.objects.filter(ac_id=ac_id, cs_id=agent_package.id).values('id')
  109. if not acp_qs.exists():
  110. LOGGER.info(
  111. f'******save_agent_package当前代理客户未添加此套餐******ac_id:{ac_id},package_id:{package_id}')
  112. return
  113. # 组装数据
  114. now_time = int(time.time())
  115. pay_price = Decimal(order_qs[0]['price']).quantize(Decimal('0.00'))
  116. profit = cls.calculate_order_profit(agent_package, pay_price)
  117. dict_data = {'ac_id': ac_id, 'serial_number': serial_number, 'csp_id': agent_package.id,
  118. 'order_id': order_id, 'status': 1, 'profit_amount': pay_price, 'profit': profit,
  119. 'pay_time': order_qs[0]['payTime'], 'created_time': now_time, 'updated_time': now_time}
  120. agent_order_obj = AgentDeviceOrder.objects.create(**dict_data)
  121. # 保存分期结算记录
  122. cls.save_order_installment(agent_order_obj.id, package_type, package_id, profit, ac_id,
  123. order_qs[0]['payTime'])
  124. LOGGER.info(f'******save_agent_package代理订单存表结束:{dict_data}')
  125. except Exception as e:
  126. LOGGER.info('*****AgentOrderView.save_agent_package:errLine:{}, errMsg:{}'
  127. .format(e.__traceback__.tb_lineno, repr(e)))
  128. @classmethod
  129. def calculate_order_profit(cls, agent_package, price):
  130. """
  131. 计算利润
  132. @param agent_package: 套餐配置
  133. @param price: 支付价格
  134. @return: 利润
  135. """
  136. profit = 0
  137. price = Decimal(price).quantize(Decimal('0.00'))
  138. if agent_package.profit_type == 1:
  139. profit = agent_package.profit
  140. elif agent_package.profit_type == 2:
  141. profit_value = Decimal(agent_package.profit).quantize(Decimal('0.00'))
  142. cost = Decimal(agent_package.cost).quantize(Decimal('0.00'))
  143. profit = (price - cost) * (profit_value / 100)
  144. profit = profit.quantize(Decimal('0.00'))
  145. return profit
  146. @classmethod
  147. def get_quarterly_settlement_dates(cls, start_date, months):
  148. """
  149. 获取季度结算日期列表,按照以下规则:
  150. 1. 固定在四个季度结算日期(1月1日、4月1日、7月1日、10月1日)进行结算
  151. 2. 从购买时间到结算日不满1个月的不在当前季度结算,累积到下一个季度
  152. 3. 中间季度每季度计算3个月
  153. 4. 最后一个季度计算剩余的时间
  154. :param start_date: 套餐开始日期(datetime)
  155. :param months: 套餐总月数
  156. :return: 包含(结算日期timestamp, 该季度使用月数)的元组列表
  157. """
  158. # 固定的季度结算日期
  159. QUARTER_DATES = [(1, 1), (4, 1), (7, 1), (10, 1)] # (月, 日)
  160. # 计算套餐结束日期
  161. end_date = start_date + timedelta(days=int(months * 30.5))
  162. # 初始化结果列表
  163. result = []
  164. # 找到开始日期后的第一个季度结算日
  165. current_year = start_date.year
  166. current_quarter_idx = 0
  167. # 找到开始日期之后的第一个季度结算日
  168. for i, (month, day) in enumerate(QUARTER_DATES):
  169. quarter_date = datetime(current_year, month, day)
  170. if quarter_date > start_date:
  171. current_quarter_idx = i
  172. break
  173. else:
  174. # 如果当年没有更多季度结算日,则移到下一年的第一个季度结算日
  175. current_year += 1
  176. current_quarter_idx = 0
  177. # 第一个季度的结算日期
  178. month, day = QUARTER_DATES[current_quarter_idx]
  179. first_settlement_date = datetime(current_year, month, day)
  180. # 计算第一个季度的整月数
  181. days_in_first_quarter = (first_settlement_date - start_date).days
  182. whole_months_first_quarter = int(days_in_first_quarter / 30.5)
  183. # 计算剩余的月数(总月数减去第一个季度的整月数,如果第一个季度有整月数)
  184. remaining_months = months
  185. # 如果第一个季度有整月数,则添加第一个季度的结算记录并减去已结算的月数
  186. if whole_months_first_quarter >= 1:
  187. result.append((int(first_settlement_date.timestamp()), whole_months_first_quarter))
  188. remaining_months -= whole_months_first_quarter
  189. else:
  190. # 即使不足1个月,也添加第一个季度的结算记录,但月数为0
  191. # 这样可以确保在7月1日进行第一次结算
  192. result.append((int(first_settlement_date.timestamp()), 0))
  193. # 如果没有剩余月数,直接返回结果
  194. if remaining_months <= 0:
  195. return result
  196. # 特殊处理年套餐(12个月)的情况
  197. if months == 12 and whole_months_first_quarter == 0:
  198. # 确保总共有5次季度结算,最后一次是剩余的月数
  199. # 第一次结算已经添加(7月1日,整月数为0)
  200. # 添加第二次结算(10月1日,整月数为3)
  201. current_quarter_idx = (current_quarter_idx + 1) % len(QUARTER_DATES)
  202. if current_quarter_idx == 0:
  203. current_year += 1
  204. month, day = QUARTER_DATES[current_quarter_idx]
  205. settlement_date = datetime(current_year, month, day)
  206. result.append((int(settlement_date.timestamp()), 3))
  207. # 添加第三次结算(1月1日,整月数为3)
  208. current_quarter_idx = (current_quarter_idx + 1) % len(QUARTER_DATES)
  209. if current_quarter_idx == 0:
  210. current_year += 1
  211. month, day = QUARTER_DATES[current_quarter_idx]
  212. settlement_date = datetime(current_year, month, day)
  213. result.append((int(settlement_date.timestamp()), 3))
  214. # 添加第四次结算(4月1日,整月数为3)
  215. current_quarter_idx = (current_quarter_idx + 1) % len(QUARTER_DATES)
  216. if current_quarter_idx == 0:
  217. current_year += 1
  218. month, day = QUARTER_DATES[current_quarter_idx]
  219. settlement_date = datetime(current_year, month, day)
  220. result.append((int(settlement_date.timestamp()), 3))
  221. # 添加第五次结算(7月1日,整月数为剩余的月数)
  222. current_quarter_idx = (current_quarter_idx + 1) % len(QUARTER_DATES)
  223. if current_quarter_idx == 0:
  224. current_year += 1
  225. month, day = QUARTER_DATES[current_quarter_idx]
  226. settlement_date = datetime(current_year, month, day)
  227. # 剩余的月数为12减去前面已经结算的月数
  228. remaining = 12 - (0 + 3 + 3 + 3)
  229. result.append((int(settlement_date.timestamp()), remaining))
  230. return result
  231. # 非年套餐的处理逻辑
  232. # 计算完整季度的数量(每季度3个月)
  233. full_quarters = int(remaining_months / 3)
  234. # 计算最后一个季度的剩余月数
  235. last_quarter_months = remaining_months % 3
  236. # 当前日期设置为第一个结算日期
  237. current_date = first_settlement_date
  238. # 添加完整季度的结算记录
  239. for _ in range(full_quarters):
  240. # 移到下一个季度结算日
  241. current_quarter_idx = (current_quarter_idx + 1) % len(QUARTER_DATES)
  242. if current_quarter_idx == 0:
  243. current_year += 1
  244. month, day = QUARTER_DATES[current_quarter_idx]
  245. settlement_date = datetime(current_year, month, day)
  246. # 添加完整季度的结算记录(3个月)
  247. result.append((int(settlement_date.timestamp()), 3))
  248. # 更新当前日期
  249. current_date = settlement_date
  250. # 如果有剩余月数,添加最后一个季度的结算记录
  251. if last_quarter_months > 0:
  252. # 移到下一个季度结算日
  253. current_quarter_idx = (current_quarter_idx + 1) % len(QUARTER_DATES)
  254. if current_quarter_idx == 0:
  255. current_year += 1
  256. month, day = QUARTER_DATES[current_quarter_idx]
  257. settlement_date = datetime(current_year, month, day)
  258. # 添加最后一个季度的结算记录(剩余月数)
  259. result.append((int(settlement_date.timestamp()), last_quarter_months))
  260. return result
  261. @staticmethod
  262. def calculate_months_in_period(start_date, end_date):
  263. """
  264. 计算两个日期之间的整月数,不足一个月不计入
  265. :param start_date: 开始日期
  266. :param end_date: 结束日期
  267. :return: 整月数
  268. """
  269. # 计算天数差
  270. days_diff = (end_date - start_date).days
  271. # 转换为整月数(按平均每月30.5天计算)
  272. whole_months = int(days_diff / 30.5)
  273. return whole_months
  274. @staticmethod
  275. def calculate_quarterly_profit(profit, settlement_dates_with_months):
  276. """
  277. 计算季度利润分配,基于整月数
  278. :param profit: 总利润
  279. :param settlement_dates_with_months: 包含(结算日期, 整月数)的元组列表
  280. :return: 每个季度的利润列表
  281. """
  282. profit = Decimal(str(profit)).quantize(Decimal('0.01'))
  283. # 计算总整月数
  284. total_months = sum(months for _, months in settlement_dates_with_months)
  285. # 如果总月数为0,返回空列表
  286. if total_months == 0:
  287. return []
  288. # 计算每月利润
  289. monthly_profit = profit / Decimal(total_months)
  290. # 计算每个季度的利润
  291. quarterly_amounts = []
  292. for _, months in settlement_dates_with_months:
  293. # 计算当前季度的利润(基于整月数)
  294. amount = (monthly_profit * Decimal(months)).quantize(Decimal('0.01'), rounding=ROUND_DOWN)
  295. quarterly_amounts.append(amount)
  296. # 处理舍入误差,确保总和等于总利润
  297. total_allocated = sum(quarterly_amounts)
  298. remainder = profit - total_allocated
  299. # 将剩余的分配到第一个季度
  300. if remainder > Decimal('0') and quarterly_amounts:
  301. quarterly_amounts[0] += remainder
  302. return quarterly_amounts
  303. @classmethod
  304. def save_order_installment(cls, agent_order_id, package_type, package_id, profit, ac_id=None, pay_time=0):
  305. """
  306. 保存代理订单分期信息(季度结算逻辑),不满一个月的时间累积到下一个季度
  307. :param cls: 类方法的约定参数
  308. :param agent_order_id: 代理订单ID
  309. :param package_type: 套餐类型(1:云存, 2:4G)
  310. :param package_id: 套餐ID
  311. :param profit: 利润总额
  312. :param ac_id: 代理客户ID
  313. :param pay_time: 订单支付时间
  314. :return: 无返回值
  315. """
  316. try:
  317. # 转换支付时间为datetime对象
  318. pay_time_dt = datetime.fromtimestamp(pay_time)
  319. # 获取套餐月数
  320. if package_type == 1: # 云存
  321. store = Store_Meal.objects.filter(id=package_id).first()
  322. if not store:
  323. LOGGER.info(f'云存套餐不存在: {package_id}')
  324. return
  325. months = store.expire
  326. else: # 4G
  327. combo = UnicomCombo.objects.filter(id=package_id).first()
  328. if not combo:
  329. LOGGER.info(f'4G套餐不存在: {package_id}')
  330. return
  331. months = int(combo.expiration_days / 30)
  332. if months <= 0 or profit <= 0:
  333. LOGGER.info(f'无效参数: months={months}, profit={profit}')
  334. return
  335. LOGGER.info(
  336. f'开始计算季度结算: 订单ID={agent_order_id}, 开始日期={pay_time_dt}, 套餐月数={months}, 总利润={profit}')
  337. # 获取季度结算日期和每个季度的整月数
  338. settlement_dates_with_months = cls.get_quarterly_settlement_dates(pay_time_dt, months)
  339. # 记录季度结算日期和月数
  340. for i, (date, months_used) in enumerate(settlement_dates_with_months):
  341. date_str = datetime.fromtimestamp(date).strftime('%Y-%m-%d')
  342. LOGGER.info(f'季度{i + 1}结算日期: {date_str}, 整月数: {months_used}')
  343. # 如果没有有效的结算日期,则退出
  344. if not settlement_dates_with_months:
  345. LOGGER.info(f'没有有效的季度结算日期: start_date={pay_time_dt}, months={months}')
  346. return
  347. # 计算每个季度的利润分配
  348. amounts = cls.calculate_quarterly_profit(profit, settlement_dates_with_months)
  349. # 记录每个季度的利润分配
  350. for i, amount in enumerate(amounts):
  351. LOGGER.info(f'季度{i + 1}利润分配: {amount}')
  352. # 创建分期记录
  353. n_time = int(time.time())
  354. installment_list = []
  355. for i, ((settlement_date, months_used), amount) in enumerate(zip(settlement_dates_with_months, amounts)):
  356. # 只有使用满一个月才创建结算记录
  357. if months_used >= 1:
  358. installment_list.append(AgentDeviceOrderInstallment(
  359. ado_id=agent_order_id,
  360. period_number=len(settlement_dates_with_months),
  361. ac_id=ac_id,
  362. amount=amount,
  363. due_date=settlement_date,
  364. status=1,
  365. created_time=n_time,
  366. updated_time=n_time
  367. ))
  368. # 批量创建
  369. if installment_list:
  370. batch_size = 100
  371. for i in range(0, len(installment_list), batch_size):
  372. AgentDeviceOrderInstallment.objects.bulk_create(installment_list[i:i + batch_size])
  373. LOGGER.info(f'季度分期结算记录创建完成: {len(installment_list)}条, 订单ID: {agent_order_id}')
  374. else:
  375. LOGGER.info(f'没有创建季度分期结算记录: 订单ID: {agent_order_id}')
  376. except Exception as e:
  377. LOGGER.error(f'保存季度分期结算记录异常: 行号:{e.__traceback__.tb_lineno}, 错误:{repr(e)}')
  378. @classmethod
  379. def update_periodic_settlement(cls):
  380. """
  381. 更新周期结算信息 - 优化版
  382. 功能:
  383. 1. 使用分布式锁确保同一时间只有一个进程在处理结算
  384. 2. 添加对账机制,确保数据准确性
  385. 3. 增加详细的日志记录
  386. 4. 使用Redis缓存避免重复处理
  387. 返回值:
  388. - 无返回值
  389. """
  390. # 初始化Redis对象
  391. redis_obj = RedisObject()
  392. # 生成唯一的请求ID用于锁
  393. request_id = f"settlement_task_{int(time.time())}"
  394. lock_key = "lock:periodic_settlement"
  395. # 尝试获取分布式锁
  396. if not redis_obj.try_lock(lock_key, request_id, expire=10, time_unit_second=60):
  397. LOGGER.info("周期结算任务已在其他进程中运行,本次跳过")
  398. return
  399. LOGGER.info("开始执行周期结算任务")
  400. try:
  401. n_time = int(time.time())
  402. # 记录开始处理的时间
  403. start_time = time.time()
  404. LOGGER.info(f"开始查询到期的分期结算记录,当前时间戳: {n_time}")
  405. # 根据条件查询需要更新结算信息的订单分期记录
  406. adoi_qs = AgentDeviceOrderInstallment.objects.filter(status=1, due_date__lte=n_time)
  407. if not adoi_qs.exists():
  408. LOGGER.info("没有找到需要结算的记录")
  409. return
  410. # 记录找到的记录数
  411. record_count = adoi_qs.count()
  412. LOGGER.info(f"找到 {record_count} 条需要结算的记录")
  413. # 使用事务处理结算过程
  414. from django.db import transaction
  415. # 准备数据
  416. settlement_records = [] # 用于记录处理的结算记录,后续对账使用
  417. ids = []
  418. a_account_list = []
  419. adoi_set = set()
  420. total_amount = Decimal('0.00')
  421. for item in adoi_qs:
  422. # 准备分期记录的id列表和账户记录列表
  423. ids.append(item.id)
  424. adoi_set.add(item.ado_id)
  425. # 记录结算金额
  426. amount = Decimal(str(item.amount)).quantize(Decimal('0.01'))
  427. total_amount += amount
  428. # 创建账户记录对象
  429. a_account_list.append(AgentAccount(
  430. ac_id=item.ac_id,
  431. amount=amount,
  432. remark=f'周期结算 - 分期ID:{item.id}',
  433. status=1,
  434. created_time=n_time,
  435. updated_time=n_time
  436. ))
  437. # 记录处理的结算记录
  438. settlement_records.append({
  439. 'id': item.id,
  440. 'ac_id': item.ac_id,
  441. 'amount': str(amount),
  442. 'due_date': item.due_date
  443. })
  444. # 缓存结算记录用于对账
  445. settlement_cache_key = f"settlement:records:{n_time}"
  446. redis_obj.set_data(settlement_cache_key, str(settlement_records), expire=86400) # 缓存24小时
  447. LOGGER.info(f"准备处理 {len(ids)} 条分期记录,总金额: {total_amount}")
  448. # 使用事务确保数据一致性
  449. with transaction.atomic():
  450. batch_size = 100
  451. # 分批更新分期记录状态
  452. updated_count = 0
  453. for i in range(0, len(ids), batch_size):
  454. batch_ids = ids[i:i + batch_size]
  455. update_result = AgentDeviceOrderInstallment.objects.filter(id__in=batch_ids) \
  456. .update(status=2, settlement_time=n_time, updated_time=n_time)
  457. updated_count += update_result
  458. LOGGER.info(f"已更新分期记录状态: {updated_count}/{len(ids)}")
  459. # 对账检查 - 确保所有记录都已更新
  460. if updated_count != len(ids):
  461. LOGGER.error(f"对账失败: 应更新 {len(ids)} 条记录,实际更新 {updated_count} 条")
  462. # 在事务中抛出异常将触发回滚
  463. raise Exception(f"结算记录更新不一致: 应更新 {len(ids)} 条,实际更新 {updated_count} 条")
  464. # 分批创建账户记录
  465. created_accounts = 0
  466. for i in range(0, len(a_account_list), batch_size):
  467. batch_accounts = a_account_list[i:i + batch_size]
  468. created_batch = AgentAccount.objects.bulk_create(batch_accounts)
  469. created_accounts += len(created_batch)
  470. LOGGER.info(f"已创建账户记录: {created_accounts}/{len(a_account_list)}")
  471. # 对账检查 - 确保所有账户记录都已创建
  472. if created_accounts != len(a_account_list):
  473. LOGGER.error(f"对账失败: 应创建 {len(a_account_list)} 条账户记录,实际创建 {created_accounts} 条")
  474. raise Exception(
  475. f"账户记录创建不一致: 应创建 {len(a_account_list)} 条,实际创建 {created_accounts} 条")
  476. # 检查是否所有分期都已结算,如果是,则更新订单状态为已结算
  477. updated_orders = 0
  478. for ado_id in adoi_set:
  479. # 检查是否还有未结算的分期
  480. if not AgentDeviceOrderInstallment.objects.filter(ado_id=ado_id, status=1).exists():
  481. # 更新订单状态为已结算
  482. update_result = AgentDeviceOrder.objects.filter(id=ado_id, status=1) \
  483. .update(status=2, settlement_time=n_time, updated_time=n_time)
  484. if update_result > 0:
  485. updated_orders += 1
  486. LOGGER.info(f"订单 {ado_id} 所有分期已结算,已更新订单状态")
  487. LOGGER.info(f"共更新了 {updated_orders} 个订单的状态为已结算")
  488. # 记录结算摘要到Redis,用于后续查询
  489. summary_key = f"settlement:summary:{n_time}"
  490. summary_data = {
  491. 'timestamp': n_time,
  492. 'record_count': record_count,
  493. 'total_amount': str(total_amount),
  494. 'updated_records': updated_count,
  495. 'created_accounts': created_accounts,
  496. 'updated_orders': updated_orders,
  497. 'duration': round(time.time() - start_time, 2)
  498. }
  499. redis_obj.set_hash_data(summary_key, summary_data)
  500. redis_obj.set_expire(summary_key, 86400 * 7) # 保存7天
  501. # 记录完成信息
  502. end_time = time.time()
  503. duration = round(end_time - start_time, 2)
  504. LOGGER.info(f"周期结算任务完成,处理时间: {duration}秒,处理记录: {record_count}条,总金额: {total_amount}")
  505. except Exception as e:
  506. # 记录详细的异常信息
  507. LOGGER.error(
  508. f'周期结算任务异常: 行号:{e.__traceback__.tb_lineno}, 错误类型:{type(e).__name__}, 错误信息:{repr(e)}')
  509. finally:
  510. # 释放分布式锁
  511. redis_obj.release_lock(lock_key, request_id)
  512. LOGGER.info("周期结算任务锁已释放")