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

Last change on this file since 11062 was 10479, checked in by Henrik Bettermann, 11 years ago

Reinvent temporary/unrectified/momentary/sessional gpa as a property attribute of study levels. The sessional gpa shown on transcript slips is now called 'rectified sessional gpa'.

  • Property svn:keywords set to Id
File size: 33.7 KB
RevLine 
[7191]1## $Id: batching.py 10479 2013-08-12 08:57:26Z 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##
[7433]18"""Batch processing components for student objects.
[6821]19
20Batch processors eat CSV files to add, update or remove large numbers
21of certain kinds of objects at once.
22
[7261]23Here we define the processors for students specific objects like
24students, studycourses, payment tickets and accommodation tickets.
[6821]25"""
26import grok
[10028]27import unicodecsv as csv # XXX: csv ops should move to dedicated module.
[8884]28from time import time
[9295]29from datetime import datetime
[9296]30from zope.i18n import translate
[6821]31from zope.interface import Interface
[6825]32from zope.schema import getFields
[9960]33from zope.component import queryUtility, getUtility, createObject
[7429]34from zope.event import notify
[6825]35from zope.catalog.interfaces import ICatalog
[7951]36from hurry.workflow.interfaces import IWorkflowState, IWorkflowInfo
[7811]37from waeup.kofa.interfaces import (
[7522]38    IBatchProcessor, FatalCSVError, IObjectConverter, IUserAccount,
[9284]39    IObjectHistory, VALIDATED, REGISTERED, IGNORE_MARKER)
[9296]40from waeup.kofa.interfaces import IKofaUtils
[7959]41from waeup.kofa.interfaces import MessageFactory as _
[7811]42from waeup.kofa.students.interfaces import (
[9960]43    IStudent, IStudentStudyCourse, IStudentStudyCourseTransfer,
[7536]44    IStudentUpdateByRegNo, IStudentUpdateByMatricNo,
[9420]45    IStudentStudyLevel, ICourseTicketImport,
[8174]46    IStudentOnlinePayment, IStudentVerdictUpdate)
[8309]47from waeup.kofa.students.workflow import  (
[9028]48    IMPORTABLE_STATES, IMPORTABLE_TRANSITIONS,
49    FORBIDDEN_POSTGRAD_TRANS, FORBIDDEN_POSTGRAD_STATES)
[7811]50from waeup.kofa.utils.batching import BatchProcessor
[6821]51
52class StudentProcessor(BatchProcessor):
53    """A batch processor for IStudent objects.
54    """
55    grok.implements(IBatchProcessor)
56    grok.provides(IBatchProcessor)
57    grok.context(Interface)
[7933]58    util_name = 'studentprocessor'
[6821]59    grok.name(util_name)
60
[7933]61    name = u'Student Processor'
[6821]62    iface = IStudent
[8581]63    iface_byregnumber = IStudentUpdateByRegNo
64    iface_bymatricnumber = IStudentUpdateByMatricNo
[6821]65
[6849]66    location_fields = []
[6821]67    factory_name = 'waeup.Student'
68
69    @property
[6849]70    def available_fields(self):
[8176]71        fields = getFields(self.iface)
[6849]72        return sorted(list(set(
[7513]73            ['student_id','reg_number','matric_number',
[8309]74            'password', 'state', 'transition'] + fields.keys())))
[6821]75
[6849]76    def checkHeaders(self, headerfields, mode='create'):
[8309]77        if 'state' in headerfields and 'transition' in headerfields:
78            raise FatalCSVError(
79                "State and transition can't be  imported at the same time!")
[6854]80        if not 'reg_number' in headerfields and not 'student_id' \
81            in headerfields and not 'matric_number' in headerfields:
[6849]82            raise FatalCSVError(
[6854]83                "Need at least columns student_id or reg_number " +
84                "or matric_number for import!")
[6849]85        if mode == 'create':
86            for field in self.required_fields:
87                if not field in headerfields:
88                    raise FatalCSVError(
89                        "Need at least columns %s for import!" %
90                        ', '.join(["'%s'" % x for x in self.required_fields]))
91        # Check for fields to be ignored...
92        not_ignored_fields = [x for x in headerfields
93                              if not x.startswith('--')]
94        if len(set(not_ignored_fields)) < len(not_ignored_fields):
95            raise FatalCSVError(
96                "Double headers: each column name may only appear once.")
97        return True
98
[6821]99    def parentsExist(self, row, site):
100        return 'students' in site.keys()
101
[6849]102    def getLocator(self, row):
[8232]103        if row.get('student_id',None) not in (None, IGNORE_MARKER):
[6849]104            return 'student_id'
[8232]105        elif row.get('reg_number',None) not in (None, IGNORE_MARKER):
[6849]106            return 'reg_number'
[8232]107        elif row.get('matric_number',None) not in (None, IGNORE_MARKER):
[6849]108            return 'matric_number'
109        else:
110            return None
111
[6821]112    # The entry never exists in create mode.
113    def entryExists(self, row, site):
[7267]114        return self.getEntry(row, site) is not None
115
116    def getParent(self, row, site):
117        return site['students']
118
119    def getEntry(self, row, site):
[6846]120        if not 'students' in site.keys():
[6849]121            return None
122        if self.getLocator(row) == 'student_id':
[6846]123            if row['student_id'] in site['students']:
124                student = site['students'][row['student_id']]
125                return student
[6849]126        elif self.getLocator(row) == 'reg_number':
[6846]127            reg_number = row['reg_number']
128            cat = queryUtility(ICatalog, name='students_catalog')
129            results = list(
130                cat.searchResults(reg_number=(reg_number, reg_number)))
131            if results:
132                return results[0]
[6849]133        elif self.getLocator(row) == 'matric_number':
[6846]134            matric_number = row['matric_number']
135            cat = queryUtility(ICatalog, name='students_catalog')
136            results = list(
137                cat.searchResults(matric_number=(matric_number, matric_number)))
138            if results:
139                return results[0]
[6849]140        return None
[6821]141
142    def addEntry(self, obj, row, site):
143        parent = self.getParent(row, site)
144        parent.addStudent(obj)
[8491]145        # Reset _curr_stud_id if student_id has been imported
146        if self.getLocator(row) == 'student_id':
147            parent._curr_stud_id -= 1
[8287]148        # We have to log this if state is provided. If not,
[7959]149        # logging is done by the event handler handle_student_added
[9701]150        if 'state' in row:
[7959]151            parent.logger.info('%s - Student record created' % obj.student_id)
[7656]152        history = IObjectHistory(obj)
[7959]153        history.addMessage(_('Student record created'))
[6821]154        return
155
156    def delEntry(self, row, site):
[7267]157        student = self.getEntry(row, site)
[7263]158        if student is not None:
[6846]159            parent = self.getParent(row, site)
[7656]160            parent.logger.info('%s - Student removed' % student.student_id)
[6846]161            del parent[student.student_id]
[6821]162        pass
[6825]163
[8309]164    def checkUpdateRequirements(self, obj, row, site):
165        """Checks requirements the object must fulfill when being updated.
166
167        This method is not used in case of deleting or adding objects.
168
169        Returns error messages as strings in case of requirement
170        problems.
171        """
172        transition = row.get('transition', IGNORE_MARKER)
173        if transition not in (IGNORE_MARKER, ''):
174            allowed_transitions = IWorkflowInfo(obj).getManualTransitionIds()
175            if transition not in allowed_transitions:
176                return 'Transition not allowed.'
[9028]177            if transition in FORBIDDEN_POSTGRAD_TRANS and \
178                obj.is_postgrad:
179                return 'Transition not allowed (pg student).'
180        state = row.get('state', IGNORE_MARKER)
181        if state not in (IGNORE_MARKER, ''):
182            if state in FORBIDDEN_POSTGRAD_STATES and \
183                obj.is_postgrad:
184                return 'State not allowed (pg student).'
[8309]185        return None
186
[9706]187    def updateEntry(self, obj, row, site, filename):
[7497]188        """Update obj to the values given in row.
189        """
[8221]190        items_changed = ''
191
[7643]192        # Remove student_id from row if empty
[9701]193        if 'student_id' in row and row['student_id'] in (None, IGNORE_MARKER):
[7643]194            row.pop('student_id')
[8221]195
196        # Update password
[9701]197        # XXX: Take DELETION_MARKER into consideration
198        if 'password' in row:
[8498]199            passwd = row.get('password', IGNORE_MARKER)
200            if passwd not in ('', IGNORE_MARKER):
201                if passwd.startswith('{SSHA}'):
202                    # already encrypted password
203                    obj.password = passwd
204                else:
205                    # not yet encrypted password
206                    IUserAccount(obj).setPassword(passwd)
207                items_changed += ('%s=%s, ' % ('password', passwd))
[8221]208            row.pop('password')
209
210        # Update registration state
[9701]211        if 'state' in row:
[8498]212            state = row.get('state', IGNORE_MARKER)
213            if state not in (IGNORE_MARKER, ''):
214                value = row['state']
215                IWorkflowState(obj).setState(value)
216                msg = _("State '${a}' set", mapping = {'a':value})
217                history = IObjectHistory(obj)
218                history.addMessage(msg)
219                items_changed += ('%s=%s, ' % ('state', state))
[8287]220            row.pop('state')
[8498]221
[9701]222        if 'transition' in row:
[8498]223            transition = row.get('transition', IGNORE_MARKER)
224            if transition not in (IGNORE_MARKER, ''):
225                value = row['transition']
226                IWorkflowInfo(obj).fireTransition(value)
227                items_changed += ('%s=%s, ' % ('transition', transition))
[8309]228            row.pop('transition')
[8221]229
230        # apply other values...
[8498]231        items_changed += super(StudentProcessor, self).updateEntry(
[9706]232            obj, row, site, filename)
[8221]233
234        # Log actions...
[7656]235        parent = self.getParent(row, site)
236        if hasattr(obj,'student_id'):
[8995]237            # Update mode: the student exists and we can get the student_id.
238            # Create mode: the record contains the student_id
[7656]239            parent.logger.info(
[9706]240                '%s - %s - %s - updated: %s'
241                % (self.name, filename, obj.student_id, items_changed))
[7656]242        else:
243            # Create mode: the student does not yet exist
[9706]244            # XXX: It seems that this never happens because student_id
245            # is always set.
246            parent.logger.info(
247                '%s - %s - %s - imported: %s'
248                % (self.name, filename, obj.student_id, items_changed))
[8221]249        return items_changed
[7497]250
[6849]251    def getMapping(self, path, headerfields, mode):
252        """Get a mapping from CSV file headerfields to actually used fieldnames.
253        """
254        result = dict()
255        reader = csv.reader(open(path, 'rb'))
256        raw_header = reader.next()
257        for num, field in enumerate(headerfields):
[8221]258            if field not in ['student_id', 'reg_number', 'matric_number'
259                             ] and mode == 'remove':
[6849]260                continue
261            if field == u'--IGNORE--':
262                # Skip ignored columns in failed and finished data files.
263                continue
264            result[raw_header[num]] = field
265        return result
266
267    def checkConversion(self, row, mode='create'):
268        """Validates all values in row.
269        """
[7643]270        iface = self.iface
[6849]271        if mode in ['update', 'remove']:
272            if self.getLocator(row) == 'reg_number':
[8581]273                iface = self.iface_byregnumber
[6849]274            elif self.getLocator(row) == 'matric_number':
[8581]275                iface = self.iface_bymatricnumber
[6849]276        converter = IObjectConverter(iface)
277        errs, inv_errs, conv_dict =  converter.fromStringDict(
[8214]278            row, self.factory_name, mode=mode)
[9701]279        if 'transition' in row:
[9028]280            if row['transition'] not in IMPORTABLE_TRANSITIONS:
281                if row['transition'] not in (IGNORE_MARKER, ''):
282                    errs.append(('transition','not allowed'))
[9701]283        if 'state' in row:
[9028]284            if row['state'] not in IMPORTABLE_STATES:
285                if row['state'] not in (IGNORE_MARKER, ''):
286                    errs.append(('state','not allowed'))
287                else:
288                    # State is an attribute of Student and must not
289                    # be changed if empty.
290                    conv_dict['state'] = IGNORE_MARKER
[8490]291        try:
292            # Correct stud_id counter. As the IConverter for students
293            # creates student objects that are not used afterwards, we
294            # have to fix the site-wide student_id counter.
295            site = grok.getSite()
296            students = site['students']
297            students._curr_stud_id -= 1
298        except (KeyError, TypeError, AttributeError):
299                pass
[6849]300        return errs, inv_errs, conv_dict
301
[8232]302
303class StudentProcessorBase(BatchProcessor):
304    """A base for student subitem processor.
305
306    Helps reducing redundancy.
[6825]307    """
[8232]308    grok.baseclass()
[6825]309
[9420]310    # additional available fields
[8884]311    # beside 'student_id', 'reg_number' and 'matric_number'
[8232]312    additional_fields = []
[6825]313
[8884]314    #: header fields additionally required
[8232]315    additional_headers = []
[6849]316
[6825]317    @property
318    def available_fields(self):
[8232]319        fields = ['student_id','reg_number','matric_number'
320                  ] + self.additional_fields
321        return sorted(list(set(fields + getFields(
[6843]322                self.iface).keys())))
[6825]323
[6837]324    def checkHeaders(self, headerfields, mode='ignore'):
[6854]325        if not 'reg_number' in headerfields and not 'student_id' \
326            in headerfields and not 'matric_number' in headerfields:
[6825]327            raise FatalCSVError(
[6854]328                "Need at least columns student_id " +
329                "or reg_number or matric_number for import!")
[8232]330        for name in self.additional_headers:
331            if not name in headerfields:
332                raise FatalCSVError(
333                    "Need %s for import!" % name)
334
[6834]335        # Check for fields to be ignored...
[6825]336        not_ignored_fields = [x for x in headerfields
337                              if not x.startswith('--')]
338        if len(set(not_ignored_fields)) < len(not_ignored_fields):
339            raise FatalCSVError(
340                "Double headers: each column name may only appear once.")
341        return True
342
[8232]343    def _getStudent(self, row, site):
[8225]344        NON_VALUES = ['', IGNORE_MARKER]
[6846]345        if not 'students' in site.keys():
[6849]346            return None
[8225]347        if row.get('student_id', '') not in NON_VALUES:
[6825]348            if row['student_id'] in site['students']:
349                student = site['students'][row['student_id']]
350                return student
[8225]351        elif row.get('reg_number', '') not in NON_VALUES:
[6825]352            reg_number = row['reg_number']
353            cat = queryUtility(ICatalog, name='students_catalog')
354            results = list(
355                cat.searchResults(reg_number=(reg_number, reg_number)))
356            if results:
357                return results[0]
[8225]358        elif row.get('matric_number', '') not in NON_VALUES:
[6843]359            matric_number = row['matric_number']
360            cat = queryUtility(ICatalog, name='students_catalog')
361            results = list(
362                cat.searchResults(matric_number=(matric_number, matric_number)))
363            if results:
364                return results[0]
[6849]365        return None
[6825]366
[7267]367    def parentsExist(self, row, site):
368        return self.getParent(row, site) is not None
369
[6825]370    def entryExists(self, row, site):
[7534]371        return self.getEntry(row, site) is not None
[6825]372
[8232]373    def checkConversion(self, row, mode='ignore'):
374        """Validates all values in row.
375        """
376        converter = IObjectConverter(self.iface)
377        errs, inv_errs, conv_dict =  converter.fromStringDict(
378            row, self.factory_name, mode=mode)
379        return errs, inv_errs, conv_dict
380
[8885]381    def getMapping(self, path, headerfields, mode):
382        """Get a mapping from CSV file headerfields to actually used fieldnames.
383        """
384        result = dict()
385        reader = csv.reader(open(path, 'rb'))
386        raw_header = reader.next()
387        for num, field in enumerate(headerfields):
[8888]388            if field not in ['student_id', 'reg_number', 'matric_number',
389                             'p_id', 'code', 'level'
[8885]390                             ] and mode == 'remove':
391                continue
392            if field == u'--IGNORE--':
393                # Skip ignored columns in failed and finished data files.
394                continue
395            result[raw_header[num]] = field
396        return result
[8232]397
[8885]398
[8232]399class StudentStudyCourseProcessor(StudentProcessorBase):
400    """A batch processor for IStudentStudyCourse objects.
401    """
402    grok.implements(IBatchProcessor)
403    grok.provides(IBatchProcessor)
404    grok.context(Interface)
405    util_name = 'studycourseupdater'
406    grok.name(util_name)
407
408    name = u'StudentStudyCourse Processor (update only)'
409    iface = IStudentStudyCourse
[9960]410    iface_transfer = IStudentStudyCourseTransfer
[8232]411    factory_name = 'waeup.StudentStudyCourse'
412
413    location_fields = []
414    additional_fields = []
415
416    def getParent(self, row, site):
417        return self._getStudent(row, site)
418
[6825]419    def getEntry(self, row, site):
[7534]420        student = self.getParent(row, site)
[7536]421        if student is None:
[6825]422            return None
423        return student.get('studycourse')
[7429]424
[9706]425    def updateEntry(self, obj, row, site, filename):
[7429]426        """Update obj to the values given in row.
427        """
[9960]428        entry_mode = row.get('entry_mode', None)
429        certificate = row.get('certificate', None)
[9962]430        current_session = row.get('current_session', None)
431        student = self.getParent(row, site)
[9960]432        if entry_mode == 'transfer':
[9962]433            # We do not expect any error here since we
434            # checked all constraints in checkConversion and
435            # in checkUpdateRequirements
436            student.transfer(
437                certificate=certificate, current_session=current_session)
[9960]438            obj = student['studycourse']
[8221]439        items_changed = super(StudentStudyCourseProcessor, self).updateEntry(
[9706]440            obj, row, site, filename)
[9962]441        student.__parent__.logger.info(
[9706]442            '%s - %s - %s - updated: %s'
[9962]443            % (self.name, filename, student.student_id, items_changed))
[7429]444        # Update the students_catalog
[9962]445        notify(grok.ObjectModifiedEvent(student))
[7429]446        return
447
[7532]448    def checkConversion(self, row, mode='ignore'):
449        """Validates all values in row.
450        """
[9960]451        # We have to use the correct interface. Transfer
452        # updates have different constraints.
453        entry_mode = row.get('entry_mode', None)
454        if entry_mode == 'transfer':
455            converter = IObjectConverter(self.iface_transfer)
456        else:
457            converter = IObjectConverter(self.iface)
458        errs, inv_errs, conv_dict =  converter.fromStringDict(
459            row, self.factory_name, mode=mode)
460
[7532]461        # We have to check if current_level is in range of certificate.
[9701]462        if 'certificate' in conv_dict and 'current_level' in conv_dict:
[8940]463            cert = conv_dict['certificate']
464            level = conv_dict['current_level']
465            if level < cert.start_level or level > cert.end_level+120:
466                errs.append(('current_level','not in range'))
[7532]467        return errs, inv_errs, conv_dict
468
[9028]469    def checkUpdateRequirements(self, obj, row, site):
470        """Checks requirements the object must fulfill when being updated.
471
472        Returns error messages as strings in case of requirement
473        problems.
474        """
[9960]475        certificate = getattr(obj, 'certificate', None)
476        entry_session = getattr(obj, 'entry_session', None)
[9028]477        current_level = row.get('current_level', None)
[9960]478        entry_mode = row.get('entry_mode', None)
479        # We have to ensure that the student can be transferred.
480        if entry_mode == 'transfer':
481            if certificate is None or entry_session is None:
482                return 'Former study course record incomplete.'
483            if 'studycourse_1' in obj.__parent__.keys() and \
484                'studycourse_2' in obj.__parent__.keys():
485                return 'Maximum number of transfers exceeded.'
[9735]486        if current_level:
487            if current_level == 999 and \
488                obj.__parent__.state in FORBIDDEN_POSTGRAD_STATES:
489                return 'Not a pg student.'
490            cert = row.get('certificate', None)
491            if certificate is None and cert is None:
492                return 'No certificate to check level.'
[9960]493            if certificate is not None and cert is None and (
[9735]494                current_level < certificate.start_level or \
495                current_level > certificate.end_level+120):
496                return 'current_level not in range.'
[9028]497        return None
498
[8232]499class StudentStudyLevelProcessor(StudentProcessorBase):
[7536]500    """A batch processor for IStudentStudyLevel objects.
501    """
502    grok.implements(IBatchProcessor)
503    grok.provides(IBatchProcessor)
504    grok.context(Interface)
[7933]505    util_name = 'studylevelprocessor'
[7536]506    grok.name(util_name)
507
[7933]508    name = u'StudentStudyLevel Processor'
[7536]509    iface = IStudentStudyLevel
510    factory_name = 'waeup.StudentStudyLevel'
511
512    location_fields = []
[9160]513
[9161]514    additional_fields = ['level']
[8232]515    additional_headers = ['level']
[7536]516
[9690]517    @property
518    def available_fields(self):
519        fields = super(StudentStudyLevelProcessor, self).available_fields
520        fields.remove('total_credits')
[10479]521        fields.remove('gpa')
[9690]522        return  fields
523
[7536]524    def getParent(self, row, site):
[8232]525        student = self._getStudent(row, site)
526        if student is None:
[7536]527            return None
[8232]528        return student['studycourse']
[7536]529
530    def getEntry(self, row, site):
531        studycourse = self.getParent(row, site)
532        if studycourse is None:
533            return None
534        return studycourse.get(row['level'])
535
[9301]536    def delEntry(self, row, site):
537        studylevel = self.getEntry(row, site)
538        parent = self.getParent(row, site)
539        if studylevel is not None:
540            student = self._getStudent(row, site)
541            student.__parent__.logger.info('%s - Level removed: %s'
542                % (student.student_id, studylevel.__name__))
543            del parent[studylevel.__name__]
544        return
545
[9706]546    def updateEntry(self, obj, row, site, filename):
[8626]547        """Update obj to the values given in row.
548        """
549        items_changed = super(StudentStudyLevelProcessor, self).updateEntry(
[9706]550            obj, row, site, filename)
[9978]551        obj.level = int(row['level'])
[8626]552        student = self.getParent(row, site).__parent__
553        student.__parent__.logger.info(
[9706]554            '%s - %s - %s - updated: %s'
555            % (self.name, filename, student.student_id, items_changed))
[8626]556        return
557
[7536]558    def addEntry(self, obj, row, site):
559        parent = self.getParent(row, site)
560        obj.level = int(row['level'])
561        parent[row['level']] = obj
562        return
563
564    def checkConversion(self, row, mode='ignore'):
565        """Validates all values in row.
566        """
[8232]567        errs, inv_errs, conv_dict = super(
568            StudentStudyLevelProcessor, self).checkConversion(row, mode=mode)
569
[7536]570        # We have to check if level is a valid integer.
[7548]571        # This is not done by the converter.
[7536]572        try:
573            level = int(row['level'])
[9301]574            if level not in range(0,1000,10) + [999]:
[7536]575                errs.append(('level','no valid integer'))
576        except ValueError:
577            errs.append(('level','no integer'))
578        return errs, inv_errs, conv_dict
[7548]579
[8232]580class CourseTicketProcessor(StudentProcessorBase):
[7548]581    """A batch processor for ICourseTicket objects.
582    """
583    grok.implements(IBatchProcessor)
584    grok.provides(IBatchProcessor)
585    grok.context(Interface)
[7933]586    util_name = 'courseticketprocessor'
[7548]587    grok.name(util_name)
588
[7933]589    name = u'CourseTicket Processor'
[9420]590    iface = ICourseTicketImport
[7548]591    factory_name = 'waeup.CourseTicket'
592
593    location_fields = []
[9316]594    additional_fields = ['level', 'code']
[8232]595    additional_headers = ['level', 'code']
[7548]596
[9420]597    @property
598    def available_fields(self):
599        fields = [
600            'student_id','reg_number','matric_number',
601            'mandatory', 'score', 'carry_over', 'automatic',
602            'level_session'
603            ] + self.additional_fields
604        return sorted(fields)
605
[7548]606    def getParent(self, row, site):
[8232]607        student = self._getStudent(row, site)
608        if student is None:
[7548]609            return None
[8232]610        return student['studycourse'].get(row['level'])
[7548]611
612    def getEntry(self, row, site):
613        level = self.getParent(row, site)
614        if level is None:
615            return None
616        return level.get(row['code'])
617
[9706]618    def updateEntry(self, obj, row, site, filename):
[8626]619        """Update obj to the values given in row.
620        """
621        items_changed = super(CourseTicketProcessor, self).updateEntry(
[9706]622            obj, row, site, filename)
[8888]623        parent = self.getParent(row, site)
[8626]624        student = self.getParent(row, site).__parent__.__parent__
625        student.__parent__.logger.info(
[9706]626            '%s - %s - %s - %s - updated: %s'
627            % (self.name, filename, student.student_id, parent.level, items_changed))
[8626]628        return
629
[7548]630    def addEntry(self, obj, row, site):
631        parent = self.getParent(row, site)
632        catalog = getUtility(ICatalog, name='courses_catalog')
633        entries = list(catalog.searchResults(code=(row['code'],row['code'])))
634        obj.fcode = entries[0].__parent__.__parent__.__parent__.code
635        obj.dcode = entries[0].__parent__.__parent__.code
636        obj.title = entries[0].title
[9420]637        #if getattr(obj, 'credits', None) is None:
638        obj.credits = entries[0].credits
639        #if getattr(obj, 'passmark', None) is None:
640        obj.passmark = entries[0].passmark
[7548]641        obj.semester = entries[0].semester
642        parent[row['code']] = obj
643        return
644
[8888]645    def delEntry(self, row, site):
646        ticket = self.getEntry(row, site)
647        parent = self.getParent(row, site)
648        if ticket is not None:
649            student = self._getStudent(row, site)
650            student.__parent__.logger.info('%s - Course ticket in %s removed: %s'
651                % (student.student_id, parent.level, ticket.code))
652            del parent[ticket.code]
653        return
654
[7548]655    def checkConversion(self, row, mode='ignore'):
656        """Validates all values in row.
657        """
[8232]658        errs, inv_errs, conv_dict = super(
659            CourseTicketProcessor, self).checkConversion(row, mode=mode)
[9420]660        if mode == 'remove':
661            return errs, inv_errs, conv_dict
662        # In update and create mode we have to check if course really exists.
[7548]663        # This is not done by the converter.
664        catalog = getUtility(ICatalog, name='courses_catalog')
665        entries = catalog.searchResults(code=(row['code'],row['code']))
666        if len(entries) == 0:
667            errs.append(('code','non-existent'))
668            return errs, inv_errs, conv_dict
[9420]669        # If level_session is provided in row we have to check if
670        # the parent studylevel exists and if its level_session
671        # attribute corresponds with the expected value in row.
[9421]672        level_session = conv_dict.get('level_session', IGNORE_MARKER)
673        if level_session not in (IGNORE_MARKER, None):
[9420]674            site = grok.getSite()
675            studylevel = self.getParent(row, site)
676            if studylevel is not None:
677                if studylevel.level_session != level_session:
678                    errs.append(('level_session','does not match %s'
679                        % studylevel.level_session))
680            else:
681                errs.append(('level','does not exist'))
[7623]682        return errs, inv_errs, conv_dict
683
[8232]684class StudentOnlinePaymentProcessor(StudentProcessorBase):
[7623]685    """A batch processor for IStudentOnlinePayment objects.
686    """
687    grok.implements(IBatchProcessor)
688    grok.provides(IBatchProcessor)
689    grok.context(Interface)
[7933]690    util_name = 'paymentprocessor'
[7623]691    grok.name(util_name)
692
[8942]693    name = u'Student Payment Processor'
[8174]694    iface = IStudentOnlinePayment
[7623]695    factory_name = 'waeup.StudentOnlinePayment'
696
697    location_fields = []
[8232]698    additional_fields = ['p_id']
[8884]699    additional_headers = []
[7623]700
[8884]701    def checkHeaders(self, headerfields, mode='ignore'):
702        super(StudentOnlinePaymentProcessor, self).checkHeaders(headerfields)
[8885]703        if mode in ('update', 'remove') and not 'p_id' in headerfields:
[8884]704            raise FatalCSVError(
[8885]705                "Need p_id for import in update and remove modes!")
[8884]706        return True
707
[8232]708    def parentsExist(self, row, site):
709        return self.getParent(row, site) is not None
[7623]710
711    def getParent(self, row, site):
[8232]712        student = self._getStudent(row, site)
713        if student is None:
[7623]714            return None
[8232]715        return student['payments']
[7623]716
717    def getEntry(self, row, site):
718        payments = self.getParent(row, site)
719        if payments is None:
720            return None
[8884]721        p_id = row.get('p_id', None)
722        if p_id is None:
723            return None
[7626]724        # We can use the hash symbol at the end of p_id in import files
725        # to avoid annoying automatic number transformation
726        # by Excel or Calc
[8884]727        p_id = p_id.strip('#')
[9467]728        if len(p_id.split('-')) != 3 and not p_id.startswith('p'):
[8884]729            # For data migration from old SRP only
730            p_id = 'p' + p_id[7:] + '0'
731        entry = payments.get(p_id)
[7623]732        return entry
733
[9706]734    def updateEntry(self, obj, row, site, filename):
[8626]735        """Update obj to the values given in row.
736        """
737        items_changed = super(StudentOnlinePaymentProcessor, self).updateEntry(
[9706]738            obj, row, site, filename)
[8626]739        student = self.getParent(row, site).__parent__
740        student.__parent__.logger.info(
[9706]741            '%s - %s - %s - updated: %s'
742            % (self.name, filename, student.student_id, items_changed))
[8626]743        return
744
[7623]745    def addEntry(self, obj, row, site):
746        parent = self.getParent(row, site)
[7626]747        p_id = row['p_id'].strip('#')
[9467]748        if len(p_id.split('-')) != 3 and not p_id.startswith('p'):
[7623]749            # For data migration from old SRP
[8884]750            obj.p_id = 'p' + p_id[7:] + '0'
[7623]751            parent[obj.p_id] = obj
752        else:
[7626]753            parent[p_id] = obj
[7623]754        return
755
[8885]756    def delEntry(self, row, site):
757        payment = self.getEntry(row, site)
758        parent = self.getParent(row, site)
759        if payment is not None:
760            student = self._getStudent(row, site)
[8886]761            student.__parent__.logger.info('%s - Payment ticket removed: %s'
[8885]762                % (student.student_id, payment.p_id))
763            del parent[payment.p_id]
[8886]764        return
[8885]765
[7623]766    def checkConversion(self, row, mode='ignore'):
767        """Validates all values in row.
768        """
[8232]769        errs, inv_errs, conv_dict = super(
770            StudentOnlinePaymentProcessor, self).checkConversion(row, mode=mode)
771
[7623]772        # We have to check p_id.
[8884]773        p_id = row.get('p_id', None)
[8942]774        if not p_id:
[8884]775            timestamp = ("%d" % int(time()*10000))[1:]
776            p_id = "p%s" % timestamp
777            conv_dict['p_id'] = p_id
778            return errs, inv_errs, conv_dict
779        else:
780            p_id = p_id.strip('#')
[7626]781        if p_id.startswith('p'):
782            if not len(p_id) == 14:
[7623]783                errs.append(('p_id','invalid length'))
784                return errs, inv_errs, conv_dict
[9467]785        elif len(p_id.split('-')) == 3:
786            # The SRP used either pins as keys ...
[9479]787            if len(p_id.split('-')[2]) not in (9, 10):
[9467]788                errs.append(('p_id','invalid pin'))
789                return errs, inv_errs, conv_dict
[7623]790        else:
[9467]791            # ... or order_ids.
[7626]792            if not len(p_id) == 19:
[7623]793                errs.append(('p_id','invalid length'))
794                return errs, inv_errs, conv_dict
795        return errs, inv_errs, conv_dict
[7951]796
797class StudentVerdictProcessor(StudentStudyCourseProcessor):
[9418]798    """A special batch processor for verdicts.
[7951]799
800    Import verdicts and perform workflow transitions.
801    """
802
803    util_name = 'verdictupdater'
804    grok.name(util_name)
805
[9418]806    name = u'Verdict Processor (special processor, update only)'
[7951]807    iface = IStudentVerdictUpdate
808    factory_name = 'waeup.StudentStudyCourse'
809
810    def checkUpdateRequirements(self, obj, row, site):
811        """Checks requirements the studycourse and the student must fulfill
812        before being updated.
813        """
814        # Check if current_levels correspond
815        if obj.current_level != row['current_level']:
816            return 'Current level does not correspond.'
817        # Check if current_sessions correspond
818        if obj.current_session != row['current_session']:
819            return 'Current session does not correspond.'
[9282]820        # Check if new verdict is provided
821        if row['current_verdict'] in (IGNORE_MARKER, ''):
[9293]822            return 'No verdict in import file.'
[9631]823        # Check if studylevel exists
[9293]824        level_string = str(obj.current_level)
825        if obj.get(level_string) is None:
826            return 'Study level object is missing.'
[9284]827        # Check if student is in state REGISTERED or VALIDATED
[9296]828        if row.get('bypass_validation'):
[9284]829            if obj.student.state not in (VALIDATED, REGISTERED):
830                return 'Student in wrong state.'
831        else:
832            if obj.student.state != VALIDATED:
833                return 'Student in wrong state.'
[7951]834        return None
835
[9706]836    def updateEntry(self, obj, row, site, filename):
[7951]837        """Update obj to the values given in row.
838        """
[8221]839        # Don't set current_session, current_level
840        vals_to_set = dict((key, val) for key, val in row.items()
841                           if key not in ('current_session','current_level'))
[9706]842        super(StudentVerdictProcessor, self).updateEntry(
843            obj, vals_to_set, site, filename)
[7951]844        parent = self.getParent(row, site)
[9293]845        # Set current_vedict in corresponding studylevel
846        level_string = str(obj.current_level)
847        obj[level_string].level_verdict = row['current_verdict']
[9296]848        # Fire transition and set studylevel attributes
849        # depending on student's state
[9284]850        if obj.__parent__.state == REGISTERED:
[9296]851            validated_by = row.get('validated_by', '')
852            if validated_by in (IGNORE_MARKER, ''):
853                portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
854                system = translate(_('System'),'waeup.kofa',
855                                  target_language=portal_language)
856                obj[level_string].validated_by = system
857            else:
858                obj[level_string].validated_by = validated_by
859            obj[level_string].validation_date = datetime.utcnow()
[9284]860            IWorkflowInfo(obj.__parent__).fireTransition('bypass_validation')
861        else:
862            IWorkflowInfo(obj.__parent__).fireTransition('return')
[7951]863        # Update the students_catalog
864        notify(grok.ObjectModifiedEvent(obj.__parent__))
865        return
Note: See TracBrowser for help on using the repository browser.