AgentCustomerController.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : AgentCustomerController.py
  4. @Time : 2024/3/7 16:56
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import time
  10. import json
  11. from decimal import Decimal
  12. from django.db.models import Sum
  13. from django.http import QueryDict
  14. from django.views import View
  15. from django.core.paginator import Paginator
  16. from datetime import datetime, timedelta
  17. from AgentModel.models import AgentCustomerInfo, AgentCustomerCard, AgentCustomerPackage, AgentCloudServicePackage, \
  18. AgentDeviceOrder, AgentAccountWithdraw, AgentDevice, AgentAccount
  19. from Model.models import UnicomCombo, Store_Meal, Device_User
  20. from Object.ResponseObject import ResponseObject
  21. from Object.TokenObject import TokenObject
  22. class AgentCustomerView(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. AgentCustomerInfo.objects.filter()
  45. language = request_dict.get('language', 'en')
  46. response = ResponseObject(language, 'pc')
  47. if operation == 'getUnicomAndIcloud':
  48. return self.get_unicom_and_icloud(response)
  49. else:
  50. tko = TokenObject(
  51. request.META.get('HTTP_AUTHORIZATION'),
  52. returntpye='pc')
  53. if tko.code != 0:
  54. return response.json(tko.code)
  55. response.lang = tko.lang
  56. userID = tko.userID
  57. # 代理用户界面(代理顾客个人信息)
  58. if operation == 'getAgentInfo':
  59. return self.get_agent_info(userID, response)
  60. # 代理云存套餐
  61. elif operation == 'getAgentServicePackage':
  62. return self.get_agent_service_package(request_dict, response)
  63. elif operation == 'addAgentServicePackage':
  64. return self.add_agent_service_package(userID, request_dict, response)
  65. elif operation == 'updateAgentServicePackage':
  66. return self.update_agent_service_package(userID, request_dict, response)
  67. elif operation == 'delAgentServicePackage':
  68. return self.del_agent_service_package(request_dict, response)
  69. # 代理客户绑定套餐
  70. elif operation == 'getCustomerList':
  71. return self.get_customer_list(request_dict, response)
  72. elif operation == 'getCustomerPackageList':
  73. return self.get_cumstomer_package_list(request_dict, response)
  74. elif operation == 'batchRebindCustomerPackage':
  75. return self.batch_rebind_customer_packages(userID, request_dict, response)
  76. elif operation == 'getAgentServicePackageList':
  77. return self.get_agent_service_package_list(response)
  78. elif operation == 'getAgentSettleOrders':
  79. return self.get_agent_settle_order(userID, request_dict, response)
  80. elif operation == 'getDataStatistics':
  81. return self.get_data_statistics(userID, response)
  82. # 代理商提现功能
  83. elif operation == 'getAgentAccountWithdraw':
  84. return self.get_agent_account_withdraw(userID, request_dict, response)
  85. elif operation == 'getCheckBalance':
  86. return self.get_check_balance(userID, response)
  87. elif operation == 'agentApplyWithdraw':
  88. return self.agent_apply_withdraw(userID, request_dict, response)
  89. elif operation == 'getWithdrawalReview':
  90. return self.get_withdrawal_review(request_dict, response)
  91. elif operation == 'updateWithdrawalReview':
  92. return self.update_withdrawal_review(userID, request_dict, response)
  93. else:
  94. return response.json(444, 'operation')
  95. def get_unicom_and_icloud(self, response):
  96. """
  97. 查询云存储套餐和物联网卡套餐列表
  98. @param response: 响应对象
  99. @return:
  100. """
  101. try:
  102. # 云存储套餐查询,只包括is_show=1的记录
  103. store_meals = Store_Meal.objects.filter(is_show=1).values('id', 'bucket__bucket').distinct()
  104. # 联通套餐查询,只包括is_show=1且未被删除的记录
  105. unicom_combos = UnicomCombo.objects.filter(is_show=1, is_del=False).values('id', 'combo_name').distinct()
  106. # 将查询结果转换为列表
  107. store_meal_list = [{'id': meal['id'], 'name': meal['bucket__bucket']} for meal in store_meals]
  108. unicom_combo_list = [{'id': combo['id'], 'name': combo['combo_name']} for combo in unicom_combos]
  109. # 合并结果并返回
  110. return response.json(0, {
  111. 'storeMeals': store_meal_list,
  112. 'unicomCombos': unicom_combo_list,
  113. })
  114. except Exception as e:
  115. print(e)
  116. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  117. def get_agent_info(self, userID, response):
  118. """
  119. 查询用户信息
  120. @param userID: userID
  121. @param response: 响应对象
  122. @return:
  123. """
  124. try:
  125. # 使用userID查询AgentCustomerInfo获取基本信息
  126. agent_info = AgentCustomerInfo.objects.filter(user_id=userID, status=1).first()
  127. if not agent_info:
  128. return response.json(444, {'error': '没有找到这个代理用户'})
  129. # userID查询用户电话
  130. device_user_qs = Device_User.objects.filter(userID=userID).first()
  131. # 代理客户ID(ac_id)查询AgentCustomerCard获取银行卡信息。
  132. card_details = AgentCustomerCard.objects.filter(ac_id=agent_info.id, status=1).first()
  133. # ac_id查询AgentCustomerPackage来找到关联的云服务套餐ID(cs_id)
  134. package_ids = AgentCustomerPackage.objects.filter(ac_id=agent_info.id).values_list('cs_id',
  135. flat=True)
  136. # cs_id查询AgentCloudServicePackage获取服务套餐详情。
  137. service_packages = AgentCloudServicePackage.objects.filter(id__in=package_ids, status=1).values()
  138. result = {
  139. 'agent_info': {
  140. 'ac_id': agent_info.id,
  141. 'company_name': agent_info.company_name,
  142. 'phone': device_user_qs.phone,
  143. 'created_time': agent_info.created_time,
  144. 'service_packages': list(service_packages),
  145. }
  146. }
  147. if card_details:
  148. result['agent_info'].update({
  149. 'card_name': card_details.name,
  150. 'card_no': card_details.card_no,
  151. 'card_address': card_details.card_address,
  152. })
  153. return response.json(0, result)
  154. except Exception as e:
  155. return response.json({'error': str(e)}, status=500)
  156. def get_agent_service_package(self, request_dict, response):
  157. """
  158. 查询所有代理云服务套餐
  159. @param request_dict: 请求参数
  160. @request_dict page: 页码
  161. @request_dict page_size: 查询分页数
  162. @param response: 响应对象
  163. @return:
  164. """
  165. page = int(request_dict.get('page', 1))
  166. page_size = int(request_dict.get('page_size', 10))
  167. try:
  168. # 查询所有有效的代理云服务套餐
  169. all_packages = AgentCloudServicePackage.objects.filter(status=1).order_by('type', '-created_time')
  170. # 创建分页对象
  171. paginator = Paginator(all_packages, page_size)
  172. # 获取请求页的数据
  173. packages_page = paginator.page(page)
  174. # 准备响应数据,转换查询集为列表形式
  175. packages_list = list(packages_page.object_list.values(
  176. 'id', 'service_name', 'package_id', 'type',
  177. 'profit_type', 'cost', 'profit', 'status',
  178. 'created_time'
  179. ))
  180. # 返回分页数据
  181. return response.json(0, {
  182. 'page': page,
  183. 'page_size': page_size,
  184. 'total': paginator.count,
  185. 'num_pages': paginator.num_pages,
  186. 'list': packages_list
  187. })
  188. except Exception as e:
  189. # 出错时返回错误信息
  190. return response.json({'error': str(e)}, status=500)
  191. def add_agent_service_package(self, userID, request_dict, response):
  192. """
  193. 添加代理云服务套餐
  194. @param request_dict: 请求参数
  195. @request_dict package_id: 代理服务id
  196. @request_dict service_name: 代理服务名称
  197. @request_dict package_type: 套餐类型 1:云存,2:4G
  198. @response_dict profit_type: 利润分配类型 1:固定值,2:百分比
  199. @response_dict cost: 成本
  200. @response_dict profit: 利润值
  201. @param response: 响应对象
  202. @return:
  203. """
  204. package_id = request_dict.get('package_id', None)
  205. service_name = request_dict.get('service_name', None)
  206. package_type = int(request_dict.get('package_type', 0)) # 默认为0,确保类型安全
  207. profit_type = int(request_dict.get('profit_type', 1)) # 默认值为1
  208. profit = request_dict.get('profit', 0)
  209. cost = request_dict.get('cost', 0)
  210. try:
  211. # 创建AgentCloudServicePackage实例并保存
  212. if not all([package_id, service_name]):
  213. return response.json(444)
  214. if package_type == 1:
  215. query_set = Store_Meal.objects.filter(is_show=1, id=package_id)
  216. elif package_type == 2:
  217. query_set = UnicomCombo.objects.filter(is_show=1, is_del=False, id=package_id)
  218. else:
  219. return response.json(444, 'error package_type')
  220. if not query_set.exists():
  221. return response.json(173)
  222. AgentCloudServicePackage.objects.create(
  223. service_name=service_name,
  224. package_id=package_id,
  225. type=package_type,
  226. profit_type=profit_type,
  227. profit=profit,
  228. status=1,
  229. cost=cost,
  230. created_by=userID,
  231. created_time=int(time.time()),
  232. updated_by=userID,
  233. updated_time=int(time.time())
  234. )
  235. return response.json(0)
  236. except Exception as e:
  237. return response.json({'error': str(e)}, status=500)
  238. def update_agent_service_package(self, userID, request_dict, response):
  239. """
  240. 更新代理云服务套餐
  241. @param request_dict: 请求参数
  242. @request_dict package_id: 代理服务id
  243. @request_dict service_name: 代理服务名称
  244. @response_dict profit_type: 利润分配类型 1:固定值,2:百分比
  245. @response_dict cost: 成本
  246. @response_dict profit: 利润值
  247. @param response: 响应对象
  248. @return:
  249. """
  250. id = request_dict.get('id', None)
  251. service_name = request_dict.get('service_name', None)
  252. profit_type = request_dict.get('profit_type', None)
  253. cost = request_dict.get('cost', None)
  254. profit = request_dict.get('profit', None)
  255. if not all([id, service_name, profit_type, cost, profit]):
  256. return response.json(444)
  257. try:
  258. ac_service_package = AgentCloudServicePackage.objects.get(pk=id)
  259. ac_service_package.service_name = service_name
  260. ac_service_package.profit_type = profit_type
  261. ac_service_package.cost = cost
  262. ac_service_package.profit = profit
  263. ac_service_package.updated_time = int(time.time())
  264. ac_service_package.updated_by = userID
  265. ac_service_package.save()
  266. return response.json(0)
  267. except AgentCloudServicePackage.DoesNotExist:
  268. return response.json(173)
  269. except Exception as e:
  270. return response.json({'error': str(e)}, status=500)
  271. def del_agent_service_package(self, request_dict, response):
  272. """
  273. 删除代理云服务套餐
  274. @param userID: 用户ID(执行删除操作的用户)
  275. @param request_dict: 请求参数
  276. @request_dict package_id: 代理服务id
  277. @param response: 响应对象
  278. @return:
  279. """
  280. id = request_dict.get('id', None)
  281. if not id:
  282. return response.json(444, 'Missing package_id')
  283. try:
  284. ac_service_package = AgentCloudServicePackage.objects.get(pk=id)
  285. #假删除,否则查利润会出问题
  286. ac_service_package.status=0
  287. ac_service_package.save()
  288. return response.json(0)
  289. except AgentCloudServicePackage.DoesNotExist:
  290. return response.json(173, 'Package does not exist.')
  291. except Exception as e:
  292. return response.json(500, {'error': str(e)})
  293. def get_customer_list(self, request_dict, response):
  294. """
  295. 查询代理商信息,并进行分页处理
  296. @param request_dict: 请求对象,用于接收分页参数
  297. @param response: 响应对象
  298. @return:
  299. """
  300. # 接收分页参数
  301. page = int(request_dict.get('page', 1))
  302. page_size = int(request_dict.get('page_size', 10))
  303. # 查询AgentCustomerInfo表以获取代理商基本信息
  304. agent_infos = AgentCustomerInfo.objects.filter(status=1).values(
  305. 'id', 'user_id', 'company_name'
  306. ).order_by('id')
  307. try:
  308. # 使用Paginator进行分页处理
  309. paginator = Paginator(agent_infos, page_size)
  310. # 获取请求页的数据
  311. packages_page = paginator.page(page)
  312. # 准备最终的代理商列表
  313. agents_list = []
  314. for agent_info in packages_page:
  315. # 查询Device_User表获取用户信息
  316. user_info = Device_User.objects.filter(userID=agent_info['user_id']).values('phone',
  317. 'userEmail').first()
  318. # 查询AgentCustomerCard表获取卡信息
  319. card_info = AgentCustomerCard.objects.filter(ac_id=agent_info['id']).values('name', 'card_no',
  320. 'card_address').first()
  321. # 组合信息
  322. agent_record = {
  323. 'id': agent_info['id'],
  324. 'company_name': agent_info['company_name'],
  325. 'user_id': agent_info['user_id'],
  326. 'phone': user_info.get('phone') if user_info else None,
  327. 'userEmail': user_info.get('userEmail') if user_info else None,
  328. 'card_name': card_info.get('name') if card_info else None,
  329. 'card_no': card_info.get('card_no') if card_info else None,
  330. 'card_address': card_info.get('card_address') if card_info else None,
  331. }
  332. agents_list.append(agent_record)
  333. return response.json(0, {'page': page, 'page_size': page_size, 'total': paginator.count,
  334. 'num_pages': paginator.num_pages, 'list': agents_list})
  335. except Exception as e:
  336. print(e)
  337. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  338. def get_cumstomer_package_list(self, request_dict, response):
  339. """
  340. 查询代理商服务套餐列表
  341. @param response: 响应对象
  342. @return:
  343. """
  344. ac_id = request_dict.get('id', None)
  345. try:
  346. if ac_id is None:
  347. return response.json(444, 'Missing ac_id')
  348. # ac_id查询AgentCustomerPackage来找到关联的云服务套餐ID(cs_id)
  349. package_ids = AgentCustomerPackage.objects.filter(ac_id=ac_id).values_list('cs_id', flat=True)
  350. # cs_id查询AgentCloudServicePackage获取服务套餐详情。
  351. service_packages = AgentCloudServicePackage.objects.filter(id__in=package_ids, status=1).values(
  352. 'id', 'service_name', 'type'
  353. )
  354. service_packages_list = list(service_packages)
  355. return response.json(0, {'service_packages': service_packages_list})
  356. except Exception as e:
  357. print(e)
  358. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  359. def batch_rebind_customer_packages(self, userID, request_dict, response):
  360. """
  361. 清空并重新绑定代理商服务套餐
  362. @param userID: 操作用户的ID
  363. @param request_dict: 请求参数,包含代理商ID和新的服务套餐ID列表
  364. @param response: 响应对象
  365. @return:
  366. """
  367. ac_id = request_dict.get('ac_id', None) # 代理客户ID
  368. new_cs_ids = json.loads(request_dict.get('cs_ids', '[]')) # 新的服务套餐ID列表
  369. if not ac_id:
  370. return response.json(444, 'Missing agent customer ID.')
  371. if not new_cs_ids:
  372. return response.json(444, 'Service package IDs are required.')
  373. try:
  374. # 删除该代理客户的所有现有绑定
  375. AgentCustomerPackage.objects.filter(ac_id=ac_id).delete()
  376. # 过滤出存在且状态为有效的套餐ID
  377. valid_new_cs_ids = AgentCloudServicePackage.objects.filter(id__in=new_cs_ids, status=1).values_list('id',
  378. flat=True)
  379. # 准备批量创建的数据
  380. packages_to_bind = [
  381. AgentCustomerPackage(
  382. ac_id=ac_id,
  383. cs_id=cs_id,
  384. created_by=userID,
  385. updated_by=userID,
  386. created_time=int(time.time()),
  387. updated_time=int(time.time())
  388. )
  389. for cs_id in valid_new_cs_ids
  390. ]
  391. # 批量创建新的绑定关系
  392. AgentCustomerPackage.objects.bulk_create(packages_to_bind)
  393. return response.json(0)
  394. except Exception as e:
  395. print(e)
  396. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  397. def get_agent_service_package_list(self, response):
  398. """
  399. 查询云服务套餐列表 id + service_name
  400. @param response: 响应对象
  401. @return:
  402. """
  403. try:
  404. # 查询所有有效的代理云服务套餐
  405. all_packages = AgentCloudServicePackage.objects.filter(status=1).order_by('-created_time').values('id',
  406. 'service_name')
  407. # 转换查询集为列表形式
  408. packages_list = list(all_packages)
  409. # 返回数据
  410. return response.json(0, {'packages': packages_list})
  411. except Exception as e:
  412. # 出错时返回错误信息
  413. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  414. def get_agent_settle_order(self, userID, request_dict, response):
  415. """
  416. 查询结算明细
  417. @param userID: userID
  418. @param request_dict: 请求参数
  419. @param request_dict status: 结算状态
  420. @param request_dict time: 年-季度 2023-1
  421. @param response: 响应对象
  422. @return:
  423. """
  424. agent_customer_info = AgentCustomerInfo.objects.filter(user_id=userID).first()
  425. if not agent_customer_info:
  426. return response.json(104, 'Agent customer not found')
  427. ac_id = agent_customer_info.id
  428. status = request_dict.get('status', None)
  429. time_str = request_dict.get('time', None)
  430. startTime = int(request_dict.get('start_time', 1))
  431. endTime = int(request_dict.get('end_time', 0))
  432. page = int(request_dict.get('page', 1)) # 默认为第一页
  433. page_size = int(request_dict.get('page_size', 10)) # 默认每页10条记录
  434. try:
  435. agent_device_orders_qs = AgentDeviceOrder.objects.filter(ac_id=ac_id, is_del=0)
  436. if time_str:
  437. year, quarter = map(int, time_str.split('-'))
  438. start_month = 3 * (quarter - 1) + 1
  439. end_month = start_month + 2
  440. start_date = datetime(year, start_month, 1)
  441. end_date = datetime(year + 1, 1, 1) if end_month == 12 else datetime(year, end_month + 1, 1)
  442. start_time = int(start_date.timestamp())
  443. end_time = int(end_date.timestamp()) - 1
  444. agent_device_orders_qs = agent_device_orders_qs.filter(created_time__gte=start_time,
  445. created_time__lte=end_time)
  446. if status:
  447. agent_device_orders_qs = agent_device_orders_qs.filter(status=status)
  448. if startTime < endTime:
  449. agent_device_orders_qs = agent_device_orders_qs.filter(created_time__gte=startTime,
  450. created_time__lte=endTime)
  451. # 计算利润总额和订单总数
  452. total_profit = agent_device_orders_qs.aggregate(Sum('profit'))['profit__sum'] or 0
  453. # 应用分页
  454. agent_device_orders_qs = agent_device_orders_qs.order_by('-created_time')
  455. paginator = Paginator(agent_device_orders_qs, page_size)
  456. current_page = paginator.get_page(page)
  457. orders = []
  458. for order in current_page:
  459. csp = AgentCloudServicePackage.objects.filter(id=order.csp_id).first()
  460. service_name = csp.service_name if csp else order.csp_id
  461. orders.append({
  462. 'id': order.id,
  463. 'serial_number': order.serial_number,
  464. 'status': order.status,
  465. 'service_name': service_name,
  466. 'profit_amount': order.profit_amount,
  467. 'profit': order.profit,
  468. 'settlement_time': order.settlement_time,
  469. 'remark': order.remark,
  470. 'created_time':order.created_time
  471. })
  472. response_data = {
  473. 'list': orders,
  474. 'total_profit': total_profit,
  475. 'total': paginator.count,
  476. 'page': current_page.number,
  477. 'page_size': page_size,
  478. 'num_pages': paginator.num_pages,
  479. }
  480. return response.json(0, response_data)
  481. except Exception as e:
  482. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  483. def get_agent_account_withdraw(self, userID, request_dict, response):
  484. """
  485. 查询提现明细
  486. @param userID: userID
  487. @param request_dict: 请求参数
  488. @param response: 响应对象
  489. @return:
  490. """
  491. agent_customer_info = AgentCustomerInfo.objects.filter(user_id=userID).first()
  492. if not agent_customer_info:
  493. return response.json(104, 'Agent customer not found')
  494. ac_id = agent_customer_info.id
  495. try:
  496. agent_account_withdraw_qs = AgentAccountWithdraw.objects.filter(ac_id=ac_id).order_by('-updated_time')
  497. page = int(request_dict.get('page', 1)) # 默认为第一页
  498. page_size = int(request_dict.get('page_size', 10)) # 默认每页10条记录
  499. # 应用分页
  500. paginator = Paginator(agent_account_withdraw_qs, page_size)
  501. current_page = paginator.get_page(page)
  502. withdraw_list = []
  503. for withdraw in current_page:
  504. agent_customer_card = AgentCustomerCard.objects.filter(ac_id=ac_id).first()
  505. card_no = agent_customer_card.card_no
  506. withdraw_list.append({
  507. 'id': withdraw.id,
  508. 'amount': withdraw.amount,
  509. 'created_time': withdraw.created_time,
  510. 'card_no': card_no,
  511. 'status': withdraw.status,
  512. 'remark': withdraw.remark,
  513. 'arrival_time': withdraw.arrival_time
  514. })
  515. response_data = {
  516. 'list': withdraw_list,
  517. 'total': paginator.count,
  518. 'page': current_page.number,
  519. 'page_size': page_size,
  520. 'num_pages': paginator.num_pages,
  521. }
  522. return response.json(0, response_data)
  523. except Exception as e:
  524. # 出错时返回错误信息
  525. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  526. def get_check_balance(self, userID, response):
  527. """
  528. 查询余额
  529. @param userID: userID
  530. @param response: 响应对象
  531. @return:
  532. """
  533. agent_customer_info = AgentCustomerInfo.objects.filter(user_id=userID).first()
  534. if not agent_customer_info:
  535. return response.json(104, 'Agent customer not found')
  536. ac_id = agent_customer_info.id
  537. try:
  538. # 计算冻结金额
  539. frozen_amount_qs = AgentAccountWithdraw.objects.filter(ac_id=ac_id, status__in=[1,2,3])
  540. frozen_amount = frozen_amount_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
  541. # 计算余额:已结算 - (退款+已打款)
  542. incomes_qs = AgentAccount.objects.filter(ac_id=ac_id, status=1)
  543. expense_qs = AgentAccount.objects.filter(ac_id=ac_id, status__in=[2,3])
  544. incomes_all = incomes_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
  545. expense_all = expense_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
  546. total_profit = incomes_all - expense_all
  547. # 可用余额 = 总余额 - 冻结金额
  548. available_balance = total_profit - frozen_amount
  549. # 构造返回数据
  550. balance_data = {
  551. 'frozen_amount': frozen_amount, # 冻结金额
  552. 'total_profit': total_profit, # 总余额
  553. 'available_balance': available_balance # 可用余额
  554. }
  555. return response.json(0, balance_data)
  556. except Exception as e:
  557. # 出错时返回错误信息
  558. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  559. def get_data_statistics(self, userID, response):
  560. """
  561. 首页总览
  562. @param userID: userID
  563. @param response: 响应对象
  564. @return:
  565. """
  566. agent_customer_info = AgentCustomerInfo.objects.filter(user_id=userID).first()
  567. if not agent_customer_info:
  568. return response.json(104, 'Agent customer not found')
  569. ac_id = agent_customer_info.id
  570. now = datetime.now()
  571. today_start = datetime(now.year, now.month, now.day)
  572. yesterday_start = today_start - timedelta(days=1)
  573. tomorrow_start = today_start + timedelta(days=1)
  574. try:
  575. # 总利润
  576. total_profit_all = \
  577. AgentDeviceOrder.objects.filter(ac_id=ac_id, status__in=[1, 2], is_del=False).aggregate(
  578. total=Sum('profit'))[
  579. 'total'] or Decimal('0.00')
  580. total_profit_no = \
  581. AgentDeviceOrder.objects.filter(ac_id=ac_id, status=1, is_del=False).aggregate(total=Sum('profit'))[
  582. 'total'] or Decimal('0.00')
  583. total_profit_yes = \
  584. AgentDeviceOrder.objects.filter(ac_id=ac_id, status=2, is_del=False).aggregate(total=Sum('profit'))[
  585. 'total'] or Decimal('0.00')
  586. # 总营业额
  587. profit_amount_all = AgentDeviceOrder.objects.filter(ac_id=ac_id, status__in=[1, 2], is_del=False).aggregate(
  588. total=Sum('profit_amount'))['total'] or Decimal('0.00')
  589. # 今日总营业额
  590. profit_amount_today_all = AgentDeviceOrder.objects.filter(
  591. ac_id=ac_id,
  592. status__in=[1, 2],
  593. is_del=False,
  594. created_time__gte=int(today_start.timestamp()),
  595. created_time__lt=int(tomorrow_start.timestamp())
  596. ).aggregate(total=Sum('profit_amount'))['total'] or Decimal('0.00')
  597. # 昨日总营业额
  598. profit_amount_yesterday_all = AgentDeviceOrder.objects.filter(
  599. ac_id=ac_id,
  600. status__in=[1, 2],
  601. is_del=False,
  602. created_time__gte=int(yesterday_start.timestamp()),
  603. created_time__lt=int(today_start.timestamp())
  604. ).aggregate(total=Sum('profit_amount'))['total'] or Decimal('0.00')
  605. # 激活设备数
  606. active_device_count_today = AgentDevice.objects.filter(
  607. ac_id=ac_id, status=1,
  608. created_time__gte=int(today_start.timestamp()),
  609. created_time__lt=int(tomorrow_start.timestamp())
  610. ).count()
  611. active_device_count_yesterday = AgentDevice.objects.filter(
  612. ac_id=ac_id, status=1,
  613. created_time__gte=int(yesterday_start.timestamp()),
  614. created_time__lt=int(today_start.timestamp())
  615. ).count()
  616. # 总设备数
  617. active_device_count = AgentDevice.objects.filter(ac_id=ac_id, status=1).count()
  618. inactive_device_count = AgentDevice.objects.filter(ac_id=ac_id, status=0).count()
  619. return response.json(0, {
  620. 'total_profit_all': total_profit_all,
  621. 'total_profit_no': total_profit_no,
  622. 'total_profit_yes': total_profit_yes,
  623. 'profit_amount_all': profit_amount_all,
  624. 'profit_amount_today_all': profit_amount_today_all,
  625. 'profit_amount_yesterday_all': profit_amount_yesterday_all,
  626. 'active_device_count_today': active_device_count_today,
  627. 'active_device_count_yesterday': active_device_count_yesterday,
  628. 'active_device_count': active_device_count,
  629. 'inactive_device_count': inactive_device_count,
  630. 'all_device_count': active_device_count + inactive_device_count
  631. })
  632. except Exception as e:
  633. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  634. def agent_apply_withdraw(self, userID, request_dict, response):
  635. """
  636. 用户提现申请
  637. @param userID: userID
  638. @param request_dict: 请求参数
  639. @param request_dict amount: 金额
  640. @param response: 响应对象
  641. @return:
  642. """
  643. amount = Decimal(request_dict.get('amount', '0.00'))
  644. if amount == Decimal('0.00'):
  645. return response.json(444)
  646. agent_customer_info = AgentCustomerInfo.objects.filter(user_id=userID).first()
  647. if not agent_customer_info:
  648. return response.json(104, 'Agent customer not found')
  649. ac_id = agent_customer_info.id
  650. try:
  651. # 计算余额:已结算 - (退款+已打款)
  652. incomes_qs = AgentAccount.objects.filter(ac_id=ac_id, status=1)
  653. expense_qs = AgentAccount.objects.filter(ac_id=ac_id, status__in=[2, 3])
  654. incomes_all = incomes_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
  655. expense_all = expense_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
  656. total_profit = incomes_all - expense_all
  657. # 冻结余额
  658. frozen_amount_qs = AgentAccountWithdraw.objects.filter(ac_id=ac_id, status__in=[1,2,3])
  659. frozen_amount = frozen_amount_qs.aggregate(total=Sum('amount'))['total'] or Decimal('0.00')
  660. # 可提现余额 = 总余额 - 冻结金额
  661. available_balance = total_profit - frozen_amount
  662. if amount > available_balance:
  663. return response.json(173, f'余额不足,无法提现')
  664. # 提交提现申请
  665. acc = AgentCustomerCard.objects.filter(ac_id=ac_id).first()
  666. AgentAccountWithdraw.objects.create(ac_id=ac_id, status=1, card_id=acc.id, amount=amount,
  667. created_time=int(time.time()), updated_time=int(time.time()))
  668. return response.json(0)
  669. except Exception as e:
  670. print(e)
  671. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  672. def get_withdrawal_review(self, request_dict, response):
  673. """
  674. 后台用户提现申请审核列表
  675. @param request_dict: 请求参数
  676. @param request_dict company_name: 公司名称
  677. @param request_dict status: 审核状态
  678. @param response: 响应对象
  679. @return:
  680. """
  681. company_name = request_dict.get('company_name', None)
  682. status = request_dict.get('status', None)
  683. page = int(request_dict.get('page', 1)) # 默认为第一页
  684. page_size = int(request_dict.get('page_size', 10)) # 默认每页10条记录
  685. agent_account_withdraw_qs = AgentAccountWithdraw.objects.filter().order_by('updated_time')
  686. if company_name:
  687. agent_customer_info = AgentCustomerInfo.objects.filter(company_name=company_name).first()
  688. ac_id = agent_customer_info.id
  689. agent_account_withdraw_qs = agent_account_withdraw_qs.filter(ac_id=ac_id)
  690. if status:
  691. agent_account_withdraw_qs = agent_account_withdraw_qs.filter(status=status)
  692. # 提现id 公司名 审核状态 提现金额 余额
  693. paginator = Paginator(agent_account_withdraw_qs, page_size)
  694. current_page = paginator.get_page(page)
  695. review_list = []
  696. for review in current_page:
  697. ac_id = review.ac_id
  698. agent_customer_info = AgentCustomerInfo.objects.filter(id=ac_id).first()
  699. company_name = agent_customer_info.company_name
  700. review_list.append({
  701. "id": review.id,
  702. "company_name": company_name,
  703. "status": review.status,
  704. "amount": review.amount,
  705. "remark": review.remark,
  706. })
  707. response_data = {
  708. 'list': review_list,
  709. 'total': paginator.count,
  710. 'page': current_page.number,
  711. 'page_size': page_size,
  712. 'num_pages': paginator.num_pages,
  713. }
  714. return response.json(0, response_data)
  715. def update_withdrawal_review(self, userID, request_dict, response):
  716. """
  717. 后台提现审核
  718. @param request_dict: 请求参数
  719. @param request_dict id: 提现单id
  720. @param request_dict status: 提现单状态
  721. @param request_dict remark: 提现单备注
  722. @param response: 响应对象
  723. @return:
  724. """
  725. id = request_dict.get('id', None)
  726. status = request_dict.get('status', None)
  727. remark = request_dict.get('remark', "")
  728. if not all([id, status]):
  729. return response.json(444)
  730. try:
  731. agent_account_withdraw = AgentAccountWithdraw.objects.get(pk=id)
  732. agent_account_withdraw.status = status
  733. agent_account_withdraw.remark = remark
  734. agent_account_withdraw.save()
  735. if int(status) == 4:
  736. AgentAccount.objects.create(ac_id=agent_account_withdraw.ac_id,
  737. amount=agent_account_withdraw.amount,
  738. status=3,
  739. created_time = int(time.time()),
  740. updated_time = int(time.time()),
  741. remark = f"{userID}修改为已提现")
  742. return response.json(0)
  743. except Exception as e:
  744. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))