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