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

Last change on this file since 17740 was 17641, checked in by Henrik Bettermann, 14 months ago

Catch AttributeError?.

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