employe
[auf_rh_dae.git] / project / dae / management / commands / dae.py
1 # -*- encoding: utf-8 -*-
2
3 import codecs
4 from django.core.management.base import BaseCommand
5 from project.dae import models as dae
6 from project.rh import models as rh
7
8 class Command(BaseCommand):
9
10 def clean_employe(self, source, copy, field, value):
11 if source.employe.id_rh is not None:
12 copy.employe = source.employe.id_rh
13 else:
14 raise Exception('Creer un employe')
15
16 def duplicate(self, obj, level=0, skip=(), dry_run=True):
17 klass = getattr(rh, obj.__class__.__name__)
18 copy = klass()
19
20 indent = " "*level*4
21 self.stdout.write(u"\n%s [%s] %s" % (indent, str(obj.__class__),
22 obj))
23
24 self.stdout.write(u"\n*** SKIP: %s ***" % (", ".join(skip)))
25
26 for f in [f for f in obj._meta.fields if f.name not in skip]:
27 value = getattr(obj, f.name)
28 self.stdout.write(u"\n%s * %s: %s" % (indent, f.name, value))
29
30 cleanup_fct = "clean_%s" % f.name
31 if hasattr(self, cleanup_fct):
32 cleaner = getattr(self, cleanup_fct)
33 cleaner(obj, copy, f, value)
34 else:
35 setattr(copy, f.name, value)
36
37 for obj_composition in obj._meta._related_objects_cache:
38 app_label, dummy = obj_composition.name.split(':')
39 field_name = obj_composition.field.rel.related_name
40 if field_name in skip:
41 continue
42 if app_label == obj._meta.app_label:
43 try:
44 children = getattr(obj, field_name)
45 self.stdout.write(u"\n%s + [%s] %s" % (indent,
46 app_label, field_name))
47 except:
48 # no reverse relation
49 #print "%s %s %s" % (indent, obj_composition, field_name)
50 continue
51 for child in children.all():
52 extra_skip = []
53
54 for f in child._meta.fields:
55 if getattr(child, f.name) == obj:
56 extra_skip.append(f.name)
57
58 child_copy = self.duplicate(child, level+1, skip +
59 extra_skip, dry_run)
60 if not dry_run:
61 copy.save()
62 setattr(child_copy, "%s_id" % extra_skip[0], copy.id)
63 if not dry_run:
64 child_copy.save()
65 return copy
66
67
68 def handle(self, *args, **options):
69
70 self.stdout = codecs.getwriter('utf8')(self.stdout)
71
72 if len(args) < 2:
73 print len(args)
74 self.stdout.write("dae <modele> <id> <run>\n")
75 return
76
77 classname = args[0]
78 klass = getattr(dae, classname, None)
79 if klass is None:
80 self.stdout.write("Le modèle %s n'existe pas dans DAE.\n" % classname)
81
82 id = int(args[1])
83 try:
84 obj = klass.objects.get(id=id)
85 except:
86 self.stdout.write("L'id %s n'existe pas pour le modèle %s dans DAE.\n" % \
87 (id, classname))
88 return
89
90
91 dry_run = True
92 if len(args) == 3 and args[2] == "run":
93 dry_run = False
94
95 copy = self.duplicate(obj, skip=['id', 'dae_dossiers', ],
96 dry_run=dry_run)
97 self.stdout.write(u"\n[%s] DAE:%s => RH:%s\n" % (obj.__class__.__name__, obj.id, copy.id))
98