source: main/waeup.kofa/trunk/src/waeup/kofa/students/export.py @ 17253

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

Improve export and reimport of previous study course data.

  • Property svn:keywords set to Id
File size: 41.1 KB
Line 
1## $Id: export.py 16831 2022-02-24 10:23:10Z 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"""Exporters for student related stuff.
19"""
20import os
21import grok
22from copy import deepcopy
23from datetime import datetime, timedelta
24from zope.component import getUtility
25from waeup.kofa.interfaces import (
26    IExtFileStore, IFileStoreNameChooser, IKofaUtils)
27from waeup.kofa.interfaces import MessageFactory as _
28from waeup.kofa.university.interfaces import ICertificateCourse, ICourse
29from waeup.kofa.students.catalog import StudentsQuery, CourseTicketsQuery
30from waeup.kofa.students.interfaces import (
31    IStudent, IStudentStudyCourse, IStudentStudyLevel, ICourseTicket,
32    IStudentOnlinePayment, ICSVStudentExporter, IBedTicket)
33from waeup.kofa.students.vocabularies import study_levels
34from waeup.kofa.utils.batching import ExporterBase
35from waeup.kofa.utils.helpers import iface_names, to_timezone
36
37
38def get_students(site, stud_filter=StudentsQuery()):
39    """Get all students registered in catalog in `site`.
40    """
41    return stud_filter.query()
42
43def get_studycourses(students, previous=0):
44    """Get studycourses of `students`.
45    """
46    studycourse = 'studycourse'
47    if previous == 1:
48        studycourse = 'studycourse_1'
49    elif previous == 2:
50        studycourse = 'studycourse_2'
51    for x in students:
52        if x.get(studycourse, None) is None:
53            continue
54        yield x.get(studycourse, None)
55
56def get_levels(students, previous=0, **kw):
57    """Get all studylevels of `students`.
58    """
59    levels = []
60    level_session = kw.get('level_session', None)
61    for course in get_studycourses(students, previous):
62        for level in course.values():
63            if level_session not in ('all', None) and \
64                int(level_session) != level.level_session:
65                continue
66            levels.append(level)
67    return levels
68
69def get_tickets(students, previous=0, **kw):
70    """Get course tickets of `students`.
71    If code is passed through, filter course tickets
72    which belong to this course code and meet level=level
73    and level_session=level_session.
74    If not, but ct_level, ct_session and ct_semester
75    are passed through, filter course tickets
76    which meet level==ct_level, level_session==ct_session
77    and semester==ct_semester.
78    """
79    tickets = []
80    code = kw.get('code', None)
81    level = kw.get('level', None)
82    session = kw.get('session', None)
83    ct_level = kw.get('ct_level', None)
84    ct_session = kw.get('ct_session', None)
85    ct_semester = kw.get('ct_semester', None)
86    if code is None:
87        for level_obj in get_levels(students, previous, **kw):
88            for ticket in level_obj.values():
89                if ct_level not in ('all', None):
90                    if level_obj.level in (10, 999, 1000, None)  \
91                        and int(ct_level) != level_obj.level:
92                        continue
93                    if level_obj.level not in range(
94                        int(ct_level), int(ct_level)+100, 10):
95                        continue
96                if ct_session not in ('all', None) and \
97                    int(ct_session) != level_obj.level_session:
98                    continue
99                if ct_semester not in ('all', None) and \
100                    int(ct_semester) != ticket.semester:
101                    continue
102                tickets.append(ticket)
103    else:
104        for level_obj in get_levels(students, previous, **kw):
105            for ticket in level_obj.values():
106                if ticket.code != code:
107                    continue
108                if level not in ('all', None):
109                    if level_obj.level in (10, 999, 1000, None)  \
110                        and int(level) != level_obj.level:
111                        continue
112                    if level_obj.level not in range(
113                        int(level), int(level)+100, 10):
114                        continue
115                if session not in ('all', None) and \
116                    int(session) != level_obj.level_session:
117                    continue
118                tickets.append(ticket)
119    return tickets
120
121def get_tickets_for_lecturer(students, previous=0, **kw):
122    """Get course tickets of `students`.
123    Filter course tickets which belong to this course code and
124    which are editable by lecturers. The latter requirement was disabled
125    on 10/03/21.
126    """
127    tickets = []
128    code = kw.get('code', None)
129    level_session = kw.get('session', None)
130    level = kw.get('level', None)
131    for level_obj in get_levels(students, previous, **kw):
132        for ticket in level_obj.values():
133            if ticket.code != code:
134                continue
135            # Disabled on 10/03/21
136            #if not ticket.editable_by_lecturer:
137            #    continue
138            if level not in ('all', None):
139                if level_obj.level in (10, 999, 1000, None)  \
140                    and int(level) != level_obj.level:
141                    continue
142                if level_obj.level not in range(int(level), int(level)+100, 10):
143                    continue
144            if level_session not in ('all', None) and \
145                int(level_session) != level_obj.level_session:
146                continue
147            tickets.append(ticket)
148    return tickets
149
150def get_outstanding(students, **kw):
151    """Get students with outstanding certificate courses.
152    """
153    students_wo = []
154    for student in students:
155        certificate = getattr(
156            student.get('studycourse', None), 'certificate', None)
157        if certificate:
158            allticketcodes = list()
159            failedticketcodes = list() # taken but failed
160            nottakenticketcodes = list() # registered but not taken
161            missedticketcodes = list() # not registered
162            # collect failed, not taken and all courses
163            for level in student['studycourse'].values():
164                # check if already failed or not taken courses have been passed later
165                failedticketcodes_copy = deepcopy(failedticketcodes)
166                nottakenticketcodes_copy = deepcopy(nottakenticketcodes)
167                for code in failedticketcodes_copy:
168                    if code.strip('m_').strip('_m') in level.passed_params[6]:
169                        failedticketcodes.remove(code)
170                for code in nottakenticketcodes_copy:
171                    if code in level.passed_params[6]:
172                        nottakenticketcodes.remove(code)
173                failedticketcodes += level.passed_params[4].split()
174                nottakenticketcodes += level.passed_params[5].split()
175                for ticket in level.values():
176                    allticketcodes.append(ticket.code)
177            # collect missed tickets
178            for certcourse in certificate.values():
179                if certcourse.getCourseCode() not in allticketcodes:
180                    missedticketcodes.append(certcourse.__name__)
181            student_wo = (student, missedticketcodes,
182                          failedticketcodes, nottakenticketcodes)
183            students_wo.append(student_wo)
184    return students_wo
185
186def get_payments(students, p_states=None, **kw):
187    """Get all payment tickets of `students` within given payment_date period.
188    """
189    date_format = '%d/%m/%Y'
190    payments = []
191    p_start = kw.get('payments_start')
192    p_end = kw.get('payments_end')
193    paycat = kw.get('paycat')
194    paysession = kw.get('paysession')
195    for student in students:
196        for payment in student.get('payments', {}).values():
197            if p_start and p_end:
198                if not payment.payment_date:
199                    continue
200                payments_start = datetime.strptime(p_start, date_format)
201                payments_end = datetime.strptime(p_end, date_format)
202                tz = getUtility(IKofaUtils).tzinfo
203                payments_start = tz.localize(payments_start)
204                payments_end = tz.localize(payments_end) + timedelta(days=1)
205                payment_date = to_timezone(payment.payment_date, tz)
206                if payment_date < payments_start or payment_date > payments_end:
207                    continue
208            if p_states and not payment.p_state in p_states:
209                continue
210            if paycat not in ('all', None) and payment.p_category != paycat:
211                continue
212            if paysession not in ('all', None) \
213                and payment.p_session != int(paysession):
214                continue
215            payments.append(payment)
216    return payments
217
218def get_bedtickets(students):
219    """Get all bed tickets of `students`.
220    """
221    tickets = []
222    for student in students:
223        for ticket in student.get('accommodation', {}).values():
224            tickets.append(ticket)
225    return tickets
226
227class StudentExporterBase(ExporterBase):
228    """Exporter for students or related objects.
229    This is a baseclass.
230    """
231    grok.baseclass()
232    grok.implements(ICSVStudentExporter)
233    grok.provides(ICSVStudentExporter)
234
235    def filter_func(self, x, **kw):
236        return x
237
238    def get_filtered(self, site, **kw):
239        """Get students from a catalog filtered by keywords.
240        students_catalog is the default catalog. The keys must be valid
241        catalog index names.
242        Returns a simple empty list, a list with `Student`
243        objects or a catalog result set with `Student`
244        objects.
245
246        .. seealso:: `waeup.kofa.students.catalog.StudentsCatalog`
247
248        """
249        # Pass only given keywords to create FilteredCatalogQuery objects.
250        # This way we avoid
251        # trouble with `None` value ambivalences and queries are also
252        # faster (normally less indexes to ask). Drawback is, that
253        # developers must look into catalog to see what keywords are
254        # valid.
255        if kw.get('catalog', None) == 'coursetickets':
256            coursetickets = CourseTicketsQuery(**kw).query()
257            students = []
258            for ticket in coursetickets:
259                students.append(ticket.student)
260            return list(set(students))
261        # Payments can be filtered by payment date and payment category.
262        # These parameters are not keys of the catalog and must thus be
263        # removed from kw.
264        try:
265            del kw['payments_start']
266            del kw['payments_end']
267            del kw['paycat']
268            del kw['paysession']
269        except KeyError:
270            pass
271        # Coursetickets can be filtered by level and session.
272        # These parameters are not keys of the catalog and must thus be
273        # removed from kw.
274        try:
275            del kw['ct_level']
276            del kw['ct_session']
277            del kw['ct_semester']
278        except KeyError:
279            pass
280        # Studylevels can be filtered by level_session.
281        # This parameter is not a key of the catalog and must thus be
282        # removed from kw.
283        try:
284            del kw['level_session']
285        except KeyError:
286            pass
287        query = StudentsQuery(**kw)
288        return query.query()
289
290    def get_selected(self, site, selected):
291        """Get set of selected students.
292        Returns a simple empty list or a list with `Student`
293        objects.
294        """
295        students = []
296        students_container = site.get('students', {})
297        for id in selected:
298            student = students_container.get(id, None)
299            if student is None:
300                # try matric number
301                result = list(StudentsQuery(matric_number=id).query())
302                if result:
303                    student = result[0]
304                else:
305                    continue
306            students.append(student)
307        return students
308
309    def export(self, values, filepath=None):
310        """Export `values`, an iterable, as CSV file.
311        If `filepath` is ``None``, a raw string with CSV data is returned.
312        """
313        writer, outfile = self.get_csv_writer(filepath)
314        for value in values:
315            self.write_item(value, writer)
316        return self.close_outfile(filepath, outfile)
317
318    def export_all(self, site, filepath=None):
319        """Export students into filepath as CSV data.
320        If `filepath` is ``None``, a raw string with CSV data is returned.
321        """
322        return self.export(self.filter_func(get_students(site)), filepath)
323
324    def export_student(self, student, filepath=None):
325        return self.export(self.filter_func([student]), filepath=filepath)
326
327    def export_filtered(self, site, filepath=None, **kw):
328        """Export items denoted by `kw`.
329        If `filepath` is ``None``, a raw string with CSV data should
330        be returned.
331        """
332        data = self.get_filtered(site, **kw)
333        return self.export(self.filter_func(data, **kw), filepath=filepath)
334
335    def export_selected(self,site, filepath=None, **kw):
336        """Export data for selected set of students.
337        """
338        selected = kw.get('selected', [])
339        data = self.get_selected(site, selected)
340        return self.export(self.filter_func(data, **kw), filepath=filepath)
341
342
343class StudentExporter(grok.GlobalUtility, StudentExporterBase):
344    """The Student Exporter first filters the set of students by searching the
345    students catalog. Then it exports student base data of this set of students.
346    """
347    grok.name('students')
348
349    fields = tuple(sorted(iface_names(IStudent))) + (
350        'password', 'state', 'history', 'certcode', 'is_postgrad',
351        'current_level', 'current_session', 'entry_session')
352    title = _(u'Students (Data Backup)')
353
354    def mangle_value(self, value, name, context=None):
355        """The mangler prepares the history messages and adds a hash symbol at
356        the end of the phone number to avoid annoying automatic number
357        transformation by Excel or Calc."""
358        if name == 'history':
359            value = value.messages
360        if 'phone' in name and value is not None:
361            # Append hash '#' to phone numbers to circumvent
362            # unwanted excel automatic
363            value = str('%s#' % value)
364        return super(
365            StudentExporter, self).mangle_value(
366            value, name, context=context)
367
368class TrimmedDataExporter(grok.GlobalUtility, StudentExporterBase):
369    """The Student Trimmed Data Exporter first filters the set of students
370    by searching the students catalog. Then it exports a trimmed data set
371    of this set of students.
372    """
373    grok.name('trimmed')
374
375    fields = (
376        'student_id',
377        'matric_number',
378        'reg_number',
379        'firstname',
380        'middlename',
381        'lastname',
382        'sex',
383        'email',
384        'phone',
385        'nationality',
386        'date_of_birth',
387        'state',
388        'current_mode',
389        'certcode',
390        'faccode',
391        'depcode',
392        'current_level',
393        'current_session',
394        'current_verdict',
395        'entry_session')
396    title = _(u'Students (Trimmed Data)')
397
398    def mangle_value(self, value, name, context=None):
399        """The mangler prepares the history messages and adds a hash symbol at
400        the end of the phone number to avoid annoying automatic number
401        transformation by Excel or Calc."""
402        if 'phone' in name and value is not None:
403            # Append hash '#' to phone numbers to circumvent
404            # unwanted excel automatic
405            value = str('%s#' % value)
406        return super(
407            TrimmedDataExporter, self).mangle_value(
408            value, name, context=context)
409
410class StudentStudyCourseExporter(grok.GlobalUtility, StudentExporterBase):
411    """The Student Study Course Exporter first filters the set of students
412    by searching the students catalog. Then it exports the data of the current
413    study course container of each student from this set. It does
414    not export their content.
415    """
416    grok.name('studentstudycourses')
417    previous = 0
418
419    fields = tuple(sorted(iface_names(IStudentStudyCourse))) + (
420        'student_id', 'previous')
421    title = _(u'Student Study Courses (Data Backup)')
422
423    def filter_func(self, x, **kw):
424        return get_studycourses(x)
425
426    def mangle_value(self, value, name, context=None):
427        """The mangler determines the certificate code and the student id.
428        """
429        if name == 'certificate' and value is not None:
430            # XXX: hopefully cert codes are unique site-wide
431            value = value.code
432        if name == 'student_id' and context is not None:
433            student = context.student
434            value = getattr(student, name, None)
435        if name == 'previous':
436            return self.previous
437        return super(
438            StudentStudyCourseExporter, self).mangle_value(
439            value, name, context=context)
440
441class FirstStudentStudyCourseExporter(StudentStudyCourseExporter):
442    """The First Student Study Course Exporter exports the first
443    study course if student was transferred.
444    """
445    grok.name('studentstudycourses_1')
446    previous = 1
447    title = _(u'First Student Study Courses (Data Backup)')
448
449    def filter_func(self, x, **kw):
450        return get_studycourses(x, 1)
451
452class SecondStudentStudyCourseExporter(StudentStudyCourseExporter):
453    """The Second Student Study Course Exporter exports the second
454    study course if student was transferred twice.
455    """
456    grok.name('studentstudycourses_2')
457    previous = 2
458    title = _(u'Second Student Study Courses (Data Backup)')
459
460    def filter_func(self, x, **kw):
461        return get_studycourses(x, 2)
462
463class StudentStudyLevelExporter(grok.GlobalUtility, StudentExporterBase):
464    """The Student Study Level Exporter first filters the set of students
465    by searching the students catalog. Then it exports the data of the student's
466    study level container data but not their content (course tickets).
467    The exporter iterates over all objects in the students' ``studycourse``
468    containers.
469    """
470    grok.name('studentstudylevels')
471    previous = 0
472
473    fields = tuple(sorted(iface_names(
474        IStudentStudyLevel))) + (
475        'student_id', 'number_of_tickets','certcode', 'previous')
476    title = _(u'Student Study Levels (Data Backup)')
477
478    def filter_func(self, x, **kw):
479        return get_levels(x, **kw)
480
481    def mangle_value(self, value, name, context=None):
482        """The mangler determines the student id, nothing else.
483        """
484        if name == 'student_id' and context is not None:
485            student = context.student
486            value = getattr(student, name, None)
487        if name == 'previous':
488            return self.previous
489        return super(
490            StudentStudyLevelExporter, self).mangle_value(
491            value, name, context=context)
492
493class FirstStudentStudyLevelExporter(StudentStudyLevelExporter):
494    """The First Student Study Level Exporter exports study levels of the
495    first study course if the student was transferred.
496    """
497    grok.name('studentstudylevels_1')
498    previous = 1
499    title = _(u'First Course Student Study Levels (Data Backup)')
500
501    def filter_func(self, x, **kw):
502        return get_levels(x, 1, **kw)
503
504class SecondStudentStudyLevelExporter(StudentStudyLevelExporter):
505    """The Second Student Study Level Exporter exports study levels of the
506    second tudy course if the student was transferred twice.
507    """
508    grok.name('studentstudylevels_2')
509    previous = 2
510    title = _(u'Second Course Student Study Levels (Data Backup)')
511
512    def filter_func(self, x, **kw):
513        return get_levels(x, 2, **kw)
514
515class CourseTicketExporter(grok.GlobalUtility, StudentExporterBase):
516    """The Course Ticket Exporter exports course tickets. Usually,
517    the exporter first filters the set of students by searching the
518    students catalog. Then it collects and iterates over all ``studylevel``
519    containers of the filtered student set and finally
520    iterates over all items inside these containers.
521
522    If the course code is passed through, the exporter uses a different
523    catalog. It searches for students in the course tickets catalog and
524    exports those course tickets which belong to the given course code and
525    also meet level and session passed through at the same time.
526    This happens if the exporter is called at course level in the academic
527    section.
528    """
529    grok.name('coursetickets')
530
531    fields = tuple(sorted(iface_names(ICourseTicket) +
532        ['level', 'code', 'level_session'])) + ('student_id',
533        'certcode', 'display_fullname', 'previous')
534    title = _(u'Course Tickets (Data Backup)')
535    previous = 0
536
537    def filter_func(self, x, **kw):
538        return get_tickets(x, **kw)
539
540    def mangle_value(self, value, name, context=None):
541        """The mangler determines the student's id and fullname.
542        """
543        if context is not None:
544            student = context.student
545            if name in ('student_id', 'display_fullname') and student is not None:
546                value = getattr(student, name, None)
547        if name == 'previous':
548            return self.previous
549        return super(
550            CourseTicketExporter, self).mangle_value(
551            value, name, context=context)
552
553class FirstCourseTicketExporter(CourseTicketExporter):
554    """The First Course Ticket Exporter exports course tickets of
555    first study courses if the student was transferred.
556    """
557    grok.name('coursetickets_1')
558    previous = 1
559    title = _(u'First Course Course Tickets (Data Backup)')
560
561    def filter_func(self, x, **kw):
562        return get_tickets(x, 1, **kw)
563
564class SecondCourseTicketExporter(CourseTicketExporter):
565    """The Second Course Ticket Exporter exports course tickets of
566    second study courses if the student was transferred twice.
567    """
568    grok.name('coursetickets_2')
569    previous = 2
570    title = _(u'Second Course Course Tickets (Data Backup)')
571
572    def filter_func(self, x, **kw):
573        return get_tickets(x, 2, **kw)
574
575class StudentPaymentExporter(grok.GlobalUtility, StudentExporterBase):
576    """The Student Payment Exporter first filters the set of students
577    by searching the students catalog. Then it exports student payment
578    tickets by iterating over the items of the student's ``payments``
579    container. If the payment period is given, only tickets, which were
580    paid in payment period, are considered for export.
581    """
582    grok.name('studentpayments')
583
584    fields = tuple(
585        sorted(iface_names(
586            IStudentOnlinePayment, exclude_attribs=False,
587            omit=['display_item', 'certificate', 'student', 'p_option']))) + (
588            'student_id','state','current_session')
589    title = _(u'Student Payments (Data Backup)')
590
591    def filter_func(self, x, **kw):
592        return get_payments(x, **kw)
593
594    def mangle_value(self, value, name, context=None):
595        """The mangler determines the student's id, registration
596        state and current session.
597        """
598        if context is not None:
599            student = context.student
600            if name in ['student_id','state','entry_session',
601                        'current_session'] and student is not None:
602                value = getattr(student, name, None)
603        return super(
604            StudentPaymentExporter, self).mangle_value(
605            value, name, context=context)
606
607class StudentTrimmedPaymentExporter(grok.GlobalUtility, StudentExporterBase):
608    """The Student Trimmed Payment Exporter is a slightly customized version
609    of the StudentPaymentExporter requested by Uniben.
610    """
611    grok.name('trimmedpayments')
612
613    fields = tuple(
614        sorted(iface_names(
615            IStudentOnlinePayment, exclude_attribs=False,
616            omit=['display_item', 'certificate', 'student', 'ac', 'p_option']))) + (
617            'student_id','faccode', 'depcode', 'state','current_session')
618    title = _(u'Student Payments (Sorted Data)')
619
620    def filter_func(self, x, **kw):
621        payments = get_payments(x, **kw)
622        return sorted([payment for payment in payments],
623            key=lambda payment: str(payment.p_category) + str(payment.student.faccode)
624                + str(payment.student.depcode) + str(payment.p_item))
625
626    def mangle_value(self, value, name, context=None):
627        """The mangler determines the student's id, registration
628        state and current session.
629        """
630        if context is not None:
631            student = context.student
632            if name in ['student_id','state', 'faccode', 'depcode',
633                        'current_session'] and student is not None:
634                value = getattr(student, name, None)
635        return super(
636            StudentTrimmedPaymentExporter, self).mangle_value(
637            value, name, context=context)
638
639class DataForLecturerExporter(grok.GlobalUtility, StudentExporterBase):
640    """The Data for Lecturer Exporter searches for students in the course
641    tickets catalog and exports those course tickets which belong to the
642    given course code, meet level and session passed through at the
643    same time, and which are editable by lecturers (disabled on 10/03/21).
644    This exporter can only be called at course level in the academic section.
645    """
646    grok.name('lecturer')
647
648    fields = ('matric_number', 'student_id', 'display_fullname',
649              'level', 'code', 'level_session', 'score')
650
651    title = _(u'Data for Lecturer')
652
653    def filter_func(self, x, **kw):
654        tickets = get_tickets_for_lecturer(x, **kw)
655        return sorted([ticket for ticket in tickets],
656            key=lambda ticket: str(ticket.fcode) + str(ticket.dcode)
657                + str(ticket.student.matric_number))
658
659    def mangle_value(self, value, name, context=None):
660        """The mangler determines the student's id and fullname.
661        """
662        if context is not None:
663            student = context.student
664            if name in ('matric_number',
665                        'reg_number',
666                        'student_id',
667                        'display_fullname',) and student is not None:
668                value = getattr(student, name, None)
669        return super(
670            DataForLecturerExporter, self).mangle_value(
671            value, name, context=context)
672
673class OutstandingCoursesExporter(grok.GlobalUtility, StudentExporterBase):
674    """The Student Outstanding Courses Exporter first filters the set of
675    students by searching the students catalog. Then it exports students with
676    lists of outstanding courses, i.e. courses which the student has
677    missed (not registered at all), failed (registered but not passed)
678    or nottaken (registered but not taken).
679    """
680    grok.name('outstandingcourses')
681
682    fields = ('student_id', 'matric_number', 'certcode', 'display_fullname',
683              'missed', 'failed', 'nottaken')
684    title = _(u'Outstanding Courses')
685
686    def filter_func(self, x, **kw):
687        return get_outstanding(x, **kw)
688
689    def mangle_value(self, value, name, context=None):
690        """The mangler determines the student's id, fullname and certcode,
691        and it collects the lists of outstanding courses.
692        """
693        if context is not None:
694            if name in ('student_id', 'matric_number',
695                        'display_fullname', 'certcode'):
696                value = getattr(context[0], name, None)
697            elif name == 'missed':
698                value = ' '.join(context[1])
699            elif name == 'failed':
700                value = ' '.join(context[2])
701            elif name == 'nottaken':
702                value = ' '.join(context[3])
703        return super(
704            OutstandingCoursesExporter, self).mangle_value(
705            value, name, context=context)
706
707class UnpaidPaymentsExporter(StudentPaymentExporter):
708    """The Unpaid Payments Exporter works just like the
709    Student Payment (singular intended) Exporter  but it exports only
710    unpaid tickets. This exporter is designed for finding and finally
711    purging outdated payment tickets.
712    """
713    grok.name('unpaidpayments')
714
715    title = _(u'Unpaid Payment Tickets')
716
717    def filter_func(self, x, **kw):
718        return get_payments(x, p_states=('unpaid',) , **kw)
719
720class DataForBursaryExporter(StudentPaymentExporter):
721    """The Data for Bursary Exporter works just like the Student Payment
722    Exporter but it exports much more information about the student. It combines
723    payment and student data in one table in order to spare postprocessing of
724    two seperate export files. The exporter is primarily used by bursary
725    officers who have exclusively access to this exporter. The exporter
726    exports ``paid``, ``waived`` and ``scholarship`` payment tickets.
727    """
728    grok.name('bursary')
729
730    def filter_func(self, x, **kw):
731        return get_payments(x, p_states=('paid', 'waived', 'scholarship'), **kw)
732
733    fields = tuple(
734        sorted(iface_names(
735            IStudentOnlinePayment, exclude_attribs=False,
736            omit=['display_item', 'certificate', 'student', 'p_option']))) + (
737            'student_id','matric_number','reg_number',
738            'firstname', 'middlename', 'lastname','sex',
739            'state','current_session',
740            'entry_session', 'entry_mode',
741            'faccode', 'depcode','certcode')
742    title = _(u'Payment Data for Bursary')
743
744    def mangle_value(self, value, name, context=None):
745        """The mangler fetches the student data.
746        """
747        if context is not None:
748            student = context.student
749            if name in [
750                'student_id','matric_number', 'reg_number',
751                'firstname', 'middlename', 'lastname','sex',
752                'state', 'current_session',
753                'entry_session', 'entry_mode',
754                'faccode', 'depcode', 'certcode'] and student is not None:
755                value = getattr(student, name, None)
756        return super(
757            StudentPaymentExporter, self).mangle_value(
758            value, name, context=context)
759
760class AccommodationPaymentsExporter(DataForBursaryExporter):
761    """The Accommodation Payments Exporter works like the Data for Bursary
762    Exporter above. The exporter exports ``paid``, ``waived`` and ``scholarship``
763    payment tickets with category ``bed_allocation`` or ``hostel_maintenance``.
764    The exporter is primarily used by accommodation officers who have
765    exclusively access to this exporter.
766    """
767    grok.name('accommodationpayments')
768
769    def filter_func(self, x, **kw):
770        kw['paycat'] = 'bed_allocation'
771        payments = get_payments(x, p_states=(
772          'paid', 'waived', 'scholarship'), **kw)
773        kw['paycat'] = 'hostel_maintenance'
774        payments += get_payments(x, p_states=(
775          'paid', 'waived', 'scholarship'), **kw)
776        return payments
777
778    title = _(u'Accommodation Payments')
779
780class BedTicketExporter(grok.GlobalUtility, StudentExporterBase):
781    """The Bed Ticket Exporter first filters the set of students
782    by searching the students catalog. Then it exports bed
783    tickets by iterating over the items of the student's ``accommodation``
784    container.
785    """
786    grok.name('bedtickets')
787
788    fields = tuple(
789        sorted(iface_names(
790            IBedTicket, exclude_attribs=False,
791            omit=['display_coordinates', 'maint_payment_made']))) + (
792            'student_id', 'actual_bed_type')
793    title = _(u'Bed Tickets (Data Backup)')
794
795    def filter_func(self, x, **kw):
796        return get_bedtickets(x)
797
798    def mangle_value(self, value, name, context=None):
799        """The mangler determines the student id and the type of the bed
800        which has been booked in the ticket.
801        """
802        if context is not None:
803            student = context.student
804            if name in ['student_id'] and student is not None:
805                value = getattr(student, name, None)
806        if name == 'bed' and value is not None:
807            value = getattr(value, 'bed_id', None)
808        if name == 'actual_bed_type':
809            value = getattr(getattr(context, 'bed', None), 'bed_type', None)
810        return super(
811            BedTicketExporter, self).mangle_value(
812            value, name, context=context)
813
814class SchoolFeePaymentsOverviewExporter(StudentExporter):
815    """The School Fee Payments Overview Exporter first filters the set of students
816    by searching the students catalog. Then it exports some student base data
817    together with the total school fee amount paid in each year over a
818    predefined year range (current year - 9, ... , current year + 1).
819    """
820    grok.name('sfpaymentsoverview')
821
822    curr_year = datetime.now().year
823    year_range = range(curr_year - 11, curr_year + 1)
824    year_range_tuple = tuple([str(year) for year in year_range])
825    fields = ('student_id', 'matric_number', 'display_fullname',
826        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
827        'current_level', 'current_session', 'current_mode',
828        'entry_session', 'reg_number'
829        ) + year_range_tuple
830    title = _(u'School Fee Payments Overview')
831
832    def mangle_value(self, value, name, context=None):
833        """The mangler summarizes the school fee amounts made per year. It
834        iterates over all paid school fee payment tickets and
835        adds together the amounts paid in a year. Waived payments
836        are marked ``waived`` and scholarship payments marked `scholarship`.
837        """
838        if name in self.year_range_tuple and context is not None:
839            value = 0
840            for ticket in context['payments'].values():
841                if ticket.p_category == 'schoolfee' and \
842                    ticket.p_session == int(name):
843                    if ticket.p_state == 'waived':
844                        value = 'waived'
845                        break
846                    if ticket.p_state == 'scholarship':
847                        value = 'scholarship'
848                        break
849                    if ticket.p_state == 'paid':
850                        try:
851                            value += ticket.amount_auth
852                        except TypeError:
853                            pass
854            if value == 0:
855                value = ''
856            elif isinstance(value, float):
857                value = round(value, 2)
858        return super(
859            StudentExporter, self).mangle_value(
860            value, name, context=context)
861
862class SessionPaymentsOverviewExporter(StudentExporter):
863    """The Session Payments Overview Exporter first filters the set of students
864    by searching the students catalog. Then it exports some student base data
865    together with the total amount paid in predefined payment categories
866    over the previous three session (referring to current academic session).
867    Sample output:
868
869    header: ``...schoolfee13,schoolfee14,schoolfee15,gown13,gown14,gown15...``
870
871    data: ``...2000.0,,3000.0,,,1000.0,...``
872
873    This csv data string means that the student paid 2000.0 school fee in 2013
874    and 3000.0 in 2015. S/He furthermore paid 1000.0 for gown rental in 2015.
875    """
876    grok.name('sessionpaymentsoverview')
877
878    paycats = ('schoolfee', 'clearance', 'gown', 'transcript')
879    regular_fields = ('student_id', 'matric_number', 'display_fullname',
880        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
881        'current_level', 'current_session', 'current_mode',
882        'entry_session', 'reg_number'
883        )
884    title = _(u'Session Payments Overview')
885
886    @property
887    def paycatyears(self):
888        cas = grok.getSite()['configuration'].current_academic_session
889        paycatyears = []
890        if cas:
891            year_range = range(cas-2, cas+1)
892            year_range_tuple = tuple([str(year)[2:] for year in year_range])
893            paycatyears = [
894                cat+year for cat in self.paycats for year in year_range_tuple]
895        return paycatyears
896
897    @property
898    def fields(self):
899        return self.regular_fields + tuple(self.paycatyears)
900
901    def mangle_value(self, value, name, context=None):
902        """
903        """
904        amounts = dict()
905        for catyear in self.paycatyears:
906            amounts[catyear] = 0.0
907        if name[:-2] in self.paycats and context is not None:
908            for ticket in context['payments'].values():
909                if ticket.p_category == name[:-2]:
910                    if ticket.p_state in ('waived', 'paid'):
911                        if str(ticket.p_session)[2:] == name[-2:]:
912                            amounts[name] += ticket.amount_auth
913            if amounts[name] == 0.0:
914                value = ''
915            elif isinstance(amounts[name], float):
916                value = round(amounts[name], 2)
917        return super(
918            StudentExporter, self).mangle_value(
919            value, name, context=context)
920
921class StudyLevelsOverviewExporter(StudentExporter):
922    """The Student Study Levels Overview Exporter first filters the set of
923    students by searching the students catalog. Then it exports some student
924    base data together with the session key of registered levels.
925    Sample output:
926
927    header: ``...100,110,120,200,210,220,300...``
928
929    data: ``...2010,,,2011,2012,,2013...``
930
931    This csv data string means that level 100 was registered in session
932    2010/2011, level 200 in session 2011/2012, level 210 (200 on 1st probation)
933    in session 2012/2013 and level 300 in session 2013/2014.
934    """
935    grok.name('studylevelsoverview')
936
937    avail_levels = tuple([str(x) for x in study_levels(None)])
938
939    fields = ('student_id', ) + (
940        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
941        'entry_session', 'current_level', 'current_session',
942        ) + avail_levels
943    title = _(u'Study Levels Overview')
944
945    def mangle_value(self, value, name, context=None):
946        """The mangler checks if a given level has been registered. It returns
947        the ``level_session`` attribute of the student study level object
948        if the named level exists.
949        """
950        if name in self.avail_levels and context is not None:
951            value = ''
952            for level in context['studycourse'].values():
953                if level.level == int(name):
954                    value = '%s' % level.level_session
955                    break
956        return super(
957            StudentExporter, self).mangle_value(
958            value, name, context=context)
959
960class ComboCardDataExporter(grok.GlobalUtility, StudentExporterBase):
961    """Like all other exporters the Combo Card Data Exporter first filters the
962    set of students by searching the students catalog. Then it exports some
963    student base data which are neccessary to print for the Interswitch combo
964    card (identity card for students). The output contains a ``passport_path``
965    column which contains the filesystem path of the passport image file.
966    If no path is given, no passport image file exists.
967    """
968    grok.name('combocard')
969
970    fields = ('display_fullname',
971              'student_id','matric_number',
972              'certificate', 'faculty', 'department', 'passport_path')
973    title = _(u'Combo Card Data')
974
975    def mangle_value(self, value, name, context=None):
976        """The mangler determines the titles of faculty, department
977        and certificate. It also computes the path of passport image file
978        stored in the filesystem.
979        """
980        certificate = context['studycourse'].certificate
981        if name == 'certificate' and certificate is not None:
982            value = certificate.title
983        if name == 'department' and certificate is not None:
984            value = certificate.__parent__.__parent__.longtitle
985        if name == 'faculty' and certificate is not None:
986            value = certificate.__parent__.__parent__.__parent__.longtitle
987        if name == 'passport_path' and certificate is not None:
988            file_id = IFileStoreNameChooser(context).chooseName(
989                attr='passport.jpg')
990            os_path = getUtility(IExtFileStore)._pathFromFileID(file_id)
991            if not os.path.exists(os_path):
992                value = None
993            else:
994                value = '/'.join(os_path.split('/')[-4:])
995        return super(
996            ComboCardDataExporter, self).mangle_value(
997            value, name, context=context)
998
999class TranscriptDataExporter(StudentExporter):
1000    """The Transcript Data Exporter first filters the set of
1001    students by searching the students catalog. Then it exports student data
1002    along with their transcript data.
1003    """
1004    grok.name('transcriptdata')
1005
1006    fields = ('student_id', ) + (
1007        'state', 'certcode', 'faccode', 'depcode',
1008        'entry_session', 'current_level', 'current_session',
1009        'transcript_data')
1010    title = _(u'Transcript Data')
1011
1012    def mangle_value(self, value, name, context=None):
1013        """The mangler determines and formats the transcript data.
1014        """
1015        if name == 'transcript_data':
1016            value = {}
1017            td = context['studycourse'].getTranscriptData()[0]
1018            for level in td:
1019                tickets_1 = ','.join(i.code for i in level['tickets_1'])
1020                tickets_2 = ','.join(i.code for i in level['tickets_2'])
1021                tickets_3 = ','.join(i.code for i in level['tickets_3'])
1022                value = "Level %s; 1st: %s; 2nd: %s; 3rd: %s; sgpa: %s" % (
1023                    level['level_key'], tickets_1, tickets_2,
1024                    tickets_3, level['sgpa'],
1025                    )
1026        return super(
1027            TranscriptDataExporter, self).mangle_value(
1028            value, name, context=context)
Note: See TracBrowser for help on using the repository browser.