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

Last change on this file since 16827 was 16821, checked in by Henrik Bettermann, 3 years ago

Allow import of duplicate payments if paid.

  • Property svn:keywords set to Id
File size: 44.5 KB
Line 
1## $Id: batching.py 16821 2022-02-21 13:22:51Z 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 unicodecsv as csv # XXX: csv ops should move to dedicated module.
28from time import time
29from ast import literal_eval
30from datetime import datetime
31from zope.i18n import translate
32from zope.interface import Interface
33from zope.schema import getFields
34from zope.component import queryUtility, getUtility, createObject
35from zope.event import notify
36from zope.catalog.interfaces import ICatalog
37from hurry.workflow.interfaces import IWorkflowState, IWorkflowInfo
38from waeup.kofa.interfaces import (
39    IBatchProcessor, FatalCSVError, IObjectConverter, IUserAccount,
40    IObjectHistory, VALIDATED, REGISTERED, IGNORE_MARKER, DELETION_MARKER)
41from waeup.kofa.interfaces import IKofaUtils, DuplicationError
42from waeup.kofa.interfaces import MessageFactory as _
43from waeup.kofa.students.interfaces import (
44    IStudent, IStudentStudyCourse, IStudentStudyCourseTransfer,
45    IStudentUpdateByRegNo, IStudentUpdateByMatricNo,
46    IStudentStudyLevel, ICourseTicketImport,
47    IStudentOnlinePayment, IStudentVerdictUpdate)
48from waeup.kofa.payments.interfaces import IPayer
49from waeup.kofa.students.workflow import  (
50    IMPORTABLE_STATES, IMPORTABLE_TRANSITIONS,
51    FORBIDDEN_POSTGRAD_TRANS, FORBIDDEN_POSTGRAD_STATES)
52from waeup.kofa.utils.batching import BatchProcessor
53
54class StudentProcessor(BatchProcessor):
55    """The Student Processor imports student base data.
56
57    In create mode no locator is required. If no `student_id` is given,
58    the portal automatically assigns a new student id.
59
60    In update or remove mode the processor uses
61    either the `student_id`, `reg_number` or `matric_number` to localize the
62    student object, exactly in this order. If `student_id` is given and an
63    object can be found, `reg_number` and `matric_number` will be overwritten
64    by the values provided in the import file. If `student_id` is missing,
65    `reg_number` is used to localize the object and only `matric_number`
66    will be overwritten. `matric_number` is used as locator only if both
67    `student_id` and `reg_number` are missing. `student_id` can't be changed
68    by the batch processor.
69
70    There are two ways to change the workflow state of the student,
71    an unsafe and a safe way. The safe way makes use of workflow transitions.
72    Transitions are only possible between allowed workflow states. Only
73    transitions ensure that the registration workflow is maintained.
74
75    **Always prefer the safe way!**
76    """
77    grok.implements(IBatchProcessor)
78    grok.provides(IBatchProcessor)
79    grok.context(Interface)
80    util_name = 'studentprocessor'
81    grok.name(util_name)
82
83    name = _('Student Processor')
84    iface = IStudent
85    iface_byregnumber = IStudentUpdateByRegNo
86    iface_bymatricnumber = IStudentUpdateByMatricNo
87
88    factory_name = 'waeup.Student'
89
90    @property
91    def available_fields(self):
92        fields = getFields(self.iface)
93        return sorted(list(set(
94            ['student_id','reg_number','matric_number',
95            'password', 'state', 'transition', 'history'] + fields.keys())))
96
97    def checkHeaders(self, headerfields, mode='create'):
98        if 'state' in headerfields and 'transition' in headerfields:
99            raise FatalCSVError(
100                "State and transition can't be imported at the same time!")
101        if not 'reg_number' in headerfields and not 'student_id' \
102            in headerfields and not 'matric_number' in headerfields:
103            raise FatalCSVError(
104                "Need at least columns student_id or reg_number " +
105                "or matric_number for import!")
106        if mode == 'create':
107            for field in self.required_fields:
108                if not field in headerfields:
109                    raise FatalCSVError(
110                        "Need at least columns %s for import!" %
111                        ', '.join(["'%s'" % x for x in self.required_fields]))
112        # Check for fields to be ignored...
113        not_ignored_fields = [x for x in headerfields
114                              if not x.startswith('--')]
115        if len(set(not_ignored_fields)) < len(not_ignored_fields):
116            raise FatalCSVError(
117                "Double headers: each column name may only appear once.")
118        return True
119
120    def parentsExist(self, row, site):
121        return 'students' in site.keys()
122
123    def getLocator(self, row):
124        if row.get('student_id',None) not in (None, IGNORE_MARKER):
125            return 'student_id'
126        elif row.get('reg_number',None) not in (None, IGNORE_MARKER):
127            return 'reg_number'
128        elif row.get('matric_number',None) not in (None, IGNORE_MARKER):
129            return 'matric_number'
130        else:
131            return None
132
133    # The entry never exists in create mode.
134    def entryExists(self, row, site):
135        return self.getEntry(row, site) is not None
136
137    def getParent(self, row, site):
138        return site['students']
139
140    def getEntry(self, row, site):
141        if not 'students' in site.keys():
142            return None
143        if self.getLocator(row) == 'student_id':
144            if row['student_id'] in site['students']:
145                student = site['students'][row['student_id']]
146                return student
147        elif self.getLocator(row) == 'reg_number':
148            reg_number = row['reg_number']
149            cat = queryUtility(ICatalog, name='students_catalog')
150            results = list(
151                cat.searchResults(reg_number=(reg_number, reg_number)))
152            if results:
153                return results[0]
154        elif self.getLocator(row) == 'matric_number':
155            matric_number = row['matric_number']
156            cat = queryUtility(ICatalog, name='students_catalog')
157            results = list(
158                cat.searchResults(matric_number=(matric_number, matric_number)))
159            if results:
160                return results[0]
161        return None
162
163    def addEntry(self, obj, row, site):
164        parent = self.getParent(row, site)
165        parent.addStudent(obj)
166        # Reset _curr_stud_id if student_id has been imported
167        if self.getLocator(row) == 'student_id':
168            parent._curr_stud_id -= 1
169        # We have to log this if state is provided. If not,
170        # logging is done by the event handler handle_student_added
171        if 'state' in row:
172            parent.logger.info('%s - Student record created' % obj.student_id)
173        return
174
175    def delEntry(self, row, site):
176        student = self.getEntry(row, site)
177        if student is not None:
178            parent = self.getParent(row, site)
179            parent.logger.info('%s - Student removed' % student.student_id)
180            del parent[student.student_id]
181        pass
182
183    def checkUpdateRequirements(self, obj, row, site):
184        """Checks requirements the object must fulfill when being updated.
185
186        This method is not used in case of deleting or adding objects.
187
188        Returns error messages as strings in case of requirement
189        problems.
190        """
191        transition = row.get('transition', IGNORE_MARKER)
192        if transition not in (IGNORE_MARKER, ''):
193            allowed_transitions = IWorkflowInfo(obj).getManualTransitionIds()
194            if transition not in allowed_transitions:
195                return 'Transition not allowed.'
196            if transition in FORBIDDEN_POSTGRAD_TRANS and \
197                obj.is_postgrad:
198                return 'Transition not allowed (pg student).'
199        state = row.get('state', IGNORE_MARKER)
200        if state not in (IGNORE_MARKER, ''):
201            if state in FORBIDDEN_POSTGRAD_STATES and \
202                obj.is_postgrad:
203                return 'State not allowed (pg student).'
204        return None
205
206    def updateEntry(self, obj, row, site, filename):
207        """Update obj to the values given in row.
208        """
209        items_changed = ''
210
211        # Remove student_id from row if empty
212        if 'student_id' in row and row['student_id'] in (None, IGNORE_MARKER):
213            row.pop('student_id')
214
215        # Update password
216        if 'password' in row:
217            passwd = row.get('password', IGNORE_MARKER)
218            if passwd not in ('', IGNORE_MARKER):
219                if passwd.startswith('{SSHA}'):
220                    # already encrypted password
221                    obj.password = passwd
222                elif passwd == DELETION_MARKER:
223                    obj.password = None
224                else:
225                    # not yet encrypted password
226                    IUserAccount(obj).setPassword(passwd)
227                items_changed += ('%s=%s, ' % ('password', passwd))
228            row.pop('password')
229
230        # Replace entire history
231        if 'history' in row:
232            new_history = row.get('history', IGNORE_MARKER)
233            if new_history not in (IGNORE_MARKER, ''):
234                history = IObjectHistory(obj)
235                history._annotations[
236                    history.history_key] = literal_eval(new_history)
237                items_changed += ('%s=%s, ' % ('history', new_history))
238            row.pop('history')
239
240        # Update registration state
241        if 'state' in row:
242            state = row.get('state', IGNORE_MARKER)
243            if state not in (IGNORE_MARKER, ''):
244                value = row['state']
245                IWorkflowState(obj).setState(value)
246                msg = _("State '${a}' imported", mapping = {'a':value})
247                history = IObjectHistory(obj)
248                history.addMessage(msg)
249                items_changed += ('%s=%s, ' % ('state', state))
250            row.pop('state')
251
252        if 'transition' in row:
253            transition = row.get('transition', IGNORE_MARKER)
254            if transition not in (IGNORE_MARKER, ''):
255                value = row['transition']
256                IWorkflowInfo(obj).fireTransition(value)
257                items_changed += ('%s=%s, ' % ('transition', transition))
258            row.pop('transition')
259
260        # apply other values...
261        items_changed += super(StudentProcessor, self).updateEntry(
262            obj, row, site, filename)
263
264        # Log actions...
265        parent = self.getParent(row, site)
266        if hasattr(obj,'student_id'):
267            # Update mode: the student exists and we can get the student_id.
268            # Create mode: the record contains the student_id
269            parent.logger.info(
270                '%s - %s - %s - updated: %s'
271                % (self.name, filename, obj.student_id, items_changed))
272        else:
273            # Create mode: the student does not yet exist
274            # XXX: It seems that this never happens because student_id
275            # is always set.
276            parent.logger.info(
277                '%s - %s - %s - imported: %s'
278                % (self.name, filename, obj.student_id, items_changed))
279        notify(grok.ObjectModifiedEvent(obj))
280        return items_changed
281
282    def getMapping(self, path, headerfields, mode):
283        """Get a mapping from CSV file headerfields to actually used fieldnames.
284        """
285        result = dict()
286        reader = csv.reader(open(path, 'rb'))
287        raw_header = reader.next()
288        for num, field in enumerate(headerfields):
289            if field not in ['student_id', 'reg_number', 'matric_number'
290                             ] and mode == 'remove':
291                continue
292            if field == u'--IGNORE--':
293                # Skip ignored columns in failed and finished data files.
294                continue
295            result[raw_header[num]] = field
296        return result
297
298    def checkConversion(self, row, mode='create'):
299        """Validates all values in row.
300        """
301        iface = self.iface
302        if mode in ['update', 'remove']:
303            if self.getLocator(row) == 'reg_number':
304                iface = self.iface_byregnumber
305            elif self.getLocator(row) == 'matric_number':
306                iface = self.iface_bymatricnumber
307        converter = IObjectConverter(iface)
308        errs, inv_errs, conv_dict =  converter.fromStringDict(
309            row, self.factory_name, mode=mode)
310        # We cannot import both state and transition.
311        if 'transition' in row and 'state' in row:
312            if row['transition'] not in (IGNORE_MARKER, '') and \
313                row['state'] not in (IGNORE_MARKER, ''):
314                errs.append(('workflow','not allowed'))
315        if 'transition' in row:
316            if row['transition'] not in IMPORTABLE_TRANSITIONS:
317                if row['transition'] not in (IGNORE_MARKER, ''):
318                    errs.append(('transition','not allowed'))
319        if 'state' in row:
320            if row['state'] not in IMPORTABLE_STATES:
321                if row['state'] not in (IGNORE_MARKER, ''):
322                    errs.append(('state','not allowed'))
323                else:
324                    # State is an attribute of Student and must not
325                    # be changed if empty.
326                    conv_dict['state'] = IGNORE_MARKER
327        if 'history' in row:
328            if row['history'] not in (IGNORE_MARKER, ''):
329                try:
330                    new_history = literal_eval(row['history'])
331                except:
332                    errs.append(('history','malformed string'))
333        try:
334            # Correct stud_id counter. As the IConverter for students
335            # creates student objects that are not used afterwards, we
336            # have to fix the site-wide student_id counter.
337            site = grok.getSite()
338            students = site['students']
339            students._curr_stud_id -= 1
340        except (KeyError, TypeError, AttributeError):
341                pass
342        return errs, inv_errs, conv_dict
343
344
345class StudentProcessorBase(BatchProcessor):
346    """A base for student subitem processor.
347
348    Helps reducing redundancy.
349    """
350    grok.baseclass()
351
352    # additional available fields
353    # beside 'student_id', 'reg_number' and 'matric_number'
354    additional_fields = []
355
356    # additional required fields (subset of additional_fields)
357    additional_fields_required = []
358
359    @property
360    def available_fields(self):
361        fields = ['student_id','reg_number','matric_number'
362                  ] + self.additional_fields
363        return sorted(list(set(fields + getFields(
364                self.iface).keys())))
365
366    def checkHeaders(self, headerfields, mode='ignore'):
367        if not 'reg_number' in headerfields and not 'student_id' \
368            in headerfields and not 'matric_number' in headerfields:
369            raise FatalCSVError(
370                "Need at least columns student_id " +
371                "or reg_number or matric_number for import!")
372        for name in self.additional_fields_required:
373            if not name in headerfields:
374                raise FatalCSVError(
375                    "Need %s for import!" % name)
376
377        # Check for fields to be ignored...
378        not_ignored_fields = [x for x in headerfields
379                              if not x.startswith('--')]
380        if len(set(not_ignored_fields)) < len(not_ignored_fields):
381            raise FatalCSVError(
382                "Double headers: each column name may only appear once.")
383        return True
384
385    def _getStudent(self, row, site):
386        NON_VALUES = ['', IGNORE_MARKER]
387        if not 'students' in site.keys():
388            return None
389        if row.get('student_id', '') not in NON_VALUES:
390            if row['student_id'] in site['students']:
391                student = site['students'][row['student_id']]
392                return student
393        elif row.get('reg_number', '') not in NON_VALUES:
394            reg_number = row['reg_number']
395            cat = queryUtility(ICatalog, name='students_catalog')
396            results = list(
397                cat.searchResults(reg_number=(reg_number, reg_number)))
398            if results:
399                return results[0]
400        elif row.get('matric_number', '') not in NON_VALUES:
401            matric_number = row['matric_number']
402            cat = queryUtility(ICatalog, name='students_catalog')
403            results = list(
404                cat.searchResults(matric_number=(matric_number, matric_number)))
405            if results:
406                return results[0]
407        return None
408
409    def parentsExist(self, row, site):
410        return self.getParent(row, site) is not None
411
412    def entryExists(self, row, site):
413        return self.getEntry(row, site) is not None
414
415    def checkConversion(self, row, mode='ignore'):
416        """Validates all values in row.
417        """
418        converter = IObjectConverter(self.iface)
419        errs, inv_errs, conv_dict =  converter.fromStringDict(
420            row, self.factory_name, mode=mode)
421        return errs, inv_errs, conv_dict
422
423    def getMapping(self, path, headerfields, mode):
424        """Get a mapping from CSV file headerfields to actually used fieldnames.
425        """
426        result = dict()
427        reader = csv.reader(open(path, 'rb'))
428        raw_header = reader.next()
429        for num, field in enumerate(headerfields):
430            if field not in ['student_id', 'reg_number', 'matric_number',
431                             'p_id', 'code', 'level'
432                             ] and mode == 'remove':
433                continue
434            if field == u'--IGNORE--':
435                # Skip ignored columns in failed and finished data files.
436                continue
437            result[raw_header[num]] = field
438        return result
439
440
441class StudentStudyCourseProcessor(StudentProcessorBase):
442    """The Student Study Course Processor imports data which refer
443    to the student's course of study. The study course container data
444    describe the current state of the course of study and it stores the
445    entry conditions, i.e. when the student started the course.
446
447    Most important is the `certificate` attribute which tells us which course
448    the student is studying. The terms 'study course' and 'course of study'
449    are used synonymously. The 'certificate' is the study programme described
450    in the acadmic section. The study course object stores a referrer to a
451    certificate in the acadmic section.
452
453    When importing a new certificate code, `checkConversion` does not only
454    check whether a certificate with the same code exists, it also
455    proves if `current_level` is inside the level range of the certificate.
456    For example, some study programmes start at level 200. The imported
457    current level must thus be 200 or higher.
458
459    `checkUpdateRequirements` looks up if the imported values match the
460    certificate already stored with the study course object. The imported
461    `current_level` must be in the range of the certificate already
462    stored.
463
464    .. note::
465
466      The processor does only offer an update mode. An 'empty' study course
467      object is automatically created when the student object is added. So this
468      object always exists. It can neither be added a second time nor
469      be removed.
470
471    Students can be transferred by import. A transfer is initialized if the
472    `entry_mode` value is ``transfer``. In this case `checkConversion` uses a
473    different interface for data validation and `checkUpdateRequirements`
474    ensures that a student can only be transferred twice. The student transfer
475    process is described elsewhere.
476    """
477    grok.implements(IBatchProcessor)
478    grok.provides(IBatchProcessor)
479    grok.context(Interface)
480    util_name = 'studycourseupdater'
481    grok.name(util_name)
482
483    name = _('StudentStudyCourse Processor (update only)')
484    iface = IStudentStudyCourse
485    iface_transfer = IStudentStudyCourseTransfer
486    factory_name = 'waeup.StudentStudyCourse'
487
488    def getParent(self, row, site):
489        return self._getStudent(row, site)
490
491    def getEntry(self, row, site):
492        student = self.getParent(row, site)
493        if student is None:
494            return None
495        return student.get('studycourse')
496
497    def updateEntry(self, obj, row, site, filename):
498        """Update obj to the values given in row.
499        """
500        entry_mode = row.get('entry_mode', None)
501        certificate = row.get('certificate', None)
502        current_session = row.get('current_session', None)
503        student = self.getParent(row, site)
504        if entry_mode == 'transfer':
505            # We do not expect any error here since we
506            # checked all constraints in checkConversion and
507            # in checkUpdateRequirements
508            student.transfer(
509                certificate=certificate, current_session=current_session)
510            obj = student['studycourse']
511        items_changed = super(StudentStudyCourseProcessor, self).updateEntry(
512            obj, row, site, filename)
513        student.__parent__.logger.info(
514            '%s - %s - %s - updated: %s'
515            % (self.name, filename, student.student_id, items_changed))
516        # Update the students_catalog
517        notify(grok.ObjectModifiedEvent(student))
518        return
519
520    def checkConversion(self, row, mode='ignore'):
521        """Validates all values in row.
522        """
523        # We have to use the correct interface. Transfer
524        # updates have different constraints.
525        entry_mode = row.get('entry_mode', None)
526        if entry_mode == 'transfer':
527            converter = IObjectConverter(self.iface_transfer)
528        else:
529            converter = IObjectConverter(self.iface)
530        errs, inv_errs, conv_dict =  converter.fromStringDict(
531            row, self.factory_name, mode=mode)
532
533        # We have to check if current_level is in range of certificate.
534        if 'certificate' in conv_dict and 'current_level' in conv_dict:
535            cert = conv_dict['certificate']
536            level = conv_dict['current_level']
537            if level < cert.start_level or level > cert.end_level+120:
538                errs.append(('current_level','not in range'))
539        return errs, inv_errs, conv_dict
540
541    def checkUpdateRequirements(self, obj, row, site):
542        """Checks requirements the object must fulfill when being updated.
543        Returns error messages as strings in case of requirement
544        problems.
545        """
546        if obj.student.studycourse_locked:
547            return 'Studycourse is locked.'
548        certificate = getattr(obj, 'certificate', None)
549        entry_session = getattr(obj, 'entry_session', None)
550        current_level = row.get('current_level', None)
551        entry_mode = row.get('entry_mode', None)
552        # We have to ensure that the student can be transferred.
553        if entry_mode == 'transfer':
554            if certificate is None or entry_session is None:
555                return 'Former study course record incomplete.'
556            if 'studycourse_1' in obj.__parent__.keys() and \
557                'studycourse_2' in obj.__parent__.keys():
558                return 'Maximum number of transfers exceeded.'
559        if current_level:
560            if current_level == 999 and \
561                obj.__parent__.state in FORBIDDEN_POSTGRAD_STATES:
562                return 'Not a pg student.'
563            cert = row.get('certificate', None)
564            if certificate is None and cert is None:
565                return 'No certificate to check level.'
566            if certificate is not None and cert is None and (
567                current_level < certificate.start_level or \
568                current_level > certificate.end_level+120):
569                return 'current_level not in range.'
570        return None
571
572class StudentStudyLevelProcessor(StudentProcessorBase):
573    """The Student Study Level Processor imports study level data.
574    It overwrites the container attributes but not the content of the container,
575    i.e. the course tickets stored inside the container. There is nothing
576    special about this processor.
577    """
578    grok.implements(IBatchProcessor)
579    grok.provides(IBatchProcessor)
580    grok.context(Interface)
581    util_name = 'studylevelprocessor'
582    grok.name(util_name)
583
584    name = _('StudentStudyLevel Processor')
585    iface = IStudentStudyLevel
586    factory_name = 'waeup.StudentStudyLevel'
587
588    additional_fields_required = ['level']
589
590    @property
591    def available_fields(self):
592        fields = super(StudentStudyLevelProcessor, self).available_fields
593        fields.remove('total_credits')
594        fields.remove('gpa')
595        return  fields
596
597    def getParent(self, row, site):
598        student = self._getStudent(row, site)
599        if student is None:
600            return None
601        return student['studycourse']
602
603    def getEntry(self, row, site):
604        studycourse = self.getParent(row, site)
605        if studycourse is None:
606            return None
607        try:
608            entry = studycourse.get(str(row['level']))
609        except KeyError:
610            return None
611        return entry
612
613    def delEntry(self, row, site):
614        studylevel = self.getEntry(row, site)
615        parent = self.getParent(row, site)
616        if studylevel is not None:
617            student = self._getStudent(row, site)
618            student.__parent__.logger.info('%s - Level removed: %s'
619                % (student.student_id, studylevel.__name__))
620            del parent[studylevel.__name__]
621        return
622
623    def updateEntry(self, obj, row, site, filename):
624        """Update obj to the values given in row.
625        """
626        items_changed = super(StudentStudyLevelProcessor, self).updateEntry(
627            obj, row, site, filename)
628        student = self.getParent(row, site).__parent__
629        student.__parent__.logger.info(
630            '%s - %s - %s - updated: %s'
631            % (self.name, filename, student.student_id, items_changed))
632        return
633
634    def addEntry(self, obj, row, site):
635        if IGNORE_MARKER == str(row['level']):
636            raise FatalCSVError("level: Invalid value")
637        parent = self.getParent(row, site)
638        parent[str(row['level'])] = obj
639        return
640
641    def checkCreateRequirements(self, parent, row, site):
642        """
643        """
644        if parent.student.studycourse_locked:
645            return 'Studycourse is locked.'
646        return None
647
648    def checkUpdateRequirements(self, obj, row, site):
649        """
650        """
651        if obj.student.studycourse_locked:
652            return 'Studylevel is locked.'
653        return None
654
655    def checkRemoveRequirements(self, obj, row, site):
656        """
657        """
658        if obj.student.studycourse_locked:
659            return 'Studycourse is locked.'
660        return None
661
662class CourseTicketProcessor(StudentProcessorBase):
663    """The Course Ticket Processor imports course tickets, the subobjects
664    of student study levels (= course lists).
665
666    An imported course ticket contains a copy of the original course data.
667    During import only a few attributes can be set/overwritten.
668
669    Like all other student data importers, this processor also requires
670    either `student_id`, `reg_number` or `matric_number` to find the student.
671    Then it needs `level` and `code` to localize the course ticket.
672
673    `checkConversion` first searches the courses catalog for the imported
674    `code` and ensures that a course with such a code really exists
675    in the academic section. It furthermore checks if `level_session` in
676    the row corresponds with the session of the parent student
677    study level object. It fails if one of the conditions is not met.
678
679    In create mode `fcode`, `dcode`, `title`, `credits`, `passmark` and
680    `semester` are taken from the course found in the academic section.
681    `fcode` and `dcode` can nevermore be changed, neither via the user interface
682    nor by import. Other values can be overwritten by import.
683
684    `ticket_session` is an additional field which can be used to store the
685    session of the course when it was taken. Usually this information is
686    redundant because the parent study level object already contains this
687    information, except for the study level zero container which can be used to
688    store 'orphaned' course tickets.
689
690    `checkUpdateRequirements` ensures that the `score` attribute can't
691    be accidentally overwritten by import in update mode. The `score`
692    attribute can be unlocked by setting the boolean field
693    `unlock_score` = 1.
694    """
695    grok.implements(IBatchProcessor)
696    grok.provides(IBatchProcessor)
697    grok.context(Interface)
698    util_name = 'courseticketprocessor'
699    grok.name(util_name)
700
701    name = _('CourseTicket Processor')
702    iface = ICourseTicketImport
703    factory_name = 'waeup.CourseTicket'
704
705    additional_fields = ['level', 'code']
706    additional_fields_required = additional_fields
707
708    @property
709    def available_fields(self):
710        fields = [
711            'student_id','reg_number','matric_number',
712            'mandatory', 'score', 'carry_over', 'automatic',
713            'outstanding', 'course_category', 'level_session',
714            'title', 'credits', 'passmark', 'semester', 'ticket_session',
715            'unlock_score'
716            ] + self.additional_fields
717        return sorted(fields)
718
719    def getParent(self, row, site):
720        student = self._getStudent(row, site)
721        if student is None:
722            return None
723        return student['studycourse'].get(str(row['level']))
724
725    def getEntry(self, row, site):
726        level = self.getParent(row, site)
727        if level is None:
728            return None
729        return level.get(row['code'])
730
731    def updateEntry(self, obj, row, site, filename):
732        """Update obj to the values given in row.
733        """
734        items_changed = super(CourseTicketProcessor, self).updateEntry(
735            obj, row, site, filename)
736        parent = self.getParent(row, site)
737        student = self.getParent(row, site).__parent__.__parent__
738        student.__parent__.logger.info(
739            '%s - %s - %s - %s - updated: %s'
740            % (self.name, filename, student.student_id, parent.level, items_changed))
741        return
742
743    def addEntry(self, obj, row, site):
744        parent = self.getParent(row, site)
745        catalog = getUtility(ICatalog, name='courses_catalog')
746        entries = list(catalog.searchResults(code=(row['code'],row['code'])))
747        obj.fcode = entries[0].__parent__.__parent__.__parent__.code
748        obj.dcode = entries[0].__parent__.__parent__.code
749        if getattr(obj, 'title', None) is None:
750            obj.title = entries[0].title
751        if getattr(obj, 'credits', None) is None:
752            obj.credits = entries[0].credits
753        if getattr(obj, 'passmark', None) is None:
754            obj.passmark = entries[0].passmark
755        if getattr(obj, 'semester', None) is None:
756            obj.semester = entries[0].semester
757        parent[row['code']] = obj
758        return
759
760    def delEntry(self, row, site):
761        ticket = self.getEntry(row, site)
762        parent = self.getParent(row, site)
763        if ticket is not None:
764            student = self._getStudent(row, site)
765            student.__parent__.logger.info('%s - Course ticket in %s removed: %s'
766                % (student.student_id, parent.level, ticket.code))
767            del parent[ticket.code]
768        return
769
770    def checkCreateRequirements(self, parent, row, site):
771        """
772        """
773        if parent.student.studycourse_locked:
774            return 'Studycourse is locked.'
775        return None
776
777    def checkUpdateRequirements(self, obj, row, site):
778        """
779        """
780        if obj.student.studycourse_locked:
781            return 'Studycourse is locked.'
782        if row.get('score',None) and obj.score and not row.get(
783            'unlock_score',None):
784            return 'Score attribute is locked.'
785        return None
786
787    def checkRemoveRequirements(self, obj, row, site):
788        """
789        """
790        if obj.student.studycourse_locked:
791            return 'Studycourse is locked.'
792        return None
793
794    def checkConversion(self, row, mode='ignore'):
795        """Validates all values in row.
796        """
797        errs, inv_errs, conv_dict = super(
798            CourseTicketProcessor, self).checkConversion(row, mode=mode)
799        if mode == 'remove':
800            return errs, inv_errs, conv_dict
801        # In update and create mode we have to check if course really exists.
802        # This is not done by the converter.
803        catalog = getUtility(ICatalog, name='courses_catalog')
804        entries = catalog.searchResults(code=(row['code'],row['code']))
805        if len(entries) == 0:
806            errs.append(('code','non-existent'))
807            return errs, inv_errs, conv_dict
808        # If level_session is provided in row we have to check if
809        # the parent studylevel exists and if its level_session
810        # attribute corresponds with the expected value in row.
811        level_session = conv_dict.get('level_session', IGNORE_MARKER)
812        if level_session not in (IGNORE_MARKER, None):
813            site = grok.getSite()
814            studylevel = self.getParent(row, site)
815            if studylevel is not None:
816                if studylevel.level_session != level_session:
817                    errs.append(('level_session','does not match %s'
818                        % studylevel.level_session))
819            else:
820                errs.append(('level object','does not exist'))
821        return errs, inv_errs, conv_dict
822
823class StudentOnlinePaymentProcessor(StudentProcessorBase):
824    """The Student Online Payment Processor imports student payment tickets.
825    The tickets are located in the ``payments`` subfolder of the student
826    container. The only additional locator is `p_id`, the object id.
827
828    The `checkConversion` method checks the format of the payment identifier.
829    In create mode it does also ensures that same `p_id` does not exist
830    elsewhere. It must be portal-wide unique.
831
832    When adding a payment ticket, the `addEntry` method checks if the same
833    payment has already been made. It compares `p_category` and `p_session`
834    in the row with the corresponding attributes  of existing payment
835    tickets in state ``paid``. If they match, a `DuplicationError` is raised.
836    """
837    grok.implements(IBatchProcessor)
838    grok.provides(IBatchProcessor)
839    grok.context(Interface)
840    util_name = 'paymentprocessor'
841    grok.name(util_name)
842
843    name = _('StudentOnlinePayment Processor')
844    iface = IStudentOnlinePayment
845    factory_name = 'waeup.StudentOnlinePayment'
846
847    additional_fields = ['p_id']
848
849    @property
850    def available_fields(self):
851        af = super(
852            StudentOnlinePaymentProcessor, self).available_fields
853        af.remove('display_item')
854        return af
855
856    def checkHeaders(self, headerfields, mode='ignore'):
857        super(StudentOnlinePaymentProcessor, self).checkHeaders(headerfields)
858        if mode in ('update', 'remove') and not 'p_id' in headerfields:
859            raise FatalCSVError(
860                "Need p_id for import in update and remove modes!")
861        return True
862
863    def parentsExist(self, row, site):
864        return self.getParent(row, site) is not None
865
866    def getParent(self, row, site):
867        student = self._getStudent(row, site)
868        if student is None:
869            return None
870        return student['payments']
871
872    def getEntry(self, row, site):
873        payments = self.getParent(row, site)
874        if payments is None:
875            return None
876        p_id = row.get('p_id', None)
877        if p_id in (None, IGNORE_MARKER):
878            return None
879        # We can use the hash symbol at the end of p_id in import files
880        # to avoid annoying automatic number transformation
881        # by Excel or Calc
882        p_id = p_id.strip('#')
883        if len(p_id.split('-')) != 3 and not p_id.startswith('p'):
884            # For data migration from old SRP only
885            p_id = 'p' + p_id[7:] + '0'
886        entry = payments.get(p_id)
887        return entry
888
889    def updateEntry(self, obj, row, site, filename):
890        """Update obj to the values given in row.
891        """
892        items_changed = super(StudentOnlinePaymentProcessor, self).updateEntry(
893            obj, row, site, filename)
894        student = self.getParent(row, site).__parent__
895        student.__parent__.logger.info(
896            '%s - %s - %s - updated: %s'
897            % (self.name, filename, student.student_id, items_changed))
898        return
899
900    def samePaymentMade(self, student, category, p_session):
901        for key in student['payments'].keys():
902            ticket = student['payments'][key]
903            if ticket.p_state == 'paid' and\
904               ticket.p_category == category and \
905               ticket.p_session == p_session and \
906               ticket.p_item != 'Balance':
907                  return True
908        return False
909
910    def addEntry(self, obj, row, site):
911        parent = self.getParent(row, site)
912        student = parent.student
913        p_id = row['p_id'].strip('#')
914        # Requirement added on 19/02/2015: same payment must not exist.
915        if obj.p_item != 'Balance' and obj.p_state != 'paid' and self.samePaymentMade(
916            student, obj.p_category, obj.p_session):
917            student.__parent__.logger.info(
918                '%s - %s - previous update cancelled'
919                % (self.name, student.student_id))
920            raise DuplicationError('Same payment has already been made.')
921        if len(p_id.split('-')) != 3 and not p_id.startswith('p'):
922            # For data migration from old SRP
923            obj.p_id = 'p' + p_id[7:] + '0'
924            parent[obj.p_id] = obj
925        else:
926            parent[p_id] = obj
927        return
928
929    def delEntry(self, row, site):
930        payment = self.getEntry(row, site)
931        parent = self.getParent(row, site)
932        if payment is not None:
933            student = self._getStudent(row, site)
934            student.__parent__.logger.info('%s - Payment ticket removed: %s'
935                % (student.student_id, payment.p_id))
936            del parent[payment.p_id]
937        return
938
939    def checkConversion(self, row, mode='ignore'):
940        """Validates all values in row.
941        """
942        errs, inv_errs, conv_dict = super(
943            StudentOnlinePaymentProcessor, self).checkConversion(row, mode=mode)
944
945        # We have to check p_id.
946        p_id = row.get('p_id', None)
947        if mode == 'create' and p_id in (None, IGNORE_MARKER):
948            timestamp = ("%d" % int(time()*10000))[1:]
949            p_id = "p%s" % timestamp
950            conv_dict['p_id'] = p_id
951            return errs, inv_errs, conv_dict
952        elif p_id in (None, IGNORE_MARKER):
953            errs.append(('p_id','missing'))
954            return errs, inv_errs, conv_dict
955        else:
956            p_id = p_id.strip('#')
957            if p_id.startswith('p'):
958                if not len(p_id) == 14:
959                    errs.append(('p_id','invalid length'))
960                    return errs, inv_errs, conv_dict
961            elif len(p_id.split('-')) == 3:
962                # The SRP used either pins as keys ...
963                if len(p_id.split('-')[2]) not in (9, 10):
964                    errs.append(('p_id','invalid pin'))
965                    return errs, inv_errs, conv_dict
966            else:
967                # ... or order_ids.
968                if not len(p_id) == 19:
969                    errs.append(('p_id','invalid format'))
970                    return errs, inv_errs, conv_dict
971        # Requirement added on 24/01/2015: p_id must be portal-wide unique.
972        if mode == 'create':
973            cat = getUtility(ICatalog, name='payments_catalog')
974            results = list(cat.searchResults(p_id=(p_id, p_id)))
975            if len(results) > 0:
976                sids = [IPayer(payment).id for payment in results]
977                sids_string = ''
978                for id in sids:
979                    sids_string += '%s ' % id
980                errs.append(('p_id','p_id exists in %s' % sids_string))
981                return errs, inv_errs, conv_dict
982        return errs, inv_errs, conv_dict
983
984class StudentVerdictProcessor(StudentStudyCourseProcessor):
985    """The Student Verdict Processor inherits from the Student Study
986    Course Processor. It's a pure updater. Import step 2 raises a warning
987    message if a datacenter manager tries to select another mode.
988    But it does more than only overwriting study course attributes.
989
990    The Student Verdict Processor is the only processor which cannot be
991    used for restoring data. Purpose is to announce a verdict at the end of
992    each academic session. The processor does not only import a verdict,
993    it also conditions the student data so that the student can pay for the
994    next session and proceed to the next study level.
995
996    The `checkUpdateRequirements` method ensures that the imported data
997    really correspond to the actual state of the student.
998    `current_level` and `current_session` in the row must be on par
999    with the attributes of the study course object. Thus, the processor
1000    does not use these values to overwrite the attributes of the study course
1001    but to control that the verdict is really meant for the current session of
1002    the student. The verdict is only imported if a corresponding study level
1003    object exists and the student is in the right registration state,
1004    either ``courses validated`` or ``courses registered``. Course registration
1005    can be bypassed by setting `bypass_validation` to ``True``.
1006
1007    The `updateEntry` method does not only update the current verdict of
1008    the student study course, it also updates the matching student study
1009    level object. It saves the current verdict as `level_verdict` and sets
1010    the `validated_by` and `validation_date` attributes, whereas `validated_by`
1011    is taken from the row of the import file and `validation_date` is set to the
1012    actual UTC datetime. Finally, the student is moved to state ``returning``.
1013    """
1014
1015    util_name = 'verdictupdater'
1016    grok.name(util_name)
1017
1018    name = _('Verdict Processor (special processor, update only)')
1019    iface = IStudentVerdictUpdate
1020    factory_name = 'waeup.StudentStudyCourse'
1021
1022    additional_fields_required = [
1023        'current_level', 'current_session', 'current_verdict']
1024
1025    def checkUpdateRequirements(self, obj, row, site):
1026        """Checks requirements the studycourse and the student must fulfill
1027        before being updated.
1028        """
1029        # Check if current_levels correspond
1030        if obj.current_level != row['current_level']:
1031            return 'Current level does not correspond.'
1032        # Check if current_sessions correspond
1033        if obj.current_session != row['current_session']:
1034            return 'Current session does not correspond.'
1035        # Check if new verdict is provided
1036        if row['current_verdict'] in (IGNORE_MARKER, ''):
1037            return 'No verdict in import file.'
1038        # Check if studylevel exists
1039        level_string = str(obj.current_level)
1040        if obj.get(level_string) is None:
1041            return 'Study level object is missing.'
1042        # Check if student is in state REGISTERED or VALIDATED
1043        if row.get('bypass_validation'):
1044            if obj.student.state not in (VALIDATED, REGISTERED):
1045                return 'Student in wrong state.'
1046        else:
1047            if obj.student.state != VALIDATED:
1048                return 'Student in wrong state.'
1049        return None
1050
1051    def updateEntry(self, obj, row, site, filename):
1052        """Update obj to the values given in row.
1053        """
1054        # Don't set current_session, current_level
1055        vals_to_set = dict((key, val) for key, val in row.items()
1056                           if key not in ('current_session','current_level'))
1057        super(StudentVerdictProcessor, self).updateEntry(
1058            obj, vals_to_set, site, filename)
1059        parent = self.getParent(row, site)
1060        # Set current_verdict in corresponding studylevel
1061        level_string = str(obj.current_level)
1062        obj[level_string].level_verdict = row['current_verdict']
1063        # Fire transition and set studylevel attributes
1064        # depending on student's state
1065        if obj.__parent__.state == REGISTERED:
1066            validated_by = row.get('validated_by', '')
1067            if validated_by in (IGNORE_MARKER, ''):
1068                portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
1069                system = translate(_('System'),'waeup.kofa',
1070                                  target_language=portal_language)
1071                obj[level_string].validated_by = system
1072            else:
1073                obj[level_string].validated_by = validated_by
1074            obj[level_string].validation_date = datetime.utcnow()
1075            IWorkflowInfo(obj.__parent__).fireTransition('bypass_validation')
1076        else:
1077            IWorkflowInfo(obj.__parent__).fireTransition('return')
1078        # Update the students_catalog
1079        notify(grok.ObjectModifiedEvent(obj.__parent__))
1080        return
Note: See TracBrowser for help on using the repository browser.