w.c.s : ajout de la génération d'une liste des dossiers JSON
[progfou.git] / wcs / wcs-extract.py
CommitLineData
0f48356a
P
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import os
5import os.path
a9de62a1
P
6import shutil
7import logging
0f48356a
P
8from time import gmtime, strftime
9import simplejson as json
10
0cd61ae9
P
11from wcs import publisher
12from wcs.formdef import FormDef
13from wcs.fields import TitleField, CommentField, TextField, \
14 StringField, ItemField, EmailField, \
15 DateField, FileField, BoolField
0f48356a 16
0f48356a 17
0cd61ae9
P
18def reduce_to_alnum(s, replacement_char='-'):
19 """réduction d'une chaîne de caractères à de l'alpha-numérique"""
20
0f48356a
P
21 avec_accent = u'çÇáàâÁÀÂéèêëÉÈÊËíìîïÍÌÎÏóòôöÓÒÔÖúùûüÚÙÛÜýỳyÿÝỲYŸ'
22 sans_accent = u'cCaaaAAAeeeeEEEEiiiiIIIIooooOOOOuuuuUUUUyyyyYYYY'
23 if type(s) is not unicode:
24 s = unicode(s, 'utf-8')
25 u = False
26 r = ''
27 for c in s:
28 index = avec_accent.find(c)
29 if index >= 0:
30 r += sans_accent[index]
31 elif ('a' <= c.lower() <= 'z') or ('0' <= c <= '9'):
32 r += c
33 elif len(r) > 0 and r[-1] != replacement_char:
34 r += replacement_char
35 else: # r == '' or r[-1] == replacement_char
36 pass
37 r = r.strip(replacement_char)
38 if not u:
39 r = r.encode('utf-8')
40 return r
41
0f48356a 42
0cd61ae9
P
43def extract_fields(formdef, output_directory):
44 """nommage des champs de façon unique"""
45 # TODO: devrait retourner un résultat, qui serait alors sauvé en dehors
46
36319452
P
47 # XXX: hack temporaire… :-/
48 global field_names
49
0cd61ae9
P
50 f = open(os.path.join(output_directory, 'field-names.txt'), 'w')
51
52 field_names = {}
53 field_names_duplicates = {}
0f48356a 54 for field in formdef.fields:
0f48356a
P
55 if isinstance(field, TitleField) or isinstance(field, CommentField):
56 continue
0cd61ae9
P
57 name = reduce_to_alnum(field.label,'_').lower()
58 if name in field_names.values(): # duplicat
59 field_names_duplicates[name] = field_names_duplicates.get(name, 1) + 1
60 name = '%s_%d' % (name, field_names_duplicates[name])
61 field_names.update({field.id: name})
62 print >>f, "%s:%s:%s" % (field.id, field_names[field.id], field.label)
63
0f48356a
P
64 f.close()
65
0cd61ae9
P
66 f = open(os.path.join(output_directory, 'field-names.json'), 'wb')
67 f.write(json.dumps(field_names, ensure_ascii=False))
68 f.close()
69
70
71def extract_data(formdef, output_directory):
72 """extraction des données du formulaire"""
73 # TODO: devrait retourner un résultat, qui serait alors sauvé en dehors
74
2e14236b 75 liste_dossiers = []
0cd61ae9
P
76 for object in formdef.data_class().select():
77 result = {
78 'num_dossier': object.id,
79 'wcs_status': object.status,
80 'wcs_workflow_status': object.get_workflow_status().name,
81 'wcs_user_email': object.user.email,
82 'wcs_user_display_name': object.user.display_name,
83 #'wcs_last_modified': strftime('%Y-%m-%d %H:%M:%S', gmtime(object.last_modified())),
84 }
85 qfiles = { }
86 for field in formdef.fields:
87 field_id = str(field.id)
88 if not field_id in object.data:
89 continue
90 if isinstance(field, TitleField) or isinstance(field, CommentField):
91 continue
92 field_name = field_names[field_id]
93 data = object.data.get(field_id)
94 if isinstance(field, StringField) or isinstance(field, TextField) \
95 or isinstance(field, EmailField) or isinstance(field, ItemField):
96 result[field_name] = data
97 elif isinstance(field, BoolField):
98 result[field_name] = (data == 'True')
99 elif isinstance(field, DateField):
100 result[field_name] = strftime('%Y-%m-%d', data)
101 elif isinstance(field, FileField):
102 extension = data.orig_filename.rpartition('.')[2].lower()
103 result[field_name] = "%s.%s" % (field_name, extension)
104 qfiles[field_name] = data.qfilename
105 else:
a9de62a1
P
106 logging.error("Type de champ inconnu '%s' pour '%s'.",
107 field.__class__.__name__, field.label)
0cd61ae9
P
108 raise RuntimeError
109
110 num_dossier = result['num_dossier']
111 nom = reduce_to_alnum(result['nom']).upper()
112 prenom = reduce_to_alnum(result['prenom']).upper()
113 adel = result['adresse_electronique'].replace('@','-').lower()
114
115 filename = "%04d-%s-%s-%s" % (num_dossier, nom, prenom, adel)
2e14236b 116 liste_dossiers.append(filename + '.json')
0cd61ae9 117
0cd61ae9
P
118 # copie des fichiers joints
119 for f in qfiles:
120 result[f] = filename + '_' + result[f]
121 src = os.path.join(pub.app_dir, 'uploads', qfiles[f])
a9de62a1 122 dst = os.path.join(output_directory, 'data', result[f])
0cd61ae9 123 if not os.path.exists(dst) or os.path.getmtime(src) > os.path.getmtime(dst):
a9de62a1 124 shutil.copy2(src, dst)
0cd61ae9
P
125 os.chmod(dst, 0644)
126
127 # génération du fichier JSON
a9de62a1
P
128 jsonname = os.path.join(output_directory, 'data', filename + '.json')
129 f = open(jsonname, 'wb')
0cd61ae9
P
130 f.write(json.dumps(result, ensure_ascii=False))
131 f.close()
132
a9de62a1
P
133 logging.info("Dossier '%s' : %s.",
134 filename, result['wcs_workflow_status'])
0cd61ae9 135
2e14236b
P
136 f = open(os.path.join(output_directory, 'liste-dossiers.json'), 'wb')
137 f.write(json.dumps(liste_dossiers, ensure_ascii=False))
138 f.close()
139
0cd61ae9
P
140
141if __name__ == '__main__':
142 import sys
143
144 if len(sys.argv) != 4:
145 print >>sys.stderr, "Usage : %s <dossier-destination> <site> <formulaire>" % sys.argv[0]
146 sys.exit(1)
147
148 VHOST = sys.argv[2]
149 FORM_NAME = sys.argv[3]
150 OUTPUT_DIRECTORY = os.path.join(sys.argv[1], VHOST, FORM_NAME)
151
152 os.umask(0022)
153 # création du dossier d'extraction, au besoin
154 if not os.path.isdir(OUTPUT_DIRECTORY):
155 os.makedirs(OUTPUT_DIRECTORY, 0755)
156
a9de62a1
P
157 logging.basicConfig(level=logging.DEBUG,
158 format='%(asctime)s %(levelname)s %(message)s',
159 filename=os.path.join(OUTPUT_DIRECTORY, 'last-run.log'),
160 filemode='w')
161
162 logging.info('Début.')
163
0cd61ae9
P
164 pub = publisher.WcsPublisher.create_publisher()
165 pub.app_dir = os.path.join(pub.app_dir, VHOST)
166
167 formdef = FormDef.get_by_urlname(FORM_NAME)
168
169 extract_fields(formdef, OUTPUT_DIRECTORY)
170
171 extract_data(formdef, OUTPUT_DIRECTORY)
172
a9de62a1 173 logging.info('Fin.')
0f48356a 174