admin.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # -*- coding: utf-8 -*-
  2. from __future__ import unicode_literals
  3. from datetime import date
  4. from django.shortcuts import get_object_or_404
  5. from django.contrib import admin
  6. from django.contrib import messages
  7. from django.contrib.admin import SimpleListFilter
  8. from django.contrib.auth.admin import UserAdmin
  9. from django.contrib.contenttypes.models import ContentType
  10. from django.http import HttpResponseRedirect
  11. from django.conf.urls import url
  12. from django.conf import settings
  13. from django.core.urlresolvers import reverse
  14. from django.utils.safestring import mark_safe
  15. from coin.members.models import (
  16. Member, CryptoKey, LdapUser, MembershipFee, Offer, OfferSubscription, RowLevelPermission)
  17. from coin.members.forms import AdminMemberChangeForm, MemberCreationForm
  18. from coin.utils import delete_selected
  19. import autocomplete_light
  20. class CryptoKeyInline(admin.StackedInline):
  21. model = CryptoKey
  22. extra = 0
  23. class MembershipFeeInline(admin.TabularInline):
  24. model = MembershipFee
  25. extra = 0
  26. fields = ('start_date', 'end_date', 'amount', 'payment_method',
  27. 'reference', 'payment_date')
  28. class OfferSubscriptionInline(admin.TabularInline):
  29. model = OfferSubscription
  30. extra = 0
  31. writable_fields = ('subscription_date', 'resign_date', 'commitment', 'offer')
  32. all_fields = ('get_subscription_reference',) + writable_fields
  33. def get_fields(self, request, obj=None):
  34. if obj:
  35. return self.all_fields
  36. else:
  37. return self.writable_fields
  38. def get_readonly_fields(self, request, obj=None):
  39. # création ou superuser : lecture écriture
  40. if not obj or request.user.is_superuser:
  41. return ('get_subscription_reference',)
  42. # modification : lecture seule seulement
  43. else:
  44. return self.all_fields
  45. show_change_link = True
  46. def formfield_for_foreignkey(self, db_field, request, **kwargs):
  47. if request.user.is_superuser:
  48. return super(OfferSubscriptionInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
  49. else:
  50. if db_field.name == "offer":
  51. kwargs["queryset"] = Offer.objects.manageable_by(request.user)
  52. return super(OfferSubscriptionInline, self).formfield_for_foreignkey(db_field, request, **kwargs)
  53. def has_add_permission(self, request):
  54. # - Quand on *crée* un membre on autorise à ajouter un abonnement
  55. # - Quand on *édite* un membre, on interdit l'ajout d'abonnements (sauf
  56. # par le bureau) car cela permettrait de gagner à loisir accès à
  57. # toute fiche adhérent en lui ajoutant un abonnement à une offre dont
  58. # on a la gestion).
  59. return (
  60. request.resolver_match.view_name == 'admin:members_member_add'
  61. or
  62. request.user.is_superuser
  63. )
  64. # sinon on pourrait supprimer les abo qu'on ne peut pas gérer
  65. # pourrait peut-être être plus fin, obj réfère ici au member de la page
  66. def has_delete_permission(self, request, obj=None):
  67. return request.user.is_superuser
  68. class DataRetentionFilter(SimpleListFilter):
  69. # Human-readable title which will be displayed in the
  70. # right admin sidebar just above the filter options.
  71. title = 'péremption des données'
  72. # Parameter for the filter that will be used in the URL query.
  73. parameter_name = 'data_cleanup'
  74. def lookups(self, request, model_admin):
  75. return (
  76. ('pending_deletion', 'Pouvant légalement être supprimé'),
  77. )
  78. def queryset(self, request, queryset):
  79. if self.value() == 'pending_deletion':
  80. return queryset.could_be_deleted()
  81. class MembershipFeeFilter(SimpleListFilter):
  82. # Human-readable title which will be displayed in the
  83. # right admin sidebar just above the filter options.
  84. title = 'Cotisations'
  85. # Parameter for the filter that will be used in the URL query.
  86. parameter_name = 'fee'
  87. def lookups(self, request, model_admin):
  88. return (
  89. ('paidup', 'À jour de cotisation'),
  90. ('late', 'En retard'),
  91. )
  92. def queryset(self, request, queryset):
  93. if self.value() == 'paidup':
  94. return queryset.paidup_fee()
  95. if self.value() == 'late':
  96. return queryset.no_fee_or_late()
  97. class MemberAdmin(UserAdmin):
  98. list_display = ('id', 'status', 'username', 'first_name',
  99. 'name_or_organization_name',
  100. 'nickname', 'email',
  101. 'enhanced_end_date_of_membership')
  102. list_display_links = ('id', 'username', 'first_name', 'name_or_organization_name')
  103. list_filter = ('status', MembershipFeeFilter, DataRetentionFilter)
  104. search_fields = ['username', 'first_name', 'last_name', 'email', 'nickname']
  105. ordering = ('status', 'username')
  106. actions = [delete_selected, 'set_as_member', 'set_as_non_member',
  107. 'bulk_send_welcome_email', 'bulk_send_call_for_membership_fee_email']
  108. form = AdminMemberChangeForm
  109. add_form = MemberCreationForm
  110. def name_or_organization_name(self, obj):
  111. """ Used to spare some horizontal space in list view"""
  112. return obj.organization_name or obj.last_name
  113. name_or_organization_name.short_description = 'Nom'
  114. def enhanced_end_date_of_membership(self, obj):
  115. membership_end = obj.end_date_of_membership()
  116. active_subscriptions = obj.get_active_subscriptions()
  117. recent_inactive_subscriptions = obj.get_recent_inactive_subscriptions()
  118. note = ''
  119. tooltip = ''
  120. if (membership_end is not None and membership_end < date.today()
  121. and recent_inactive_subscriptions.exists() and not active_subscriptions.exists()):
  122. note = ' <i class="fa fa-question-circle" style="color: #cccc40"></i>'
  123. tooltip = (
  124. "Cet·te ancien·ne adhérent·e a un service résilié depuis moins d'un an. "
  125. "Légalement, il faut conserver sa fiche un an après la résiliation du service."
  126. )
  127. if (active_subscriptions.exists() and (
  128. membership_end is None or membership_end <= date.today())):
  129. note = ' <i class="fa fa-question-circle" style="color: red"></i>'
  130. tooltip = (
  131. "Cet·te adhérent·e bénéficie d'un service mais n'est pas à jour de cotisation."
  132. )
  133. out = '{}{}'.format(
  134. obj.end_date_of_membership() or "pas de cotisation", note)
  135. if note:
  136. return mark_safe('<span style="cursor: help;" title="{}">{}</span>'.format(tooltip, out))
  137. else:
  138. return mark_safe(out)
  139. return mark_safe()
  140. enhanced_end_date_of_membership.short_description = "Date de fin d'adhésion"
  141. def get_fieldsets(self, request, obj=None):
  142. coord_fieldset = ('Coordonnées', {'fields': (
  143. ('email', 'send_membership_fees_email'),
  144. ('home_phone_number', 'mobile_phone_number'),
  145. 'address',
  146. ('postal_code', 'city', 'country'))})
  147. auth_fieldset = ('Authentification', {'fields': (
  148. ('username', 'password'))})
  149. perm_fieldset = ('Permissions', {'fields': (
  150. ('is_active', 'is_staff', 'is_superuser', 'groups'))})
  151. # if obj is null then it is a creation, otherwise it is a modification
  152. if obj:
  153. fieldsets = (
  154. ('Adhérent', {'fields': (
  155. ('status', 'date_joined', 'resign_date'),
  156. 'type',
  157. ('first_name', 'last_name', 'nickname'),
  158. 'organization_name',
  159. 'comments'
  160. )}),
  161. coord_fieldset,
  162. auth_fieldset,
  163. perm_fieldset,
  164. (None, {'fields': ('date_last_call_for_membership_fees_email',)})
  165. )
  166. else:
  167. fieldsets = (
  168. ('Adhérent', {'fields': (
  169. ('status', 'date_joined'),
  170. 'type',
  171. ('first_name', 'last_name', 'nickname'),
  172. 'organization_name',
  173. 'comments')}),
  174. coord_fieldset,
  175. auth_fieldset,
  176. perm_fieldset
  177. )
  178. if settings.HANDLE_BALANCE:
  179. fieldsets[0][1]['fields'] += ('balance',)
  180. return fieldsets
  181. radio_fields = {"type": admin.HORIZONTAL}
  182. save_on_top = True
  183. inlines = [CryptoKeyInline, MembershipFeeInline, OfferSubscriptionInline]
  184. def get_queryset(self, request):
  185. qs = super(MemberAdmin, self).get_queryset(request)
  186. if request.user.is_superuser:
  187. return qs
  188. else:
  189. offers = Offer.objects.manageable_by(request.user)
  190. return qs.filter(offersubscription__offer__in=offers).distinct()
  191. def get_readonly_fields(self, request, obj=None):
  192. readonly_fields = []
  193. if obj:
  194. # Remove help_text for readonly field (can't do that in the Form
  195. # django seems to user help_text from model for readonly fields)
  196. username_field = [
  197. f for f in obj._meta.fields if f.name == 'username']
  198. username_field[0].help_text = ''
  199. readonly_fields.append('username')
  200. if not request.user.is_superuser:
  201. readonly_fields += ['is_active', 'is_staff', 'is_superuser', 'groups', 'date_last_call_for_membership_fees_email']
  202. return readonly_fields
  203. def set_as_member(self, request, queryset):
  204. rows_updated = queryset.update(status='member')
  205. self.message_user(
  206. request,
  207. '%d membre(s) définis comme adhérent(s).' % rows_updated)
  208. set_as_member.short_description = 'Définir comme adhérent'
  209. def set_as_non_member(self, request, queryset):
  210. rows_updated = queryset.update(status='not_member')
  211. self.message_user(
  212. request,
  213. '%d membre(s) définis comme non adhérent(s).' % rows_updated)
  214. set_as_non_member.short_description = "Définir comme non adhérent"
  215. def get_urls(self):
  216. """Custom admin urls"""
  217. urls = super(MemberAdmin, self).get_urls()
  218. my_urls = [
  219. url(r'^send_welcome_email/(?P<id>\d+)$',
  220. self.admin_site.admin_view(self.send_welcome_email),
  221. name='send_welcome_email'),
  222. ]
  223. return my_urls + urls
  224. def send_welcome_email(self, request, id, return_httpredirect=True):
  225. """
  226. Vue appelée lorsque l'admin souhaite envoyer l'email de bienvenue à un
  227. membre.
  228. """
  229. # TODO : Add better perm here
  230. if request.user.is_superuser:
  231. member = get_object_or_404(Member, pk=id)
  232. member.send_welcome_email()
  233. messages.success(request,
  234. 'Le courriel de bienvenue a été envoyé à %s' % member.email)
  235. else:
  236. messages.error(
  237. request, 'Vous n\'avez pas l\'autorisation d\'envoyer des '
  238. 'courriels de bienvenue.')
  239. if return_httpredirect:
  240. return HttpResponseRedirect(reverse('admin:members_member_changelist'))
  241. def bulk_send_welcome_email(self, request, queryset):
  242. """
  243. Action appelée lorsque l'admin souhaite envoyer un lot d'email de bienvenue
  244. depuis une sélection de membre dans la vue liste de l'admin
  245. """
  246. for member in queryset.all():
  247. self.send_welcome_email(
  248. request, member.id, return_httpredirect=False)
  249. messages.success(request,
  250. 'Le courriel de bienvenue a été envoyé à %d membre(s).' % queryset.count())
  251. bulk_send_welcome_email.short_description = "Envoyer le courriel de bienvenue"
  252. def bulk_send_call_for_membership_fee_email(self, request, queryset):
  253. # TODO : Add better perm here
  254. if not request.user.is_superuser:
  255. messages.error(
  256. request, 'Vous n\'avez pas l\'autorisation d\'envoyer des '
  257. 'courriels de relance.')
  258. return
  259. cpt_success = 0
  260. for member in queryset.all():
  261. if member.send_call_for_membership_fees_email():
  262. cpt_success += 1
  263. else:
  264. messages.warning(request,
  265. "Le courriel de relance de cotisation n\'a pas "
  266. "été envoyé à {member} ({email}) car il a déjà "
  267. "reçu une relance le {last_call_date}"\
  268. .format(member=member,
  269. email=member.email,
  270. last_call_date=member.date_last_call_for_membership_fees_email))
  271. if cpt_success == 1:
  272. member = queryset.first()
  273. messages.success(request,
  274. "Le courriel de relance de cotisation a été "
  275. "envoyé à {member} ({email})"\
  276. .format(member=member, email=member.email))
  277. elif cpt_success > 1:
  278. messages.success(request,
  279. "Le courriel de relance de cotisation a été "
  280. "envoyé à {cpt} membres"\
  281. .format(cpt=cpt_success))
  282. bulk_send_call_for_membership_fee_email.short_description = 'Envoyer le courriel de relance de cotisation'
  283. class MembershipFeeAdmin(admin.ModelAdmin):
  284. list_display = ('member', 'end_date', 'amount', 'payment_method',
  285. 'payment_date')
  286. form = autocomplete_light.modelform_factory(MembershipFee, fields='__all__')
  287. class RowLevelPermissionAdmin(admin.ModelAdmin):
  288. def get_changeform_initial_data(self, request):
  289. return {'content_type': ContentType.objects.get_for_model(OfferSubscription)}
  290. admin.site.register(Member, MemberAdmin)
  291. admin.site.register(MembershipFee, MembershipFeeAdmin)
  292. # admin.site.unregister(Group)
  293. # admin.site.register(LdapUser, LdapUserAdmin)
  294. admin.site.register(RowLevelPermission, RowLevelPermissionAdmin)