123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224 |
- # -*- coding: utf-8 -*-
- from __future__ import unicode_literals
- from django.shortcuts import render, get_object_or_404
- from django.contrib import admin
- from django.contrib import messages
- from django.contrib.auth.admin import UserAdmin
- from django.contrib.auth.models import Group
- from django.http import HttpResponseRedirect
- from django.conf.urls import url
- from django.db.models.query import QuerySet
- from django.core.urlresolvers import reverse
- from django.utils.html import format_html
- from coin.members.models import (
- Member, CryptoKey, LdapUser, MembershipFee, OfferSubscription)
- from coin.members.membershipfee_filter import MembershipFeeFilter
- from coin.members.forms import MemberChangeForm, MemberCreationForm
- from coin.utils import delete_selected
- import autocomplete_light
- class CryptoKeyInline(admin.StackedInline):
- model = CryptoKey
- extra = 0
- class MembershipFeeInline(admin.TabularInline):
- model = MembershipFee
- extra = 0
- fields = ('start_date', 'end_date', 'amount', 'payment_method',
- 'reference', 'payment_date')
- class OfferSubscriptionInline(admin.TabularInline):
- model = OfferSubscription
- extra = 0
- readonly_fields = ('get_subscription_reference', 'subscription_date', 'resign_date',
- 'commitment', 'offer', 'show_change_link')
- # FIXME: Workaround en attendant la migration vers Django >=1.8
- # À remplacer par InlineModelAdmin.show_change_link = True
- def show_change_link(self, obj=None):
- url = reverse('admin:%s_%s_change' % (obj._meta.app_label,
- obj._meta.model_name),
- args=[obj.id])
- return format_html(u'<a href="{}">Éditer</a>', url)
- show_change_link.short_description = 'Éditer ?'
- def has_add_permission(self, request, obj=None):
- return False
- def has_delete_permission(self, request, obj=None):
- return False
- class MemberAdmin(UserAdmin):
- list_display = ('id', 'status', 'username', 'first_name', 'last_name',
- 'nickname', 'organization_name', 'email',
- 'end_date_of_membership')
- list_display_links = ('id', 'username', 'first_name', 'last_name')
- list_filter = ('status', MembershipFeeFilter)
- search_fields = ['username', 'first_name', 'last_name', 'email', 'nickname']
- ordering = ('status', 'username')
- actions = [delete_selected, 'set_as_member', 'set_as_non_member',
- 'bulk_send_welcome_email', 'bulk_send_call_for_membership_fee_email']
- form = MemberChangeForm
- add_form = MemberCreationForm
- fieldsets = (
- ('Adhérent', {'fields': (
- ('status', 'resign_date'),
- 'type',
- ('first_name', 'last_name', 'nickname'),
- 'organization_name',
- 'comments')}),
- ('Coordonnées', {'fields': (
- 'email',
- ('home_phone_number', 'mobile_phone_number'),
- 'address',
- ('postal_code', 'city', 'country'))}),
- ('Authentification', {'fields': (
- ('username', 'password'))}),
- ('Permissions', {'fields': (
- ('is_active', 'is_staff', 'is_superuser'))}),
- (None, {'fields': ('date_last_call_for_membership_fees_email',)})
- )
- add_fieldsets = (
- ('Adhérent', {'fields': (
- 'status',
- 'type',
- ('first_name', 'last_name', 'nickname'),
- 'organization_name',
- 'comments')}),
- ('Coordonnées', {'fields': (
- 'email',
- ('home_phone_number', 'mobile_phone_number'),
- 'address',
- ('postal_code', 'city', 'country'))}),
- ('Authentification', {'fields': (
- ('username', 'password'),)}),
- ('Permissions', {'fields': (
- ('is_active', 'is_staff', 'is_superuser', 'date_joined'))})
- )
- radio_fields = {"type": admin.HORIZONTAL}
- save_on_top = True
- inlines = [CryptoKeyInline, MembershipFeeInline, OfferSubscriptionInline]
- def get_readonly_fields(self, request, obj=None):
- if obj:
- # Remove help_text for readonly field (can't do that in the Form
- # django seems to user help_text from model for readonly fields)
- username_field = [
- f for f in obj._meta.fields if f.name == 'username']
- username_field[0].help_text = ''
- return ['username', ]
- else:
- return []
- def set_as_member(self, request, queryset):
- rows_updated = queryset.update(status='member')
- self.message_user(
- request,
- '%d membre(s) définis comme adhérent(s).' % rows_updated)
- set_as_member.short_description = 'Définir comme adhérent'
- def set_as_non_member(self, request, queryset):
- rows_updated = queryset.update(status='not_member')
- self.message_user(
- request,
- '%d membre(s) définis comme non adhérent(s).' % rows_updated)
- set_as_non_member.short_description = "Définir comme non adhérent"
- def get_urls(self):
- """Custom admin urls"""
- urls = super(MemberAdmin, self).get_urls()
- my_urls = [
- url(r'^send_welcome_email/(?P<id>\d+)$',
- self.admin_site.admin_view(self.send_welcome_email),
- name='send_welcome_email'),
- ]
- return my_urls + urls
- def send_welcome_email(self, request, id, return_httpredirect=True):
- """
- Vue appelée lorsque l'admin souhaite envoyer l'email de bienvenue à un
- membre.
- """
- # TODO : Add better perm here
- if request.user.is_superuser:
- member = get_object_or_404(Member, pk=id)
- member.send_welcome_email()
- messages.success(request,
- 'Le courriel de bienvenue a été envoyé à %s' % member.email)
- else:
- messages.error(
- request, 'Vous n\'avez pas l\'autorisation d\'envoyer des '
- 'courriels de bienvenue.')
- if return_httpredirect:
- return HttpResponseRedirect(reverse('admin:members_member_changelist'))
- def bulk_send_welcome_email(self, request, queryset):
- """
- Action appelée lorsque l'admin souhaite envoyer un lot d'email de bienvenue
- depuis une sélection de membre dans la vue liste de l'admin
- """
- for member in queryset.all():
- self.send_welcome_email(
- request, member.id, return_httpredirect=False)
- messages.success(request,
- 'Le courriel de bienvenue a été envoyé à %d membre(s).' % queryset.count())
- bulk_send_welcome_email.short_description = "Envoyer le courriel de bienvenue"
- def bulk_send_call_for_membership_fee_email(self, request, queryset):
- # TODO : Add better perm here
- if not request.user.is_superuser:
- messages.error(
- request, 'Vous n\'avez pas l\'autorisation d\'envoyer des '
- 'courriels de relance.')
- return
- cpt_success = 0
- for member in queryset.all():
- if member.send_call_for_membership_fees_email():
- cpt_success += 1
- else:
- messages.warning(request,
- "Le courriel de relance de cotisation n\'a pas "
- "été envoyé à {member} ({email}) car il a déjà "
- "reçu une relance le {last_call_date}"\
- .format(member=member,
- email=member.email,
- last_call_date=member.date_last_call_for_membership_fees_email))
- if queryset.count() == 1 and cpt_success == 1:
- member = queryset.first()
- messages.success(request,
- "Le courriel de relance de cotisation a été "
- "envoyé à {member} ({email})"\
- .format(member=member, email=member.email))
- elif cpt_success>1:
- messages.success(request,
- "Le courriel de relance de cotisation a été "
- "envoyé à {cpt} membres"\
- .format(cpt=cpt_success))
- bulk_send_call_for_membership_fee_email.short_description = 'Envoyer le courriel de relance de cotisation'
- class MembershipFeeAdmin(admin.ModelAdmin):
- list_display = ('member', 'end_date', 'amount', 'payment_method',
- 'payment_date')
- form = autocomplete_light.modelform_factory(MembershipFee, fields='__all__')
- admin.site.register(Member, MemberAdmin)
- admin.site.register(MembershipFee, MembershipFeeAdmin)
- admin.site.unregister(Group)
- # admin.site.register(LdapUser, LdapUserAdmin)
|