import logging from django.utils.translation import gettext as _ from django.forms.models import model_to_dict from rest_framework.response import Response from rest_framework.exceptions import NotFound from pingcap_sso.api.base import AskTUGAdminEndpoint from pingcap_sso.api.permissions import AskTUGModeratorOrStaffWithMethodPermission from pingcap_sso.lib.user import ( user_activities, user_profile_for_marketing ) from pingcap_sso.utils import time as ptime from pingcap_sso.discourse.models import DiscoursePost, DiscourseTopic from pingcap_sso.discourse.consts import QA_FEEDBACK_CATEGORIES from pingcap_sso.models import ( User, OrganizationUser, UserTiDBUsage, UserDailyActivity ) logger = logging.getLogger(__name__) class UserDetailEndpoint(AskTUGAdminEndpoint): permission_classes = (AskTUGModeratorOrStaffWithMethodPermission, ) perms_map = { 'GET': ['pingcap_sso.view_user_profile'] } def get(self, request, username, *args, **kwargs): """audit_log: 在 AskTUG 插件中查看了用户详情""" access_user = request.user try: user = User.objects.get(username=username) except Exception: raise NotFound topic_count = DiscourseTopic.objects.filter( deleted_at__isnull=True, visible=True, archetype='regular', user__username=user.username ).count() post_count = DiscoursePost.objects.filter( topic__deleted_at__isnull=True, topic__visible=True, topic__archetype='regular', deleted_at__isnull=True, hidden=False, post_type=1, user__username=user.username ).exclude(post_number=1).count() activites, activites_date_range = user_activities(user) data = { 'username': user.username, 'points': user.point_stat.points, 'exps': user.point_stat.experience, 'topic_count': topic_count, 'post_count': post_count, 'pass_pcta': user.pass_pcta, 'pass_pctp': user.pass_pctp, 'pass_pcsd': user.pass_pcsd, 'is_contributor': user.is_contributor, 'active_map': activites, 'active_date_range': activites_date_range, } if access_user.is_staff_with_permission: try: org = OrganizationUser.objects.get(user=user).organization org_info = { 'name': org.name, 'slug': org.slug } except OrganizationUser.DoesNotExist: org_info = None try: staff_annotation = { 'content': user.userstaffannotation.content, 'editor': user.userstaffannotation.editor.username, 'updated_at': ptime.local_time_format(user.userstaffannotation.updated_at) } except User.userstaffannotation.RelatedObjectDoesNotExist: staff_annotation = None profile = user_profile_for_marketing(user) data.update({ 'org': org_info, 'name': profile['name'], 'company_name': profile['company'], 'job_title_text': profile['job_title'], 'address': profile['address'], 'joined_at': user.date_joined.strftime('%Y/%m/%d %H:%M'), 'signup_channel': user.signup_channel, 'last_login_at': ptime.local_time_format(user.last_login) if user.last_login else None, 'staff_annotation': staff_annotation }) return Response({ 'detail': _('success'), 'data': data, 'is_staff': access_user.is_staff_with_permission, 'is_moderator': access_user.is_asktug_moderator }) class UserActivityDetailEndpoint(AskTUGAdminEndpoint): permission_classes = (AskTUGModeratorOrStaffWithMethodPermission, ) perms_map = { 'GET': ['pingcap_sso.view_user_profile'] } def get(self, request, username, *arg, **kwargs): """audit_log: 在 AskTUG 插件中查看了用户热力图详情""" day = request.GET.get('day') try: activity = UserDailyActivity.objects.get( user__username=username, day=day ) except Exception: raise NotFound detail = [] for field, value in model_to_dict( activity, exclude=['id', 'user', 'day', 'community_score', 'track_events_count'] ).items(): if value == 0: continue detail.append({ 'help_text': UserDailyActivity._meta.get_field(field).help_text, 'value': value }) return Response({ 'detail': _('success'), 'data': { 'score': activity.community_score, 'day': activity.day.strftime('%Y-%m-%d'), 'track_events_count': activity.track_events_count, 'detail': detail } })