poste importer
authorOlivier Larchevêque <olivier.larcheveque@auf.org>
Fri, 23 Mar 2012 15:35:17 +0000 (11:35 -0400)
committerOlivier Larchevêque <olivier.larcheveque@auf.org>
Fri, 23 Mar 2012 15:35:17 +0000 (11:35 -0400)
project/dae/management/commands/dae.py

index 63332e4..1b7af8e 100644 (file)
 # -*- encoding: utf-8 -*-
 
+import sys
 import codecs
+import os
+import  shutil
+
 from django.core.management.base import BaseCommand
+from django.conf import settings
+
 from project.dae import  models as dae
 from project.rh import  models as rh
 
-class Command(BaseCommand):
 
-    def clean_employe(self, source, copy, field, value):
-        if source.employe.id_rh is not None:
-            copy.employe = source.employe.id_rh
-        else:
-            raise Exception('Creer un employe')
+class SuperCopier(object):
+    dry_run = True
+    verbosity = 0   
+    stdout = codecs.getwriter('utf8')(sys.stdout)
+
+    def __init__(self, dry_run=True, verbosity=0):
+        self.verbosity = verbosity
+        self.dry_run = dry_run
+
+    def out(self, txt, level=0):
+        if self.verbosity >= level:
+            self.stdout.write(txt)
+
+    def clean_id(self, source, copy, parent, field, value):
+        pass
 
-    def duplicate(self, obj, level=0, skip=(), dry_run=True):
+    def parent(self, parent, child):
+        klass = parent.__class__.__name__.lower()
+        k = "%s_id" % klass
+        setattr(child, k, parent.id)
+
+    def duplicate(self, obj, parent=None, level=0):
         klass = getattr(rh, obj.__class__.__name__)
         copy = klass()
     
         indent = " "*level*4
-        self.stdout.write(u"\n%s [%s] %s" % (indent, str(obj.__class__),
-            obj))
+        self.out(u"\n%s [%s] %s" % (indent, str(obj.__class__),
+            obj), 1)
         
-        self.stdout.write(u"\n*** SKIP: %s ***" % (", ".join(skip)))
-    
-        for f in [f for f in obj._meta.fields if f.name not in skip]:
+        for f in obj._meta.fields:
             value = getattr(obj, f.name)
-            self.stdout.write(u"\n%s * %s: %s" % (indent, f.name, value))
+            self.out(u"\n%s * %s: %s" % (indent, f.name, value), 2)
 
             cleanup_fct = "clean_%s" % f.name
             if hasattr(self, cleanup_fct):
                 cleaner = getattr(self, cleanup_fct)
-                cleaner(obj, copy, f, value)
+                cleaner(obj, copy, parent, f, value)
             else:
                 setattr(copy, f.name, value)
+
+        if not self.dry_run:
+            copy.save()
     
         for obj_composition in obj._meta._related_objects_cache:
             app_label, dummy = obj_composition.name.split(':')
             field_name = obj_composition.field.rel.related_name
-            if field_name in skip:
+            if field_name == '+':
                 continue
-            if app_label == obj._meta.app_label:
-                try:
-                    children = getattr(obj, field_name)
-                    self.stdout.write(u"\n%s + [%s] %s" % (indent,
-                        app_label, field_name))
-                except:
-                    # no reverse relation
-                    #print "%s %s %s" % (indent, obj_composition, field_name)
-                    continue
-                for child in children.all():
-                    extra_skip = []
-                    
-                    for f in child._meta.fields:
-                        if getattr(child, f.name) == obj:
-                            extra_skip.append(f.name)
-                    
-                    child_copy = self.duplicate(child, level+1, skip +
-                            extra_skip, dry_run)
-                    if not dry_run:
-                        copy.save()
-                    setattr(child_copy, "%s_id" % extra_skip[0], copy.id)
-                    if not dry_run:
-                        child_copy.save()
+            #if app_label == obj._meta.app_label:
+            try:
+                cleanup_fct = "clean_%s" % field_name
+                if hasattr(self, cleanup_fct):
+                    cleaner = getattr(self, cleanup_fct)
+                    children = cleaner(obj, copy, parent, f, value)
+                else:
+                    children = getattr(obj, field_name).all()
+                self.out(u"\n%s + [%s] %s" % (indent, app_label, field_name), 1)
+            except Exception, e:
+                # no reverse relation
+                #print "%s %s %s" % (indent, obj_composition, field_name)
+                self.out(" %s %s" % (field_name, str(e)), 1)
+                continue
+            
+            for child in children:
+                child_copy = self.duplicate(child, parent=copy, level=level+1,)
+                parentship_fct = "parent_%s" % (field_name)
+                if hasattr(self,parentship_fct):
+                    parentship = getattr(self, parentship_fct)
+                else:
+                    parentship = getattr(self, "parent")
+                parentship(copy, child_copy)
+                
+                if not self.dry_run:
+                    child_copy.save()
         return copy
 
 
-    def handle(self, *args, **options):
+class PosteCopier(SuperCopier):
+
+    def clean_rh_dossiers(self, source, copy, parent, field, value):
+        self.out("\n** SKIP **", 1)
+        return []
+
+    def clean_rh_comparaisons_internes(self, source, copy, parent, field, value):
+        self.out("\n** SKIP **", 1)
+        return []
+
+    def clean_rh_financements(self, source, copy, parent, field, value):
+        self.out("\n** SKIP **", 1)
+        return []
+
+    def clean_rh_pieces(self, source, copy, parent, field, value):
+        self.out("\n** SKIP **", 1)
+        return []
 
-        self.stdout = codecs.getwriter('utf8')(self.stdout)
+    def clean_dae_dossiers(self, source, copy, parent, field, value):
+        self.out("\n** SKIP **", 1)
+        return []
+
+    def clean_fichier(self, source, copy, parent, field, value):
+        filename = value.path.split('/')[-1]
+        copy.poste_id = parent.id
+        new_value = rh.poste_piece_dispatch(copy, filename)
+
+        app, model, id, f = new_value.split('/')
+        app_path = os.path.join(settings.PRIVE_MEDIA_ROOT, app)
+        model_path = os.path.join(settings.PRIVE_MEDIA_ROOT, app, model)
+        id_path = os.path.join(settings.PRIVE_MEDIA_ROOT, app, model, id)
+        if not os.path.exists(app_path):
+            os.mkdir(app_path)
+        if not os.path.exists(model_path):
+            os.mkdir(model_path)
+        if not os.path.exists(id_path):
+            os.mkdir(id_path)
+        src = value.path
+        dst = os.path.join(settings.PRIVE_MEDIA_ROOT, new_value)
+        shutil.copy(src, dst)
+        setattr(copy, field.name, new_value)
+
+
+class DossierCopier(SuperCopier):
+
+    def clean_employe(self, source, copy, field, value):
+        if source.employe.id_rh is not None:
+            copy.employe = source.employe.id_rh
+        else:
+            nouvel_employe = rh.Employe()
+            nouvel_employe.nom = source.employe.nom
+            nouvel_employe.prenom = source.employe.prenom
+            nouvel_employe.genre = source.employe.genre
+            nouvel_employe.save()
+            copy.employe = nouvel_employe
+
+    def clean_fichier(self, source, copy, field, value):
+        pass
+
+    def clean_poste(self, source, copy, field, value):
+        pass
+
+
+class Command(BaseCommand):
+
+    
+    def handle(self, *args, **options):
 
         if len(args) < 2:
             print len(args)
@@ -92,7 +180,13 @@ class Command(BaseCommand):
         if len(args) == 3 and args[2] == "run":
             dry_run = False
 
-        copy = self.duplicate(obj, skip=['id', 'dae_dossiers', ],
+        verbosity = 0
+        if len(args) == 4:
+            verbosity = int(args[3])
+
+        copier = globals()[ "%sCopier" %  classname.title()](verbosity=verbosity,
                 dry_run=dry_run)
+
+        copy = copier.duplicate(obj)
         self.stdout.write(u"\n[%s] DAE:%s => RH:%s\n" % (obj.__class__.__name__, obj.id, copy.id))