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