admin.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from django.shortcuts import render, get_object_or_404
  4. from django.contrib import admin
  5. from django.contrib import messages
  6. from django.contrib.auth.admin import UserAdmin
  7. from django.contrib.auth.models import Group
  8. from django.http import HttpResponseRedirect
  9. from django.conf.urls import url
  10. from django.db.models.query import QuerySet
  11. from django.core.urlresolvers import reverse
  12. from django.utils.html import format_html
  13. from coin.members.models import (
  14. Member, CryptoKey, LdapUser, MembershipFee, OfferSubscription)
  15. from coin.members.membershipfee_filter import MembershipFeeFilter
  16. from coin.members.forms import MemberChangeForm, MemberCreationForm
  17. from coin.utils import delete_selected
  18. import autocomplete_light
  19. class CryptoKeyInline(admin.StackedInline):
  20. model = CryptoKey
  21. extra = 0
  22. class MembershipFeeInline(admin.TabularInline):
  23. model = MembershipFee
  24. extra = 0
  25. fields = ('start_date', 'end_date', 'amount', 'payment_method',
  26. 'reference', 'payment_date')
  27. class OfferSubscriptionInline(admin.TabularInline):
  28. model = OfferSubscription
  29. extra = 0
  30. readonly_fields = ('get_subscription_reference', 'subscription_date', 'resign_date',
  31. 'commitment', 'offer', 'show_change_link')
  32. # FIXME: Workaround en attendant la migration vers Django >=1.8
  33. # À remplacer par InlineModelAdmin.show_change_link = True
  34. def show_change_link(self, obj=None):
  35. url = reverse('admin:%s_%s_change' % (obj._meta.app_label,
  36. obj._meta.model_name),
  37. args=[obj.id])
  38. return format_html(u'<a href="{}">Éditer</a>', url)
  39. show_change_link.short_description = 'Éditer ?'
  40. def has_add_permission(self, request, obj=None):
  41. return False
  42. def has_delete_permission(self, request, obj=None):
  43. return False
  44. class MemberAdmin(UserAdmin):
  45. list_display = ('id', 'status', 'username', 'first_name', 'last_name',
  46. 'nickname', 'organization_name', 'email',
  47. 'end_date_of_membership')
  48. list_display_links = ('id', 'username', 'first_name', 'last_name')
  49. list_filter = ('status', MembershipFeeFilter)
  50. search_fields = ['username', 'first_name', 'last_name', 'email', 'nickname']
  51. ordering = ('status', 'username')
  52. actions = [delete_selected, 'set_as_member', 'set_as_non_member',
  53. 'bulk_send_welcome_email', 'bulk_send_call_for_membership_fee_email']
  54. form = MemberChangeForm
  55. add_form = MemberCreationForm
  56. fieldsets = (
  57. ('Adhérent', {'fields': (
  58. ('status', 'resign_date'),
  59. 'type',
  60. ('first_name', 'last_name', 'nickname'),
  61. 'organization_name',
  62. 'comments')}),
  63. ('Coordonnées', {'fields': (
  64. 'email',
  65. ('home_phone_number', 'mobile_phone_number'),
  66. 'address',
  67. ('postal_code', 'city', 'country'))}),
  68. ('Authentification', {'fields': (
  69. ('username', 'password'))}),
  70. ('Permissions', {'fields': (
  71. ('is_active', 'is_staff', 'is_superuser'))}),
  72. (None, {'fields': ('date_last_call_for_membership_fees_email',)})
  73. )
  74. add_fieldsets = (
  75. ('Adhérent', {'fields': (
  76. 'status',
  77. 'type',
  78. ('first_name', 'last_name', 'nickname'),
  79. 'organization_name',
  80. 'comments')}),
  81. ('Coordonnées', {'fields': (
  82. 'email',
  83. ('home_phone_number', 'mobile_phone_number'),
  84. 'address',
  85. ('postal_code', 'city', 'country'))}),
  86. ('Authentification', {'fields': (
  87. ('username', 'password'),)}),
  88. ('Permissions', {'fields': (
  89. ('is_active', 'is_staff', 'is_superuser', 'date_joined'))})
  90. )
  91. radio_fields = {"type": admin.HORIZONTAL}
  92. save_on_top = True
  93. inlines = [CryptoKeyInline, MembershipFeeInline, OfferSubscriptionInline]
  94. def get_readonly_fields(self, request, obj=None):
  95. if obj:
  96. # Remove help_text for readonly field (can't do that in the Form
  97. # django seems to user help_text from model for readonly fields)
  98. username_field = [
  99. f for f in obj._meta.fields if f.name == 'username']
  100. username_field[0].help_text = ''
  101. return ['username', ]
  102. else:
  103. return []
  104. def set_as_member(self, request, queryset):
  105. rows_updated = queryset.update(status='member')
  106. self.message_user(
  107. request,
  108. '%d membre(s) définis comme adhérent(s).' % rows_updated)
  109. set_as_member.short_description = 'Définir comme adhérent'
  110. def set_as_non_member(self, request, queryset):
  111. rows_updated = queryset.update(status='not_member')
  112. self.message_user(
  113. request,
  114. '%d membre(s) définis comme non adhérent(s).' % rows_updated)
  115. set_as_non_member.short_description = "Définir comme non adhérent"
  116. def get_urls(self):
  117. """Custom admin urls"""
  118. urls = super(MemberAdmin, self).get_urls()
  119. my_urls = [
  120. url(r'^send_welcome_email/(?P<id>\d+)$',
  121. self.admin_site.admin_view(self.send_welcome_email),
  122. name='send_welcome_email'),
  123. ]
  124. return my_urls + urls
  125. def send_welcome_email(self, request, id, return_httpredirect=True):
  126. """
  127. Vue appelée lorsque l'admin souhaite envoyer l'email de bienvenue à un
  128. membre.
  129. """
  130. # TODO : Add better perm here
  131. if request.user.is_superuser:
  132. member = get_object_or_404(Member, pk=id)
  133. member.send_welcome_email()
  134. messages.success(request,
  135. 'Le courriel de bienvenue a été envoyé à %s' % member.email)
  136. else:
  137. messages.error(
  138. request, 'Vous n\'avez pas l\'autorisation d\'envoyer des '
  139. 'courriels de bienvenue.')
  140. if return_httpredirect:
  141. return HttpResponseRedirect(reverse('admin:members_member_changelist'))
  142. def bulk_send_welcome_email(self, request, queryset):
  143. """
  144. Action appelée lorsque l'admin souhaite envoyer un lot d'email de bienvenue
  145. depuis une sélection de membre dans la vue liste de l'admin
  146. """
  147. for member in queryset.all():
  148. self.send_welcome_email(
  149. request, member.id, return_httpredirect=False)
  150. messages.success(request,
  151. 'Le courriel de bienvenue a été envoyé à %d membre(s).' % queryset.count())
  152. bulk_send_welcome_email.short_description = "Envoyer le courriel de bienvenue"
  153. def bulk_send_call_for_membership_fee_email(self, request, queryset):
  154. # TODO : Add better perm here
  155. if not request.user.is_superuser:
  156. messages.error(
  157. request, 'Vous n\'avez pas l\'autorisation d\'envoyer des '
  158. 'courriels de relance.')
  159. return
  160. cpt_success = 0
  161. for member in queryset.all():
  162. if member.send_call_for_membership_fees_email():
  163. cpt_success += 1
  164. else:
  165. messages.warning(request,
  166. "Le courriel de relance de cotisation n\'a pas "
  167. "été envoyé à {member} ({email}) car il a déjà "
  168. "reçu une relance le {last_call_date}"\
  169. .format(member=member,
  170. email=member.email,
  171. last_call_date=member.date_last_call_for_membership_fees_email))
  172. if queryset.count() == 1 and cpt_success == 1:
  173. member = queryset.first()
  174. messages.success(request,
  175. "Le courriel de relance de cotisation a été "
  176. "envoyé à {member} ({email})"\
  177. .format(member=member, email=member.email))
  178. elif cpt_success>1:
  179. messages.success(request,
  180. "Le courriel de relance de cotisation a été "
  181. "envoyé à {cpt} membres"\
  182. .format(cpt=cpt_success))
  183. bulk_send_call_for_membership_fee_email.short_description = 'Envoyer le courriel de relance de cotisation'
  184. class MembershipFeeAdmin(admin.ModelAdmin):
  185. list_display = ('member', 'end_date', 'amount', 'payment_method',
  186. 'payment_date')
  187. form = autocomplete_light.modelform_factory(MembershipFee, fields='__all__')
  188. admin.site.register(Member, MemberAdmin)
  189. admin.site.register(MembershipFee, MembershipFeeAdmin)
  190. admin.site.unregister(Group)
  191. # admin.site.register(LdapUser, LdapUserAdmin)