You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

reports.py 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from django.http import HttpResponse
  2. from django.utils.translation import ugettext_lazy as _
  3. from oscar.apps.dashboard.reports.csv_utils import CsvUnicodeWriter
  4. from oscar.core import utils
  5. class ReportGenerator(object):
  6. """
  7. Top-level class that needs to be subclassed to provide a
  8. report generator.
  9. """
  10. filename_template = 'report-%s-to-%s.csv'
  11. content_type = 'text/csv'
  12. code = ''
  13. description = '<insert report description>'
  14. def __init__(self, **kwargs):
  15. if 'start_date' in kwargs and 'end_date' in kwargs:
  16. self.start_date = kwargs['start_date']
  17. self.end_date = kwargs['end_date']
  18. self.formatter = self.formatters['%s_formatter' % kwargs['formatter']]()
  19. def report_description(self):
  20. return _('%(report_filter)s between %(start_date)s and %(end_date)s') % {
  21. 'report_filter': self.description,
  22. 'start_date': self.start_date,
  23. 'end_date': self.end_date,
  24. }
  25. def generate(self, response):
  26. pass
  27. def filename(self):
  28. """
  29. Returns the filename for this report
  30. """
  31. return self.formatter.filename()
  32. def is_available_to(self, user):
  33. """
  34. Checks whether this report is available to this user
  35. """
  36. return user.is_staff
  37. class ReportFormatter(object):
  38. def format_datetime(self, dt):
  39. if not dt:
  40. return ''
  41. return utils.format_datetime(dt, 'DATETIME_FORMAT')
  42. def format_date(self, d):
  43. if not d:
  44. return ''
  45. return utils.format_datetime(d, 'DATE_FORMAT')
  46. def filename(self):
  47. return self.filename_template
  48. class ReportCSVFormatter(ReportFormatter):
  49. def get_csv_writer(self, file_handle, **kwargs):
  50. return CsvUnicodeWriter(file_handle, **kwargs)
  51. def generate_response(self, objects, **kwargs):
  52. response = HttpResponse(content_type='text/csv')
  53. response['Content-Disposition'] = 'attachment; filename=%s' % self.filename(**kwargs)
  54. self.generate_csv(response, objects)
  55. return response
  56. class ReportHTMLFormatter(ReportFormatter):
  57. def generate_response(self, objects, **kwargs):
  58. return objects