Browse Source

commande « adherents »

Élie Bouttier 8 years ago
parent
commit
9eafd6ee8b

+ 1 - 1
adhesions/admin.py

@@ -45,7 +45,7 @@ class AdherentTypeFilter(admin.SimpleListFilter):
 
 
 class AdherentAdmin(admin.ModelAdmin):
-    list_display = ('id', 'name', 'type',)
+    list_display = ('id', 'get_name', 'type',)
     list_filter = (AdherentTypeFilter,)
     fields = ('id',)
     readonly_fields = ('id',)

+ 0 - 0
adhesions/management/__init__.py


+ 0 - 0
adhesions/management/commands/__init__.py


+ 78 - 0
adhesions/management/commands/adherents.py

@@ -0,0 +1,78 @@
+from django.core.management.base import BaseCommand, CommandParser, CommandError
+from django.contrib.contenttypes.models import ContentType
+
+from django.contrib.auth.models import User
+from adhesions.models import Adherent, Corporation
+
+
+class Command(BaseCommand):
+    help = 'Gestion des adhérents'
+
+    def add_arguments(self, parser):
+        cmd = self
+        class SubParser(CommandParser):
+            def __init__(self, **kwargs):
+                super().__init__(cmd, **kwargs)
+        subparsers = parser.add_subparsers(dest='command', parser_class=SubParser)
+        subparsers.required = True
+
+        parser_list = subparsers.add_parser('list', help='Lister les adhérents')
+        group = parser_list.add_mutually_exclusive_group()
+        group.add_argument('--physique', action='store_true',
+            help='Afficher uniquement les personnes physiques')
+        group.add_argument('--morale', action='store_true',
+            help='Afficher uniquement les personnes morales')
+
+        parser_change = subparsers.add_parser('create', help='Créer un adhérent')
+        parser_change.add_argument('-i', '--id', type=int, help='Spécifier le numéro du nouvel adhérent')
+        subsubparsers = parser_change.add_subparsers(dest='type', parser_class=SubParser)
+        subsubparsers.required = True
+
+        parser_physique = subsubparsers.add_parser('physique', help='Créer une personne physique')
+        parser_physique.add_argument('--login', dest='username', required=True, help='Login')
+        parser_physique.add_argument('--firstname', dest='first_name', required=True, help='Prénom')
+        parser_physique.add_argument('--lastname', dest='last_name', required=True, help='Nom de famille')
+        parser_physique.add_argument('--email', help='Adresse email')
+
+        parser_morale = subsubparsers.add_parser('morale', help='Créer une personne morale')
+        parser_morale.add_argument('--name', dest='social_reason', required=True, help='Nom ou raison sociale')
+        parser_morale.add_argument('--description', help='Description', default='')
+
+    def handle(self, *args, **options):
+        cmd = options.pop('command')
+        getattr(self, 'handle_{cmd}'.format(cmd=cmd))(*args, **options)
+
+    def handle_list(self, *args, **options):
+        adherents = Adherent.objects.all()
+        if options['physique']:
+            adherents = adherents.filter(adherent_type=ContentType.objects.get(app_label='auth', model='user'))
+        if options['morale']:
+            adherents = adherents.filter(adherent_type=ContentType.objects.get(app_label='adhesions', model='corporation'))
+        for adh in adherents:
+            print("#{id:<8}{name:<30}{type:<20}".format(**{
+                'id': adh.id,
+                'name': adh.get_name(),
+                'type': adh.type,
+            }))
+
+    def handle_create(self, *args, **options):
+        if options['id'] and Adherent.objects.filter(id=options['id']).exists():
+            raise CommandError('Le numéro d’adherent "%d" est déjà attribué' % options['id'])
+        getattr(self, 'handle_create_personne_{type}'.format(**{
+            'type': options.pop('type'),
+        }))(*args, **options)
+
+    def handle_create_personne_physique(self, *args, **options):
+        if User.objects.filter(username=options['username']).exists():
+            raise CommandError('Le nom d’utilisateur "%s" est déjà utilisé' % options['username'])
+        user = User.objects.create_user(**{key: options[key] for key in ['username', 'email', 'first_name', 'last_name']})
+        adherent = Adherent.objects.create(id=options['id'], adherent=user)
+        self.stdout.write(self.style.SUCCESS('Adhérent #%d créé avec succès' % adherent.id))
+
+    def handle_create_personne_morale(self, *args, **options):
+        if Corporation.objects.filter(social_reason=options['social_reason']).exists():
+            raise CommandError('La raison sociale "%s" est déjà utilisé' % options['social_reason'])
+        corporation = Corporation.objects.create(**{key: options[key] for key in ['social_reason', 'description']})
+        adherent = Adherent.objects.create(id=options['id'], adherent=corporation)
+        self.stdout.write(self.style.SUCCESS('Adhérent #%d créé avec succès' % adherent.id))
+        

+ 20 - 0
adhesions/migrations/0004_auto_20170111_0040.py

@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.10 on 2017-01-10 23:40
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('adhesions', '0003_remove_adherent_contribution'),
+    ]
+
+    operations = [
+        migrations.AlterField(
+            model_name='corporation',
+            name='social_reason',
+            field=models.CharField(max_length=256, unique=True, verbose_name='Raison sociale'),
+        ),
+    ]

+ 3 - 3
adhesions/models.py

@@ -30,12 +30,12 @@ class Adherent(models.Model):
         else:
             return 'Personne morale'
 
-    def name(self):
+    def get_name(self):
         if self.adherent_type.app_label == 'auth' and self.adherent_type.model == 'user':
             return str(self.adherent.profile)
         else:
             return str(self.adherent)
-    name.short_description = 'Nom ou raison sociale'
+    get_name.short_description = 'Nom ou raison sociale'
 
     def __str__(self):
         if self.id:
@@ -77,7 +77,7 @@ class Profile(AdhesionMixin, models.Model):
 
 
 class Corporation(AdhesionMixin, models.Model):
-    social_reason = models.CharField(max_length=256, verbose_name='Raison sociale')
+    social_reason = models.CharField(max_length=256, verbose_name='Raison sociale', unique=True)
     description = models.TextField(blank=True, default='')
     address = models.TextField(blank=True, default='', verbose_name='Adresse')
     members = models.ManyToManyField(User, blank=True, verbose_name='Membres')