source: main/waeup.kofa/trunk/src/waeup/kofa/students/reports/student_statistics.py @ 11954

Last change on this file since 11954 was 11254, checked in by uli, 11 years ago

Merge changes from uli-diazo-themed back into trunk. If this works, then a miracle happened.

  • Property svn:keywords set to Id
File size: 9.5 KB
Line 
1## $Id: student_statistics.py 11254 2014-02-22 15:46:03Z uli $
2##
3## Copyright (C) 2012 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##
18import grok
19from zope.catalog.interfaces import ICatalog
20from zope.component import queryUtility, getUtility
21from zope.interface import implementer, Interface, Attribute
22from waeup.kofa.interfaces import (
23    IKofaUtils,
24    academic_sessions_vocab, registration_states_vocab)
25from waeup.kofa.interfaces import MessageFactory as _
26from waeup.kofa.reports import IReport
27
28class IStudentStatisticsReport(IReport):
29
30    session = Attribute('Session to report')
31    mode = Attribute('Study modes group to report')
32    creation_dt_string = Attribute('Human readable report creation datetime')
33
34def get_student_stats(session, mode):
35    """Get students in a certain session and study mode.
36
37    Returns a table ordered by faculty code (one per row) and
38    registration state (cols). The result is a 3-tuple representing
39    ((<FACULTY_CODES>), (<STATES>), (<NUM_OF_STUDENTS>)). The
40    (<NUM_OF_STUDENTS>) is an n-tuple with each entry containing the
41    number of students found in that faculty and with the respective
42    state.
43
44    Sample result:
45
46      >>> ((u'FAC1', u'FAC2'),
47      ...  ('created', 'accepted', 'registered'),
48      ...  ((12, 10, 1), (0, 5, 25)))
49
50    This result means: there are 5 students in FAC2 in state
51    'accepted' while 12 students in 'FAC1' are in state 'created'.
52    """
53    site = grok.getSite()
54    states = tuple([x.value for x in registration_states_vocab])
55    states = states + (u'Total',)
56    fac_codes = tuple(sorted([x for x in site['faculties'].keys()],
57                             key=lambda x: x.lower()))
58    fac_codes = fac_codes + (u'Total',)
59    # XXX: Here we do _one_ query and then examine the single
60    #   students. One could also do multiple queries and just look for
61    #   the result length (not introspecting the delivered students
62    #   further).
63    cat = queryUtility(ICatalog, name="students_catalog")
64    result = cat.searchResults(current_session=(session, session))
65    table = [[0 for x in xrange(len(states))] for y in xrange(len(fac_codes))]
66    mode_groups = getUtility(IKofaUtils).MODE_GROUPS
67    for stud in result:
68        if mode != 'All' and stud.current_mode not in mode_groups[mode]:
69            continue
70        if stud.faccode not in fac_codes:
71            # studs can have a faccode ``None``
72            continue
73        row = fac_codes.index(stud.faccode)
74        col = states.index(stud.state)
75        table[row][col] += 1
76        table[-1][col] += 1
77        table[row][-1] += 1
78        table[-1][-1] += 1
79    # turn lists into tuples
80    table = tuple([tuple(row) for row in table])
81    return (fac_codes, states, table)
82
83from reportlab.lib import colors
84from reportlab.lib.styles import getSampleStyleSheet
85from reportlab.lib.units import cm
86from reportlab.platypus import Paragraph, Table, Spacer
87from waeup.kofa.reports import IReport, IReportGenerator
88from waeup.kofa.reports import Report
89from waeup.kofa.browser.interfaces import IPDFCreator
90
91STYLE = getSampleStyleSheet()
92
93def tbl_data_to_table(row_names, col_names, data):
94    result = []
95    new_col_names = []
96    for name in col_names:
97        new_col_names.append(name.replace(' ', '\n'))
98    head = [''] + list(new_col_names)
99    result = [head]
100    for idx, row_name in enumerate(row_names):
101        row = [row_name] + list(data[idx])
102        result.append(row)
103    return result
104
105TABLE_STYLE = [
106    ('FONT', (0,0), (-1,-1), 'Helvetica', 8),
107    ('FONT', (0,0), (0,-1), 'Helvetica-Bold', 8),
108    ('FONT', (0,0), (-1,0), 'Helvetica-Bold', 8),
109    ('FONT', (0,-1), (-1,-1), 'Helvetica-Bold', 8),
110    ('FONT', (-1,0), (-1,-1), 'Helvetica-Bold', 8),
111    ('ALIGN', (1,1), (-1,-1), 'RIGHT'),
112    ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
113    ('LINEBELOW', (0,-1), (-1,-1), 0.25, colors.black),
114    ('LINEAFTER', (-1,0), (-1,-1), 0.25, colors.black),
115    ('LINEBEFORE', (-1,0), (-1,-1), 1.0, colors.black),
116    #('LINEABOVE', (0,-1), (-1,-1), 1.0, colors.black),
117    #('LINEABOVE', (0,0), (-1,0), 0.25, colors.black),
118    ]
119
120@implementer(IStudentStatisticsReport)
121class StudentStatisticsReport(Report):
122    data = None
123    session = None
124    mode = None
125
126    def __init__(self, session, mode, author='System'):
127        super(StudentStatisticsReport, self).__init__(
128            args=[session, mode], kwargs={'author':author})
129        self.session = academic_sessions_vocab.getTerm(session).title
130        self.mode = mode
131        self.author = author
132        self.creation_dt_string = self.creation_dt.astimezone(
133            getUtility(IKofaUtils).tzinfo).strftime("%Y-%m-%d %H:%M:%S %Z")
134        self.data = get_student_stats(session, mode)
135
136    def create_pdf(self):
137        creator = getUtility(IPDFCreator, name='landscape')
138        table_data = tbl_data_to_table(*self.data)
139        col_widths = [None,] + [1.6*cm] * len(self.data[1]) + [None,]
140        pdf_data = [Paragraph('<b>%s</b>' % self.creation_dt_string,
141                              STYLE["Normal"]),
142                    Spacer(1, 12),]
143        pdf_data += [
144            Table(table_data, style=TABLE_STYLE, colWidths=col_widths)]
145        doc_title = '%s Students in Session %s' % (self.mode, self.session)
146        pdf = creator.create_pdf(
147            pdf_data, None, doc_title, self.author,
148            'Students in Session %s' % self.session
149            )
150        return pdf
151
152@implementer(IReportGenerator)
153class StudentStatisticsReportGenerator(grok.GlobalUtility):
154
155    title = _('Student Statistics')
156    grok.name('student_stats')
157
158    def generate(self, site, session=None, mode=None, author=None):
159        result = StudentStatisticsReport(session=session, mode=mode, author=author)
160        return result
161
162###############################################################
163## Browser related stuff
164##
165## XXX: move to local browser module
166###############################################################
167from waeup.kofa.browser.layout import KofaPage
168from waeup.kofa.interfaces import academic_sessions_vocab
169from waeup.kofa.reports import get_generators
170from waeup.kofa.browser.breadcrumbs import Breadcrumb
171grok.templatedir('browser_templates')
172class StudentStatisticsReportGeneratorPage(KofaPage):
173
174    grok.context(StudentStatisticsReportGenerator)
175    grok.name('index.html')
176    grok.require('waeup.manageReports')
177
178    label = _('Create student statistics report')
179
180    @property
181    def generator_name(self):
182        for name, gen in get_generators():
183            if gen == self.context:
184                return name
185        return None
186
187    def update(self, CREATE=None, session=None, mode=None):
188        self.parent_url = self.url(self.context.__parent__)
189        self._set_session_values()
190        self._set_mode_values()
191        if CREATE and session:
192            # create a new report job for students by session
193            container = self.context.__parent__
194            user_id = self.request.principal.id
195            kw = dict(
196                session=int(session),
197                mode=mode)
198            self.flash(_('New report is being created in background'))
199            job_id = container.start_report_job(
200                self.generator_name, user_id, kw=kw)
201            ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
202            grok.getSite().logger.info(
203                '%s - report %s created: %s (session=%s, mode=%s)' % (
204                ob_class, job_id, self.context.title, session, mode))
205            self.redirect(self.parent_url)
206            return
207        return
208
209    def _set_session_values(self):
210        vocab_terms = academic_sessions_vocab.by_value.values()
211        self.sessions = [(x.title, x.token) for x in vocab_terms]
212        return
213
214    def _set_mode_values(self):
215        mode_groups = getUtility(IKofaUtils).MODE_GROUPS
216        self.modes = sorted([(key, key) for key in mode_groups.keys()])
217        return
218
219class StudentStatisticsReportPDFView(grok.View):
220
221    grok.context(IStudentStatisticsReport)
222    grok.name('pdf')
223    grok.require('waeup.Public')
224    prefix = ''
225
226    def _filename(self):
227        return 'StudentStatisticsReport_%s_%s_%s.pdf' % (
228            self.context.session, self.context.mode,
229            self.context.creation_dt_string)
230
231    def render(self):
232        filename = self._filename().replace(
233            '/', '_').replace(' ','_').replace(':', '-')
234        self.response.setHeader(
235            'Content-Type', 'application/pdf')
236        self.response.setHeader(
237            'Content-Disposition:', 'attachment; filename="%s' % filename)
238        pdf_stream = self.context.create_pdf()
239        ob_class = self.__implemented__.__name__.replace('waeup.kofa.','')
240        grok.getSite().logger.info('%s - report %s downloaded: %s' % (
241            ob_class, self.context.__name__, filename))
242        return pdf_stream
243
244class StudentStatsBreadcrumb(Breadcrumb):
245    """A breadcrumb for reports.
246    """
247    grok.context(StudentStatisticsReportGenerator)
248    title = _(u'Student Statistics')
249    target = None
Note: See TracBrowser for help on using the repository browser.