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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. formatter_name = '%s_formatter' % kwargs['formatter']
  19. self.formatter = self.formatters[formatter_name]()
  20. def report_description(self):
  21. return _('%(report_filter)s between %(start_date)s and %(end_date)s') \
  22. % {'report_filter': self.description,
  23. 'start_date': self.start_date,
  24. 'end_date': self.end_date,
  25. }
  26. def generate(self, response):
  27. pass
  28. def filename(self):
  29. """
  30. Returns the filename for this report
  31. """
  32. return self.formatter.filename()
  33. def is_available_to(self, user):
  34. """
  35. Checks whether this report is available to this user
  36. """
  37. return user.is_staff
  38. class ReportFormatter(object):
  39. def format_datetime(self, dt):
  40. if not dt:
  41. return ''
  42. return utils.format_datetime(dt, 'DATETIME_FORMAT')
  43. def format_date(self, d):
  44. if not d:
  45. return ''
  46. return utils.format_datetime(d, 'DATE_FORMAT')
  47. def filename(self):
  48. return self.filename_template
  49. class ReportCSVFormatter(ReportFormatter):
  50. def get_csv_writer(self, file_handle, **kwargs):
  51. return CsvUnicodeWriter(file_handle, **kwargs)
  52. def generate_response(self, objects, **kwargs):
  53. response = HttpResponse(content_type='text/csv')
  54. response['Content-Disposition'] = 'attachment; filename=%s' \
  55. % self.filename(**kwargs)
  56. self.generate_csv(response, objects)
  57. return response
  58. class ReportHTMLFormatter(ReportFormatter):
  59. def generate_response(self, objects, **kwargs):
  60. return objects