# Path: api_v3/views/expenses.py
# class ExpensesEndpoint(
#         JSONApiEndpoint,
#         mixins.CreateModelMixin,
#         mixins.DestroyModelMixin,
#         mixins.UpdateModelMixin,
#         viewsets.ReadOnlyModelViewSet):
# 
#     queryset = Expense.objects.all()
#     serializer_class = ExpenseSerializer
#     ordering_fields = ('created_at', 'updated_at')
#     filter_fields = {
#         'created_at': ['range'],
#         'scope': ['exact'],
#         'payment_method': ['exact'],
#         'ticket': ['exact'],
#         'user': ['exact']
#     }
# 
#     def get_queryset(self):
#         queryset = super(ExpensesEndpoint, self).get_queryset()
# 
#         if self.request.user.is_staff or self.request.user.is_superuser:
#             return queryset
# 
#         return queryset.none()
# 
#     def perform_create(self, serializer):
#         """Make sure every new expense is linked to current user."""
#         if not (self.request.user.is_staff or self.request.user.is_superuser):
#             raise serializers.ValidationError(
#                 [{'attributes/ticket': {'detail': 'Ticket not found.'}}]
#             )
# 
#         expense = serializer.save(user=self.request.user)
# 
#         Action.objects.create(
#             action=expense,
#             target=expense.ticket,
#             actor=self.request.user,
#             verb=self.action_name()
#         )
# 
#         return expense
# 
#     def perform_update(self, serializer):
#         """Allow only super users and ticket responders to update the expense"""
#         if not (self.request.user.is_staff or self.request.user.is_superuser):
#             raise exceptions.NotFound()
# 
#         return serializer.save()
# 
#     def perform_destroy(self, instance):
#         """Make sure only super user or author can remove the expense."""
#         if not (self.request.user.is_staff or self.request.user.is_superuser):
#             raise exceptions.NotFound()
# 
#         Action.objects.create(
#             actor=self.request.user, target=instance.ticket,
#             action=instance.user, verb=self.action_name())
# 
#         return instance.delete()
# 
# 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 .expenses import ExpensesEndpoint
from .ticket_exports import TicketExportsEndpoint, DummyBuffer




class ExpenseExportsEndpoint(ExpensesEndpoint):
    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(
            Link=Concat(

# Path: api_v3/views/expenses.py
# class ExpensesEndpoint(
#         JSONApiEndpoint,
#         mixins.CreateModelMixin,
#         mixins.DestroyModelMixin,
#         mixins.UpdateModelMixin,
#         viewsets.ReadOnlyModelViewSet):
# 
#     queryset = Expense.objects.all()
#     serializer_class = ExpenseSerializer
#     ordering_fields = ('created_at', 'updated_at')
#     filter_fields = {
#         'created_at': ['range'],
#         'scope': ['exact'],
#         'payment_method': ['exact'],
#         'ticket': ['exact'],
#         'user': ['exact']
#     }
# 
#     def get_queryset(self):
#         queryset = super(ExpensesEndpoint, self).get_queryset()
# 
#         if self.request.user.is_staff or self.request.user.is_superuser:
#             return queryset
# 
#         return queryset.none()
# 
#     def perform_create(self, serializer):
#         """Make sure every new expense is linked to current user."""
#         if not (self.request.user.is_staff or self.request.user.is_superuser):
#             raise serializers.ValidationError(
#                 [{'attributes/ticket': {'detail': 'Ticket not found.'}}]
#             )
# 
#         expense = serializer.save(user=self.request.user)
# 
#         Action.objects.create(
#             action=expense,
#             target=expense.ticket,
#             actor=self.request.user,
#             verb=self.action_name()
#         )
# 
#         return expense
# 
#     def perform_update(self, serializer):
#         """Allow only super users and ticket responders to update the expense"""
#         if not (self.request.user.is_staff or self.request.user.is_superuser):
#             raise exceptions.NotFound()
# 
#         return serializer.save()
# 
#     def perform_destroy(self, instance):
#         """Make sure only super user or author can remove the expense."""
#         if not (self.request.user.is_staff or self.request.user.is_superuser):
#             raise exceptions.NotFound()
# 
#         Action.objects.create(
#             actor=self.request.user, target=instance.ticket,
#             action=instance.user, verb=self.action_name())
# 
#         return instance.delete()
# 
# 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/expense_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 .expenses import ExpensesEndpoint
from .ticket_exports import TicketExportsEndpoint, DummyBuffer





class ExpenseExportsEndpoint(ExpensesEndpoint):
    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(
            Link=Concat(

                models.Value(ticket_url),