UserSubscriptionController.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UserSubscriptionController.py
  4. @Time : 2024/5/21 16:31
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import threading
  10. import time
  11. from django.http import QueryDict
  12. from django.views import View
  13. from Model.models import Device_User, CountryModel, UserEmailSubscriptions
  14. from Object.ResponseObject import ResponseObject
  15. from Object.TokenObject import TokenObject
  16. from Object.YotpoCoreObject import YotpoCoreObject
  17. from Ansjer.config import LOGGER
  18. class UserSubscriptionControllerView(View):
  19. def get(self, request, *args, **kwargs):
  20. request.encoding = 'utf-8'
  21. operation = kwargs.get('operation')
  22. return self.validation(request.GET, request, operation)
  23. def post(self, request, *args, **kwargs):
  24. request.encoding = 'utf-8'
  25. operation = kwargs.get('operation')
  26. return self.validation(request.POST, request, operation)
  27. def delete(self, request, *args, **kwargs):
  28. request.encoding = 'utf-8'
  29. operation = kwargs.get('operation')
  30. delete = QueryDict(request.body)
  31. if not delete:
  32. delete = request.GET
  33. return self.validation(delete, request, operation)
  34. def put(self, request, *args, **kwargs):
  35. request.encoding = 'utf-8'
  36. operation = kwargs.get('operation')
  37. put = QueryDict(request.body)
  38. return self.validation(put, request, operation)
  39. def validation(self, request_dict, request, operation):
  40. response = ResponseObject('cn')
  41. tko = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
  42. if tko.code != 0:
  43. return response.json(tko.code)
  44. response.lang = tko.lang
  45. userID = tko.userID
  46. if operation == 'checkSubscriptionStatus':
  47. return self.check_subscription_status(userID, response)
  48. elif operation == 'switchSubscription':
  49. return self.switch_subscription(userID, request_dict, response)
  50. else:
  51. return response.json(414)
  52. @staticmethod
  53. def check_subscription_status(user_id, response):
  54. """
  55. 检查订阅状态
  56. @param user_id: str
  57. @param response: 响应
  58. @return: response
  59. """
  60. user_qs = Device_User.objects.filter(userID=user_id)
  61. if not user_qs.exists():
  62. return response.json(104)
  63. user_sub = UserEmailSubscriptions.objects.filter(user_id=user_id).values('status').first()
  64. if not user_sub:
  65. return response.json(0, {"status": 0})
  66. user_sub = {"status": user_sub['status']}
  67. return response.json(0, user_sub)
  68. def switch_subscription(self, user_id, request_dict, response):
  69. """
  70. 订阅开关
  71. @param user_id: str
  72. @param request_dict: dict
  73. @param response
  74. """
  75. user_qs = Device_User.objects.filter(userID=user_id)
  76. status = request_dict.get('status', None)
  77. if not status:
  78. return response.json(444, "status")
  79. if not user_qs.exists():
  80. return response.json(104)
  81. # 修改数据库中订阅状态
  82. status = int(status)
  83. user_sub_qs = UserEmailSubscriptions.objects.filter(user_id=user_id)
  84. # 订阅
  85. if status == 1:
  86. subscribers = Device_User.objects.filter(userID=user_id).values('NickName', 'userEmail',
  87. 'region_country').first()
  88. if not subscribers["userEmail"]:
  89. LOGGER.info(f'subscribers{user_id}邮箱为空,无法订阅')
  90. return response.json(183)
  91. if user_sub_qs.exists():
  92. user_sub_qs.update(status=1, updated_time=int(time.time()))
  93. else:
  94. UserEmailSubscriptions.objects.create(user_id=user_id, status=1, email=subscribers["userEmail"],
  95. created_time=int(time.time()), updated_time=int(time.time()))
  96. subscription_thread = threading.Thread(target=self.subscription, args=(subscribers,))
  97. subscription_thread.start()
  98. # 取消订阅
  99. else:
  100. device_user = Device_User.objects.filter(userID=user_id).values('userEmail').first()
  101. if device_user:
  102. customer = {
  103. "email": device_user["userEmail"],
  104. "first_name": device_user["userEmail"],
  105. "last_name": "APP",
  106. }
  107. else:
  108. return response.json(0, {"status": status})
  109. yotpo = YotpoCoreObject()
  110. list_id = 8589406
  111. subscription_thread = threading.Thread(target=yotpo.close_subscribers, args=(customer, list_id))
  112. subscription_thread.start()
  113. if user_sub_qs.exists():
  114. customer["status"] = "unsubscription"
  115. user_sub_qs.update(status=0, sub_result=customer)
  116. return response.json(0, {"status": status})
  117. @staticmethod
  118. def subscription(subscribers):
  119. """
  120. 订阅
  121. @param subscribers: dict
  122. @return: boolean
  123. """
  124. yotpo = YotpoCoreObject()
  125. try:
  126. # 查询顾客所在地区
  127. if subscribers["region_country"]:
  128. country = CountryModel.objects.filter(id=subscribers["region_country"]).values('country_code').first()
  129. if country:
  130. country_code = country["country_code"]
  131. else:
  132. country_code = ''
  133. # 构建顾客订阅格式
  134. customer = {
  135. "email": subscribers["userEmail"],
  136. "first_name": subscribers["userEmail"],
  137. "last_name": "APP",
  138. 'address': {
  139. "country_code": country_code,
  140. },
  141. "custom_properties": {
  142. "subscription_office": "ZosiApp",
  143. }
  144. }
  145. else:
  146. customer = {
  147. "email": subscribers["userEmail"],
  148. "first_name": subscribers["userEmail"],
  149. "last_name": "APP",
  150. "custom_properties": {
  151. "subscription_office": "ZosiApp",
  152. }
  153. }
  154. result = yotpo.creat_and_update_customers(customer)
  155. list_id = 8589406
  156. sub_status, sub_result = yotpo.create_subscribers(customer, list_id)
  157. if result and sub_status:
  158. # 创建结果写入数据库
  159. user_sub_qs = UserEmailSubscriptions.objects.filter(email=subscribers["userEmail"])
  160. if user_sub_qs.exists():
  161. user_sub_qs.update(email=subscribers["userEmail"], status=1, sub_result=sub_result, list_id=list_id,
  162. updated_time=int(time.time()))
  163. LOGGER.info(f'在yotpo创建客户并订阅成功,customer:{customer}')
  164. return True
  165. else:
  166. LOGGER.info(f'在yotpo创建客户并订阅失败,customer:{customer}')
  167. return False
  168. except Exception as e:
  169. LOGGER.error(f'{subscribers["userEmail"]}订阅失败:{e}')
  170. return False