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

Last change on this file since 12395 was 12104, checked in by Henrik Bettermann, 10 years ago

Ease customization of STUDENT_EXPORTER_NAMES.

  • Property svn:keywords set to Id
File size: 19.4 KB
Line 
1## $Id: export.py 12104 2014-12-01 14:43:16Z 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
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
59    If code is passed through, filter course tickets
60    which belong to this course code and meets level
61    and level_session.
62    """
63    tickets = []
64    code = kw.get('code', None)
65    level = kw.get('level', None)
66    level_session = kw.get('level_session', None)
67    if code is None:
68        for level_obj in get_levels(students):
69            for ticket in level_obj.values():
70                tickets.append(ticket)
71    else:
72        for level_obj in get_levels(students):
73            for ticket in level_obj.values():
74                if ticket.code != code:
75                    continue
76                if level is not None:
77                    level = int(level)
78                    if level_obj.level in (10, 999, None)  \
79                        and int(level) != level_obj.level:
80                        continue
81                    if level_obj.level not in range(level, level+100, 10):
82                        continue
83                if level_session is not None and \
84                    int(level_session) != level_obj.level_session:
85                    continue
86                tickets.append(ticket)
87    return tickets
88
89def get_payments(students, paid=False, **kw):
90    """Get all payments of `students` within given payment_date period.
91
92    """
93    date_format = '%d/%m/%Y'
94    payments = []
95    payments_start = kw.get('payments_start')
96    payments_end = kw.get('payments_end')
97    if payments_start and payments_end:
98        # Payment period given
99        payments_start = datetime.strptime(payments_start, date_format)
100        payments_end = datetime.strptime(payments_end, date_format)
101        tz = getUtility(IKofaUtils).tzinfo
102        payments_start = tz.localize(payments_start)
103        payments_end = tz.localize(payments_end)
104        if paid:
105            # Only paid tickets in payment period are considered
106            for student in students:
107                for payment in student.get('payments', {}).values():
108                    if payment.payment_date and payment.p_state == 'paid':
109                        payment_date = to_timezone(payment.payment_date, tz)
110                        if payment_date > payments_start and \
111                            payment_date < payments_end:
112                            payments.append(payment)
113        else:
114            # All tickets in payment period are considered
115            for student in students:
116                for payment in student.get('payments', {}).values():
117                    if payment.payment_date:
118                        payment_date = to_timezone(payment.payment_date, tz)
119                        if payment_date > payments_start and \
120                            payment_date < payments_end:
121                            payments.append(payment)
122    else:
123        # Payment period not given
124        if paid:
125            # Only paid tickets are considered
126            for student in students:
127                for payment in student.get('payments', {}).values():
128                    if payment.p_state == 'paid':
129                        payments.append(payment)
130        else:
131            # All tickets are considered
132            for student in students:
133                for payment in student.get('payments', {}).values():
134                    payments.append(payment)
135    return payments
136
137def get_bedtickets(students):
138    """Get all bedtickets of `students`.
139    """
140    tickets = []
141    for student in students:
142        for ticket in student.get('accommodation', {}).values():
143            tickets.append(ticket)
144    return tickets
145
146class StudentExporterBase(ExporterBase):
147    """Exporter for students or related objects.
148
149    This is a baseclass.
150    """
151    grok.baseclass()
152    grok.implements(ICSVStudentExporter)
153    grok.provides(ICSVStudentExporter)
154
155    def filter_func(self, x, **kw):
156        return x
157
158    def get_filtered(self, site, **kw):
159        """Get students from a catalog filtered by keywords.
160
161        students_catalog is the default catalog. The keys must be valid
162        catalog index names.
163        Returns a simple empty list, a list with `Student`
164        objects or a catalog result set with `Student`
165        objects.
166
167        .. seealso:: `waeup.kofa.students.catalog.StudentsCatalog`
168
169        """
170        # Pass only given keywords to create FilteredCatalogQuery objects.
171        # This way we avoid
172        # trouble with `None` value ambivalences and queries are also
173        # faster (normally less indexes to ask). Drawback is, that
174        # developers must look into catalog to see what keywords are
175        # valid.
176        if kw.get('catalog', None) == 'coursetickets':
177            coursetickets = CourseTicketsQuery(**kw).query()
178            students = []
179            for ticket in coursetickets:
180                students.append(ticket.student)
181            return list(set(students))
182        # Payments can be filtered by payment_date. The period boundaries
183        # are not keys of the catalog and must thus be removed from kw.
184        try:
185            del kw['payments_start']
186            del kw['payments_end']
187        except KeyError:
188            pass
189        query = StudentsQuery(**kw)
190        return query.query()
191
192    def export(self, values, filepath=None):
193        """Export `values`, an iterable, as CSV file.
194
195        If `filepath` is ``None``, a raw string with CSV data is returned.
196        """
197        writer, outfile = self.get_csv_writer(filepath)
198        for value in values:
199            self.write_item(value, writer)
200        return self.close_outfile(filepath, outfile)
201
202    def export_all(self, site, filepath=None):
203        """Export students into filepath as CSV data.
204
205        If `filepath` is ``None``, a raw string with CSV data is returned.
206        """
207        return self.export(self.filter_func(get_students(site)), filepath)
208
209    def export_student(self, student, filepath=None):
210        return self.export(self.filter_func([student]), filepath=filepath)
211
212    def export_filtered(self, site, filepath=None, **kw):
213        """Export items denoted by `kw`.
214
215        If `filepath` is ``None``, a raw string with CSV data should
216        be returned.
217        """
218        data = self.get_filtered(site, **kw)
219        return self.export(self.filter_func(data, **kw), filepath=filepath)
220
221
222class StudentExporter(grok.GlobalUtility, StudentExporterBase):
223    """Exporter for Students.
224    """
225    grok.name('students')
226
227    #: Fieldnames considered by this exporter
228    fields = tuple(sorted(iface_names(IStudent))) + (
229        'password', 'state', 'history', 'certcode', 'is_postgrad',
230        'current_level', 'current_session')
231
232    #: The title under which this exporter will be displayed
233    title = _(u'Students')
234
235    def mangle_value(self, value, name, context=None):
236        if name == 'history':
237            value = value.messages
238        if name == 'phone' and value is not None:
239            # Append hash '#' to phone numbers to circumvent
240            # unwanted excel automatic
241            value = str('%s#' % value)
242        return super(
243            StudentExporter, self).mangle_value(
244            value, name, context=context)
245
246
247class StudentStudyCourseExporter(grok.GlobalUtility, StudentExporterBase):
248    """Exporter for StudentStudyCourses.
249    """
250    grok.name('studentstudycourses')
251
252    #: Fieldnames considered by this exporter
253    fields = tuple(sorted(iface_names(IStudentStudyCourse))) + ('student_id',)
254
255    #: The title under which this exporter will be displayed
256    title = _(u'Student Study Courses')
257
258    def filter_func(self, x, **kw):
259        return get_studycourses(x)
260
261    def mangle_value(self, value, name, context=None):
262        """Treat location values special.
263        """
264        if name == 'certificate' and value is not None:
265            # XXX: hopefully cert codes are unique site-wide
266            value = value.code
267        if name == 'student_id' and context is not None:
268            student = context.student
269            value = getattr(student, name, None)
270        return super(
271            StudentStudyCourseExporter, self).mangle_value(
272            value, name, context=context)
273
274
275class StudentStudyLevelExporter(grok.GlobalUtility, StudentExporterBase):
276    """Exporter for StudentStudyLevels.
277    """
278    grok.name('studentstudylevels')
279
280    #: Fieldnames considered by this exporter
281    fields = tuple(sorted(iface_names(
282        IStudentStudyLevel) + ['level'])) + (
283        'student_id', 'number_of_tickets','certcode')
284
285    #: The title under which this exporter will be displayed
286    title = _(u'Student Study Levels')
287
288    def filter_func(self, x, **kw):
289        return get_levels(x)
290
291    def mangle_value(self, value, name, context=None):
292        """Treat location values special.
293        """
294        if name == 'student_id' and context is not None:
295            student = context.student
296            value = getattr(student, name, None)
297        return super(
298            StudentStudyLevelExporter, self).mangle_value(
299            value, name, context=context)
300
301class CourseTicketExporter(grok.GlobalUtility, StudentExporterBase):
302    """Exporter for CourseTickets.
303    """
304    grok.name('coursetickets')
305
306    #: Fieldnames considered by this exporter
307    fields = tuple(sorted(iface_names(ICourseTicket) +
308        ['level', 'code', 'level_session'])) + ('student_id',
309        'certcode', 'display_fullname')
310
311    #: The title under which this exporter will be displayed
312    title = _(u'Course Tickets')
313
314    def filter_func(self, x, **kw):
315        return get_tickets(x, **kw)
316
317    def mangle_value(self, value, name, context=None):
318        """Treat location values special.
319        """
320        if context is not None:
321            student = context.student
322            if name in ('student_id', 'display_fullname') and student is not None:
323                value = getattr(student, name, None)
324            #if name == 'level':
325            #    value = getattr(context, 'level', lambda: None)
326            #if name == 'level_session':
327            #    value = getattr(context, 'level_session', lambda: None)
328        return super(
329            CourseTicketExporter, self).mangle_value(
330            value, name, context=context)
331
332
333class StudentPaymentsExporter(grok.GlobalUtility, StudentExporterBase):
334    """Exporter for OnlinePayment instances.
335    """
336    grok.name('studentpayments')
337
338    #: Fieldnames considered by this exporter
339    fields = tuple(
340        sorted(iface_names(
341            IStudentOnlinePayment, exclude_attribs=False,
342            omit=['display_item']))) + (
343            'student_id','state','current_session')
344
345    #: The title under which this exporter will be displayed
346    title = _(u'Student Payments')
347
348    def filter_func(self, x, **kw):
349        return get_payments(x, **kw)
350
351    def mangle_value(self, value, name, context=None):
352        """Treat location values special.
353        """
354        if context is not None:
355            student = context.student
356            if name in ['student_id','state',
357                        'current_session'] and student is not None:
358                value = getattr(student, name, None)
359        return super(
360            StudentPaymentsExporter, self).mangle_value(
361            value, name, context=context)
362
363class DataForBursaryExporter(StudentPaymentsExporter):
364    """Exporter for OnlinePayment instances.
365    """
366    grok.name('bursary')
367
368    def filter_func(self, x, **kw):
369        return get_payments(x, paid=True, **kw)
370
371    #: Fieldnames considered by this exporter
372    fields = tuple(
373        sorted(iface_names(
374            IStudentOnlinePayment, exclude_attribs=False,
375            omit=['display_item']))) + (
376            'student_id','matric_number','reg_number',
377            'firstname', 'middlename', 'lastname',
378            'state','current_session',
379            'entry_session', 'entry_mode',
380            'faccode', 'depcode','certcode')
381
382    #: The title under which this exporter will be displayed
383    title = _(u'Payment Data for Bursary')
384
385    def mangle_value(self, value, name, context=None):
386        """Treat location values special.
387        """
388        if context is not None:
389            student = context.student
390            if name in [
391                'student_id','matric_number', 'reg_number',
392                'firstname', 'middlename', 'lastname',
393                'state', 'current_session',
394                'entry_session', 'entry_mode',
395                'faccode', 'depcode', 'certcode'] and student is not None:
396                value = getattr(student, name, None)
397        return super(
398            StudentPaymentsExporter, self).mangle_value(
399            value, name, context=context)
400
401class BedTicketsExporter(grok.GlobalUtility, StudentExporterBase):
402    """Exporter for BedTicket instances.
403    """
404    grok.name('bedtickets')
405
406    #: Fieldnames considered by this exporter
407    fields = tuple(
408        sorted(iface_names(
409            IBedTicket, exclude_attribs=False,
410            omit=['display_coordinates']))) + (
411            'student_id', 'actual_bed_type')
412
413    #: The title under which this exporter will be displayed
414    title = _(u'Bed Tickets')
415
416    def filter_func(self, x, **kw):
417        return get_bedtickets(x)
418
419    def mangle_value(self, value, name, context=None):
420        """Treat location values and others special.
421        """
422        if context is not None:
423            student = context.student
424            if name in ['student_id'] and student is not None:
425                value = getattr(student, name, None)
426        if name == 'bed' and value is not None:
427            value = getattr(value, 'bed_id', None)
428        if name == 'actual_bed_type':
429            value = getattr(getattr(context, 'bed', None), 'bed_type')
430        return super(
431            BedTicketsExporter, self).mangle_value(
432            value, name, context=context)
433
434class StudentPaymentsOverviewExporter(StudentExporter):
435    """Exporter for students with payment overview.
436    """
437    grok.name('paymentsoverview')
438
439    curr_year = datetime.now().year
440    year_range = range(curr_year - 9, curr_year + 1)
441    year_range_tuple = tuple([str(year) for year in year_range])
442
443    #: Fieldnames considered by this exporter
444    fields = ('student_id', 'matric_number', 'display_fullname',
445        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
446        'current_level', 'current_session', 'current_mode',
447        ) + year_range_tuple
448
449    #: The title under which this exporter will be displayed
450    title = _(u'Student Payments Overview')
451
452    def mangle_value(self, value, name, context=None):
453        if name in self.year_range_tuple and context is not None:
454            value = 0
455            for ticket in context['payments'].values():
456                if ticket.p_state == 'paid' and \
457                    ticket.p_category == 'schoolfee' and \
458                    ticket.p_session == int(name):
459                    try:
460                        value += ticket.amount_auth
461                    except TypeError:
462                        pass
463            if value == 0:
464                value = ''
465        return super(
466            StudentExporter, self).mangle_value(
467            value, name, context=context)
468
469class StudentStudyLevelsOverviewExporter(StudentExporter):
470    """Exporter for students with study level overview.
471    """
472    grok.name('studylevelsoverview')
473
474    avail_levels = tuple([str(x) for x in study_levels(None)])
475
476    #: Fieldnames considered by this exporter
477    fields = ('student_id', ) + (
478        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
479        'entry_session', 'current_level', 'current_session',
480        ) + avail_levels
481
482    #: The title under which this exporter will be displayed
483    title = _(u'Student Study Levels Overview')
484
485    def mangle_value(self, value, name, context=None):
486        if name in self.avail_levels and context is not None:
487            value = ''
488            for level in context['studycourse'].values():
489                if level.level == int(name):
490                    #value = '%s|%s|%s|%s' % (
491                    #    level.level_session,
492                    #    len(level),
493                    #    level.validated_by,
494                    #    level.level_verdict)
495                    value = '%s' % level.level_session
496                    break
497        return super(
498            StudentExporter, self).mangle_value(
499            value, name, context=context)
500
501class ComboCardDataExporter(grok.GlobalUtility, StudentExporterBase):
502    """Exporter for Interswitch Combo Card Data.
503    """
504    grok.name('combocard')
505
506    #: Fieldnames considered by this exporter
507    fields = ('display_fullname',
508              'student_id','matric_number',
509              'certificate', 'faculty', 'department', 'passport_path')
510
511    #: The title under which this exporter will be displayed
512    title = _(u'Combo Card Data')
513
514    def mangle_value(self, value, name, context=None):
515        certificate = context['studycourse'].certificate
516        if name == 'certificate' and certificate is not None:
517            value = certificate.title
518        if name == 'department' and certificate is not None:
519            value = certificate.__parent__.__parent__.longtitle
520        if name == 'faculty' and certificate is not None:
521            value = certificate.__parent__.__parent__.__parent__.longtitle
522        if name == 'passport_path' and certificate is not None:
523            file_id = IFileStoreNameChooser(context).chooseName(attr='passport.jpg')
524            os_path = getUtility(IExtFileStore)._pathFromFileID(file_id)
525            if not os.path.exists(os_path):
526                value = None
527            else:
528                value = '/'.join(os_path.split('/')[-4:])
529        return super(
530            ComboCardDataExporter, self).mangle_value(
531            value, name, context=context)
Note: See TracBrowser for help on using the repository browser.