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

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

Add converter for entry_mode.

  • Property svn:keywords set to Id
File size: 8.7 KB
Line 
1## $Id: fix_import_file.py 7632 2012-02-11 07:09:57Z 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"""
31import csv
32import datetime
33import re
34import sys
35
36##
37## CONFIGURATION SECTION
38##
39# keys are fieldnames in input file, values are methods of class
40# Converter (see below)
41OPTIONS = {
42    'sex': 'gender',
43    'birthday': 'date',
44    'request_date': 'datetime',
45    'marit_stat': 'marit_stat',
46    'session': 'session',
47    'entry_session': 'session',
48    'current_session': 'session',
49    'session_id': 'session',
50    'entry_mode': 'mode',
51    'reg_state': 'reg_state',
52    'password': 'password',
53    'phone': 'phone',
54    'level': 'level',
55    'start_level': 'level',
56    'end_level': 'level',
57    'level_id': 'level',
58    'current_level': 'level',
59    'semester': 'semester',
60    'application_category': 'application_category',
61    'lga': 'lga',
62    'order_id': 'no_int',
63    }
64
65# Mapping input file colnames --> output file colnames
66COLNAME_MAPPING = {
67    # base date
68    'jamb_reg_no': 'reg_number',
69    'birthday': 'date_of_birth',
70    'clr_ac_pin': 'clr_code',
71    # study course
72    'study_course': 'certificate',
73    # study level
74    'session': 'level_session',
75    'verdict': 'level_verdict',
76    # course ticket
77    'level_id': 'level',
78    # payment ticket
79    'order_id': 'p_id',
80    'status': 'p_state',
81    'category': 'p_category',
82    'resp_pay_reference': 'r_pay_reference',
83    'resp_desc': 'r_desc',
84    'resp_approved_amount': 'r_amount_approved',
85    'item': 'p_item',
86    'amount': 'amount_auth',
87    'resp_card_num': 'r_card_num',
88    'resp_code': 'r_code',
89    'date': 'creation_date',
90    'surcharge': 'surcharge_1',
91    'session_id': 'p_session',
92    }
93
94# Mapping input regh_state --> output reg_state
95REGSTATE_MAPPING = {
96    'student_created': 'created',
97    'admitted': 'admitted',
98    'objection_raised': 'clearance started',
99    'clearance_pin_entered': 'clearance started',
100    'clearance_requested': 'clearance requested',
101    'cleared_and_validated': 'cleared',
102    'school_fee_paid': 'school fee paid',
103    'returning': 'returning',
104    'courses_registered': 'courses registered',
105    'courses_validated': 'courses validated',
106    }
107
108##
109## END OF CONFIG
110##
111
112# Look for the first sequence of numbers
113RE_PHONE = re.compile('[^\d]*(\d*)[^\d]*')
114
115def convert_fieldnames(fieldnames):
116    """Replace input fieldnames by fieldnames of COLNAME_MAPPING.
117    """
118    header = dict([(name, name) for name in fieldnames])
119    for in_name, out_name in COLNAME_MAPPING.items():
120        if in_name not in header:
121            continue
122        header[in_name] = out_name
123    return header
124
125class Converters():
126    """Converters to turn old-style values into new ones.
127    """
128    @classmethod
129    def reg_state(self, value):
130        """ 'courses_validated' --> 'courses validated'
131        """
132        return REGSTATE_MAPPING.get(value,value)
133
134    @classmethod
135    def level(self, value):
136        """ '000' --> '10'
137        """
138        try:
139            number = int(value)
140        except ValueError:
141            return 9999
142        if number == 0:
143            return 10
144        return number
145
146    @classmethod
147    def semester(self, value):
148        """ '0' --> '9'
149        """
150        try:
151            number = int(value)
152        except ValueError:
153            return 9999
154        if number == 0:
155            return 9
156        return number
157
158    @classmethod
159    def application_category(self, value):
160        """ '' --> 'no'
161        """
162        if value == '':
163            return 'no'
164        return value
165
166    @classmethod
167    def lga(self, value):
168        """ Remove apostrophe
169        """
170        if value == 'akwa_ibom_uru_offong_oruko':
171            return 'akwa_ibom_urue-offong-oruko'
172        try:
173            value = value.replace("'","")
174            value = value.lower()
175        except:
176            return ''
177        return value
178
179
180    @classmethod
181    def session(self, value):
182        """ '08' --> '2008'
183        """
184        try:
185            number = int(value)
186        except ValueError:
187            #import pdb; pdb.set_trace()
188            return 9999
189        if number < 14:
190            return number + 2000
191        elif number in range(2000,2015):
192            return number
193        else:
194            return 9999
195
196    @classmethod
197    def marit_stat(self, value):
198        """ 'True'/'False' --> 'married'/'unmarried'
199        """
200        if value in ('True','married'):
201            value = 'married'
202        elif value in ('False','unmarried'):
203            value = 'unmarried'
204        else:
205            value = ''
206        return value
207
208    @classmethod
209    def gender(self, value):
210        """ 'True'/'False' --> 'f'/'m'
211        """
212        if value in ('True','f'):
213            value = 'f'
214        elif value in ('False','m'):
215            value = 'm'
216        else:
217            value = ''
218        return value
219
220    @classmethod
221    def date(self, value):
222        """ 'yyyy/mm/dd' --> 'yyyy-mm-dd'
223        """
224        if value == "None":
225            value = ""
226        elif value == "":
227            value = ""
228        else:
229            value = value.replace('/', '-')
230            # We add the hash symbol to avoid automatic date transformation
231            # in Excel and Calc for further processing
232            value += '#'
233        return value
234
235    @classmethod
236    def no_int(self, value):
237        """ Add hash.
238        """
239        # We add the hash symbol to avoid automatic number transformation
240        # in Excel and Calc for further processing
241        value += '#'
242        return value
243
244
245    @classmethod
246    def datetime(self, value):
247        """ 'yyyy/mm/dd' --> 'yyyy-mm-dd'
248        """
249        #print  "IN: ", value
250        if value == "None":
251            value = ""
252        elif value == "":
253            value = ""
254        else:
255            #value = datetime.datetime.strptime(value, '%Y/%m/%d')
256            #value = datetime.datetime.strftime(value, '%Y-%m-%d')
257            pass
258        #print "OUT: ", value
259        return value
260
261    @classmethod
262    def mode(self, value):
263        if value == "transfer_fulltime":
264            return "transfer_ft"
265        return value
266
267    @classmethod
268    def password(self, value):
269        if value == "not set":
270            return ""
271        return value
272
273    @classmethod
274    def phone(self, value):
275        """ '<num-seq1>-<num-seq2> asd' -> '--<num-seq1><num-seq2>'
276
277        Dashes and slashes are removed before looking for sequences
278        of numbers.
279        """
280        value = value.replace('-', '')
281        value = value.replace('/', '')
282        match = RE_PHONE.match(value)
283        phone = match.groups()[0]
284        value = '--%s' % phone
285        return value
286
287
288def main():
289    input_file = '%s' % sys.argv[1]
290    output_file = '%s_edited.csv' % sys.argv[1].split('.')[0]
291    reader = csv.DictReader(open(input_file, 'rb'))
292    writer = None
293
294    for num, row in enumerate(reader):
295        if num == 0:
296            writer = csv.DictWriter(open(output_file, 'wb'), reader.fieldnames)
297            print "FIELDS: "
298            for x, y in enumerate(reader.fieldnames):
299                print x, y
300            header = convert_fieldnames(reader.fieldnames)
301            writer.writerow(header)
302        for key, value in row.items():
303            if not key in OPTIONS.keys():
304                continue
305            conv_name = OPTIONS[key]
306            converter = getattr(Converters, conv_name, None)
307            if converter is None:
308                print "WARNING: cannot find converter %s" % conv_name
309                continue
310            row[key] = converter(row[key])
311        try:
312            writer.writerow(row)
313        except:
314            print row['student_id']
315
316    print "Output written to %s" % output_file
317
318
319if __name__ == '__main__':
320    if len(sys.argv) != 2:
321        print 'Usage: %s <filename>' % __file__
322        sys.exit(1)
323    main()
Note: See TracBrowser for help on using the repository browser.