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