source: main/waeup.kofa/trunk/src/waeup/kofa/students/batching.py @ 8925

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

Add delEntry method to CourseTicketProcessor?.

  • Property svn:keywords set to Id
File size: 27.0 KB
Line 
1## $Id: batching.py 8888 2012-07-03 11:20:18Z 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
20Batch processors eat CSV files to add, update or remove large numbers
21of certain kinds of objects at once.
22
23Here we define the processors for students specific objects like
24students, studycourses, payment tickets and accommodation tickets.
25"""
26import grok
27import csv
28from time import time
29from zope.interface import Interface
30from zope.schema import getFields
31from zope.component import queryUtility, getUtility
32from zope.event import notify
33from zope.catalog.interfaces import ICatalog
34from hurry.workflow.interfaces import IWorkflowState, IWorkflowInfo
35from waeup.kofa.interfaces import (
36    IBatchProcessor, FatalCSVError, IObjectConverter, IUserAccount,
37    IObjectHistory, VALIDATED, IGNORE_MARKER)
38from waeup.kofa.interfaces import MessageFactory as _
39from waeup.kofa.students.interfaces import (
40    IStudent, IStudentStudyCourse,
41    IStudentUpdateByRegNo, IStudentUpdateByMatricNo,
42    IStudentStudyLevel, ICourseTicket,
43    IStudentOnlinePayment, IStudentVerdictUpdate)
44from waeup.kofa.students.workflow import  (
45    IMPORTABLE_STATES, IMPORTABLE_TRANSITIONS)
46from waeup.kofa.utils.batching import BatchProcessor
47
48class 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            parent.logger.info(
227                '%s - Student record updated: %s'
228                % (obj.student_id, items_changed))
229        else:
230            # Create mode: the student does not yet exist
231            parent.logger.info('Student data imported: %s' % items_changed)
232        return items_changed
233
234    def getMapping(self, path, headerfields, mode):
235        """Get a mapping from CSV file headerfields to actually used fieldnames.
236        """
237        result = dict()
238        reader = csv.reader(open(path, 'rb'))
239        raw_header = reader.next()
240        for num, field in enumerate(headerfields):
241            if field not in ['student_id', 'reg_number', 'matric_number'
242                             ] and mode == 'remove':
243                continue
244            if field == u'--IGNORE--':
245                # Skip ignored columns in failed and finished data files.
246                continue
247            result[raw_header[num]] = field
248        return result
249
250    def checkConversion(self, row, mode='create'):
251        """Validates all values in row.
252        """
253        iface = self.iface
254        if mode in ['update', 'remove']:
255            if self.getLocator(row) == 'reg_number':
256                iface = self.iface_byregnumber
257            elif self.getLocator(row) == 'matric_number':
258                iface = self.iface_bymatricnumber
259        converter = IObjectConverter(iface)
260        errs, inv_errs, conv_dict =  converter.fromStringDict(
261            row, self.factory_name, mode=mode)
262        if row.has_key('transition') and \
263            not row['transition'] in IMPORTABLE_TRANSITIONS:
264            if row['transition'] not in (IGNORE_MARKER, ''):
265                errs.append(('transition','not allowed'))
266        if row.has_key('state') and \
267            not row['state'] in IMPORTABLE_STATES:
268            if row['state'] not in (IGNORE_MARKER, ''):
269                errs.append(('state','not allowed'))
270            else:
271                # state is an attribute of Student and must not
272                # be changed if empty
273                conv_dict['state'] = IGNORE_MARKER
274
275        try:
276            # Correct stud_id counter. As the IConverter for students
277            # creates student objects that are not used afterwards, we
278            # have to fix the site-wide student_id counter.
279            site = grok.getSite()
280            students = site['students']
281            students._curr_stud_id -= 1
282        except (KeyError, TypeError, AttributeError):
283                pass
284        return errs, inv_errs, conv_dict
285
286
287class StudentProcessorBase(BatchProcessor):
288    """A base for student subitem processor.
289
290    Helps reducing redundancy.
291    """
292    grok.baseclass()
293
294    # additional available  fields
295    # beside 'student_id', 'reg_number' and 'matric_number'
296    additional_fields = []
297
298    #: header fields additionally required
299    additional_headers = []
300
301    @property
302    def available_fields(self):
303        fields = ['student_id','reg_number','matric_number'
304                  ] + self.additional_fields
305        return sorted(list(set(fields + getFields(
306                self.iface).keys())))
307
308    def checkHeaders(self, headerfields, mode='ignore'):
309        if not 'reg_number' in headerfields and not 'student_id' \
310            in headerfields and not 'matric_number' in headerfields:
311            raise FatalCSVError(
312                "Need at least columns student_id " +
313                "or reg_number or matric_number for import!")
314        for name in self.additional_headers:
315            if not name in headerfields:
316                raise FatalCSVError(
317                    "Need %s for import!" % name)
318
319        # Check for fields to be ignored...
320        not_ignored_fields = [x for x in headerfields
321                              if not x.startswith('--')]
322        if len(set(not_ignored_fields)) < len(not_ignored_fields):
323            raise FatalCSVError(
324                "Double headers: each column name may only appear once.")
325        return True
326
327    def _getStudent(self, row, site):
328        NON_VALUES = ['', IGNORE_MARKER]
329        if not 'students' in site.keys():
330            return None
331        if row.get('student_id', '') not in NON_VALUES:
332            if row['student_id'] in site['students']:
333                student = site['students'][row['student_id']]
334                return student
335        elif row.get('reg_number', '') not in NON_VALUES:
336            reg_number = row['reg_number']
337            cat = queryUtility(ICatalog, name='students_catalog')
338            results = list(
339                cat.searchResults(reg_number=(reg_number, reg_number)))
340            if results:
341                return results[0]
342        elif row.get('matric_number', '') not in NON_VALUES:
343            matric_number = row['matric_number']
344            cat = queryUtility(ICatalog, name='students_catalog')
345            results = list(
346                cat.searchResults(matric_number=(matric_number, matric_number)))
347            if results:
348                return results[0]
349        return None
350
351    def parentsExist(self, row, site):
352        return self.getParent(row, site) is not None
353
354    def entryExists(self, row, site):
355        return self.getEntry(row, site) is not None
356
357    def checkConversion(self, row, mode='ignore'):
358        """Validates all values in row.
359        """
360        converter = IObjectConverter(self.iface)
361        errs, inv_errs, conv_dict =  converter.fromStringDict(
362            row, self.factory_name, mode=mode)
363        return errs, inv_errs, conv_dict
364
365    def getMapping(self, path, headerfields, mode):
366        """Get a mapping from CSV file headerfields to actually used fieldnames.
367        """
368        result = dict()
369        reader = csv.reader(open(path, 'rb'))
370        raw_header = reader.next()
371        for num, field in enumerate(headerfields):
372            if field not in ['student_id', 'reg_number', 'matric_number',
373                             'p_id', 'code', 'level'
374                             ] and mode == 'remove':
375                continue
376            if field == u'--IGNORE--':
377                # Skip ignored columns in failed and finished data files.
378                continue
379            result[raw_header[num]] = field
380        return result
381
382
383class StudentStudyCourseProcessor(StudentProcessorBase):
384    """A batch processor for IStudentStudyCourse objects.
385    """
386    grok.implements(IBatchProcessor)
387    grok.provides(IBatchProcessor)
388    grok.context(Interface)
389    util_name = 'studycourseupdater'
390    grok.name(util_name)
391
392    name = u'StudentStudyCourse Processor (update only)'
393    iface = IStudentStudyCourse
394    factory_name = 'waeup.StudentStudyCourse'
395
396    location_fields = []
397    additional_fields = []
398
399    def getParent(self, row, site):
400        return self._getStudent(row, site)
401
402    def getEntry(self, row, site):
403        student = self.getParent(row, site)
404        if student is None:
405            return None
406        return student.get('studycourse')
407
408    def updateEntry(self, obj, row, site):
409        """Update obj to the values given in row.
410        """
411        items_changed = super(StudentStudyCourseProcessor, self).updateEntry(
412            obj, row, site)
413        parent = self.getParent(row, site)
414        parent.__parent__.logger.info(
415            '%s - Study course updated: %s'
416            % (parent.student_id, items_changed))
417        # Update the students_catalog
418        notify(grok.ObjectModifiedEvent(obj.__parent__))
419        return
420
421    def checkConversion(self, row, mode='ignore'):
422        """Validates all values in row.
423        """
424        errs, inv_errs, conv_dict = super(
425            StudentStudyCourseProcessor, self).checkConversion(row, mode=mode)
426        # We have to check if current_level is in range of certificate.
427        if conv_dict.has_key('certificate'):
428          cert = conv_dict['certificate']
429          if conv_dict['current_level'] < cert.start_level or \
430              conv_dict['current_level'] > cert.end_level+120:
431              errs.append(('current_level','not in range'))
432        return errs, inv_errs, conv_dict
433
434class StudentStudyLevelProcessor(StudentProcessorBase):
435    """A batch processor for IStudentStudyLevel objects.
436    """
437    grok.implements(IBatchProcessor)
438    grok.provides(IBatchProcessor)
439    grok.context(Interface)
440    util_name = 'studylevelprocessor'
441    grok.name(util_name)
442
443    name = u'StudentStudyLevel Processor'
444    iface = IStudentStudyLevel
445    factory_name = 'waeup.StudentStudyLevel'
446
447    location_fields = []
448    additional_fields = ['level']
449    additional_headers = ['level']
450
451    def getParent(self, row, site):
452        student = self._getStudent(row, site)
453        if student is None:
454            return None
455        return student['studycourse']
456
457    def getEntry(self, row, site):
458        studycourse = self.getParent(row, site)
459        if studycourse is None:
460            return None
461        return studycourse.get(row['level'])
462
463    def updateEntry(self, obj, row, site):
464        """Update obj to the values given in row.
465        """
466        items_changed = super(StudentStudyLevelProcessor, self).updateEntry(
467            obj, row, site)
468        student = self.getParent(row, site).__parent__
469        student.__parent__.logger.info(
470            '%s - Study level updated: %s'
471            % (student.student_id, items_changed))
472        return
473
474    def addEntry(self, obj, row, site):
475        parent = self.getParent(row, site)
476        obj.level = int(row['level'])
477        parent[row['level']] = obj
478        return
479
480    def checkConversion(self, row, mode='ignore'):
481        """Validates all values in row.
482        """
483        errs, inv_errs, conv_dict = super(
484            StudentStudyLevelProcessor, self).checkConversion(row, mode=mode)
485
486        # We have to check if level is a valid integer.
487        # This is not done by the converter.
488        try:
489            level = int(row['level'])
490            if level not in range(0,700,10):
491                errs.append(('level','no valid integer'))
492        except ValueError:
493            errs.append(('level','no integer'))
494        return errs, inv_errs, conv_dict
495
496class CourseTicketProcessor(StudentProcessorBase):
497    """A batch processor for ICourseTicket objects.
498    """
499    grok.implements(IBatchProcessor)
500    grok.provides(IBatchProcessor)
501    grok.context(Interface)
502    util_name = 'courseticketprocessor'
503    grok.name(util_name)
504
505    name = u'CourseTicket Processor'
506    iface = ICourseTicket
507    factory_name = 'waeup.CourseTicket'
508
509    location_fields = []
510    additional_fields = ['level', 'code']
511    additional_headers = ['level', 'code']
512
513    def getParent(self, row, site):
514        student = self._getStudent(row, site)
515        if student is None:
516            return None
517        return student['studycourse'].get(row['level'])
518
519    def getEntry(self, row, site):
520        level = self.getParent(row, site)
521        if level is None:
522            return None
523        return level.get(row['code'])
524
525    def updateEntry(self, obj, row, site):
526        """Update obj to the values given in row.
527        """
528        items_changed = super(CourseTicketProcessor, self).updateEntry(
529            obj, row, site)
530        parent = self.getParent(row, site)
531        student = self.getParent(row, site).__parent__.__parent__
532        student.__parent__.logger.info(
533            '%s - Course ticket in %s updated: %s'
534            % (student.student_id,  parent.level, items_changed))
535        return
536
537    def addEntry(self, obj, row, site):
538        parent = self.getParent(row, site)
539        catalog = getUtility(ICatalog, name='courses_catalog')
540        entries = list(catalog.searchResults(code=(row['code'],row['code'])))
541        obj.fcode = entries[0].__parent__.__parent__.__parent__.code
542        obj.dcode = entries[0].__parent__.__parent__.code
543        obj.title = entries[0].title
544        obj.credits = entries[0].credits
545        obj.passmark = entries[0].passmark
546        obj.semester = entries[0].semester
547        parent[row['code']] = obj
548        return
549
550    def delEntry(self, row, site):
551        ticket = self.getEntry(row, site)
552        parent = self.getParent(row, site)
553        if ticket is not None:
554            student = self._getStudent(row, site)
555            student.__parent__.logger.info('%s - Course ticket in %s removed: %s'
556                % (student.student_id, parent.level, ticket.code))
557            del parent[ticket.code]
558        return
559
560    def checkConversion(self, row, mode='ignore'):
561        """Validates all values in row.
562        """
563        errs, inv_errs, conv_dict = super(
564            CourseTicketProcessor, self).checkConversion(row, mode=mode)
565
566        # We have to check if course really exists.
567        # This is not done by the converter.
568        catalog = getUtility(ICatalog, name='courses_catalog')
569        entries = catalog.searchResults(code=(row['code'],row['code']))
570        if len(entries) == 0:
571            errs.append(('code','non-existent'))
572            return errs, inv_errs, conv_dict
573        return errs, inv_errs, conv_dict
574
575class StudentOnlinePaymentProcessor(StudentProcessorBase):
576    """A batch processor for IStudentOnlinePayment objects.
577    """
578    grok.implements(IBatchProcessor)
579    grok.provides(IBatchProcessor)
580    grok.context(Interface)
581    util_name = 'paymentprocessor'
582    grok.name(util_name)
583
584    name = u'Payment Processor'
585    iface = IStudentOnlinePayment
586    factory_name = 'waeup.StudentOnlinePayment'
587
588    location_fields = []
589    additional_fields = ['p_id']
590    additional_headers = []
591
592    def checkHeaders(self, headerfields, mode='ignore'):
593        super(StudentOnlinePaymentProcessor, self).checkHeaders(headerfields)
594        if mode in ('update', 'remove') and not 'p_id' in headerfields:
595            raise FatalCSVError(
596                "Need p_id for import in update and remove modes!")
597        return True
598
599    def parentsExist(self, row, site):
600        return self.getParent(row, site) is not None
601
602    def getParent(self, row, site):
603        student = self._getStudent(row, site)
604        if student is None:
605            return None
606        return student['payments']
607
608    def getEntry(self, row, site):
609        payments = self.getParent(row, site)
610        if payments is None:
611            return None
612        p_id = row.get('p_id', None)
613        if p_id is None:
614            return None
615        # We can use the hash symbol at the end of p_id in import files
616        # to avoid annoying automatic number transformation
617        # by Excel or Calc
618        p_id = p_id.strip('#')
619        if not p_id.startswith('p'):
620            # For data migration from old SRP only
621            p_id = 'p' + p_id[7:] + '0'
622        entry = payments.get(p_id)
623        return entry
624
625    def updateEntry(self, obj, row, site):
626        """Update obj to the values given in row.
627        """
628        items_changed = super(StudentOnlinePaymentProcessor, self).updateEntry(
629            obj, row, site)
630        student = self.getParent(row, site).__parent__
631        student.__parent__.logger.info(
632            '%s - Payment ticket updated: %s'
633            % (student.student_id, items_changed))
634        return
635
636    def addEntry(self, obj, row, site):
637        parent = self.getParent(row, site)
638        p_id = row['p_id'].strip('#')
639        if not p_id.startswith('p'):
640            # For data migration from old SRP
641            obj.p_id = 'p' + p_id[7:] + '0'
642            parent[obj.p_id] = obj
643        else:
644            parent[p_id] = obj
645        return
646
647    def delEntry(self, row, site):
648        payment = self.getEntry(row, site)
649        parent = self.getParent(row, site)
650        if payment is not None:
651            student = self._getStudent(row, site)
652            student.__parent__.logger.info('%s - Payment ticket removed: %s'
653                % (student.student_id, payment.p_id))
654            del parent[payment.p_id]
655        return
656
657    def checkConversion(self, row, mode='ignore'):
658        """Validates all values in row.
659        """
660        errs, inv_errs, conv_dict = super(
661            StudentOnlinePaymentProcessor, self).checkConversion(row, mode=mode)
662
663        # We have to check p_id.
664        p_id = row.get('p_id', None)
665        if p_id is None:
666            timestamp = ("%d" % int(time()*10000))[1:]
667            p_id = "p%s" % timestamp
668            conv_dict['p_id'] = p_id
669            return errs, inv_errs, conv_dict
670        else:
671            p_id = p_id.strip('#')
672        if p_id.startswith('p'):
673            if not len(p_id) == 14:
674                errs.append(('p_id','invalid length'))
675                return errs, inv_errs, conv_dict
676        else:
677            if not len(p_id) == 19:
678                errs.append(('p_id','invalid length'))
679                return errs, inv_errs, conv_dict
680        return errs, inv_errs, conv_dict
681
682class StudentVerdictProcessor(StudentStudyCourseProcessor):
683    """A batch processor for verdicts.
684
685    Import verdicts and perform workflow transitions.
686    """
687
688    util_name = 'verdictupdater'
689    grok.name(util_name)
690
691    name = u'Verdict Processor (update only)'
692    iface = IStudentVerdictUpdate
693    factory_name = 'waeup.StudentStudyCourse'
694
695    additional_fields = ['current_session', 'current_level']
696
697    def checkUpdateRequirements(self, obj, row, site):
698        """Checks requirements the studycourse and the student must fulfill
699        before being updated.
700        """
701        # Check if current_levels correspond
702        if obj.current_level != row['current_level']:
703            return 'Current level does not correspond.'
704        # Check if current_sessions correspond
705        if obj.current_session != row['current_session']:
706            return 'Current session does not correspond.'
707        # Check if student is in state REGISTERED
708        if obj.student.state != VALIDATED:
709            return 'Student in wrong state.'
710        return None
711
712    def updateEntry(self, obj, row, site):
713        """Update obj to the values given in row.
714        """
715        # Don't set current_session, current_level
716        vals_to_set = dict((key, val) for key, val in row.items()
717                           if key not in ('current_session','current_level'))
718        items_changed = super(StudentVerdictProcessor, self).updateEntry(
719            obj, vals_to_set, site)
720        parent = self.getParent(row, site)
721        parent.__parent__.logger.info(
722            '%s - Verdict updated: %s'
723            % (parent.student_id, items_changed))
724        # Fire transition
725        IWorkflowInfo(obj.__parent__).fireTransition('return')
726        # Update the students_catalog
727        notify(grok.ObjectModifiedEvent(obj.__parent__))
728        return
Note: See TracBrowser for help on using the repository browser.