1 | ## $Id: batching.py 8995 2012-07-13 08:18:02Z henrik $ |
---|
2 | ## |
---|
3 | ## Copyright (C) 2011 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 | """Batch processing components for student objects. |
---|
19 | |
---|
20 | Batch processors eat CSV files to add, update or remove large numbers |
---|
21 | of certain kinds of objects at once. |
---|
22 | |
---|
23 | Here we define the processors for students specific objects like |
---|
24 | students, studycourses, payment tickets and accommodation tickets. |
---|
25 | """ |
---|
26 | import grok |
---|
27 | import csv |
---|
28 | from time import time |
---|
29 | from zope.interface import Interface |
---|
30 | from zope.schema import getFields |
---|
31 | from zope.component import queryUtility, getUtility |
---|
32 | from zope.event import notify |
---|
33 | from zope.catalog.interfaces import ICatalog |
---|
34 | from hurry.workflow.interfaces import IWorkflowState, IWorkflowInfo |
---|
35 | from waeup.kofa.interfaces import ( |
---|
36 | IBatchProcessor, FatalCSVError, IObjectConverter, IUserAccount, |
---|
37 | IObjectHistory, VALIDATED, IGNORE_MARKER) |
---|
38 | from waeup.kofa.interfaces import MessageFactory as _ |
---|
39 | from waeup.kofa.students.interfaces import ( |
---|
40 | IStudent, IStudentStudyCourse, |
---|
41 | IStudentUpdateByRegNo, IStudentUpdateByMatricNo, |
---|
42 | IStudentStudyLevel, ICourseTicket, |
---|
43 | IStudentOnlinePayment, IStudentVerdictUpdate) |
---|
44 | from waeup.kofa.students.workflow import ( |
---|
45 | IMPORTABLE_STATES, IMPORTABLE_TRANSITIONS) |
---|
46 | from waeup.kofa.utils.batching import BatchProcessor |
---|
47 | |
---|
48 | class StudentProcessor(BatchProcessor): |
---|
49 | """A batch processor for IStudent objects. |
---|
50 | """ |
---|
51 | grok.implements(IBatchProcessor) |
---|
52 | grok.provides(IBatchProcessor) |
---|
53 | grok.context(Interface) |
---|
54 | util_name = 'studentprocessor' |
---|
55 | grok.name(util_name) |
---|
56 | |
---|
57 | name = u'Student Processor' |
---|
58 | iface = IStudent |
---|
59 | iface_byregnumber = IStudentUpdateByRegNo |
---|
60 | iface_bymatricnumber = IStudentUpdateByMatricNo |
---|
61 | |
---|
62 | location_fields = [] |
---|
63 | factory_name = 'waeup.Student' |
---|
64 | |
---|
65 | @property |
---|
66 | def available_fields(self): |
---|
67 | fields = getFields(self.iface) |
---|
68 | return sorted(list(set( |
---|
69 | ['student_id','reg_number','matric_number', |
---|
70 | 'password', 'state', 'transition'] + fields.keys()))) |
---|
71 | |
---|
72 | def checkHeaders(self, headerfields, mode='create'): |
---|
73 | if 'state' in headerfields and 'transition' in headerfields: |
---|
74 | raise FatalCSVError( |
---|
75 | "State and transition can't be imported at the same time!") |
---|
76 | if not 'reg_number' in headerfields and not 'student_id' \ |
---|
77 | in headerfields and not 'matric_number' in headerfields: |
---|
78 | raise FatalCSVError( |
---|
79 | "Need at least columns student_id or reg_number " + |
---|
80 | "or matric_number for import!") |
---|
81 | if mode == 'create': |
---|
82 | for field in self.required_fields: |
---|
83 | if not field in headerfields: |
---|
84 | raise FatalCSVError( |
---|
85 | "Need at least columns %s for import!" % |
---|
86 | ', '.join(["'%s'" % x for x in self.required_fields])) |
---|
87 | # Check for fields to be ignored... |
---|
88 | not_ignored_fields = [x for x in headerfields |
---|
89 | if not x.startswith('--')] |
---|
90 | if len(set(not_ignored_fields)) < len(not_ignored_fields): |
---|
91 | raise FatalCSVError( |
---|
92 | "Double headers: each column name may only appear once.") |
---|
93 | return True |
---|
94 | |
---|
95 | def parentsExist(self, row, site): |
---|
96 | return 'students' in site.keys() |
---|
97 | |
---|
98 | def getLocator(self, row): |
---|
99 | if row.get('student_id',None) not in (None, IGNORE_MARKER): |
---|
100 | return 'student_id' |
---|
101 | elif row.get('reg_number',None) not in (None, IGNORE_MARKER): |
---|
102 | return 'reg_number' |
---|
103 | elif row.get('matric_number',None) not in (None, IGNORE_MARKER): |
---|
104 | return 'matric_number' |
---|
105 | else: |
---|
106 | return None |
---|
107 | |
---|
108 | # The entry never exists in create mode. |
---|
109 | def entryExists(self, row, site): |
---|
110 | return self.getEntry(row, site) is not None |
---|
111 | |
---|
112 | def getParent(self, row, site): |
---|
113 | return site['students'] |
---|
114 | |
---|
115 | def getEntry(self, row, site): |
---|
116 | if not 'students' in site.keys(): |
---|
117 | return None |
---|
118 | if self.getLocator(row) == 'student_id': |
---|
119 | if row['student_id'] in site['students']: |
---|
120 | student = site['students'][row['student_id']] |
---|
121 | return student |
---|
122 | elif self.getLocator(row) == 'reg_number': |
---|
123 | reg_number = row['reg_number'] |
---|
124 | cat = queryUtility(ICatalog, name='students_catalog') |
---|
125 | results = list( |
---|
126 | cat.searchResults(reg_number=(reg_number, reg_number))) |
---|
127 | if results: |
---|
128 | return results[0] |
---|
129 | elif self.getLocator(row) == 'matric_number': |
---|
130 | matric_number = row['matric_number'] |
---|
131 | cat = queryUtility(ICatalog, name='students_catalog') |
---|
132 | results = list( |
---|
133 | cat.searchResults(matric_number=(matric_number, matric_number))) |
---|
134 | if results: |
---|
135 | return results[0] |
---|
136 | return None |
---|
137 | |
---|
138 | def addEntry(self, obj, row, site): |
---|
139 | parent = self.getParent(row, site) |
---|
140 | parent.addStudent(obj) |
---|
141 | # Reset _curr_stud_id if student_id has been imported |
---|
142 | if self.getLocator(row) == 'student_id': |
---|
143 | parent._curr_stud_id -= 1 |
---|
144 | # We have to log this if state is provided. If not, |
---|
145 | # logging is done by the event handler handle_student_added |
---|
146 | if row.has_key('state'): |
---|
147 | parent.logger.info('%s - Student record created' % obj.student_id) |
---|
148 | history = IObjectHistory(obj) |
---|
149 | history.addMessage(_('Student record created')) |
---|
150 | return |
---|
151 | |
---|
152 | def delEntry(self, row, site): |
---|
153 | student = self.getEntry(row, site) |
---|
154 | if student is not None: |
---|
155 | parent = self.getParent(row, site) |
---|
156 | parent.logger.info('%s - Student removed' % student.student_id) |
---|
157 | del parent[student.student_id] |
---|
158 | pass |
---|
159 | |
---|
160 | def checkUpdateRequirements(self, obj, row, site): |
---|
161 | """Checks requirements the object must fulfill when being updated. |
---|
162 | |
---|
163 | This method is not used in case of deleting or adding objects. |
---|
164 | |
---|
165 | Returns error messages as strings in case of requirement |
---|
166 | problems. |
---|
167 | """ |
---|
168 | transition = row.get('transition', IGNORE_MARKER) |
---|
169 | if transition not in (IGNORE_MARKER, ''): |
---|
170 | allowed_transitions = IWorkflowInfo(obj).getManualTransitionIds() |
---|
171 | if transition not in allowed_transitions: |
---|
172 | return 'Transition not allowed.' |
---|
173 | return None |
---|
174 | |
---|
175 | def updateEntry(self, obj, row, site): |
---|
176 | """Update obj to the values given in row. |
---|
177 | """ |
---|
178 | items_changed = '' |
---|
179 | |
---|
180 | # Remove student_id from row if empty |
---|
181 | if row.has_key('student_id') and row['student_id'] in ( |
---|
182 | None, IGNORE_MARKER): |
---|
183 | row.pop('student_id') |
---|
184 | |
---|
185 | # Update password |
---|
186 | if row.has_key('password'): |
---|
187 | passwd = row.get('password', IGNORE_MARKER) |
---|
188 | if passwd not in ('', IGNORE_MARKER): |
---|
189 | if passwd.startswith('{SSHA}'): |
---|
190 | # already encrypted password |
---|
191 | obj.password = passwd |
---|
192 | else: |
---|
193 | # not yet encrypted password |
---|
194 | IUserAccount(obj).setPassword(passwd) |
---|
195 | items_changed += ('%s=%s, ' % ('password', passwd)) |
---|
196 | row.pop('password') |
---|
197 | |
---|
198 | # Update registration state |
---|
199 | if row.has_key('state'): |
---|
200 | state = row.get('state', IGNORE_MARKER) |
---|
201 | if state not in (IGNORE_MARKER, ''): |
---|
202 | value = row['state'] |
---|
203 | IWorkflowState(obj).setState(value) |
---|
204 | msg = _("State '${a}' set", mapping = {'a':value}) |
---|
205 | history = IObjectHistory(obj) |
---|
206 | history.addMessage(msg) |
---|
207 | items_changed += ('%s=%s, ' % ('state', state)) |
---|
208 | row.pop('state') |
---|
209 | |
---|
210 | if row.has_key('transition'): |
---|
211 | transition = row.get('transition', IGNORE_MARKER) |
---|
212 | if transition not in (IGNORE_MARKER, ''): |
---|
213 | value = row['transition'] |
---|
214 | IWorkflowInfo(obj).fireTransition(value) |
---|
215 | items_changed += ('%s=%s, ' % ('transition', transition)) |
---|
216 | row.pop('transition') |
---|
217 | |
---|
218 | # apply other values... |
---|
219 | items_changed += super(StudentProcessor, self).updateEntry( |
---|
220 | obj, row, site) |
---|
221 | |
---|
222 | # Log actions... |
---|
223 | parent = self.getParent(row, site) |
---|
224 | if hasattr(obj,'student_id'): |
---|
225 | # Update mode: the student exists and we can get the student_id. |
---|
226 | # Create mode: the record contains the student_id |
---|
227 | parent.logger.info( |
---|
228 | '%s - Student record updated: %s' |
---|
229 | % (obj.student_id, items_changed)) |
---|
230 | else: |
---|
231 | # Create mode: the student does not yet exist |
---|
232 | parent.logger.info('Student data imported: %s' % items_changed) |
---|
233 | return items_changed |
---|
234 | |
---|
235 | def getMapping(self, path, headerfields, mode): |
---|
236 | """Get a mapping from CSV file headerfields to actually used fieldnames. |
---|
237 | """ |
---|
238 | result = dict() |
---|
239 | reader = csv.reader(open(path, 'rb')) |
---|
240 | raw_header = reader.next() |
---|
241 | for num, field in enumerate(headerfields): |
---|
242 | if field not in ['student_id', 'reg_number', 'matric_number' |
---|
243 | ] and mode == 'remove': |
---|
244 | continue |
---|
245 | if field == u'--IGNORE--': |
---|
246 | # Skip ignored columns in failed and finished data files. |
---|
247 | continue |
---|
248 | result[raw_header[num]] = field |
---|
249 | return result |
---|
250 | |
---|
251 | def checkConversion(self, row, mode='create'): |
---|
252 | """Validates all values in row. |
---|
253 | """ |
---|
254 | iface = self.iface |
---|
255 | if mode in ['update', 'remove']: |
---|
256 | if self.getLocator(row) == 'reg_number': |
---|
257 | iface = self.iface_byregnumber |
---|
258 | elif self.getLocator(row) == 'matric_number': |
---|
259 | iface = self.iface_bymatricnumber |
---|
260 | converter = IObjectConverter(iface) |
---|
261 | errs, inv_errs, conv_dict = converter.fromStringDict( |
---|
262 | row, self.factory_name, mode=mode) |
---|
263 | if row.has_key('transition') and \ |
---|
264 | not row['transition'] in IMPORTABLE_TRANSITIONS: |
---|
265 | if row['transition'] not in (IGNORE_MARKER, ''): |
---|
266 | errs.append(('transition','not allowed')) |
---|
267 | if row.has_key('state') and \ |
---|
268 | not row['state'] in IMPORTABLE_STATES: |
---|
269 | if row['state'] not in (IGNORE_MARKER, ''): |
---|
270 | errs.append(('state','not allowed')) |
---|
271 | else: |
---|
272 | # state is an attribute of Student and must not |
---|
273 | # be changed if empty |
---|
274 | conv_dict['state'] = IGNORE_MARKER |
---|
275 | |
---|
276 | try: |
---|
277 | # Correct stud_id counter. As the IConverter for students |
---|
278 | # creates student objects that are not used afterwards, we |
---|
279 | # have to fix the site-wide student_id counter. |
---|
280 | site = grok.getSite() |
---|
281 | students = site['students'] |
---|
282 | students._curr_stud_id -= 1 |
---|
283 | except (KeyError, TypeError, AttributeError): |
---|
284 | pass |
---|
285 | return errs, inv_errs, conv_dict |
---|
286 | |
---|
287 | |
---|
288 | class StudentProcessorBase(BatchProcessor): |
---|
289 | """A base for student subitem processor. |
---|
290 | |
---|
291 | Helps reducing redundancy. |
---|
292 | """ |
---|
293 | grok.baseclass() |
---|
294 | |
---|
295 | # additional available fields |
---|
296 | # beside 'student_id', 'reg_number' and 'matric_number' |
---|
297 | additional_fields = [] |
---|
298 | |
---|
299 | #: header fields additionally required |
---|
300 | additional_headers = [] |
---|
301 | |
---|
302 | @property |
---|
303 | def available_fields(self): |
---|
304 | fields = ['student_id','reg_number','matric_number' |
---|
305 | ] + self.additional_fields |
---|
306 | return sorted(list(set(fields + getFields( |
---|
307 | self.iface).keys()))) |
---|
308 | |
---|
309 | def checkHeaders(self, headerfields, mode='ignore'): |
---|
310 | if not 'reg_number' in headerfields and not 'student_id' \ |
---|
311 | in headerfields and not 'matric_number' in headerfields: |
---|
312 | raise FatalCSVError( |
---|
313 | "Need at least columns student_id " + |
---|
314 | "or reg_number or matric_number for import!") |
---|
315 | for name in self.additional_headers: |
---|
316 | if not name in headerfields: |
---|
317 | raise FatalCSVError( |
---|
318 | "Need %s for import!" % name) |
---|
319 | |
---|
320 | # Check for fields to be ignored... |
---|
321 | not_ignored_fields = [x for x in headerfields |
---|
322 | if not x.startswith('--')] |
---|
323 | if len(set(not_ignored_fields)) < len(not_ignored_fields): |
---|
324 | raise FatalCSVError( |
---|
325 | "Double headers: each column name may only appear once.") |
---|
326 | return True |
---|
327 | |
---|
328 | def _getStudent(self, row, site): |
---|
329 | NON_VALUES = ['', IGNORE_MARKER] |
---|
330 | if not 'students' in site.keys(): |
---|
331 | return None |
---|
332 | if row.get('student_id', '') not in NON_VALUES: |
---|
333 | if row['student_id'] in site['students']: |
---|
334 | student = site['students'][row['student_id']] |
---|
335 | return student |
---|
336 | elif row.get('reg_number', '') not in NON_VALUES: |
---|
337 | reg_number = row['reg_number'] |
---|
338 | cat = queryUtility(ICatalog, name='students_catalog') |
---|
339 | results = list( |
---|
340 | cat.searchResults(reg_number=(reg_number, reg_number))) |
---|
341 | if results: |
---|
342 | return results[0] |
---|
343 | elif row.get('matric_number', '') not in NON_VALUES: |
---|
344 | matric_number = row['matric_number'] |
---|
345 | cat = queryUtility(ICatalog, name='students_catalog') |
---|
346 | results = list( |
---|
347 | cat.searchResults(matric_number=(matric_number, matric_number))) |
---|
348 | if results: |
---|
349 | return results[0] |
---|
350 | return None |
---|
351 | |
---|
352 | def parentsExist(self, row, site): |
---|
353 | return self.getParent(row, site) is not None |
---|
354 | |
---|
355 | def entryExists(self, row, site): |
---|
356 | return self.getEntry(row, site) is not None |
---|
357 | |
---|
358 | def checkConversion(self, row, mode='ignore'): |
---|
359 | """Validates all values in row. |
---|
360 | """ |
---|
361 | converter = IObjectConverter(self.iface) |
---|
362 | errs, inv_errs, conv_dict = converter.fromStringDict( |
---|
363 | row, self.factory_name, mode=mode) |
---|
364 | return errs, inv_errs, conv_dict |
---|
365 | |
---|
366 | def getMapping(self, path, headerfields, mode): |
---|
367 | """Get a mapping from CSV file headerfields to actually used fieldnames. |
---|
368 | """ |
---|
369 | result = dict() |
---|
370 | reader = csv.reader(open(path, 'rb')) |
---|
371 | raw_header = reader.next() |
---|
372 | for num, field in enumerate(headerfields): |
---|
373 | if field not in ['student_id', 'reg_number', 'matric_number', |
---|
374 | 'p_id', 'code', 'level' |
---|
375 | ] and mode == 'remove': |
---|
376 | continue |
---|
377 | if field == u'--IGNORE--': |
---|
378 | # Skip ignored columns in failed and finished data files. |
---|
379 | continue |
---|
380 | result[raw_header[num]] = field |
---|
381 | return result |
---|
382 | |
---|
383 | |
---|
384 | class StudentStudyCourseProcessor(StudentProcessorBase): |
---|
385 | """A batch processor for IStudentStudyCourse objects. |
---|
386 | """ |
---|
387 | grok.implements(IBatchProcessor) |
---|
388 | grok.provides(IBatchProcessor) |
---|
389 | grok.context(Interface) |
---|
390 | util_name = 'studycourseupdater' |
---|
391 | grok.name(util_name) |
---|
392 | |
---|
393 | name = u'StudentStudyCourse Processor (update only)' |
---|
394 | iface = IStudentStudyCourse |
---|
395 | factory_name = 'waeup.StudentStudyCourse' |
---|
396 | |
---|
397 | location_fields = [] |
---|
398 | additional_fields = [] |
---|
399 | |
---|
400 | def getParent(self, row, site): |
---|
401 | return self._getStudent(row, site) |
---|
402 | |
---|
403 | def getEntry(self, row, site): |
---|
404 | student = self.getParent(row, site) |
---|
405 | if student is None: |
---|
406 | return None |
---|
407 | return student.get('studycourse') |
---|
408 | |
---|
409 | def updateEntry(self, obj, row, site): |
---|
410 | """Update obj to the values given in row. |
---|
411 | """ |
---|
412 | items_changed = super(StudentStudyCourseProcessor, self).updateEntry( |
---|
413 | obj, row, site) |
---|
414 | parent = self.getParent(row, site) |
---|
415 | parent.__parent__.logger.info( |
---|
416 | '%s - Study course updated: %s' |
---|
417 | % (parent.student_id, items_changed)) |
---|
418 | # Update the students_catalog |
---|
419 | notify(grok.ObjectModifiedEvent(obj.__parent__)) |
---|
420 | return |
---|
421 | |
---|
422 | def checkConversion(self, row, mode='ignore'): |
---|
423 | """Validates all values in row. |
---|
424 | """ |
---|
425 | errs, inv_errs, conv_dict = super( |
---|
426 | StudentStudyCourseProcessor, self).checkConversion(row, mode=mode) |
---|
427 | # We have to check if current_level is in range of certificate. |
---|
428 | if conv_dict.has_key('certificate') and \ |
---|
429 | conv_dict.has_key('current_level'): |
---|
430 | cert = conv_dict['certificate'] |
---|
431 | level = conv_dict['current_level'] |
---|
432 | if level < cert.start_level or level > cert.end_level+120: |
---|
433 | errs.append(('current_level','not in range')) |
---|
434 | return errs, inv_errs, conv_dict |
---|
435 | |
---|
436 | class StudentStudyLevelProcessor(StudentProcessorBase): |
---|
437 | """A batch processor for IStudentStudyLevel objects. |
---|
438 | """ |
---|
439 | grok.implements(IBatchProcessor) |
---|
440 | grok.provides(IBatchProcessor) |
---|
441 | grok.context(Interface) |
---|
442 | util_name = 'studylevelprocessor' |
---|
443 | grok.name(util_name) |
---|
444 | |
---|
445 | name = u'StudentStudyLevel Processor' |
---|
446 | iface = IStudentStudyLevel |
---|
447 | factory_name = 'waeup.StudentStudyLevel' |
---|
448 | |
---|
449 | location_fields = [] |
---|
450 | additional_fields = ['level'] |
---|
451 | additional_headers = ['level'] |
---|
452 | |
---|
453 | def getParent(self, row, site): |
---|
454 | student = self._getStudent(row, site) |
---|
455 | if student is None: |
---|
456 | return None |
---|
457 | return student['studycourse'] |
---|
458 | |
---|
459 | def getEntry(self, row, site): |
---|
460 | studycourse = self.getParent(row, site) |
---|
461 | if studycourse is None: |
---|
462 | return None |
---|
463 | return studycourse.get(row['level']) |
---|
464 | |
---|
465 | def updateEntry(self, obj, row, site): |
---|
466 | """Update obj to the values given in row. |
---|
467 | """ |
---|
468 | items_changed = super(StudentStudyLevelProcessor, self).updateEntry( |
---|
469 | obj, row, site) |
---|
470 | student = self.getParent(row, site).__parent__ |
---|
471 | student.__parent__.logger.info( |
---|
472 | '%s - Study level updated: %s' |
---|
473 | % (student.student_id, items_changed)) |
---|
474 | return |
---|
475 | |
---|
476 | def addEntry(self, obj, row, site): |
---|
477 | parent = self.getParent(row, site) |
---|
478 | obj.level = int(row['level']) |
---|
479 | parent[row['level']] = obj |
---|
480 | return |
---|
481 | |
---|
482 | def checkConversion(self, row, mode='ignore'): |
---|
483 | """Validates all values in row. |
---|
484 | """ |
---|
485 | errs, inv_errs, conv_dict = super( |
---|
486 | StudentStudyLevelProcessor, self).checkConversion(row, mode=mode) |
---|
487 | |
---|
488 | # We have to check if level is a valid integer. |
---|
489 | # This is not done by the converter. |
---|
490 | try: |
---|
491 | level = int(row['level']) |
---|
492 | if level not in range(0,700,10): |
---|
493 | errs.append(('level','no valid integer')) |
---|
494 | except ValueError: |
---|
495 | errs.append(('level','no integer')) |
---|
496 | return errs, inv_errs, conv_dict |
---|
497 | |
---|
498 | class CourseTicketProcessor(StudentProcessorBase): |
---|
499 | """A batch processor for ICourseTicket objects. |
---|
500 | """ |
---|
501 | grok.implements(IBatchProcessor) |
---|
502 | grok.provides(IBatchProcessor) |
---|
503 | grok.context(Interface) |
---|
504 | util_name = 'courseticketprocessor' |
---|
505 | grok.name(util_name) |
---|
506 | |
---|
507 | name = u'CourseTicket Processor' |
---|
508 | iface = ICourseTicket |
---|
509 | factory_name = 'waeup.CourseTicket' |
---|
510 | |
---|
511 | location_fields = [] |
---|
512 | additional_fields = ['level', 'code'] |
---|
513 | additional_headers = ['level', 'code'] |
---|
514 | |
---|
515 | def getParent(self, row, site): |
---|
516 | student = self._getStudent(row, site) |
---|
517 | if student is None: |
---|
518 | return None |
---|
519 | return student['studycourse'].get(row['level']) |
---|
520 | |
---|
521 | def getEntry(self, row, site): |
---|
522 | level = self.getParent(row, site) |
---|
523 | if level is None: |
---|
524 | return None |
---|
525 | return level.get(row['code']) |
---|
526 | |
---|
527 | def updateEntry(self, obj, row, site): |
---|
528 | """Update obj to the values given in row. |
---|
529 | """ |
---|
530 | items_changed = super(CourseTicketProcessor, self).updateEntry( |
---|
531 | obj, row, site) |
---|
532 | parent = self.getParent(row, site) |
---|
533 | student = self.getParent(row, site).__parent__.__parent__ |
---|
534 | student.__parent__.logger.info( |
---|
535 | '%s - Course ticket in %s updated: %s' |
---|
536 | % (student.student_id, parent.level, items_changed)) |
---|
537 | return |
---|
538 | |
---|
539 | def addEntry(self, obj, row, site): |
---|
540 | parent = self.getParent(row, site) |
---|
541 | catalog = getUtility(ICatalog, name='courses_catalog') |
---|
542 | entries = list(catalog.searchResults(code=(row['code'],row['code']))) |
---|
543 | obj.fcode = entries[0].__parent__.__parent__.__parent__.code |
---|
544 | obj.dcode = entries[0].__parent__.__parent__.code |
---|
545 | obj.title = entries[0].title |
---|
546 | obj.credits = entries[0].credits |
---|
547 | obj.passmark = entries[0].passmark |
---|
548 | obj.semester = entries[0].semester |
---|
549 | parent[row['code']] = obj |
---|
550 | return |
---|
551 | |
---|
552 | def delEntry(self, row, site): |
---|
553 | ticket = self.getEntry(row, site) |
---|
554 | parent = self.getParent(row, site) |
---|
555 | if ticket is not None: |
---|
556 | student = self._getStudent(row, site) |
---|
557 | student.__parent__.logger.info('%s - Course ticket in %s removed: %s' |
---|
558 | % (student.student_id, parent.level, ticket.code)) |
---|
559 | del parent[ticket.code] |
---|
560 | return |
---|
561 | |
---|
562 | def checkConversion(self, row, mode='ignore'): |
---|
563 | """Validates all values in row. |
---|
564 | """ |
---|
565 | errs, inv_errs, conv_dict = super( |
---|
566 | CourseTicketProcessor, self).checkConversion(row, mode=mode) |
---|
567 | |
---|
568 | # We have to check if course really exists. |
---|
569 | # This is not done by the converter. |
---|
570 | catalog = getUtility(ICatalog, name='courses_catalog') |
---|
571 | entries = catalog.searchResults(code=(row['code'],row['code'])) |
---|
572 | if len(entries) == 0: |
---|
573 | errs.append(('code','non-existent')) |
---|
574 | return errs, inv_errs, conv_dict |
---|
575 | return errs, inv_errs, conv_dict |
---|
576 | |
---|
577 | class StudentOnlinePaymentProcessor(StudentProcessorBase): |
---|
578 | """A batch processor for IStudentOnlinePayment objects. |
---|
579 | """ |
---|
580 | grok.implements(IBatchProcessor) |
---|
581 | grok.provides(IBatchProcessor) |
---|
582 | grok.context(Interface) |
---|
583 | util_name = 'paymentprocessor' |
---|
584 | grok.name(util_name) |
---|
585 | |
---|
586 | name = u'Student Payment Processor' |
---|
587 | iface = IStudentOnlinePayment |
---|
588 | factory_name = 'waeup.StudentOnlinePayment' |
---|
589 | |
---|
590 | location_fields = [] |
---|
591 | additional_fields = ['p_id'] |
---|
592 | additional_headers = [] |
---|
593 | |
---|
594 | def checkHeaders(self, headerfields, mode='ignore'): |
---|
595 | super(StudentOnlinePaymentProcessor, self).checkHeaders(headerfields) |
---|
596 | if mode in ('update', 'remove') and not 'p_id' in headerfields: |
---|
597 | raise FatalCSVError( |
---|
598 | "Need p_id for import in update and remove modes!") |
---|
599 | return True |
---|
600 | |
---|
601 | def parentsExist(self, row, site): |
---|
602 | return self.getParent(row, site) is not None |
---|
603 | |
---|
604 | def getParent(self, row, site): |
---|
605 | student = self._getStudent(row, site) |
---|
606 | if student is None: |
---|
607 | return None |
---|
608 | return student['payments'] |
---|
609 | |
---|
610 | def getEntry(self, row, site): |
---|
611 | payments = self.getParent(row, site) |
---|
612 | if payments is None: |
---|
613 | return None |
---|
614 | p_id = row.get('p_id', None) |
---|
615 | if p_id is None: |
---|
616 | return None |
---|
617 | # We can use the hash symbol at the end of p_id in import files |
---|
618 | # to avoid annoying automatic number transformation |
---|
619 | # by Excel or Calc |
---|
620 | p_id = p_id.strip('#') |
---|
621 | if not p_id.startswith('p'): |
---|
622 | # For data migration from old SRP only |
---|
623 | p_id = 'p' + p_id[7:] + '0' |
---|
624 | entry = payments.get(p_id) |
---|
625 | return entry |
---|
626 | |
---|
627 | def updateEntry(self, obj, row, site): |
---|
628 | """Update obj to the values given in row. |
---|
629 | """ |
---|
630 | items_changed = super(StudentOnlinePaymentProcessor, self).updateEntry( |
---|
631 | obj, row, site) |
---|
632 | student = self.getParent(row, site).__parent__ |
---|
633 | student.__parent__.logger.info( |
---|
634 | '%s - Payment ticket updated: %s' |
---|
635 | % (student.student_id, items_changed)) |
---|
636 | return |
---|
637 | |
---|
638 | def addEntry(self, obj, row, site): |
---|
639 | parent = self.getParent(row, site) |
---|
640 | p_id = row['p_id'].strip('#') |
---|
641 | if not p_id.startswith('p'): |
---|
642 | # For data migration from old SRP |
---|
643 | obj.p_id = 'p' + p_id[7:] + '0' |
---|
644 | parent[obj.p_id] = obj |
---|
645 | else: |
---|
646 | parent[p_id] = obj |
---|
647 | return |
---|
648 | |
---|
649 | def delEntry(self, row, site): |
---|
650 | payment = self.getEntry(row, site) |
---|
651 | parent = self.getParent(row, site) |
---|
652 | if payment is not None: |
---|
653 | student = self._getStudent(row, site) |
---|
654 | student.__parent__.logger.info('%s - Payment ticket removed: %s' |
---|
655 | % (student.student_id, payment.p_id)) |
---|
656 | del parent[payment.p_id] |
---|
657 | return |
---|
658 | |
---|
659 | def checkConversion(self, row, mode='ignore'): |
---|
660 | """Validates all values in row. |
---|
661 | """ |
---|
662 | errs, inv_errs, conv_dict = super( |
---|
663 | StudentOnlinePaymentProcessor, self).checkConversion(row, mode=mode) |
---|
664 | |
---|
665 | # We have to check p_id. |
---|
666 | p_id = row.get('p_id', None) |
---|
667 | if not p_id: |
---|
668 | timestamp = ("%d" % int(time()*10000))[1:] |
---|
669 | p_id = "p%s" % timestamp |
---|
670 | conv_dict['p_id'] = p_id |
---|
671 | return errs, inv_errs, conv_dict |
---|
672 | else: |
---|
673 | p_id = p_id.strip('#') |
---|
674 | if p_id.startswith('p'): |
---|
675 | if not len(p_id) == 14: |
---|
676 | errs.append(('p_id','invalid length')) |
---|
677 | return errs, inv_errs, conv_dict |
---|
678 | else: |
---|
679 | if not len(p_id) == 19: |
---|
680 | errs.append(('p_id','invalid length')) |
---|
681 | return errs, inv_errs, conv_dict |
---|
682 | return errs, inv_errs, conv_dict |
---|
683 | |
---|
684 | class StudentVerdictProcessor(StudentStudyCourseProcessor): |
---|
685 | """A batch processor for verdicts. |
---|
686 | |
---|
687 | Import verdicts and perform workflow transitions. |
---|
688 | """ |
---|
689 | |
---|
690 | util_name = 'verdictupdater' |
---|
691 | grok.name(util_name) |
---|
692 | |
---|
693 | name = u'Verdict Processor (update only)' |
---|
694 | iface = IStudentVerdictUpdate |
---|
695 | factory_name = 'waeup.StudentStudyCourse' |
---|
696 | |
---|
697 | additional_fields = ['current_session', 'current_level'] |
---|
698 | |
---|
699 | def checkUpdateRequirements(self, obj, row, site): |
---|
700 | """Checks requirements the studycourse and the student must fulfill |
---|
701 | before being updated. |
---|
702 | """ |
---|
703 | # Check if current_levels correspond |
---|
704 | if obj.current_level != row['current_level']: |
---|
705 | return 'Current level does not correspond.' |
---|
706 | # Check if current_sessions correspond |
---|
707 | if obj.current_session != row['current_session']: |
---|
708 | return 'Current session does not correspond.' |
---|
709 | # Check if student is in state REGISTERED |
---|
710 | if obj.student.state != VALIDATED: |
---|
711 | return 'Student in wrong state.' |
---|
712 | return None |
---|
713 | |
---|
714 | def updateEntry(self, obj, row, site): |
---|
715 | """Update obj to the values given in row. |
---|
716 | """ |
---|
717 | # Don't set current_session, current_level |
---|
718 | vals_to_set = dict((key, val) for key, val in row.items() |
---|
719 | if key not in ('current_session','current_level')) |
---|
720 | items_changed = super(StudentVerdictProcessor, self).updateEntry( |
---|
721 | obj, vals_to_set, site) |
---|
722 | parent = self.getParent(row, site) |
---|
723 | parent.__parent__.logger.info( |
---|
724 | '%s - Verdict updated: %s' |
---|
725 | % (parent.student_id, items_changed)) |
---|
726 | # Fire transition |
---|
727 | IWorkflowInfo(obj.__parent__).fireTransition('return') |
---|
728 | # Update the students_catalog |
---|
729 | notify(grok.ObjectModifiedEvent(obj.__parent__)) |
---|
730 | return |
---|