UserSubscriptionController.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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', 'push_sub_status').first()
  64. if not user_sub:
  65. UserEmailSubscriptions.objects.create(user_id=user_id, status=0, push_sub_status=1,
  66. updated_time=int(time.time()), created_time=int(time.time()))
  67. return response.json(0, {"emailSubStatus": 0, 'pushSubStatus': 1})
  68. email_sub_status = 1 if user_sub["status"] == 1 else 0
  69. push_sub_status = 0 if user_sub["push_sub_status"] == 0 else 1
  70. user_sub = {"emailSubStatus": email_sub_status, 'pushSubStatus': push_sub_status}
  71. return response.json(0, user_sub)
  72. def switch_subscription(self, user_id, request_dict, response):
  73. """
  74. 邮件订阅开关
  75. @param user_id: str
  76. @param request_dict: dict
  77. @param response
  78. """
  79. user_qs = Device_User.objects.filter(userID=user_id)
  80. email_sub_status = request_dict.get('emailSubStatus', None)
  81. push_sub_status = request_dict.get('pushSubStatus', None)
  82. if not email_sub_status and not push_sub_status:
  83. return response.json(444, "emailSubStatus or pushSubStatus")
  84. if not user_qs.exists():
  85. return response.json(104)
  86. # 用户推送订阅
  87. if push_sub_status:
  88. push_sub_status = int(push_sub_status)
  89. user_sub_qs = UserEmailSubscriptions.objects.filter(user_id=user_id)
  90. if user_sub_qs.exists():
  91. user_sub_qs.update(push_sub_status=push_sub_status, updated_time=int(time.time()))
  92. else:
  93. user = user_qs.values('userEmail', 'phone').first()
  94. push_sub = {
  95. "user_id": user_id,
  96. "push_sub_status": push_sub_status,
  97. "created_time": int(time.time()),
  98. "updated_time": int(time.time())
  99. }
  100. if user["userEmail"]:
  101. push_sub["email"] = user["userEmail"]
  102. if user["phone"]:
  103. push_sub["phone"] = user["phone"]
  104. UserEmailSubscriptions.objects.create(**push_sub)
  105. else:
  106. user_sub = UserEmailSubscriptions.objects.filter(user_id=user_id).values('status',
  107. 'push_sub_status').first()
  108. if not user_sub:
  109. push_sub_status = 1
  110. else:
  111. push_sub_status = user_sub["push_sub_status"]
  112. if email_sub_status:
  113. # 修改数据库中订阅状态
  114. email_sub_status = int(email_sub_status)
  115. user_sub_qs = UserEmailSubscriptions.objects.filter(user_id=user_id)
  116. # 邮件订阅
  117. if email_sub_status == 1:
  118. subscribers = user_qs.values('NickName', 'userEmail', 'region_country').first()
  119. if not subscribers["userEmail"]:
  120. LOGGER.info(f'subscribers{user_id}邮箱为空,无法订阅')
  121. return response.json(183)
  122. if user_sub_qs.exists():
  123. user_sub_qs.update(email=subscribers["userEmail"], status=1, updated_time=int(time.time()))
  124. else:
  125. UserEmailSubscriptions.objects.create(user_id=user_id, status=1, email=subscribers["userEmail"],
  126. created_time=int(time.time()), updated_time=int(time.time()))
  127. subscription_thread = threading.Thread(target=self.subscription, args=(subscribers,))
  128. subscription_thread.start()
  129. # 取消订阅
  130. elif email_sub_status == 0:
  131. device_user = Device_User.objects.filter(userID=user_id).values('userEmail').first()
  132. if device_user:
  133. customer = {
  134. "email": device_user["userEmail"],
  135. "first_name": device_user["userEmail"],
  136. "last_name": "APP",
  137. }
  138. yotpo = YotpoCoreObject()
  139. list_id = 8589406
  140. subscription_thread = threading.Thread(target=yotpo.close_subscribers, args=(customer, list_id))
  141. subscription_thread.start()
  142. if user_sub_qs.exists():
  143. customer["status"] = "unsubscription"
  144. user_sub_qs.update(email=device_user["userEmail"], status=0, sub_result=customer,
  145. updated_time=int(time.time()))
  146. else:
  147. user_sub = UserEmailSubscriptions.objects.filter(user_id=user_id).values('status').first()
  148. if not user_sub:
  149. email_sub_status = 0
  150. else:
  151. email_sub_status = user_sub["status"]
  152. return response.json(0, {"emailSubStatus": email_sub_status, "pushSubStatus": push_sub_status})
  153. @staticmethod
  154. def subscription(subscribers):
  155. """
  156. 订阅
  157. @param subscribers: dict
  158. @return: boolean
  159. """
  160. yotpo = YotpoCoreObject()
  161. try:
  162. # 查询顾客所在地区
  163. if subscribers["region_country"]:
  164. country = CountryModel.objects.filter(id=subscribers["region_country"]).values('country_code').first()
  165. if country:
  166. country_code = country["country_code"]
  167. else:
  168. country_code = ''
  169. # 构建顾客订阅格式
  170. customer = {
  171. "email": subscribers["userEmail"],
  172. "first_name": subscribers["userEmail"],
  173. "last_name": "APP",
  174. 'address': {
  175. "country_code": country_code,
  176. },
  177. "custom_properties": {
  178. "subscription_office": "ZosiApp",
  179. }
  180. }
  181. else:
  182. customer = {
  183. "email": subscribers["userEmail"],
  184. "first_name": subscribers["userEmail"],
  185. "last_name": "APP",
  186. "custom_properties": {
  187. "subscription_office": "ZosiApp",
  188. }
  189. }
  190. result = yotpo.creat_and_update_customers(customer)
  191. list_id = 8589406
  192. sub_status, sub_result = yotpo.create_subscribers(customer, list_id)
  193. if result and sub_status:
  194. # 创建结果写入数据库
  195. user_sub_qs = UserEmailSubscriptions.objects.filter(email=subscribers["userEmail"])
  196. if user_sub_qs.exists():
  197. user_sub_qs.update(email=subscribers["userEmail"], status=1, sub_result=sub_result, list_id=list_id,
  198. updated_time=int(time.time()))
  199. LOGGER.info(f'在yotpo创建客户并订阅成功,customer:{customer}')
  200. return True
  201. else:
  202. LOGGER.info(f'在yotpo创建客户并订阅失败,customer:{customer}')
  203. return False
  204. except Exception as e:
  205. LOGGER.error(f'{subscribers["userEmail"]}订阅失败:{e}')
  206. return False