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

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

Let's use the script also for editing study level migration files.

  • Property svn:keywords set to Id
File size: 5.7 KB
Line 
1## $Id: fix_import_file.py 7537 2012-01-30 07:46:08Z 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    'session': 'session',
56    'entry_session': 'session',
57    'current_session': 'session',
58    'reg_state': 'reg_state',
59    'password': 'password',
60    }
61
62# Mapping input file colnames --> output file colnames
63COLNAME_MAPPING = {
64    'jamb_reg_no': 'reg_number',
65    'birthday': 'date_of_birth',
66    'clr_ac_pin': 'clr_code',
67    'study_course': 'certificate',
68    'session': 'level_session',
69    'verdict': 'level_verdict',
70    }
71
72# Mapping input regh_state --> output reg_state
73REGSTATE_MAPPING = {
74    'student_created': 'created',
75    'admitted': 'admitted',
76    'clearance_pin_entered': 'clearance started',
77    'clearance_requested': 'clearance requested',
78    'cleared_and_validated': 'cleared',
79    'school_fee_paid': 'school fee paid',
80    'returning': 'returning',
81    'courses_registered': 'courses registered',
82    'courses_validated': 'courses validated',
83    }
84
85##
86## END OF CONFIG
87##
88
89import csv
90import datetime
91import sys
92
93def convert_fieldnames(fieldnames):
94    """Replace input fieldnames by fieldnames of COLNAME_MAPPING.
95    """
96    header = dict([(name, name) for name in fieldnames])
97    for in_name, out_name in COLNAME_MAPPING.items():
98        if in_name not in header:
99            continue
100        header[in_name] = out_name
101    return header
102
103class Converters():
104    """Converters to turn old-style values into new ones.
105    """
106    @classmethod
107    def reg_state(self, value):
108        """ 'courses_validated' --> 'courses validated'
109        """
110        return REGSTATE_MAPPING.get(value,value)
111
112    @classmethod
113    def session(self, value):
114        """ '08' --> '2008'
115        """
116        try:
117            number = int(value)
118        except ValueError:
119            return 9999
120        if number < 14:
121            return number + 2000
122        elif number in range(2000,2015):
123            return number
124        else:
125            return 9999
126
127    @classmethod
128    def marit_stat(self, value):
129        """ 'True'/'False' --> 'married'/'unmarried'
130        """
131        if value == 'True':
132            value = 'married'
133        elif value == 'False':
134            value = 'unmarried'
135        else:
136            value = ''
137        return value
138
139    @classmethod
140    def gender(self, value):
141        """ 'True'/'False' --> 'f'/'m'
142        """
143        if value == 'True':
144            value = 'f'
145        elif value == 'False':
146            value = 'm'
147        else:
148            value = ''
149        return value
150
151    @classmethod
152    def date(self, value):
153        """ 'yyyy/mm/dd' --> 'yyyy-mm-dd'
154        """
155        if value == "None":
156            value = ""
157        elif value == "":
158            value = ""
159        else:
160            value = value.replace('/', '-')
161            # We add the hash symbol to avoid automatic date transformation
162            # in Excel and Calc for further processing
163            value += '#'
164        return value
165
166    @classmethod
167    def datetime(self, value):
168        """ 'yyyy/mm/dd' --> 'yyyy-mm-dd'
169        """
170        #print  "IN: ", value
171        if value == "None":
172            value = ""
173        elif value == "":
174            value = ""
175        else:
176            #value = datetime.datetime.strptime(value, '%Y/%m/%d')
177            #value = datetime.datetime.strftime(value, '%Y-%m-%d')
178            pass
179        #print "OUT: ", value
180        return value
181
182    @classmethod
183    def password(self, value):
184        if value == "not set":
185            return ""
186        return value
187
188
189reader = csv.DictReader(open(INPUT_FILE, 'rb'))
190writer = None
191
192for num, row in enumerate(reader):
193    if num == 0:
194        writer = csv.DictWriter(open(OUTPUT_FILE, 'wb'), reader.fieldnames)
195        print "FIELDS: "
196        for x, y in enumerate(reader.fieldnames):
197            print x, y
198        header = convert_fieldnames(reader.fieldnames)
199        writer.writerow(header)
200    for key, value in row.items():
201        if not key in OPTIONS.keys():
202            continue
203        conv_name = OPTIONS[key]
204        converter = getattr(Converters, conv_name, None)
205        if converter is None:
206            print "WARNING: cannot find converter %s" % conv_name
207            continue
208        row[key] = converter(row[key])
209    writer.writerow(row)
210
211print "Output written to %s" % OUTPUT_FILE
Note: See TracBrowser for help on using the repository browser.