1 | ## $Id: export.py 10017 2013-03-12 09:24:07Z 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') |
---|
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 and int(level) != level_obj.level: |
---|
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 | |
---|
89 | def get_payments(students): |
---|
90 | """Get all payments of `students`. |
---|
91 | """ |
---|
92 | payments = [] |
---|
93 | for student in students: |
---|
94 | for payment in student.get('payments', {}).values(): |
---|
95 | payments.append(payment) |
---|
96 | return payments |
---|
97 | |
---|
98 | def get_bedtickets(students): |
---|
99 | """Get all bedtickets of `students`. |
---|
100 | """ |
---|
101 | tickets = [] |
---|
102 | for student in students: |
---|
103 | for ticket in student.get('accommodation', {}).values(): |
---|
104 | tickets.append(ticket) |
---|
105 | return tickets |
---|
106 | |
---|
107 | class StudentExporterBase(ExporterBase): |
---|
108 | """Exporter for students or related objects. |
---|
109 | |
---|
110 | This is a baseclass. |
---|
111 | """ |
---|
112 | grok.baseclass() |
---|
113 | grok.implements(ICSVStudentExporter) |
---|
114 | grok.provides(ICSVStudentExporter) |
---|
115 | |
---|
116 | def filter_func(self, x, **kw): |
---|
117 | return x |
---|
118 | |
---|
119 | def get_filtered(self, site, **kw): |
---|
120 | """Get students from a catalog filtered by keywords. |
---|
121 | |
---|
122 | students_catalog is the default catalog. The keys must be valid |
---|
123 | catalog index names. |
---|
124 | Returns a simple empty list, a list with `Student` |
---|
125 | objects or a catalog result set with `Student` |
---|
126 | objects. |
---|
127 | |
---|
128 | .. seealso:: `waeup.kofa.students.catalog.StudentsCatalog` |
---|
129 | |
---|
130 | """ |
---|
131 | # Pass only given keywords to create FilteredCatalogQuery objects. |
---|
132 | # This way we avoid |
---|
133 | # trouble with `None` value ambivalences and queries are also |
---|
134 | # faster (normally less indexes to ask). Drawback is, that |
---|
135 | # developers must look into catalog to see what keywords are |
---|
136 | # valid. |
---|
137 | if kw.get('catalog', None) == 'coursetickets': |
---|
138 | coursetickets = CourseTicketsQuery(**kw).query() |
---|
139 | students = [] |
---|
140 | for ticket in coursetickets: |
---|
141 | students.append(ticket.student) |
---|
142 | return list(set(students)) |
---|
143 | query = StudentsQuery(**kw) |
---|
144 | return query.query() |
---|
145 | |
---|
146 | def export(self, values, filepath=None): |
---|
147 | """Export `values`, an iterable, as CSV file. |
---|
148 | |
---|
149 | If `filepath` is ``None``, a raw string with CSV data is returned. |
---|
150 | """ |
---|
151 | writer, outfile = self.get_csv_writer(filepath) |
---|
152 | for value in values: |
---|
153 | self.write_item(value, writer) |
---|
154 | return self.close_outfile(filepath, outfile) |
---|
155 | |
---|
156 | def export_all(self, site, filepath=None): |
---|
157 | """Export students into filepath as CSV data. |
---|
158 | |
---|
159 | If `filepath` is ``None``, a raw string with CSV data is returned. |
---|
160 | """ |
---|
161 | return self.export(self.filter_func(get_students(site)), filepath) |
---|
162 | |
---|
163 | def export_student(self, student, filepath=None): |
---|
164 | return self.export(self.filter_func([student]), filepath=filepath) |
---|
165 | |
---|
166 | def export_filtered(self, site, filepath=None, **kw): |
---|
167 | """Export items denoted by `kw`. |
---|
168 | |
---|
169 | If `filepath` is ``None``, a raw string with CSV data should |
---|
170 | be returned. |
---|
171 | """ |
---|
172 | data = self.get_filtered(site, **kw) |
---|
173 | return self.export(self.filter_func(data, **kw), filepath=filepath) |
---|
174 | |
---|
175 | |
---|
176 | class StudentsExporter(grok.GlobalUtility, StudentExporterBase): |
---|
177 | """Exporter for Students. |
---|
178 | """ |
---|
179 | grok.name('students') |
---|
180 | |
---|
181 | #: Fieldnames considered by this exporter |
---|
182 | fields = tuple(sorted(iface_names(IStudent))) + ( |
---|
183 | 'password', 'state', 'history', 'certcode', 'is_postgrad', |
---|
184 | 'current_level', 'current_session') |
---|
185 | |
---|
186 | #: The title under which this exporter will be displayed |
---|
187 | title = _(u'Students') |
---|
188 | |
---|
189 | def mangle_value(self, value, name, context=None): |
---|
190 | if name == 'history': |
---|
191 | value = value.messages |
---|
192 | if name == 'phone' and value is not None: |
---|
193 | # Append hash '#' to phone numbers to circumvent |
---|
194 | # unwanted excel automatic |
---|
195 | value = str('%s#' % value) |
---|
196 | return super( |
---|
197 | StudentsExporter, self).mangle_value( |
---|
198 | value, name, context=context) |
---|
199 | |
---|
200 | |
---|
201 | class StudentStudyCourseExporter(grok.GlobalUtility, StudentExporterBase): |
---|
202 | """Exporter for StudentStudyCourses. |
---|
203 | """ |
---|
204 | grok.name('studentstudycourses') |
---|
205 | |
---|
206 | #: Fieldnames considered by this exporter |
---|
207 | fields = tuple(sorted(iface_names(IStudentStudyCourse))) + ('student_id',) |
---|
208 | |
---|
209 | #: The title under which this exporter will be displayed |
---|
210 | title = _(u'Student Study Courses') |
---|
211 | |
---|
212 | def filter_func(self, x, **kw): |
---|
213 | return get_studycourses(x) |
---|
214 | |
---|
215 | def mangle_value(self, value, name, context=None): |
---|
216 | """Treat location values special. |
---|
217 | """ |
---|
218 | if name == 'certificate' and value is not None: |
---|
219 | # XXX: hopefully cert codes are unique site-wide |
---|
220 | value = value.code |
---|
221 | if name == 'student_id' and context is not None: |
---|
222 | student = context.student |
---|
223 | value = getattr(student, name, None) |
---|
224 | return super( |
---|
225 | StudentStudyCourseExporter, self).mangle_value( |
---|
226 | value, name, context=context) |
---|
227 | |
---|
228 | |
---|
229 | class StudentStudyLevelExporter(grok.GlobalUtility, StudentExporterBase): |
---|
230 | """Exporter for StudentStudyLevels. |
---|
231 | """ |
---|
232 | grok.name('studentstudylevels') |
---|
233 | |
---|
234 | #: Fieldnames considered by this exporter |
---|
235 | fields = tuple(sorted(iface_names( |
---|
236 | IStudentStudyLevel) + ['level'])) + ( |
---|
237 | 'student_id', 'number_of_tickets','certcode') |
---|
238 | |
---|
239 | #: The title under which this exporter will be displayed |
---|
240 | title = _(u'Student Study Levels') |
---|
241 | |
---|
242 | def filter_func(self, x, **kw): |
---|
243 | return get_levels(x) |
---|
244 | |
---|
245 | def mangle_value(self, value, name, context=None): |
---|
246 | """Treat location values special. |
---|
247 | """ |
---|
248 | if name == 'student_id' and context is not None: |
---|
249 | student = context.student |
---|
250 | value = getattr(student, name, None) |
---|
251 | return super( |
---|
252 | StudentStudyLevelExporter, self).mangle_value( |
---|
253 | value, name, context=context) |
---|
254 | |
---|
255 | class CourseTicketExporter(grok.GlobalUtility, StudentExporterBase): |
---|
256 | """Exporter for CourseTickets. |
---|
257 | """ |
---|
258 | grok.name('coursetickets') |
---|
259 | |
---|
260 | #: Fieldnames considered by this exporter |
---|
261 | fields = tuple(sorted(iface_names(ICourseTicket) + |
---|
262 | ['level', 'code', 'level_session'])) + ('student_id', 'certcode') |
---|
263 | |
---|
264 | #: The title under which this exporter will be displayed |
---|
265 | title = _(u'Course Tickets') |
---|
266 | |
---|
267 | def filter_func(self, x, **kw): |
---|
268 | return get_tickets(x, **kw) |
---|
269 | |
---|
270 | def mangle_value(self, value, name, context=None): |
---|
271 | """Treat location values special. |
---|
272 | """ |
---|
273 | if context is not None: |
---|
274 | student = context.student |
---|
275 | if name == 'student_id' and student is not None: |
---|
276 | value = getattr(student, name, None) |
---|
277 | if name == 'level': |
---|
278 | value = getattr(context, 'level', lambda: None) |
---|
279 | if name == 'level_session': |
---|
280 | value = getattr(context, 'level_session', lambda: None) |
---|
281 | return super( |
---|
282 | CourseTicketExporter, self).mangle_value( |
---|
283 | value, name, context=context) |
---|
284 | |
---|
285 | |
---|
286 | class StudentPaymentsExporter(grok.GlobalUtility, StudentExporterBase): |
---|
287 | """Exporter for OnlinePayment instances. |
---|
288 | """ |
---|
289 | grok.name('studentpayments') |
---|
290 | |
---|
291 | #: Fieldnames considered by this exporter |
---|
292 | fields = tuple( |
---|
293 | sorted(iface_names( |
---|
294 | IStudentOnlinePayment, exclude_attribs=False, |
---|
295 | omit=['display_item']))) + ( |
---|
296 | 'student_id','student_state','current_session') |
---|
297 | |
---|
298 | #: The title under which this exporter will be displayed |
---|
299 | title = _(u'Student Payments') |
---|
300 | |
---|
301 | def filter_func(self, x, **kw): |
---|
302 | return get_payments(x) |
---|
303 | |
---|
304 | def mangle_value(self, value, name, context=None): |
---|
305 | """Treat location values special. |
---|
306 | """ |
---|
307 | if context is not None: |
---|
308 | student = context.student |
---|
309 | if name in ['student_id'] and student is not None: |
---|
310 | value = getattr(student, name, None) |
---|
311 | return super( |
---|
312 | StudentPaymentsExporter, self).mangle_value( |
---|
313 | value, name, context=context) |
---|
314 | |
---|
315 | class BedTicketsExporter(grok.GlobalUtility, StudentExporterBase): |
---|
316 | """Exporter for BedTicket instances. |
---|
317 | """ |
---|
318 | grok.name('bedtickets') |
---|
319 | |
---|
320 | #: Fieldnames considered by this exporter |
---|
321 | fields = tuple( |
---|
322 | sorted(iface_names( |
---|
323 | IBedTicket, exclude_attribs=False, |
---|
324 | omit=['display_coordinates']))) + ( |
---|
325 | 'student_id', 'actual_bed_type') |
---|
326 | |
---|
327 | #: The title under which this exporter will be displayed |
---|
328 | title = _(u'Bed Tickets') |
---|
329 | |
---|
330 | def filter_func(self, x, **kw): |
---|
331 | return get_bedtickets(x) |
---|
332 | |
---|
333 | def mangle_value(self, value, name, context=None): |
---|
334 | """Treat location values and others special. |
---|
335 | """ |
---|
336 | if context is not None: |
---|
337 | student = context.student |
---|
338 | if name in ['student_id'] and student is not None: |
---|
339 | value = getattr(student, name, None) |
---|
340 | if name == 'bed' and value is not None: |
---|
341 | value = getattr(value, 'bed_id', None) |
---|
342 | if name == 'actual_bed_type': |
---|
343 | value = getattr(getattr(context, 'bed', None), 'bed_type') |
---|
344 | return super( |
---|
345 | BedTicketsExporter, self).mangle_value( |
---|
346 | value, name, context=context) |
---|
347 | |
---|
348 | class StudentPaymentsOverviewExporter(StudentsExporter): |
---|
349 | """Exporter for students with payment overview. |
---|
350 | """ |
---|
351 | grok.name('paymentsoverview') |
---|
352 | |
---|
353 | curr_year = datetime.now().year |
---|
354 | year_range = range(curr_year - 9, curr_year + 1) |
---|
355 | year_range_tuple = tuple([str(year) for year in year_range]) |
---|
356 | |
---|
357 | #: Fieldnames considered by this exporter |
---|
358 | fields = ('student_id', 'matric_number', 'display_fullname', |
---|
359 | 'state', 'certcode', 'faccode', 'depcode', 'is_postgrad', |
---|
360 | 'current_level', 'current_session', 'current_mode', |
---|
361 | ) + year_range_tuple |
---|
362 | |
---|
363 | #: The title under which this exporter will be displayed |
---|
364 | title = _(u'Student Payments Overview') |
---|
365 | |
---|
366 | def mangle_value(self, value, name, context=None): |
---|
367 | if name in self.year_range_tuple and context is not None: |
---|
368 | value = '' |
---|
369 | for ticket in context['payments'].values(): |
---|
370 | if ticket.p_state == 'paid' and \ |
---|
371 | ticket.p_category == 'schoolfee' and \ |
---|
372 | ticket.p_session == int(name): |
---|
373 | value = ticket.amount_auth |
---|
374 | break |
---|
375 | return super( |
---|
376 | StudentsExporter, self).mangle_value( |
---|
377 | value, name, context=context) |
---|
378 | |
---|
379 | class StudentStudyLevelsOverviewExporter(StudentsExporter): |
---|
380 | """Exporter for students with study level overview. |
---|
381 | """ |
---|
382 | grok.name('studylevelsoverview') |
---|
383 | |
---|
384 | avail_levels = tuple([str(x) for x in study_levels(None)]) |
---|
385 | |
---|
386 | #: Fieldnames considered by this exporter |
---|
387 | fields = ('student_id', ) + ( |
---|
388 | 'state', 'certcode', 'faccode', 'depcode', 'is_postgrad', |
---|
389 | 'entry_session', 'current_level', 'current_session', |
---|
390 | ) + avail_levels |
---|
391 | |
---|
392 | #: The title under which this exporter will be displayed |
---|
393 | title = _(u'Student Study Levels Overview') |
---|
394 | |
---|
395 | def mangle_value(self, value, name, context=None): |
---|
396 | if name in self.avail_levels and context is not None: |
---|
397 | value = '' |
---|
398 | for level in context['studycourse'].values(): |
---|
399 | if level.level == int(name): |
---|
400 | #value = '%s|%s|%s|%s' % ( |
---|
401 | # level.level_session, |
---|
402 | # len(level), |
---|
403 | # level.validated_by, |
---|
404 | # level.level_verdict) |
---|
405 | value = '%s' % level.level_session |
---|
406 | break |
---|
407 | return super( |
---|
408 | StudentsExporter, self).mangle_value( |
---|
409 | value, name, context=context) |
---|
410 | |
---|
411 | class ComboCardDataExporter(grok.GlobalUtility, StudentExporterBase): |
---|
412 | """Exporter for Interswitch Combo Card Data. |
---|
413 | """ |
---|
414 | grok.name('combocard') |
---|
415 | |
---|
416 | #: Fieldnames considered by this exporter |
---|
417 | fields = ('display_fullname', |
---|
418 | 'student_id','matric_number', |
---|
419 | 'certificate', 'faculty', 'department', 'passport_path') |
---|
420 | |
---|
421 | #: The title under which this exporter will be displayed |
---|
422 | title = _(u'Combo Card Data') |
---|
423 | |
---|
424 | def mangle_value(self, value, name, context=None): |
---|
425 | certificate = context['studycourse'].certificate |
---|
426 | if name == 'certificate' and certificate is not None: |
---|
427 | value = certificate.title |
---|
428 | if name == 'department' and certificate is not None: |
---|
429 | value = certificate.__parent__.__parent__.longtitle() |
---|
430 | if name == 'faculty' and certificate is not None: |
---|
431 | value = certificate.__parent__.__parent__.__parent__.longtitle() |
---|
432 | if name == 'passport_path' and certificate is not None: |
---|
433 | file_id = IFileStoreNameChooser(context).chooseName(attr='passport.jpg') |
---|
434 | os_path = getUtility(IExtFileStore)._pathFromFileID(file_id) |
---|
435 | if not os.path.exists(os_path): |
---|
436 | value = None |
---|
437 | else: |
---|
438 | value = '/'.join(os_path.split('/')[-4:]) |
---|
439 | return super( |
---|
440 | ComboCardDataExporter, self).mangle_value( |
---|
441 | value, name, context=context) |
---|