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

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

Add new payment state 'waived'. This state can only be set by import
and is only used for the payments overview exporter to
mark sessions with waived fees.

  • Property svn:keywords set to Id
File size: 20.2 KB
Line 
1## $Id: export.py 12568 2015-02-07 11:26:19Z 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 get_selected(self, site, selected):
193        """Get set of selected students.
194
195        Returns a simple empty list or a list with `Student`
196        objects.
197        """
198        students = []
199        students_container = site.get('students', {})
200        for id in selected:
201            student = students_container.get(id, None)
202            if student:
203                students.append(student)
204        return students
205
206    def export(self, values, filepath=None):
207        """Export `values`, an iterable, as CSV file.
208
209        If `filepath` is ``None``, a raw string with CSV data is returned.
210        """
211        writer, outfile = self.get_csv_writer(filepath)
212        for value in values:
213            self.write_item(value, writer)
214        return self.close_outfile(filepath, outfile)
215
216    def export_all(self, site, filepath=None):
217        """Export students into filepath as CSV data.
218
219        If `filepath` is ``None``, a raw string with CSV data is returned.
220        """
221        return self.export(self.filter_func(get_students(site)), filepath)
222
223    def export_student(self, student, filepath=None):
224        return self.export(self.filter_func([student]), filepath=filepath)
225
226    def export_filtered(self, site, filepath=None, **kw):
227        """Export items denoted by `kw`.
228
229        If `filepath` is ``None``, a raw string with CSV data should
230        be returned.
231        """
232        data = self.get_filtered(site, **kw)
233        return self.export(self.filter_func(data, **kw), filepath=filepath)
234
235    def export_selected(self,site, filepath=None, **kw):
236        """Export data for selected set of students.
237        """
238        selected = kw.get('selected', [])
239        data = self.get_selected(site, selected)
240        return self.export(self.filter_func(data, **kw), filepath=filepath)
241
242
243class StudentExporter(grok.GlobalUtility, StudentExporterBase):
244    """Exporter for Students.
245    """
246    grok.name('students')
247
248    #: Fieldnames considered by this exporter
249    fields = tuple(sorted(iface_names(IStudent))) + (
250        'password', 'state', 'history', 'certcode', 'is_postgrad',
251        'current_level', 'current_session')
252
253    #: The title under which this exporter will be displayed
254    title = _(u'Students')
255
256    def mangle_value(self, value, name, context=None):
257        if name == 'history':
258            value = value.messages
259        if name == 'phone' and value is not None:
260            # Append hash '#' to phone numbers to circumvent
261            # unwanted excel automatic
262            value = str('%s#' % value)
263        return super(
264            StudentExporter, self).mangle_value(
265            value, name, context=context)
266
267
268class StudentStudyCourseExporter(grok.GlobalUtility, StudentExporterBase):
269    """Exporter for StudentStudyCourses.
270    """
271    grok.name('studentstudycourses')
272
273    #: Fieldnames considered by this exporter
274    fields = tuple(sorted(iface_names(IStudentStudyCourse))) + ('student_id',)
275
276    #: The title under which this exporter will be displayed
277    title = _(u'Student Study Courses')
278
279    def filter_func(self, x, **kw):
280        return get_studycourses(x)
281
282    def mangle_value(self, value, name, context=None):
283        """Treat location values special.
284        """
285        if name == 'certificate' and value is not None:
286            # XXX: hopefully cert codes are unique site-wide
287            value = value.code
288        if name == 'student_id' and context is not None:
289            student = context.student
290            value = getattr(student, name, None)
291        return super(
292            StudentStudyCourseExporter, self).mangle_value(
293            value, name, context=context)
294
295
296class StudentStudyLevelExporter(grok.GlobalUtility, StudentExporterBase):
297    """Exporter for StudentStudyLevels.
298    """
299    grok.name('studentstudylevels')
300
301    #: Fieldnames considered by this exporter
302    fields = tuple(sorted(iface_names(
303        IStudentStudyLevel) + ['level'])) + (
304        'student_id', 'number_of_tickets','certcode')
305
306    #: The title under which this exporter will be displayed
307    title = _(u'Student Study Levels')
308
309    def filter_func(self, x, **kw):
310        return get_levels(x)
311
312    def mangle_value(self, value, name, context=None):
313        """Treat location values special.
314        """
315        if name == 'student_id' and context is not None:
316            student = context.student
317            value = getattr(student, name, None)
318        return super(
319            StudentStudyLevelExporter, self).mangle_value(
320            value, name, context=context)
321
322class CourseTicketExporter(grok.GlobalUtility, StudentExporterBase):
323    """Exporter for CourseTickets.
324    """
325    grok.name('coursetickets')
326
327    #: Fieldnames considered by this exporter
328    fields = tuple(sorted(iface_names(ICourseTicket) +
329        ['level', 'code', 'level_session'])) + ('student_id',
330        'certcode', 'display_fullname')
331
332    #: The title under which this exporter will be displayed
333    title = _(u'Course Tickets')
334
335    def filter_func(self, x, **kw):
336        return get_tickets(x, **kw)
337
338    def mangle_value(self, value, name, context=None):
339        """Treat location values special.
340        """
341        if context is not None:
342            student = context.student
343            if name in ('student_id', 'display_fullname') and student is not None:
344                value = getattr(student, name, None)
345            #if name == 'level':
346            #    value = getattr(context, 'level', lambda: None)
347            #if name == 'level_session':
348            #    value = getattr(context, 'level_session', lambda: None)
349        return super(
350            CourseTicketExporter, self).mangle_value(
351            value, name, context=context)
352
353
354class StudentPaymentsExporter(grok.GlobalUtility, StudentExporterBase):
355    """Exporter for OnlinePayment instances.
356    """
357    grok.name('studentpayments')
358
359    #: Fieldnames considered by this exporter
360    fields = tuple(
361        sorted(iface_names(
362            IStudentOnlinePayment, exclude_attribs=False,
363            omit=['display_item']))) + (
364            'student_id','state','current_session')
365
366    #: The title under which this exporter will be displayed
367    title = _(u'Student Payments')
368
369    def filter_func(self, x, **kw):
370        return get_payments(x, **kw)
371
372    def mangle_value(self, value, name, context=None):
373        """Treat location values special.
374        """
375        if context is not None:
376            student = context.student
377            if name in ['student_id','state',
378                        'current_session'] and student is not None:
379                value = getattr(student, name, None)
380        return super(
381            StudentPaymentsExporter, self).mangle_value(
382            value, name, context=context)
383
384class DataForBursaryExporter(StudentPaymentsExporter):
385    """Exporter for OnlinePayment instances.
386    """
387    grok.name('bursary')
388
389    def filter_func(self, x, **kw):
390        return get_payments(x, paid=True, **kw)
391
392    #: Fieldnames considered by this exporter
393    fields = tuple(
394        sorted(iface_names(
395            IStudentOnlinePayment, exclude_attribs=False,
396            omit=['display_item']))) + (
397            'student_id','matric_number','reg_number',
398            'firstname', 'middlename', 'lastname',
399            'state','current_session',
400            'entry_session', 'entry_mode',
401            'faccode', 'depcode','certcode')
402
403    #: The title under which this exporter will be displayed
404    title = _(u'Payment Data for Bursary')
405
406    def mangle_value(self, value, name, context=None):
407        """Treat location values special.
408        """
409        if context is not None:
410            student = context.student
411            if name in [
412                'student_id','matric_number', 'reg_number',
413                'firstname', 'middlename', 'lastname',
414                'state', 'current_session',
415                'entry_session', 'entry_mode',
416                'faccode', 'depcode', 'certcode'] and student is not None:
417                value = getattr(student, name, None)
418        return super(
419            StudentPaymentsExporter, self).mangle_value(
420            value, name, context=context)
421
422class BedTicketsExporter(grok.GlobalUtility, StudentExporterBase):
423    """Exporter for BedTicket instances.
424    """
425    grok.name('bedtickets')
426
427    #: Fieldnames considered by this exporter
428    fields = tuple(
429        sorted(iface_names(
430            IBedTicket, exclude_attribs=False,
431            omit=['display_coordinates']))) + (
432            'student_id', 'actual_bed_type')
433
434    #: The title under which this exporter will be displayed
435    title = _(u'Bed Tickets')
436
437    def filter_func(self, x, **kw):
438        return get_bedtickets(x)
439
440    def mangle_value(self, value, name, context=None):
441        """Treat location values and others special.
442        """
443        if context is not None:
444            student = context.student
445            if name in ['student_id'] and student is not None:
446                value = getattr(student, name, None)
447        if name == 'bed' and value is not None:
448            value = getattr(value, 'bed_id', None)
449        if name == 'actual_bed_type':
450            value = getattr(getattr(context, 'bed', None), 'bed_type')
451        return super(
452            BedTicketsExporter, self).mangle_value(
453            value, name, context=context)
454
455class StudentPaymentsOverviewExporter(StudentExporter):
456    """Exporter for students with payment overview.
457    """
458    grok.name('paymentsoverview')
459
460    curr_year = datetime.now().year
461    year_range = range(curr_year - 9, curr_year + 1)
462    year_range_tuple = tuple([str(year) for year in year_range])
463
464    #: Fieldnames considered by this exporter
465    fields = ('student_id', 'matric_number', 'display_fullname',
466        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
467        'current_level', 'current_session', 'current_mode',
468        ) + year_range_tuple
469
470    #: The title under which this exporter will be displayed
471    title = _(u'Student Payments Overview')
472
473    def mangle_value(self, value, name, context=None):
474        if name in self.year_range_tuple and context is not None:
475            value = 0
476            for ticket in context['payments'].values():
477                if ticket.p_category == 'schoolfee' and \
478                    ticket.p_session == int(name):
479                    if ticket.p_state == 'waived':
480                        value = 'waived'
481                        break
482                    if ticket.p_state == 'paid':
483                        try:
484                            value += ticket.amount_auth
485                        except TypeError:
486                            pass
487            if value == 0:
488                value = ''
489        return super(
490            StudentExporter, self).mangle_value(
491            value, name, context=context)
492
493class StudentStudyLevelsOverviewExporter(StudentExporter):
494    """Exporter for students with study level overview.
495    """
496    grok.name('studylevelsoverview')
497
498    avail_levels = tuple([str(x) for x in study_levels(None)])
499
500    #: Fieldnames considered by this exporter
501    fields = ('student_id', ) + (
502        'state', 'certcode', 'faccode', 'depcode', 'is_postgrad',
503        'entry_session', 'current_level', 'current_session',
504        ) + avail_levels
505
506    #: The title under which this exporter will be displayed
507    title = _(u'Student Study Levels Overview')
508
509    def mangle_value(self, value, name, context=None):
510        if name in self.avail_levels and context is not None:
511            value = ''
512            for level in context['studycourse'].values():
513                if level.level == int(name):
514                    #value = '%s|%s|%s|%s' % (
515                    #    level.level_session,
516                    #    len(level),
517                    #    level.validated_by,
518                    #    level.level_verdict)
519                    value = '%s' % level.level_session
520                    break
521        return super(
522            StudentExporter, self).mangle_value(
523            value, name, context=context)
524
525class ComboCardDataExporter(grok.GlobalUtility, StudentExporterBase):
526    """Exporter for Interswitch Combo Card Data.
527    """
528    grok.name('combocard')
529
530    #: Fieldnames considered by this exporter
531    fields = ('display_fullname',
532              'student_id','matric_number',
533              'certificate', 'faculty', 'department', 'passport_path')
534
535    #: The title under which this exporter will be displayed
536    title = _(u'Combo Card Data')
537
538    def mangle_value(self, value, name, context=None):
539        certificate = context['studycourse'].certificate
540        if name == 'certificate' and certificate is not None:
541            value = certificate.title
542        if name == 'department' and certificate is not None:
543            value = certificate.__parent__.__parent__.longtitle
544        if name == 'faculty' and certificate is not None:
545            value = certificate.__parent__.__parent__.__parent__.longtitle
546        if name == 'passport_path' and certificate is not None:
547            file_id = IFileStoreNameChooser(context).chooseName(attr='passport.jpg')
548            os_path = getUtility(IExtFileStore)._pathFromFileID(file_id)
549            if not os.path.exists(os_path):
550                value = None
551            else:
552                value = '/'.join(os_path.split('/')[-4:])
553        return super(
554            ComboCardDataExporter, self).mangle_value(
555            value, name, context=context)
Note: See TracBrowser for help on using the repository browser.