source: main/waeup.sirp/trunk/tools/fix_import_file.py @ 7527

Last change on this file since 7527 was 7526, checked in by Henrik Bettermann, 13 years ago

Add converter for reg_state.

  • Property svn:keywords set to Id
File size: 5.6 KB
Line 
1## $Id: fix_import_file.py 7526 2012-01-27 18:26:20Z henrik $
2##
3## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18"""
19Fix exports from old SRP portal to make them importable by current portal.
20
21Usage:
22
23Change into this directory, set the options below (files are assumed
24to be in the same directory) and then run
25
26  python fix_import_file.py <filename>
27
28Errors/warnings will be displayed on the shell, the output will be put
29into the specified output file.
30"""
31
32import sys
33
34
35if len(sys.argv) != 2:
36    print 'Usage: python fix_import_file.py <filename>'
37    sys.exit(1)
38
39##
40## CONFIGURATION SECTION
41##
42# file with input data
43INPUT_FILE = '%s' % sys.argv[1]
44
45# file written with modified output
46OUTPUT_FILE = '%s_edited.csv' % sys.argv[1].split('.')[0]
47
48# keys are fieldnames in input file, values are methods of class
49# Converter (see below)
50OPTIONS = {
51    'sex': 'gender',
52    'birthday': 'date',
53    'request_date': 'datetime',
54    'marit_stat': 'marit_stat',
55    'entry_session': 'session',
56    'current_session': 'session',
57    'reg_state': 'reg_state',
58    'password': 'password',
59    }
60
61# Mapping input file colnames --> output file colnames
62COLNAME_MAPPING = {
63    'jamb_reg_no': 'reg_number',
64    'birthday': 'date_of_birth',
65    'clr_ac_pin': 'clr_code',
66    }
67
68# Mapping input regh_state --> output reg_state
69REGSTATE_MAPPING = {
70    'student_created': 'created',
71    'admitted': 'admitted',
72    'clearance_pin_entered': 'clearance started',
73    'clearance_requested': 'clearance requested',
74    'cleared_and_validated': 'cleared',
75    'school_fee_paid': 'school fee paid',
76    'returning': 'returning',
77    'courses_registered': 'courses registered',
78    'courses_validated': 'courses validated',
79    }
80
81##
82## END OF CONFIG
83##
84
85import csv
86import datetime
87import sys
88
89def convert_fieldnames(fieldnames):
90    """Replace input fieldnames by fieldnames of COLNAME_MAPPING.
91    """
92    header = dict([(name, name) for name in fieldnames])
93    for in_name, out_name in COLNAME_MAPPING.items():
94        if in_name not in header:
95            continue
96        header[in_name] = out_name
97    return header
98
99class Converters():
100    """Converters to turn old-style values into new ones.
101    """
102
103    @classmethod
104    def reg_state(self, value):
105        """ 'courses_validated' --> 'courses validated'
106        """
107        return REGSTATE_MAPPING.get(value,value)
108
109
110    @classmethod
111    def session(self, value):
112        """ '08' --> '2008'
113        """
114        try:
115            number = int(value)
116        except ValueError:
117            return 9999
118        if number < 14:
119            return number + 2000
120        elif number in range(2000,2015):
121            return number
122        else:
123            return 9999
124
125    @classmethod
126    def marit_stat(self, value):
127        """ 'True'/'False' --> 'married'/'unmarried'
128        """
129        if value == 'True':
130            value = 'married'
131        elif value == 'False':
132            value = 'unmarried'
133        else:
134            value = ''
135        return value
136
137    @classmethod
138    def gender(self, value):
139        """ 'True'/'False' --> 'f'/'m'
140        """
141        if value == 'True':
142            value = 'f'
143        elif value == 'False':
144            value = 'm'
145        else:
146            value = ''
147        return value
148
149    @classmethod
150    def date(self, value):
151        """ 'yyyy/mm/dd' --> 'yyyy-mm-dd'
152        """
153        if value == "None":
154            value = ""
155        elif value == "":
156            value = ""
157        else:
158            value = value.replace('/', '-')
159            # We add the hash symbol to avoid automatic date transformation
160            # in Excel and Calc for further processing
161            value += '#'
162        return value
163
164    @classmethod
165    def datetime(self, value):
166        """ 'yyyy/mm/dd' --> 'yyyy-mm-dd'
167        """
168        #print  "IN: ", value
169        if value == "None":
170            value = ""
171        elif value == "":
172            value = ""
173        else:
174            #value = datetime.datetime.strptime(value, '%Y/%m/%d')
175            #value = datetime.datetime.strftime(value, '%Y-%m-%d')
176            pass
177        #print "OUT: ", value
178        return value
179
180    @classmethod
181    def password(self, value):
182        if value == "not set":
183            return ""
184        return value
185
186
187reader = csv.DictReader(open(INPUT_FILE, 'rb'))
188writer = None
189
190for num, row in enumerate(reader):
191    if num == 0:
192        writer = csv.DictWriter(open(OUTPUT_FILE, 'wb'), reader.fieldnames)
193        print "FIELDS: "
194        for x, y in enumerate(reader.fieldnames):
195            print x, y
196        header = convert_fieldnames(reader.fieldnames)
197        writer.writerow(header)
198    for key, value in row.items():
199        if not key in OPTIONS.keys():
200            continue
201        conv_name = OPTIONS[key]
202        converter = getattr(Converters, conv_name, None)
203        if converter is None:
204            print "WARNING: cannot find converter %s" % conv_name
205            continue
206        row[key] = converter(row[key])
207    writer.writerow(row)
208
209print "Output written to %s" % OUTPUT_FILE
Note: See TracBrowser for help on using the repository browser.