Parcourir la source

[enh] Autocreate config

ljf il y a 7 ans
Parent
commit
41a7638b86

+ 27 - 4
coin/configuration/models.py

@@ -17,7 +17,7 @@ technical informations of a subscription.
 
 To add a new configuration backend, you have to create a new app with a model
 which inherit from Configuration.
-Your model can implement Meta verbose_name to have human readable name and a 
+Your model can implement Meta verbose_name to have human readable name and a
 url_namespace variable to specify the url namespace used by this model.
 """
 
@@ -35,9 +35,9 @@ class Configuration(PolymorphicModel):
         Génère automatiquement la liste de choix possibles de configurations
         en fonction des classes enfants de Configuration
         """
-        return tuple((x().__class__.__name__,x()._meta.verbose_name) 
+        return tuple((x().__class__.__name__,x()._meta.verbose_name)
             for x in Configuration.__subclasses__())
-    
+
     def model_name(self):
         return self.__class__.__name__
     model_name.short_description = 'Nom du modèle'
@@ -52,7 +52,7 @@ class Configuration(PolymorphicModel):
         Une url doit être nommée "details"
         """
         from django.core.urlresolvers import reverse
-        return reverse('%s:details' % self.get_url_namespace(), 
+        return reverse('%s:details' % self.get_url_namespace(),
                        args=[str(self.id)])
 
     def get_url_namespace(self):
@@ -66,10 +66,33 @@ class Configuration(PolymorphicModel):
         else:
             return self.model_name().lower()
 
+    def save(self, **kwargs):
+        self.clean()
+        os = self.offersubscription
+        for offer_ip_pool in os.offer.offerippool_set.order_by('-to_assign'):
+            IPSubnet.objects.create(
+                            configuration=self,
+                            ip_pool=offer_ip_pool.ip_pool)
+        return super(Configuration, self).save(**kwargs)
+
     class Meta:
         verbose_name = 'configuration'
 
 
+@receiver(post_save, sender=OfferSubscription)
+def offer_subscription_event(sender, **kwargs):
+    os = kwargs['instance']
+
+    if not hasattr(os, 'configuration'):
+        config_cls = None
+        for subconfig_cls in Configuration.__subclasses__():
+            if subconfig_cls().__class__.__name__ == os.offer.configuration_type:
+                config_cls = subconfig_cls
+                break
+
+        if config_cls is not None:
+            config = config_cls.objects.create(offersubscription=os)
+
 @receiver(post_save, sender=IPSubnet)
 @receiver(post_delete, sender=IPSubnet)
 def subnet_event(sender, **kwargs):

+ 28 - 0
coin/offers/migrations/0010_auto_20170818_1835.py

@@ -0,0 +1,28 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('offers', '0009_auto_20170818_1529'),
+    ]
+
+    operations = [
+        migrations.AlterModelOptions(
+            name='offerippool',
+            options={'ordering': ['-to_assign'], 'verbose_name': "pool d'IP", 'verbose_name_plural': "pools d'IP"},
+        ),
+        migrations.RenameField(
+            model_name='offer',
+            old_name='ippools',
+            new_name='ip_pools',
+        ),
+        migrations.RenameField(
+            model_name='offerippool',
+            old_name='ippool',
+            new_name='ip_pool',
+        ),
+    ]

+ 2 - 2
coin/offers/models.py

@@ -62,7 +62,7 @@ class Offer(models.Model):
                                        verbose_name='n\'est pas facturable',
                                        help_text='L\'offre ne sera pas facturée par la commande charge_members')
 
-    ippools = models.ManyToManyField(IPPool, through='OfferIPPool')
+    ip_pools = models.ManyToManyField(IPPool, through='OfferIPPool')
 
     objects = OfferManager()
 
@@ -104,7 +104,7 @@ class Offer(models.Model):
 class OfferIPPool(models.Model):
     offer = models.ForeignKey(Offer,
                               verbose_name='offre')
-    ippool = models.ForeignKey(IPPool,
+    ip_pool = models.ForeignKey(IPPool,
                                verbose_name='pool d\'IP')
     to_assign = models.BooleanField(default=False,
                                     verbose_name='assignation par défaut')

+ 4 - 0
coin/resources/models.py

@@ -111,6 +111,10 @@ class IPSubnet(models.Model):
             self.validate_inclusion()
         self.validate_reverse_dns()
 
+    def save(self, **kwargs):
+        self.clean()
+        return super(IPSubnet, self).save(**kwargs)
+
     def __unicode__(self):
         return str(self.inet)
 

+ 2 - 2
housing/models.py

@@ -14,7 +14,7 @@ from coin import validation
 
 class HousingConfiguration(Configuration):
     url_namespace = "housing"
-    activated = models.BooleanField(default=False, verbose_name='activé')
+    activated = models.BooleanField(default=True, verbose_name='activé')
     ipv4_endpoint = InetAddressField(validators=[validation.validate_v4],
                                      verbose_name="IPv4", blank=True, null=True,
                                      help_text="Adresse IPv4 utilisée par "
@@ -93,7 +93,7 @@ class HousingConfiguration(Configuration):
     def clean(self):
         # If saving for the first time and IP endpoints are not specified,
         # generate them automatically.
-        if self.pk is None:
+        if self.ipv4_endpoint is None or self.ipv6_endpoint is None:
             self.generate_endpoints()
         self.check_endpoints()
 

+ 3 - 3
vpn/models.py

@@ -23,7 +23,7 @@ class VPNConfiguration(CoinLdapSyncMixin, Configuration):
     #     'offers.OfferSubscription',
     #     related_name=backend_name,
     #     validators=[ValidateBackendType(backend_name)])
-    activated = models.BooleanField(default=False, verbose_name='activé')
+    activated = models.BooleanField(default=True, verbose_name='activé')
     login = models.CharField(max_length=50, unique=True, blank=True,
                              verbose_name="identifiant",
                              help_text="Laisser vide pour une génération automatique")
@@ -141,9 +141,9 @@ class VPNConfiguration(CoinLdapSyncMixin, Configuration):
                 ValidationError("Impossible de générer un login VPN")
         # Hash password if needed
         self.password = utils.ldap_hash(self.password)
-        # If saving for the first time and IP endpoints are not specified,
+        # If IP endpoints are not specified,
         # generate them automatically.
-        if self.pk is None:
+        if self.ipv4_endpoint is None or self.ipv6_endpoint is None:
             self.generate_endpoints()
         self.check_endpoints()
 

+ 3 - 3
vps/models.py

@@ -24,7 +24,7 @@ PROTOCOLE_TYPES = (
 
 class VPSConfiguration(Configuration):
     url_namespace = "vps"
-    activated = models.BooleanField(default=False, verbose_name='activé')
+    activated = models.BooleanField(default=True, verbose_name='activé')
     ipv4_endpoint = InetAddressField(validators=[validation.validate_v4],
                                      verbose_name="IPv4", blank=True, null=True,
                                      help_text="Adresse IPv4 utilisée par "
@@ -100,9 +100,9 @@ class VPSConfiguration(Configuration):
                 raise ValidationError(error.format(self.ipv6_endpoint))
 
     def clean(self):
-        # If saving for the first time and IP endpoints are not specified,
+        # If IP endpoints are not specified,
         # generate them automatically.
-        if self.pk is None:
+        if self.ipv4_endpoint is None or self.ipv6_endpoint is None:
             self.generate_endpoints()
         self.check_endpoints()