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

Last change on this file since 15277 was 15277, checked in by Henrik Bettermann, 6 years ago

Add AccommodationPaymentsExporter which can be used by accommodation officers.

  • Property svn:keywords set to Id
File size: 29.7 KB
Line 
1## $Id: export.py 15277 2018-12-19 22:50:36Z 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 datetime import datetime, timedelta
23from zope.component import getUtility
24from waeup.kofa.interfaces import (
25    IExtFileStore, IFileStoreNameChooser, IKofaUtils)
26from waeup.kofa.interfaces import MessageFactory as _
27from waeup.kofa.students.catalog import StudentsQuery, CourseTicketsQuery
28from waeup.kofa.students.interfaces import (
29    IStudent, IStudentStudyCourse, IStudentStudyLevel, ICourseTicket,
30    IStudentOnlinePayment, ICSVStudentExporter, IBedTicket)
31from waeup.kofa.students.vocabularies import study_levels
32from waeup.kofa.utils.batching import ExporterBase
33from waeup.kofa.utils.helpers import iface_names, to_timezone
34
35
36def get_students(site, stud_filter=StudentsQuery()):
37    """Get all students registered in catalog in `site`.
38    """
39    return stud_filter.query()
40
41def get_studycourses(students):
42    """Get studycourses of `students`.
43    """
44    return [x.get('studycourse', None) for x in students
45            if x is not None]
46
47def get_levels(students):
48    """Get all studylevels of `students`.
49    """
50    levels = []
51    for course in get_studycourses(students):
52        for level in course.values():
53            levels.append(level)
54    return levels
55
56def get_tickets(students, **kw):
57    """Get course tickets of `students`.
58    If code is passed through, filter course tickets
59    which belong to this course code and meet level=level
60    and level_session=level_session.
61    If not, but ct_level and ct_session
62    are passed through, filter course tickets
63    which meet level==ct_level and level_session==ct_session.
64    """
65    tickets = []
66    code = kw.get('code', None)
67    level = kw.get('level', None)
68    session = kw.get('session', None)
69    ct_level = kw.get('ct_level', None)
70    ct_session = kw.get('ct_session', None)
71    if code is None:
72        for level_obj in get_levels(students):
73            for ticket in level_obj.values():
74                if ct_level not in ('all', None):
75                    if level_obj.level in (10, 999, None)  \
76                        and int(ct_level) != level_obj.level:
77                        continue
78                    if level_obj.level not in range(
79                        int(ct_level), int(ct_level)+100, 10):
80                        continue
81                if ct_session not in ('all', None) and \
82                    int(ct_session) != level_obj.level_session:
83                    continue
84                tickets.append(ticket)
85    else:
86        for level_obj in get_levels(students):
87            for ticket in level_obj.values():
88                if ticket.code != code:
89                    continue
90                if level not in ('all', None):
91                    if level_obj.level in (10, 999, None)  \
92                        and int(level) != level_obj.level:
93                        continue
94                    if level_obj.level not in range(
95                        int(level), int(level)+100, 10):
96                        continue
97                if session not in ('all', None) and \
98                    int(session) != level_obj.level_session:
99                    continue
100                tickets.append(ticket)
101    return tickets
102
103def get_tickets_for_lecturer(students, **kw):
104    """Get course tickets of `students`.
105    Filter course tickets which belong to this course code and
106    which are editable by lecturers.
107    """
108    tickets = []
109    code = kw.get('code', None)
110    level_session = kw.get('session', None)
111    level = kw.get('level', None)
112    for level_obj in get_levels(students):
113        for ticket in level_obj.values():
114            if ticket.code != code:
115                continue
116            if not ticket.editable_by_lecturer:
117                continue
118            if level not in ('all', None):
119                if level_obj.level in (10, 999, None)  \
120                    and int(level) != level_obj.level:
121                    continue
122                if level_obj.level not in range(int(level), int(level)+100, 10):
123                    continue
124            if level_session not in ('all', None) and \
125                int(level_session) != level_obj.level_session:
126                continue
127            tickets.append(ticket)
128    return tickets
129
130def get_payments(students, p_states=None, **kw):
131    """Get all payments of `students` within given payment_date period.
132    """
133    date_format = '%d/%m/%Y'
134    payments = []
135    p_start = kw.get('payments_start')
136    p_end = kw.get('payments_end')
137    paycat = kw.get('paycat')
138    paysession = kw.get('paysession')
139    for student in students:
140        for payment in student.get('payments', {}).values():
141            if p_start and p_end:
142                if not payment.payment_date:
143                    continue
144                payments_start = datetime.strptime(p_start, date_format)
145                payments_end = datetime.strptime(p_end, date_format)
146                tz = getUtility(IKofaUtils).tzinfo
147                payments_start = tz.localize(payments_start)
148                payments_end = tz.localize(payments_end) + timedelta(days=1)
149                payment_date = to_timezone(payment.payment_date, tz)
150                if payment_date < payments_start or payment_date > payments_end:
151                    continue
152            if p_states and not payment.p_state in p_states:
153                continue
154            if paycat not in ('all', None) and payment.p_category != paycat:
155                continue
156            if paysession not in ('all', None) and payment.p_session != paysession:
157                continue
158            payments.append(payment)
159    return payments
160
161def get_bedtickets(students):
162    """Get all bedtickets of `students`.
163    """
164    tickets = []
165    for student in students:
166        for ticket in student.get('accommodation', {}).values():
167            tickets.append(ticket)
168    return tickets
169
170class StudentExporterBase(ExporterBase):
171    """Exporter for students or related objects.
172    This is a baseclass.
173    """
174    grok.baseclass()
175    grok.implements(ICSVStudentExporter)
176    grok.provides(ICSVStudentExporter)
177
178    def filter_func(self, x, **kw):
179        return x
180
181    def get_filtered(self, site, **kw):
182        """Get students from a catalog filtered by keywords.
183        students_catalog is the default catalog. The keys must be valid
184        catalog index names.
185        Returns a simple empty list, a list with `Student`
186        objects or a catalog result set with `Student`
187        objects.
188
189        .. seealso:: `waeup.kofa.students.catalog.StudentsCatalog`
190
191        """
192        # Pass only given keywords to create FilteredCatalogQuery objects.
193        # This way we avoid
194        # trouble with `None` value ambivalences and queries are also
195        # faster (normally less indexes to ask). Drawback is, that
196        # developers must look into catalog to see what keywords are
197        # valid.
198        if kw.get('catalog', None) == 'coursetickets':
199            coursetickets = CourseTicketsQuery(**kw).query()
200            students = []
201            for ticket in coursetickets:
202                students.append(ticket.student)
203            return list(set(students))
204        # Payments can be filtered by payment date and payment category.
205        # These parameters are not keys of the catalog and must thus be
206        # removed from kw.
207        try:
208            del kw['payments_start']
209            del kw['payments_end']
210            del kw['paycat']
211            del kw['paysession']
212        except KeyError:
213            pass
214        # Coursetickets can be filtered by level and session.
215        # These parameters are not keys of the catalog and must thus be
216        # removed from kw.
217        try:
218            del kw['ct_level']
219            del kw['ct_session']
220        except KeyError:
221            pass
222        query = StudentsQuery(**kw)
223        return query.query()
224
225    def get_selected(self, site, selected):
226        """Get set of selected students.
227        Returns a simple empty list or a list with `Student`
228        objects.
229        """
230        students = []
231        students_container = site.get('students', {})
232        for id in selected:
233            student = students_container.get(id, None)
234            if student is None:
235                # try matric number
236                result = list(StudentsQuery(matric_number=id).query())
237                if result:
238                    student = result[0]
239                else:
240                    continue
241            students.append(student)
242        return students
243
244    def export(self, values, filepath=None):
245        """Export `values`, an iterable, as CSV file.
246        If `filepath` is ``None``, a raw string with CSV data is returned.
247        """
248        writer, outfile = self.get_csv_writer(filepath)
249        for value in values:
250            self.write_item(value, writer)
251        return self.close_outfile(filepath, outfile)
252
253    def export_all(self, site, filepath=None):
254        """Export students into filepath as CSV data.
255        If `filepath` is ``None``, a raw string with CSV data is returned.
256        """
257        return self.export(self.filter_func(get_students(site)), filepath)
258
259    def export_student(self, student, filepath=None):
260        return self.export(self.filter_func([student]), filepath=filepath)
261
262    def export_filtered(self, site, filepath=None, **kw):
263        """Export items denoted by `kw`.
264        If `filepath` is ``None``, a raw string with CSV data should
265        be returned.
266        """
267        data = self.get_filtered(site, **kw)
268        return self.export(self.filter_func(data, **kw), filepath=filepath)
269
270    def export_selected(self,site, filepath=None, **kw):
271        """Export data for selected set of students.
272        """
273        selected = kw.get('selected', [])
274        data = self.get_selected(site, selected)
275        return self.export(self.filter_func(data, **kw), filepath=filepath)
276
277
278class StudentExporter(grok.GlobalUtility, StudentExporterBase):
279    """The Student Exporter first filters the set of students by searching the
280    students catalog. Then it exports student base data of this set of students.
281    """
282    grok.name('students')
283
284    fields = tuple(sorted(iface_names(IStudent))) + (
285        'password', 'state', 'history', 'certcode', 'is_postgrad',
286        'current_level', 'current_session')
287    title = _(u'Students')
288
289    def mangle_value(self, value, name, context=None):
290        """The mangler prepares the history messages and adds a hash symbol at
291        the end of the phone number to avoid annoying automatic number
292        transformation by Excel or Calc."""
293        if name == 'history':
294            value = value.messages
295        if 'phone' in name and value is not None:
296            # Append hash '#' to phone numbers to circumvent
297            # unwanted excel automatic
298            value = str('%s#' % value)
299        return super(
300            StudentExporter, self).mangle_value(
301            value, name, context=context)
302
303
304class StudentStudyCourseExporter(grok.GlobalUtility, StudentExporterBase):
305    """The Student Study Course Exporter first filters the set of students
306    by searching the students catalog. Then it exports the data of the current
307    study course container of each student from this set. It does
308    not export their content.
309    """
310    grok.name('studentstudycourses')
311
312    fields = tuple(sorted(iface_names(IStudentStudyCourse))) + ('student_id',)
313    title = _(u'Student Study Courses')
314
315    def filter_func(self, x, **kw):
316        return get_studycourses(x)
317
318    def mangle_value(self, value, name, context=None):
319        """The mangler determines the certificate code and the student id.
320        """
321        if name == 'certificate' and value is not None:
322            # XXX: hopefully cert codes are unique site-wide
323            value = value.code
324        if name == 'student_id' and context is not None:
325            student = context.student
326            value = getattr(student, name, None)
327        return super(
328            StudentStudyCourseExporter, self).mangle_value(
329            value, name, context=context)
330
331
332class StudentStudyLevelExporter(grok.GlobalUtility, StudentExporterBase):
333    """The Student Study Level Exporter first filters the set of students
334    by searching the students catalog. Then it exports the data of the student's
335    study level container data but not their content (course tickets).
336    The exporter iterates over all objects in the students' ``studycourse``
337    containers.
338    """
339    grok.name('studentstudylevels')
340
341    fields = tuple(sorted(iface_names(
342        IStudentStudyLevel))) + (
343        'student_id', 'number_of_tickets','certcode')
344    title = _(u'Student Study Levels')
345
346    def filter_func(self, x, **kw):
347        return get_levels(x)
348
349    def mangle_value(self, value, name, context=None):
350        """The mangler determines the student id, nothing else.
351        """
352        if name == 'student_id' and context is not None:
353            student = context.student
354            value = getattr(student, name, None)
355        return super(
356            StudentStudyLevelExporter, self).mangle_value(
357            value, name, context=context)
358
359class CourseTicketExporter(grok.GlobalUtility, StudentExporterBase):
360    """The Course Ticket Exporter exports course tickets. Usually,
361    the exporter first filters the set of students by searching the
362    students catalog. Then it collects and iterates over all ``studylevel``
363    containers of the filtered student set and finally
364    iterates over all items inside these containers.
365
366    If the course code is passed through, the exporter uses a different
367    catalog. It searches for students in the course tickets catalog and
368    exports those course tickets which belong to the given course code and
369    also meet level and session passed through at the same time.
370    This happens if the exporter is called at course level in the academic
371    section.
372    """
373    grok.name('coursetickets')
374
375    fields = tuple(sorted(iface_names(ICourseTicket) +
376        ['level', 'code', 'level_session'])) + ('student_id',
377        'certcode', 'display_fullname')
378    title = _(u'Course Tickets')
379
380    def filter_func(self, x, **kw):
381        return get_tickets(x, **kw)
382
383    def mangle_value(self, value, name, context=None):
384        """The mangler determines the student's id and fullname.
385        """
386        if context is not None:
387            student = context.student
388            if name in ('student_id', 'display_fullname') and student is not None:
389                value = getattr(student, name, None)
390        return super(
391            CourseTicketExporter, self).mangle_value(
392            value, name, context=context)
393
394class DataForLecturerExporter(grok.GlobalUtility, StudentExporterBase):
395    """The Data for Lecturer Exporter searches for students in the course
396    tickets catalog and exports those course tickets which belong to the
397    given course code, meet level and session passed through at the
398    same time, and which are editable by lecturers. This exporter can only
399    be called at course level in the academic section.
400    """
401    grok.name('lecturer')
402
403    fields = ('matric_number', 'student_id', 'display_fullname',
404              'level', 'code', 'level_session', 'score')
405
406    title = _(u'Data for Lecturer')
407
408    def filter_func(self, x, **kw):
409        return get_tickets_for_lecturer(x, **kw)
410
411    def mangle_value(self, value, name, context=None):
412        """The mangler determines the student's id and fullname.
413        """
414        if context is not None:
415            student = context.student
416            if name in ('matric_number',
417                        'reg_number',
418                        'student_id',
419                        'display_fullname',) and student is not None:
420                value = getattr(student, name, None)
421        return super(
422            DataForLecturerExporter, self).mangle_value(
423            value, name, context=context)
424
425class StudentPaymentExporter(grok.GlobalUtility, StudentExporterBase):
426    """The Student Payment Exporter first filters the set of students
427    by searching the students catalog. Then it exports student payment
428    tickets by iterating over the items of the student's ``payments``
429    container. If the payment period is given, only tickets, which were
430    paid in payment period, are considered for export.
431    """
432    grok.name('studentpayments')
433
434    fields = tuple(
435        sorted(iface_names(
436            IStudentOnlinePayment, exclude_attribs=False,
437            omit=['display_item', 'certificate', 'student']))) + (
438            'student_id','state','current_session')
439    title = _(u'Student Payments')
440
441    def filter_func(self, x, **kw):
442        return get_payments(x, **kw)
443
444    def mangle_value(self, value, name, context=None):
445        """The mangler determines the student's id, registration
446        state and current session.
447        """
448        if context is not None:
449            student = context.student
450            if name in ['student_id','state',
451                        'current_session'] and student is not None:
452                value = getattr(student, name, None)
453        return super(
454            StudentPaymentExporter, self).mangle_value(
455            value, name, context=context)
456
457class StudentUnpaidPaymentExporter(StudentPaymentExporter):
458    """The Student Unpaid Payment Exporter works just like the
459    Student Payments Exporter but it exports only unpaid tickets.
460    This exporter is designed for finding and finally purging outdated
461    payment ticket.
462    """
463    grok.name('studentunpaidpayments')
464
465    title = _(u'Student Unpaid Payments')
466
467    def filter_func(self, x, **kw):
468        return get_payments(x, p_states=('unpaid',) , **kw)
469
470class DataForBursaryExporter(StudentPaymentExporter):
471    """The DataForBursary Exporter works just like the Student Payment Exporter
472    but it exports much more information about the student. It combines
473    payment and student data in one table in order to spare postprocessing of
474    two seperate export files. The exporter is primarily used by bursary
475    officers who have exclusively access to this exporter. The exporter
476    exports ``paid`` and ``waived`` payment tickets.
477    """
478    grok.name('bursary')
479
480    def filter_func(self, x, **kw):
481        return get_payments(x, p_states=('paid', 'waived'), **kw)
482
483    fields = tuple(
484        sorted(iface_names(
485            IStudentOnlinePayment, exclude_attribs=False,
486            omit=['display_item', 'certificate', 'student']))) + (
487            'student_id','matric_number','reg_number',
488            'firstname', 'middlename', 'lastname',
489            'state','current_session',
490            'entry_session', 'entry_mode',
491            'faccode', 'depcode','certcode')
492    title = _(u'Payment Data for Bursary')
493
494    def mangle_value(self, value, name, context=None):
495        """The mangler fetches the student data.
496        """
497        if context is not None:
498            student = context.student
499            if name in [
500                'student_id','matric_number', 'reg_number',
501                'firstname', 'middlename', 'lastname',
502                'state', 'current_session',
503                'entry_session', 'entry_mode',
504                'faccode', 'depcode', 'certcode'] and student is not None:
505                value = getattr(student, name, None)
506        return super(
507            StudentPaymentExporter, self).mangle_value(
508            value, name, context=context)
509
510class AccommodationPaymentsExporter(DataForBursaryExporter):
511    """The AccommodationPayments Exporter works just like the Student
512    Payment Exporter but it exports much more information about the student.
513    It combines     payment and student data in one table in order to spare
514    postprocessing of     two seperate export files. The exporter is primarily
515    used by bursary officers who have exclusively access to this exporter.
516    The exporter exports ``paid`` and ``waived`` payment tickets with category
517    ``bed_allocation`` or ``hostel_maintenance``.
518    """
519    grok.name('accommodationpayments')
520
521    def filter_func(self, x, **kw):
522        kw['paycat'] = 'bed_allocation'
523        payments = get_payments(x, p_states=('paid', 'waived'), **kw)
524        kw['paycat'] = 'hostel_maintenance'
525        payments += get_payments(x, p_states=('paid', 'waived'), **kw)
526        return payments
527
528    title = _(u'Accommodation Payments')
529
530class BedTicketExporter(grok.GlobalUtility, StudentExporterBase):
531    """The Bed Ticket Exporter first filters the set of students
532    by searching the students catalog. Then it exports bed
533    tickets by iterating over the items of the student's ``accommodation``
534    container.
535    """
536    grok.name('bedtickets')
537
538    fields = tuple(
539        sorted(iface_names(
540            IBedTicket, exclude_attribs=False,
541            omit=['display_coordinates', 'maint_payment_made']))) + (
542            'student_id', 'actual_bed_type')
543    title = _(u'Bed Tickets')
544
545    def filter_func(self, x, **kw):
546        return get_bedtickets(x)
547
548    def mangle_value(self, value, name, context=None):
549        """The mangler determines the student id and the type of the bed
550        which has been booked in the ticket.
551        """
552        if context is not None:
553            student = context.student
554            if name in ['student_id'] and student is not None:
555                value = getattr(student, name, None)
556        if name == 'bed' and value is not None:
557            value = getattr(value, 'bed_id', None)
558        if name == 'actual_bed_type':
559            value = getattr(getattr(context, 'bed', None), 'bed_type', None)
560        return super(
561            BedTicketExporter, self).mangle_value(
562            value, name, context=context)
563
564class SchoolFeePaymentsOverviewExporter(StudentExporter):
565    """The School Fee Payments Overview Exporter first filters the set of students
566    by searching the students catalog. Then it exports some student base data
567    together with the total school fee amount paid in each year over a
568    predefined year range (current year - 9, ... , current year + 1).
569    """
570    grok.name('sfpaymentsoverview')
571
572    curr_year = datetime.now().year
573    year_range = range(curr_year - 11, curr_year + 1)
574    year_range_tuple = tuple([str(year) for year in year_range])
575    fields = ('student_id', 'matric_number', 'display_fullname',
576        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
577        'current_level', 'current_session', 'current_mode',
578        'entry_session', 'reg_number'
579        ) + year_range_tuple
580    title = _(u'Student School Fee Payments Overview')
581
582    def mangle_value(self, value, name, context=None):
583        """The mangler summarizes the school fee amounts made per year. It
584        iterates over all paid school fee payment tickets and
585        adds together the amounts paid in a year. Waived payments
586        are marked ``waived``.
587        """
588        if name in self.year_range_tuple and context is not None:
589            value = 0
590            for ticket in context['payments'].values():
591                if ticket.p_category == 'schoolfee' and \
592                    ticket.p_session == int(name):
593                    if ticket.p_state == 'waived':
594                        value = 'waived'
595                        break
596                    if ticket.p_state == 'paid':
597                        try:
598                            value += ticket.amount_auth
599                        except TypeError:
600                            pass
601            if value == 0:
602                value = ''
603            elif isinstance(value, float):
604                value = round(value, 2)
605        return super(
606            StudentExporter, self).mangle_value(
607            value, name, context=context)
608
609class SessionPaymentsOverviewExporter(StudentExporter):
610    """The Session Payments Overview Exporter first filters the set of students
611    by searching the students catalog. Then it exports some student base data
612    together with the total amount paid in predefined payment categories
613    over the previous three session (referring to current academic session).
614    Sample output:
615
616    header: ``...schoolfee13,schoolfee14,schoolfee15,gown13,gown14,gown15...``
617
618    data: ``...2000.0,,3000.0,,,1000.0,...``
619
620    This csv data string means that the student paid 2000.0 school fee in 2013
621    and 3000.0 in 2015. S/He furthermore paid 1000.0 for gown rental in 2015.
622    """
623    grok.name('sessionpaymentsoverview')
624
625    paycats = ('schoolfee', 'clearance', 'gown', 'transcript')
626    regular_fields = ('student_id', 'matric_number', 'display_fullname',
627        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
628        'current_level', 'current_session', 'current_mode',
629        'entry_session', 'reg_number'
630        )
631    title = _(u'Session Payments Overview')
632
633    @property
634    def paycatyears(self):
635        cas = grok.getSite()['configuration'].current_academic_session
636        paycatyears = []
637        if cas:
638            year_range = range(cas - 2, cas+1)
639            year_range_tuple = tuple([str(year)[2:] for year in year_range])
640            paycatyears = [
641                cat+year for cat in self.paycats for year in year_range_tuple]
642        return paycatyears
643
644    @property
645    def fields(self):
646        return self.regular_fields + tuple(self.paycatyears)
647
648    def mangle_value(self, value, name, context=None):
649        """
650        """
651        amounts = dict()
652        for catyear in self.paycatyears:
653            amounts[catyear] = 0.0
654        if name[:-2] in self.paycats and context is not None:
655            for ticket in context['payments'].values():
656                if ticket.p_category == name[:-2]:
657                    if ticket.p_state in ('waived', 'paid'):
658                        if str(ticket.p_session)[2:] == name[-2:]:
659                            amounts[name] += ticket.amount_auth
660            if amounts[name] == 0.0:
661                value = ''
662            elif isinstance(amounts[name], float):
663                value = round(amounts[name], 2)
664        return super(
665            StudentExporter, self).mangle_value(
666            value, name, context=context)
667
668class StudentStudyLevelsOverviewExporter(StudentExporter):
669    """The Student Study Levels Overview Exporter first filters the set of
670    students by searching the students catalog. Then it exports some student
671    base data together with the session key of registered levels.
672    Sample output:
673
674    header: ``...100,110,120,200,210,220,300...``
675
676    data: ``...2010,,,2011,2012,,2013...``
677
678    This csv data string means that level 100 was registered in session
679    2010/2011, level 200 in session 2011/2012, level 210 (200 on 1st probation)
680    in session 2012/2013 and level 300 in session 2013/2014.
681    """
682    grok.name('studylevelsoverview')
683
684    avail_levels = tuple([str(x) for x in study_levels(None)])
685
686    fields = ('student_id', ) + (
687        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
688        'entry_session', 'current_level', 'current_session',
689        ) + avail_levels
690    title = _(u'Student Study Levels Overview')
691
692    def mangle_value(self, value, name, context=None):
693        """The mangler checks if a given level has been registered. It returns
694        the ``level_session`` attribute of the student study level object
695        if the named level exists.
696        """
697        if name in self.avail_levels and context is not None:
698            value = ''
699            for level in context['studycourse'].values():
700                if level.level == int(name):
701                    value = '%s' % level.level_session
702                    break
703        return super(
704            StudentExporter, self).mangle_value(
705            value, name, context=context)
706
707class ComboCardDataExporter(grok.GlobalUtility, StudentExporterBase):
708    """Like all other exporters the Combo Card Data Exporter first filters the
709    set of students by searching the students catalog. Then it exports some
710    student base data which are neccessary to print for the Interswitch combo
711    card (identity card for students). The output contains a ``passport_path``
712    column which contains the filesystem path of the passport image file.
713    If no path is given, no passport image file exists.
714    """
715    grok.name('combocard')
716
717    fields = ('display_fullname',
718              'student_id','matric_number',
719              'certificate', 'faculty', 'department', 'passport_path')
720    title = _(u'Combo Card Data')
721
722    def mangle_value(self, value, name, context=None):
723        """The mangler determines the titles of faculty, department
724        and certificate. It also computes the path of passport image file
725        stored in the filesystem.
726        """
727        certificate = context['studycourse'].certificate
728        if name == 'certificate' and certificate is not None:
729            value = certificate.title
730        if name == 'department' and certificate is not None:
731            value = certificate.__parent__.__parent__.longtitle
732        if name == 'faculty' and certificate is not None:
733            value = certificate.__parent__.__parent__.__parent__.longtitle
734        if name == 'passport_path' and certificate is not None:
735            file_id = IFileStoreNameChooser(context).chooseName(
736                attr='passport.jpg')
737            os_path = getUtility(IExtFileStore)._pathFromFileID(file_id)
738            if not os.path.exists(os_path):
739                value = None
740            else:
741                value = '/'.join(os_path.split('/')[-4:])
742        return super(
743            ComboCardDataExporter, self).mangle_value(
744            value, name, context=context)
Note: See TracBrowser for help on using the repository browser.