# Path: api_v3/views/reviews.py
# class ReviewsEndpoint(
#         JSONApiEndpoint,
#         mixins.CreateModelMixin,
#         viewsets.GenericViewSet):
# 
#     permission_classes = (permissions.AllowAny,)
#     queryset = Review.objects.all()
#     serializer_class = ReviewSerializer
#     EMAIL_SUBJECT = 'Please review ticket ID: {}'
# 
#     def get_queryset(self):
#         queryset = super(ReviewsEndpoint, self).get_queryset()
# 
#         if self.request.user.is_superuser:
#             return queryset
# 
#         return queryset.none()
# 
#     def perform_create(self, serializer):
#         """Make sure every new comment is linked to current user."""
#         init_data = serializer.initial_data
#         ticket = Review.ticket_from_token(init_data.get('token'))
# 
#         if not ticket:
#             raise serializers.ValidationError(
#                 [{'attributes/ticket': {'detail': 'Ticket not found.'}}]
#             )
#         else:
#             review = serializer.save(ticket=ticket)
# 
#             Action.objects.create(
#                 action=review,
#                 target=ticket,
#                 verb=self.action_name()
#             )
# 
#             return review
# 
#     @staticmethod
#     @queue.task(schedule_at='7d')
#     def email_notify(_job_id, ticket_id, request_host):
#         """Sends an email to ticket users to leave a review."""
#         if settings.REVIEWS_DISABLED:
#             return
# 
#         emails = []
#         ticket = Ticket.objects.get(pk=ticket_id)
#         subject = ReviewsEndpoint.EMAIL_SUBJECT.format(ticket_id)
# 
#         # If the ticket status changed in the meantime, do not request reviews.
#         if ticket.status != Ticket.STATUSES[3][0]:
#             return None
# 
#         to_notify = [ticket.requester.__dict__]
#         to_notify += (
#             ticket.subscribers.filter(email__isnull=False).distinct('email')
#             .values('email')
#         )[:]
# 
#         for entry in to_notify:
#             emails.append([
#                 subject,
#                 render_to_string(
#                     'mail/review_request.txt', {
#                         'ticket': ticket,
#                         'token': Review.ticket_to_token(ticket),
#                         'days_to_respond': Review.MAX_DAYS_TO_RESPOND,
#                         'request_host': request_host,
#                         'site_name': settings.SITE_NAME
#                     }
#                 ),
#                 settings.DEFAULT_FROM_EMAIL,
#                 [entry['email']]
#             ])
# 
#         return send_mass_mail(emails), emails
# 
# Path: api_v3/views/ticket_exports.py
# class TicketExportsEndpoint(TicketsEndpoint):
#     TICKET_URI = 'https://{}/tickets/view/'
# 
#     permission_classes = (permissions.IsAdminUser, )
# 
#     def list(self, request, *args, **kwargs):
#         queryset = self.filter_queryset(self.get_queryset())
#         ticket_url = self.TICKET_URI.format(self.request.get_host())
# 
#         cols = dict(
#             Link=Concat(
#                 models.Value(ticket_url),
#                 models.F('id'),
#                 output_field=models.CharField()
#             ),
#             Email=models.F('requester__email'),
#             Date=models.F('created_at'),
#             Deadline=models.F('deadline_at'),
#             Status=models.F('status'),
#             Kind=models.F('kind'),
#             RequestType=models.F('request_type'),
#             Priority=models.F('priority'),
#             RequesterCountry=models.F('requester__country'),
#             OriginalCountry=models.F('country'),
#             ExtraCountries=models.Func(
#                 models.F('countries'),
#                 models.Value(','),
#                 function='ARRAY_TO_STRING',
#                 output_field=models.CharField()
#             ),
#             MemberCenter=models.F('member_center'),
#             Tags=models.Func(
#                 models.F('tags'),
#                 models.Value(','),
#                 function='ARRAY_TO_STRING',
#                 output_field=models.CharField()
#             )
#         )
# 
#         writer = DictWriter(DummyBuffer(), fieldnames=cols.keys())
#         header_with_rows = chain(
#             [dict(zip(cols.keys(), cols.keys()))],
#             queryset.values(**cols)
#         )
# 
#         response = StreamingHttpResponse(
#             streaming_content=(
#                 writer.writerow(row) for row in header_with_rows
#             ),
#             content_type='text/csv'
#         )
# 
#         response['Content-Disposition'] = (
#             'attachment; filename="tickets-{}.csv"'.format(
#                 datetime.utcnow().strftime('%x')))
# 
#         return response
# 
# class DummyBuffer:
#     """Dummy buffer to help stream the response."""
#     def write(self, value):
#         return value


from csv import DictWriter
from datetime import datetime
from itertools import chain
from django.db import models
from django.db.models.functions import Concat
from django.http import StreamingHttpResponse
from rest_framework import permissions
from .reviews import ReviewsEndpoint
from .ticket_exports import TicketExportsEndpoint, DummyBuffer




class ReviewExportsEndpoint(ReviewsEndpoint):
    permission_classes = (permissions.IsAdminUser, )

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        ticket_url = \
            TicketExportsEndpoint.TICKET_URI.format(self.request.get_host())

        cols = dict(
            Ticket=Concat(
                models.Value(ticket_url),
                models.F('ticket_id'),
                output_field=models.CharField()
            ),
            Date=models.F('created_at'),
            Rating=models.F('rating'),
            Link=models.F('link'),

# Path: api_v3/views/reviews.py
# class ReviewsEndpoint(
#         JSONApiEndpoint,
#         mixins.CreateModelMixin,
#         viewsets.GenericViewSet):
# 
#     permission_classes = (permissions.AllowAny,)
#     queryset = Review.objects.all()
#     serializer_class = ReviewSerializer
#     EMAIL_SUBJECT = 'Please review ticket ID: {}'
# 
#     def get_queryset(self):
#         queryset = super(ReviewsEndpoint, self).get_queryset()
# 
#         if self.request.user.is_superuser:
#             return queryset
# 
#         return queryset.none()
# 
#     def perform_create(self, serializer):
#         """Make sure every new comment is linked to current user."""
#         init_data = serializer.initial_data
#         ticket = Review.ticket_from_token(init_data.get('token'))
# 
#         if not ticket:
#             raise serializers.ValidationError(
#                 [{'attributes/ticket': {'detail': 'Ticket not found.'}}]
#             )
#         else:
#             review = serializer.save(ticket=ticket)
# 
#             Action.objects.create(
#                 action=review,
#                 target=ticket,
#                 verb=self.action_name()
#             )
# 
#             return review
# 
#     @staticmethod
#     @queue.task(schedule_at='7d')
#     def email_notify(_job_id, ticket_id, request_host):
#         """Sends an email to ticket users to leave a review."""
#         if settings.REVIEWS_DISABLED:
#             return
# 
#         emails = []
#         ticket = Ticket.objects.get(pk=ticket_id)
#         subject = ReviewsEndpoint.EMAIL_SUBJECT.format(ticket_id)
# 
#         # If the ticket status changed in the meantime, do not request reviews.
#         if ticket.status != Ticket.STATUSES[3][0]:
#             return None
# 
#         to_notify = [ticket.requester.__dict__]
#         to_notify += (
#             ticket.subscribers.filter(email__isnull=False).distinct('email')
#             .values('email')
#         )[:]
# 
#         for entry in to_notify:
#             emails.append([
#                 subject,
#                 render_to_string(
#                     'mail/review_request.txt', {
#                         'ticket': ticket,
#                         'token': Review.ticket_to_token(ticket),
#                         'days_to_respond': Review.MAX_DAYS_TO_RESPOND,
#                         'request_host': request_host,
#                         'site_name': settings.SITE_NAME
#                     }
#                 ),
#                 settings.DEFAULT_FROM_EMAIL,
#                 [entry['email']]
#             ])
# 
#         return send_mass_mail(emails), emails
# 
# Path: api_v3/views/ticket_exports.py
# class TicketExportsEndpoint(TicketsEndpoint):
#     TICKET_URI = 'https://{}/tickets/view/'
# 
#     permission_classes = (permissions.IsAdminUser, )
# 
#     def list(self, request, *args, **kwargs):
#         queryset = self.filter_queryset(self.get_queryset())
#         ticket_url = self.TICKET_URI.format(self.request.get_host())
# 
#         cols = dict(
#             Link=Concat(
#                 models.Value(ticket_url),
#                 models.F('id'),
#                 output_field=models.CharField()
#             ),
#             Email=models.F('requester__email'),
#             Date=models.F('created_at'),
#             Deadline=models.F('deadline_at'),
#             Status=models.F('status'),
#             Kind=models.F('kind'),
#             RequestType=models.F('request_type'),
#             Priority=models.F('priority'),
#             RequesterCountry=models.F('requester__country'),
#             OriginalCountry=models.F('country'),
#             ExtraCountries=models.Func(
#                 models.F('countries'),
#                 models.Value(','),
#                 function='ARRAY_TO_STRING',
#                 output_field=models.CharField()
#             ),
#             MemberCenter=models.F('member_center'),
#             Tags=models.Func(
#                 models.F('tags'),
#                 models.Value(','),
#                 function='ARRAY_TO_STRING',
#                 output_field=models.CharField()
#             )
#         )
# 
#         writer = DictWriter(DummyBuffer(), fieldnames=cols.keys())
#         header_with_rows = chain(
#             [dict(zip(cols.keys(), cols.keys()))],
#             queryset.values(**cols)
#         )
# 
#         response = StreamingHttpResponse(
#             streaming_content=(
#                 writer.writerow(row) for row in header_with_rows
#             ),
#             content_type='text/csv'
#         )
# 
#         response['Content-Disposition'] = (
#             'attachment; filename="tickets-{}.csv"'.format(
#                 datetime.utcnow().strftime('%x')))
# 
#         return response
# 
# class DummyBuffer:
#     """Dummy buffer to help stream the response."""
#     def write(self, value):
#         return value


# Path: api_v3/views/review_exports.py
from csv import DictWriter
from datetime import datetime
from itertools import chain
from django.db import models
from django.db.models.functions import Concat
from django.http import StreamingHttpResponse
from rest_framework import permissions
from .reviews import ReviewsEndpoint
from .ticket_exports import TicketExportsEndpoint, DummyBuffer





class ReviewExportsEndpoint(ReviewsEndpoint):
    permission_classes = (permissions.IsAdminUser, )

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        ticket_url = \
            TicketExportsEndpoint.TICKET_URI.format(self.request.get_host())

        cols = dict(
            Ticket=Concat(
                models.Value(ticket_url),
                models.F('ticket_id'),
                output_field=models.CharField()
            ),
            Date=models.F('created_at'),
            Rating=models.F('rating'),
            Link=models.F('link'),

            Comment=models.F('body')