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