0a96792f1db624ee5bddb45f49a6c890c19cc8cd
[edumed.git] / contact / admin.py
1 # -*- coding: utf-8 -*-
2 import csv
3
4 from django.contrib import admin
5 from django.utils.translation import ugettext as _
6 from django.utils.safestring import mark_safe
7 from django.conf.urls import patterns, url
8 from django.http import HttpResponse, Http404
9
10 from edumed.utils import UnicodeCSVWriter
11 from .forms import contact_forms, admin_list_width
12 from .models import Contact
13
14
15 class ContactAdminMeta(admin.ModelAdmin.__class__):
16     def __getattr__(cls, name):
17         if name.startswith('admin_list_'):
18             return lambda self: ""
19         raise AttributeError(name)
20
21
22 class ContactAdmin(admin.ModelAdmin):
23     __metaclass__ = ContactAdminMeta
24     date_hierarchy = 'created_at'
25     list_display = ['created_at', 'contact', 'form_tag'] + \
26         ["admin_list_%d" % i for i in range(admin_list_width)]
27     fields = ['form_tag', 'created_at', 'contact', 'ip']
28     readonly_fields = ['form_tag', 'created_at', 'contact', 'ip']
29     list_filter = ['form_tag']
30
31     @staticmethod
32     def admin_list(obj, nr):
33         try:
34             field_name = contact_forms[obj.form_tag].admin_list[nr]
35         except BaseException:
36             return ''
37         else:
38             return Contact.pretty_print(obj.body.get(field_name, ''), for_html=True)
39
40     def __getattr__(self, name):
41         if name.startswith('admin_list_'):
42             nr = int(name[len('admin_list_'):])
43             return lambda obj: self.admin_list(obj, nr)
44         raise AttributeError(name)
45
46     def change_view(self, request, object_id, form_url='', extra_context=None):
47         if object_id:
48             try:
49                 instance = Contact.objects.get(pk=object_id)
50                 assert isinstance(instance.body, dict)
51             except (Contact.DoesNotExist, AssertionError):
52                 pass
53             else:
54                 # Create readonly fields from the body JSON.
55                 body_fields = ['body__%s' % k for k in instance.body.keys()]
56                 attachments = list(instance.attachment_set.all())
57                 body_fields += ['body__%s' % a.tag for a in attachments]
58                 self.readonly_fields.extend(body_fields)
59
60                 # Find the original form.
61                 try:
62                     orig_fields = contact_forms[instance.form_tag]().fields
63                 except KeyError:
64                     orig_fields = {}
65
66                 # Try to preserve the original order.
67                 admin_fields = []
68                 orig_keys = list(orig_fields.keys())
69                 while orig_keys:
70                     key = orig_keys.pop(0)
71                     key = "body__%s" % key
72                     if key in body_fields:
73                         admin_fields.append(key)
74                         body_fields.remove(key)
75                 admin_fields.extend(body_fields)
76
77                 self.fieldsets = [
78                     (None, {'fields': self.fields}),
79                     (_('Body'), {'fields': admin_fields}),
80                 ]
81
82                 # Create field getters for fields and attachments.
83                 for k, v in instance.body.items():
84                     f = (lambda v: lambda self: v)(Contact.pretty_print(v, for_html=True))
85                     f.short_description = orig_fields[k].label if k in orig_fields else _(k)
86                     setattr(self, "body__%s" % k, f)
87
88                 download_link = "<a href='%(url)s'>%(url)s</a>"
89                 for attachment in attachments:
90                     k = attachment.tag
91                     link = mark_safe(download_link % {
92                             'url': attachment.get_absolute_url()})
93                     f = (lambda v: lambda self: v)(link)
94                     f.short_description = orig_fields[k].label if k in orig_fields else _(k)
95                     setattr(self, "body__%s" % k, f)
96         return super(ContactAdmin, self).change_view(
97             request, object_id, form_url=form_url, extra_context=extra_context)
98
99     def changelist_view(self, request, extra_context=None):
100         context = dict()
101         if 'form_tag' in request.GET:
102             form = contact_forms.get(request.GET['form_tag'])
103             context['extract_types'] = [
104                 {'slug': 'all', 'label': _('all')},
105                 {'slug': 'contacts', 'label': _('contacts')}]
106             context['extract_types'] += [type for type in getattr(form, 'extract_types', [])]
107         return super(ContactAdmin, self).changelist_view(request, extra_context=context)
108
109     def get_urls(self):
110         # urls = super(ContactAdmin, self).get_urls()
111         return patterns(
112             '',
113             url(r'^extract/(?P<form_tag>[\w-]+)/(?P<extract_type_slug>[\w-]+)/$',
114                 self.admin_site.admin_view(extract_view), name='contact_extract')
115         ) + super(ContactAdmin, self).get_urls()
116
117
118 def extract_view(request, form_tag, extract_type_slug):
119     contacts_by_spec = dict()
120     form = contact_forms.get(form_tag)
121     if form is None and extract_type_slug not in ('contacts', 'all'):
122         raise Http404
123
124     q = Contact.objects.filter(form_tag=form_tag)
125     at_year = request.GET.get('created_at__year')
126     at_month = request.GET.get('created_at__month')
127     if at_year:
128         q = q.filter(created_at__year=at_year)
129         if at_month:
130             q = q.filter(created_at__month=at_month)
131
132     # Segregate contacts by body key sets
133     for contact in q.all():
134         if extract_type_slug == 'contacts':
135             keys = ['contact']
136         elif extract_type_slug == 'all':
137             keys = contact.body.keys() + ['contact']
138         else:
139             keys = form.get_extract_fields(contact, extract_type_slug)
140         contacts_by_spec.setdefault(tuple(keys), []).append(contact)
141
142     response = HttpResponse(content_type='text/csv')
143     csv_writer = UnicodeCSVWriter(response)
144
145     # Generate list for each body key set
146     for keys, contacts in contacts_by_spec.items():
147         csv_writer.writerow(keys)
148         for contact in contacts:
149             if extract_type_slug == 'contacts':
150                 records = [dict(contact=contact.contact)]
151             elif extract_type_slug == 'all':
152                 records = [dict(contact=contact.contact, **contact.body)]
153             else:
154                 records = form.get_extract_records(keys, contact, extract_type_slug)
155
156             for record in records:
157                 for key in keys:
158                     if key not in record:
159                         record[key] = ''
160                     if isinstance(record[key], bool):
161                         record[key] = 'tak' if record[key] else 'nie'
162                     if isinstance(record[key], (list, tuple)):
163                         record[key] = ', '.join(record[key])
164
165                 csv_writer.writerow([record[key] for key in keys])
166         csv_writer.writerow([])
167
168     response['Content-Disposition'] = 'attachment; filename="kontakt.csv"'
169     return response
170
171 admin.site.register(Contact, ContactAdmin)