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

Last change on this file since 11610 was 11484, checked in by Henrik Bettermann, 11 years ago

Add display_fullname column to CourseTicketExporter? (requested by Uniben).

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