source: main/waeup.aaue/trunk/src/waeup/aaue/students/browser.py @ 15336

Last change on this file since 15336 was 15330, checked in by Henrik Bettermann, 6 years ago

Implement course list repair page.

  • Property svn:keywords set to Id
File size: 50.2 KB
RevLine 
[8911]1## $Id: browser.py 15330 2019-02-14 15:55:27Z henrik $
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
[13937]19import csv
[13964]20import textwrap
[14981]21import pytz
[13937]22from cStringIO import StringIO
[14981]23from datetime import datetime
[8911]24from zope.i18n import translate
[13900]25from zope.component import getUtility, queryUtility
[14113]26from zope.schema.interfaces import TooBig, TooSmall
[13523]27from zope.security import checkPermission
[13900]28from zope.catalog.interfaces import ICatalog
[13351]29from zope.formlib.textwidgets import BytesDisplayWidget
[14981]30from hurry.workflow.interfaces import IWorkflowInfo, IWorkflowState
[15330]31from waeup.kofa.browser.layout import UtilityView, KofaEditFormPage, jsaction
[8911]32from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
[14288]33from waeup.kofa.interfaces import (
[14306]34    IKofaUtils, academic_sessions_vocab, ICSVExporter, IKofaObject)
35from waeup.kofa.students.interfaces import (
[15330]36    IStudentsUtils, IStudent, IStudentRequestPW, IStudentStudyLevel)
[14000]37from waeup.kofa.students.workflow import PAID, REGISTERED, RETURNING
[9914]38from waeup.kofa.students.browser import (
[11846]39    StartClearancePage,
[9914]40    StudentBasePDFFormPage,
41    CourseTicketAddFormPage,
42    StudyLevelDisplayFormPage,
[13834]43    StudyLevelManageFormPage,
44    StudyLevelEditFormPage,
[13059]45    ExportPDFTranscriptSlip,
46    ExportPDFAdmissionSlip,
[13353]47    BedTicketAddPage,
[13380]48    StudentFilesUploadPage,
[13523]49    PaymentsManageFormPage,
[13770]50    CourseTicketDisplayFormPage,
51    CourseTicketManageFormPage,
[13900]52    EditScoresPage,
[14165]53    ExportPDFScoresSlip,
54    StudyCourseTranscriptPage,
[14288]55    DownloadScoresView,
[14534]56    StudentRequestPasswordPage,
[14981]57    StudyCourseManageFormPage,
[15330]58    UnregisterCoursesView,
59    addCourseTicket,
60    emit_lock_message
[10269]61    )
[8911]62from kofacustom.nigeria.students.browser import (
63    NigeriaOnlinePaymentDisplayFormPage,
64    NigeriaOnlinePaymentAddFormPage,
[13059]65    NigeriaExportPDFPaymentSlip,
66    NigeriaExportPDFCourseRegistrationSlip,
[13351]67    NigeriaStudentPersonalDisplayFormPage,
68    NigeriaStudentPersonalEditFormPage,
69    NigeriaStudentPersonalManageFormPage,
[14084]70    NigeriaStudentClearanceDisplayFormPage,
71    NigeriaExportPDFClearanceSlip,
72    NigeriaStudentClearanceManageFormPage,
[13362]73    NigeriaStudentClearanceEditFormPage,
[13462]74    NigeriaAccommodationManageFormPage,
[13795]75    NigeriaStudentBaseDisplayFormPage,
[14165]76    NigeriaStudentBaseManageFormPage
[10269]77    )
[9496]78from waeup.aaue.students.interfaces import (
[9914]79    ICustomStudentOnlinePayment,
[11607]80    ICustomStudentStudyLevel,
[13351]81    ICustomStudent,
82    ICustomStudentPersonal,
[13362]83    ICustomStudentPersonalEdit,
[13770]84    ICustomUGStudentClearance,
[14298]85    ICustomUGStudentClearanceEdit,
[14084]86    ICustomPGStudentClearance,
[13795]87    ICustomCourseTicket,
[14534]88    ICustomStudentBase,
89    ICustomStudentStudyCourse)
[13414]90from waeup.aaue.interswitch.browser import gateway_net_amt
[9914]91from waeup.aaue.interfaces import MessageFactory as _
[8911]92
[14306]93grok.context(IKofaObject)  # Make IKofaObject the default context
94
[15228]95def translated_values(view):
96    """Translate course ticket attribute values to be displayed on
97    studylevel pages.
98    """
99    lang = view.request.cookies.get('kofa.language')
100    for value in view.context.values():
101        value._p_activate()
102        value_dict = dict([i for i in value.__dict__.items()])
103        value_dict['url'] = view.url(value)
104        value_dict['removable_by_student'] = value.removable_by_student
105        value_dict['mandatory'] = translate(str(value.mandatory), 'zope',
106            target_language=lang)
107        value_dict['carry_over'] = translate(str(value.carry_over), 'zope',
108            target_language=lang)
109        value_dict['outstanding'] = translate(str(value.outstanding), 'zope',
110            target_language=lang)
111        value_dict['automatic'] = translate(str(value.automatic), 'zope',
112            target_language=lang)
113        value_dict['grade'] = value.grade
114        value_dict['weight'] = value.weight
115        value_dict['course_category'] = value.course_category
116        value_dict['total_score'] = value.total_score
117        semester_dict = getUtility(IKofaUtils).SEMESTER_DICT
118        value_dict['semester'] = semester_dict[
119            value.semester].replace('mester', 'm.')
120        # AAUE specific
121        value_dict['formatted_total_score'] = value.total_score
122        if getattr(value, 'imported_ts', None):
123            value_dict['formatted_total_score'] = "<strong>%s</strong>" % value.imported_ts
124        yield value_dict
125
[13795]126class CustomStudentBaseDisplayFormPage(NigeriaStudentBaseDisplayFormPage):
127    """ Page to display student base data
128    """
129    form_fields = grok.AutoFields(ICustomStudentBase).omit(
130        'password', 'suspended', 'suspended_comment', 'flash_notice')
131    form_fields[
132        'financial_clearance_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
133
134class CustomStudentBaseManageFormPage(NigeriaStudentBaseManageFormPage):
135    """ View to manage student base data
136    """
137    form_fields = grok.AutoFields(ICustomStudentBase).omit(
138        'student_id', 'adm_code', 'suspended',
139        'financially_cleared_by', 'financial_clearance_date')
140
[13351]141class CustomStudentPersonalDisplayFormPage(NigeriaStudentPersonalDisplayFormPage):
142    """ Page to display student personal data
143    """
144    form_fields = grok.AutoFields(ICustomStudentPersonal)
145    form_fields['perm_address'].custom_widget = BytesDisplayWidget
146    form_fields['father_address'].custom_widget = BytesDisplayWidget
147    form_fields['mother_address'].custom_widget = BytesDisplayWidget
148    form_fields['next_kin_address'].custom_widget = BytesDisplayWidget
149    form_fields[
150        'personal_updated'].custom_widget = FriendlyDatetimeDisplayWidget('le')
151
152class CustomStudentPersonalEditFormPage(NigeriaStudentPersonalEditFormPage):
153    """ Page to edit personal data
154    """
155    form_fields = grok.AutoFields(ICustomStudentPersonalEdit).omit('personal_updated')
156
157class CustomStudentPersonalManageFormPage(NigeriaStudentPersonalManageFormPage):
158    """ Page to edit personal data
159    """
160    form_fields = grok.AutoFields(ICustomStudentPersonal)
161    form_fields['personal_updated'].for_display = True
162    form_fields[
163        'personal_updated'].custom_widget = FriendlyDatetimeDisplayWidget('le')
164
[14661]165
166class ExportExaminationScheduleSlip(UtilityView, grok.View):
167    """Deliver a examination schedule slip.
168
169    This form page is available only in Uniben and AAUE.
170    """
171    grok.context(ICustomStudent)
172    grok.name('examination_schedule_slip.pdf')
173    grok.require('waeup.viewStudent')
174    prefix = 'form'
175
176    label = u'Examination Schedule Slip'
177
178    omit_fields = (
179        'suspended', 'phone', 'email',
180        'adm_code', 'suspended_comment',
181        'date_of_birth', 'current_level',
182        'current_mode',
183        'entry_session',
184        'flash_notice')
185
186    form_fields = []
187
188    @property
189    def note(self):
190        return """
[14674]191 <br /><br />
192 <strong>Instructions on CBT Venue Allocation Slip (VAS)</strong>
193 <br /><br />
194 You should login with your student id from Kofa and surname as password.
[14677]195 Download and print two copies of this slip and bring them to the
196 allocated CBT examination center.
197 The copies <strong>MUST</strong> be shown to the invigilators
198 before being admitted into the examination hall.
[14674]199 <br /><br />
[14677]200 How to start examination:<br /><br />
201  * Username:  "student id" from Kofa e.g E1000000<br />
202  * Password: "surname" as shown on this slip in capital letters<br />
203  * Click the course and click "start exam".
204 <br /><br />
205 <strong>WARNING:</strong> Electronic devices (phones, tablets, laptops etc.)
[14674]206 are not allowed in the examination hall. Any electronics seized will not
207 be returned. Any student caught charging his/her mobile phone at the CBT
[14677]208 centers will be penalized and the exam of such a student will be cancelled.
[14674]209 Bags and any foreign materials are not allowed at the venue of
210 the CBT exams. Any omission/other complaints should be reported to the CBT
211 committee through the HoD before the date of examination.
212 <br /><br />
213 Your examination date, time and venue is scheduled as follows:
214 <br /><br />
215 <strong>%s</strong>
[14661]216""" % self.context.flash_notice
217        return
218
219
220    def update(self):
221        if not self.context.flash_notice \
222            or not 'exam' in self.context.flash_notice.lower():
223            self.flash(_('Forbidden'), type="warning")
224            self.redirect(self.url(self.context))
225
226    def render(self):
227        studentview = StudentBasePDFFormPage(self.context.student,
228            self.request, self.omit_fields)
229        students_utils = getUtility(IStudentsUtils)
230        return students_utils.renderPDF(
231            self, 'examination_schedule_slip',
232            self.context.student, studentview,
233            omit_fields=self.omit_fields,
234            note=self.note)
235
[14084]236class CustomStudentClearanceDisplayFormPage(NigeriaStudentClearanceDisplayFormPage):
237    """ Page to display student clearance data
238    """
239
240    @property
241    def form_fields(self):
242        if self.context.is_postgrad:
243            form_fields = grok.AutoFields(
244                ICustomPGStudentClearance).omit('clearance_locked')
245        else:
246            form_fields = grok.AutoFields(
247                ICustomUGStudentClearance).omit('clearance_locked')
248        if not getattr(self.context, 'officer_comment'):
249            form_fields = form_fields.omit('officer_comment')
250        else:
251            form_fields['officer_comment'].custom_widget = BytesDisplayWidget
[14104]252        form_fields = form_fields.omit('def_adm')
[14084]253        return form_fields
254
255class CustomStudentClearanceManageFormPage(NigeriaStudentClearanceManageFormPage):
256    """ Page to edit student clearance data
257    """
258
259    @property
260    def form_fields(self):
261        if self.context.is_postgrad:
262            form_fields = grok.AutoFields(
263                ICustomPGStudentClearance).omit('clr_code')
264        else:
265            form_fields = grok.AutoFields(
266                ICustomUGStudentClearance).omit('clr_code')
[14104]267        form_fields = form_fields.omit('def_adm')
[14084]268        return form_fields
269
[13362]270class CustomStudentClearanceEditFormPage(NigeriaStudentClearanceEditFormPage):
271    """ View to edit student clearance data by student
272    """
273
274    @property
275    def form_fields(self):
276        if self.context.is_postgrad:
277            form_fields = grok.AutoFields(ICustomPGStudentClearance).omit(
278            'clearance_locked', 'nysc_location', 'clr_code', 'officer_comment',
279            'physical_clearance_date')
280        else:
[14298]281            form_fields = grok.AutoFields(ICustomUGStudentClearanceEdit).omit(
[13362]282            'clearance_locked', 'clr_code', 'officer_comment',
[14104]283            'physical_clearance_date', 'date_of_birth', 'nationality', 'lga')
284        form_fields = form_fields.omit('def_adm')
[13362]285        return form_fields
286
[11846]287class CustomStartClearancePage(StartClearancePage):
[13360]288    with_ac = False
[11846]289
[13351]290    @property
291    def all_required_fields_filled(self):
292        if not self.context.email:
293            return _("Email address is missing."), 'edit_base'
294        if not self.context.phone:
295            return _("Phone number is missing."), 'edit_base'
296        if not self.context.father_name:
297            return _("Personal data form is not properly filled."), 'edit_personal'
298        return
299
[8911]300class CustomOnlinePaymentDisplayFormPage(NigeriaOnlinePaymentDisplayFormPage):
301    """ Page to view an online payment ticket
302    """
303    grok.context(ICustomStudentOnlinePayment)
[9853]304    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).omit(
[9990]305        'provider_amt', 'gateway_amt', 'thirdparty_amt', 'p_item')
[8911]306    form_fields[
307        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
308    form_fields[
309        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
310
311class CustomOnlinePaymentAddFormPage(NigeriaOnlinePaymentAddFormPage):
312    """ Page to add an online payment ticket
313    """
314    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).select(
315        'p_category')
316
[14527]317    ALUMNI_PAYMENT_CATS =  {
[14296]318        'transcript_local': 'Transcript Fee Local',
319        'transcript_inter': 'Transcript Fee International',
320        }
321
[14533]322    REDUCED_PAYMENT_CATS =  {
[14527]323        'clearance': 'Acceptance Fee',
324        'schoolfee': 'School Fee',
325        }
326
[14986]327    IJMBE_PAYMENT_CATS =  {
328        'clearance': 'Acceptance Fee',
329        'schoolfee': 'School Fee',
[14987]330        'schoolfee_1': 'School Fee (1st instalment)',
[14986]331        'schoolfee_2': 'School Fee (2nd instalment)',
332        }
333
[14296]334    @property
335    def selectable_categories(self):
336        if 'alumni' in self.application_url():
[14527]337            return self.ALUMNI_PAYMENT_CATS.items()
[14573]338        if self.context.student.current_mode in (
[15182]339            'special_pg_ft', 'special_pg_pt', 'found'):
[14533]340            return self.REDUCED_PAYMENT_CATS.items()
[14986]341        if self.context.student.current_mode == 'ijmbe':
342            return sorted(self.IJMBE_PAYMENT_CATS.items())
[14296]343        categories = getUtility(IKofaUtils).SELECTABLE_PAYMENT_CATEGORIES
344        return sorted(categories.items())
345
[13523]346class CustomPaymentsManageFormPage(PaymentsManageFormPage):
347    """ Page to manage the student payments.
348
349    This manage form page is for both students and students officers.
350    """
351    @property
352    def manage_payments_allowed(self):
353        return checkPermission('waeup.manageStudent', self.context)
354
[13059]355class CustomExportPDFPaymentSlip(NigeriaExportPDFPaymentSlip):
[8911]356    """Deliver a PDF slip of the context.
357    """
358    grok.context(ICustomStudentOnlinePayment)
[9853]359    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).omit(
[9990]360        'provider_amt', 'gateway_amt', 'thirdparty_amt', 'p_item')
[8911]361    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[9496]362    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
[9914]363
[11625]364    @property
365    def note(self):
[13408]366        p_session = self.context.p_session
[13405]367        try:
[13408]368            academic_session = grok.getSite()['configuration'][str(p_session)]
[13405]369        except KeyError:
370            academic_session = None
[13425]371        text =  '\n\n The Amount Authorized is inclusive of: '
[13512]372        if self.context.p_category in ('schoolfee_incl', 'schoolfee_1') \
373            and academic_session:
[14385]374            #welfare_fee = gateway_net_amt(academic_session.welfare_fee)
375            #union_fee = gateway_net_amt(academic_session.union_fee)
[14244]376            if self.context.student.entry_session == 2016 \
377                and self.context.student.entry_mode == 'ug_ft' \
378                and self.context.p_session == 2016:
379                # Add student id card fee to first school fee payment.
[14385]380
381                ## Attention: The payment slip does not contain any information
382                ## whether the fee was added or not.
383                ## We can only draw conclusions from from the student's entry
384                ## session whether the fee had been included.
385                #id_card_fee = gateway_net_amt(academic_session.id_card_fee)
386                #text += ('School Fee, '
387                #         '%s Naira Student ID Card Fee, '
388                #         '%s Naira Student Union Dues, '
389                #         '%s Naira Student Welfare Assurance Fee and '
390                #         % (id_card_fee, union_fee, welfare_fee))
391
[14244]392                text += ('School Fee, '
[14385]393                         'Student ID Card Fee, '
394                         'Student Union Dues, '
[15330]395                         'Sports Fee, '
396                         'Library Levy, '
[14385]397                         'Student Welfare Assurance Fee and ')
[14244]398            else:
[14385]399
400                #text += ('School Fee, '
401                #         '%s Naira Student Union Dues, '
402                #         '%s Naira Student Welfare Assurance Fee and '
403                #         % (union_fee, welfare_fee))
404
[14244]405                text += ('School Fee, '
[14385]406                         'Student Union Dues, '
[15330]407                         'Sports Development Fee, '
408                         'Library Development Levy, '
[14385]409                         'Student Welfare Assurance Fee and ')
[13410]410        elif self.context.p_category in (
411            'clearance_incl', 'clearance_medical_incl') and academic_session:
[14385]412
413            #matric_gown_fee = gateway_net_amt(academic_session.matric_gown_fee)
414            #lapel_fee = gateway_net_amt(academic_session.lapel_fee)
415            #text += ('Acceptance Fee, '
416            #         '%s Naira Matriculation Gown Fee, '
417            #         '%s Naira Lapel/File Fee and '
418            #         % (matric_gown_fee, lapel_fee))
419
[13437]420            text += ('Acceptance Fee, '
[14385]421                     'Matriculation Gown Fee, '
422                     'Lapel/File Fee and ')
[11625]423
[14385]424        #return text + '250.0 Naira Transaction Charge.'
425
426        return text + 'Transaction Charge.'
427
[14534]428class CustomStudyCourseManageFormPage(StudyCourseManageFormPage):
429    """ Page to edit the student study course data
430    """
431    grok.context(ICustomStudentStudyCourse)
432
433    @property
434    def form_fields(self):
435        if self.context.is_postgrad:
436            form_fields = grok.AutoFields(ICustomStudentStudyCourse).omit(
437                'previous_verdict')
438        else:
439            form_fields = grok.AutoFields(ICustomStudentStudyCourse)
440        form_fields['imported_cgpa'].for_display = True
441        return form_fields
442
[14981]443class CustomUnregisterCoursesView(UnregisterCoursesView):
444    """Unregister course list by student
445    """
446    grok.context(ICustomStudentStudyLevel)
447
448    def update(self):
449        if not self.context.__parent__.is_current:
450            emit_lock_message(self)
451            return
452        try:
453            deadline = grok.getSite()['configuration'][
454                str(self.context.level_session)].coursereg_deadline
455        except (TypeError, KeyError):
456            deadline = None
457        # In AAUE fresh students are allowed to "unregister their course"
458        # aside the deadline
459        if deadline and not self.context.student.is_fresh \
460            and deadline < datetime.now(pytz.utc):
461            self.flash(_(
462                "Course registration has ended. "
463                "Unregistration is disabled."), type="warning")
464        elif str(self.context.__parent__.current_level) != self.context.__name__:
465            self.flash(_('This is not your current level.'), type="danger")
466        elif self.context.student.state == REGISTERED:
467            IWorkflowInfo(self.context.student).fireTransition('reset7')
468            message = _('Course list has been unregistered.')
469            self.flash(message)
470        else:
471            self.flash(_('You are in the wrong state.'), type="warning")
472        self.redirect(self.url(self.context))
473        return
474
[9914]475class CustomStudyLevelDisplayFormPage(StudyLevelDisplayFormPage):
476    """ Page to display student study levels
477    """
478    grok.context(ICustomStudentStudyLevel)
[10480]479    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit(
[14206]480        'total_credits', 'gpa', 'level', 'imported_gpa', 'imported_cgpa')
[9914]481    form_fields[
482        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
483
[14000]484    @property
[15228]485    def translated_values(self):
486        return translated_values(self)
487
488    @property
[14000]489    def show_results(self):
490        isStudent = getattr(
491            self.request.principal, 'user_type', None) == 'student'
[14944]492        try:
493            show_results = grok.getSite()[
494                'configuration'][str(self.context.level_session)].show_results
495        except KeyError:
[14000]496            return False
[14944]497        if isStudent and self.context.student.current_mode not in show_results:
498            return False
499        if isStudent and self.context.student.state != RETURNING \
500            and self.context.student.current_level == self.context.level:
501            return False
[14000]502        return True
503
[13834]504class CustomStudyLevelManageFormPage(StudyLevelManageFormPage):
505    """ Page to edit the student study level data
506    """
507    grok.context(ICustomStudentStudyLevel)
508
[14534]509    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit(
510        'validation_date', 'validated_by', 'total_credits', 'gpa', 'level',
511        'total_credits_s1', 'total_credits_s2')
512
513    form_fields['imported_gpa'].for_display = True
514    form_fields['imported_cgpa'].for_display = True
515
[13834]516class CustomStudyLevelEditFormPage(StudyLevelEditFormPage):
517    """ Page to edit the student study level data by students
518    """
519    grok.context(ICustomStudentStudyLevel)
520
[15330]521class StudyLevelRepairFormPage(KofaEditFormPage):
522    """ Page to repair the student study level data by students
523    """
524    grok.context(IStudentStudyLevel)
525    grok.name('repair')
526    grok.require('waeup.editStudyLevel')
527    grok.template('studylevelrepairpage')
528    pnav = 4
529    placeholder = _('Enter valid course code')
530
531    def update(self, ADD=None, course=None):
532        try:
533            studylevel_repair_enabled = grok.getSite()['configuration'][
534                str(self.context.level_session)].studylevel_repair_enabled
535        except KeyError:
536            emit_lock_message(self)
537            return
538        if not studylevel_repair_enabled:
539            emit_lock_message(self)
540            return
541        super(StudyLevelRepairFormPage, self).update()
542        if ADD is not None:
543            if not course:
544                self.flash(_('No valid course code entered.'), type="warning")
545                return
546            cat = queryUtility(ICatalog, name='courses_catalog')
547            result = cat.searchResults(code=(course, course))
548            if len(result) != 1:
549                self.flash(_('Course not found.'), type="warning")
550                return
551            course = list(result)[0]
552            addCourseTicket(self, course)
553        return
554
555    @property
556    def label(self):
557        # Here we know that the cookie has been set
558        lang = self.request.cookies.get('kofa.language')
559        level_title = translate(self.context.level_title, 'waeup.kofa',
560            target_language=lang)
561        return _('Repair course list of ${a}',
562            mapping = {'a':level_title})
563
564    @property
565    def translated_values(self):
566        return translated_values(self)
567
568    def _delCourseTicket(self, **data):
569        form = self.request.form
570        if 'val_id' in form:
571            child_id = form['val_id']
572        else:
573            self.flash(_('No ticket selected.'), type="warning")
574            self.redirect(self.url(self.context, '@@edit'))
575            return
576        if not isinstance(child_id, list):
577            child_id = [child_id]
578        deleted = []
579        for id in child_id:
580            # Students are not allowed to remove core tickets
581            if id in self.context and \
582                self.context[id].removable_by_student:
583                del self.context[id]
584                deleted.append(id)
585        if len(deleted):
586            self.flash(_('Successfully removed: ${a}',
587                mapping = {'a':', '.join(deleted)}))
588            self.context.writeLogMessage(
589                self,'removed: %s at %s' %
590                (', '.join(deleted), self.context.level))
591        self.redirect(self.url(self.context, u'@@repair'))
592        return
593
594    @jsaction(_('Remove selected tickets'))
595    def delCourseTicket(self, **data):
596        self._delCourseTicket(**data)
597        return
598
[13059]599class CustomExportPDFCourseRegistrationSlip(
600    NigeriaExportPDFCourseRegistrationSlip):
[9914]601    """Deliver a PDF slip of the context.
602    """
603    grok.context(ICustomStudentStudyLevel)
604    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit(
[10102]605        'level_session', 'level_verdict',
[14206]606        'validated_by', 'validation_date', 'gpa', 'level',
607        'imported_gpa', 'imported_cgpa')
[9914]608
[10269]609    omit_fields = ('password', 'suspended', 'suspended_comment',
[10689]610        'phone', 'adm_code', 'sex', 'email', 'date_of_birth',
[13713]611        'department', 'current_mode', 'current_level', 'flash_notice')
[10269]612
[14000]613    @property
614    def show_results(self):
615        isStudent = getattr(
616            self.request.principal, 'user_type', None) == 'student'
[14944]617        try:
618            show_results = grok.getSite()[
619                'configuration'][str(self.context.level_session)].show_results
620        except KeyError:
[14302]621            return False
[14944]622        if isStudent and self.context.student.current_mode not in show_results:
623            return False
624        if isStudent and self.context.student.state != RETURNING \
625            and self.context.student.current_level == self.context.level:
626            return False
[14302]627        return True
[14000]628
[13038]629    def update(self):
630        if self.context.student.state != REGISTERED \
[13051]631            and self.context.student.current_level == self.context.level:
[13038]632            self.flash(_('Forbidden'), type="warning")
633            self.redirect(self.url(self.context))
[14000]634            return
[13038]635
[9914]636    @property
637    def label(self):
638        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
639        lang = self.request.cookies.get('kofa.language', portal_language)
640        level_title = translate(self.context.level_title, 'waeup.kofa',
641            target_language=lang)
642        line0 = ''
[13788]643        if self.context.student.is_postgrad:
644            line0 = 'SCHOOL OF POSTGRADUATE STUDIES\n'
645        elif self.context.student.current_mode.endswith('_pt'):
[9914]646            line0 = 'DIRECTORATE OF PART-TIME DEGREE PROGRAMMES\n'
[13866]647        line1 = translate(_('Course Registration Slip'),
648            target_language=portal_language) \
[9914]649            + ' %s' % level_title
[13866]650        line2 = translate(_('Session'),
651            target_language=portal_language) \
[9914]652            + ' %s' % self.context.getSessionString
653        return '%s%s\n%s' % (line0, line1, line2)
654
655    @property
656    def title(self):
657        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]658        return translate(_('Units Registered'), target_language=portal_language)
[9914]659
660    def _signatures(self):
[13647]661        if self.context.student.current_mode.endswith('_pt') \
662            or self.context.student.current_mode == 'found':
663            return (
664                [('I have selected the course on the advise of my Head of '
665                 'Department. <br>', _('Student\'s Signature'), '<br>')],
666                [('This student has satisfied the department\'s requirements. '
667                 'I recommend to approve the course registration. <br>',
668                 _('Head of Department\'s Signature'), '<br>')],
[13946]669                [('' , _('Deputy Registrar\'s Signature'), '<br>')],
[13647]670                [('', _('Director\'s Signature'))]
671                )
672        if self.context.student.current_mode in (
673            'de_ft', 'ug_ft', 'dp_ft', 'transfer'):
[13649]674            return ([_('Academic Adviser\'s Signature'),
675                _('Faculty Officer\'s Signature'),
676                _('Student\'s Signature')],)
677
[13647]678        if self.context.student.current_mode in ('special_pg_ft', 'special_pg_pt'):
679            return (
[13676]680                [('I declare that all items of information supplied above are correct:' ,
[13680]681                    _('Student\'s Signature'), '<br>')],
[13676]682                [('We approved the above registration:',
[13680]683                    _('Major Supervisor (Name / Signature)'), '')],
684                [('', _('Co-Supervisor (Name / Signature)'), '')],
[13676]685                [('', _('Head of Department'), '<br>')],
686                [('The student has satisfied the conditions for renewal of '
687                  'registration for graduate school programme in this university:',
[13680]688                  _('Secretary <br /> (School of Postgraduate Studies)'), '')],
689                [('', _('Dean <br /> (School of Postgraduate Studies)'), '')],
[13647]690                )
691        return None
[9914]692
[13647]693
[9914]694    def render(self):
695        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]696        Sem = translate(_('Sem.'), target_language=portal_language)
697        Code = translate(_('Code'), target_language=portal_language)
698        Title = translate(_('Title'), target_language=portal_language)
699        Cred = translate(_('Cred.'), target_language=portal_language)
[14650]700        CC = translate(_('Cat.'), target_language=portal_language)
[14000]701        if self.show_results:
[15317]702            TotalScore = translate(_('Total Score'), target_language=portal_language)
[14000]703            #CA = translate(_('CA'), target_language=portal_language)
704            Grade = translate(_('Grade'), target_language=portal_language)
[13866]705        Signature = translate(_('Lecturer\'s Signature'), 'waeup.aaue',
[9914]706            target_language=portal_language)
707        studentview = StudentBasePDFFormPage(self.context.student,
708            self.request, self.omit_fields)
709        students_utils = getUtility(IStudentsUtils)
[10442]710
711        tabledata = []
712        tableheader = []
713        contenttitle = []
714        for i in range(1,7):
715            tabledata.append(sorted(
716                [value for value in self.context.values() if value.semester == i],
717                key=lambda value: str(value.semester) + value.code))
[14000]718            if self.show_results:
719                tableheader.append([(Code,'code', 2.0),
720                                   (Title,'title', 7),
[14650]721                                   (Cred, 'credits', 1.4),
722                                   (CC, 'course_category', 1.2),
[15317]723                                   (TotalScore, 'total_score', 1.4),
[14000]724                                   #(CA, 'ca', 1.4),
725                                   (Grade, 'grade', 1.4),
726                                   (Signature, 'dummy', 3),
727                                   ])
728            else:
729                tableheader.append([(Code,'code', 2.0),
730                                   (Title,'title', 7),
731                                   (Cred, 'credits', 1.5),
[14650]732                                   (CC, 'course_category', 1.2),
[14000]733                                   (Signature, 'dummy', 3),
734                                   ])
[9914]735        if len(self.label.split('\n')) == 3:
736            topMargin = 1.9
737        elif len(self.label.split('\n')) == 2:
738            topMargin = 1.7
739        else:
740            topMargin = 1.5
741        return students_utils.renderPDF(
742            self, 'course_registration_slip.pdf',
743            self.context.student, studentview,
[10442]744            tableheader=tableheader,
745            tabledata=tabledata,
[9914]746            signatures=self._signatures(),
[10269]747            topMargin=topMargin,
748            omit_fields=self.omit_fields
[9914]749            )
[10566]750
[14165]751class CustomStudyCourseTranscriptPage(StudyCourseTranscriptPage):
752    """ Page to display the student's transcript.
753    """
754    grok.require('waeup.viewStudent')
755
[13059]756class CustomExportPDFTranscriptSlip(ExportPDFTranscriptSlip):
[10566]757    """Deliver a PDF slip of the context.
758    """
[14315]759#    grok.require('waeup.viewStudent')
[10566]760
[14267]761    note = _("""
762<br /><br /><br /><br />
763<font size='10'>
764<strong>Note:</strong> This copy is subject to correction for typographical errors and ratification by the departmental board.
765</font>
766""")
767
[10566]768    def _sigsInFooter(self):
769        return []
770
771    def _signatures(self):
772        return ([(
[14999]773            'O.O OHIKHENA (Manupa)<br />Principal Asst. Registrar<br /> '
[11555]774            'Exams, Records and Data Processing Division <br /> For: Registrar')],)
[10922]775
[13834]776    def render(self):
777        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]778        Term = translate(_('Sem.'), target_language=portal_language)
779        Code = translate(_('Code'), target_language=portal_language)
780        Title = translate(_('Title'), target_language=portal_language)
781        Cred = translate(_('Credits'), target_language=portal_language)
782        Score = translate(_('Score'), target_language=portal_language)
783        Grade = translate(_('Grade'), target_language=portal_language)
[13834]784        studentview = StudentBasePDFFormPage(self.context.student,
785            self.request, self.omit_fields)
786        students_utils = getUtility(IStudentsUtils)
787
788        tableheader = [(Code,'code', 2.5),
789                         (Title,'title', 7),
790                         (Term, 'semester', 1.5),
791                         (Cred, 'credits', 1.5),
[14136]792                         (Score, 'total_score', 1.5),
[13834]793                         (Grade, 'grade', 1.5),
794                         ]
795
[15165]796        pdfstream = students_utils.renderPDFTranscript(
[13834]797            self, 'transcript.pdf',
798            self.context.student, studentview,
799            omit_fields=self.omit_fields,
800            tableheader=tableheader,
801            signatures=self._signatures(),
802            sigs_in_footer=self._sigsInFooter(),
[15165]803            digital_sigs=self._digital_sigs(),
804            save_file=self._save_file(),
[13834]805            )
[15165]806        if not pdfstream:
807            self.redirect(self.url(self.context.student))
808            return
809        return pdfstream
[13834]810
[13059]811class CustomExportPDFAdmissionSlip(ExportPDFAdmissionSlip):
[10922]812    """Deliver a PDF Admission slip.
813    """
814
815    @property
816    def label(self):
817        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]818        return translate(_('e-Admission Slip \n'),
819            target_language=portal_language) \
[10922]820            + ' %s' % self.context.display_fullname
[11597]821
[13059]822class CustomExportPDFClearanceSlip(NigeriaExportPDFClearanceSlip):
[11606]823    """Deliver a PDF slip of the context.
824    """
825
826    @property
827    def label(self):
828        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[14114]829        return translate(_('Verification/Clearance Slip\n'),
[13866]830            target_language=portal_language) \
[11606]831            + ' %s' % self.context.display_fullname
832
[14084]833    @property
834    def form_fields(self):
835        if self.context.is_postgrad:
836            form_fields = grok.AutoFields(
837                ICustomPGStudentClearance).omit('clearance_locked')
838        else:
839            form_fields = grok.AutoFields(
840                ICustomUGStudentClearance).omit('clearance_locked')
841        if not getattr(self.context, 'officer_comment'):
842            form_fields = form_fields.omit('officer_comment')
[14104]843        form_fields = form_fields.omit('def_adm')
[14084]844        return form_fields
845
[11597]846class StudentGetMatricNumberPage(UtilityView, grok.View):
847    """ Construct and set the matriculation number.
848    """
849    grok.context(IStudent)
850    grok.name('get_matric_number')
851    grok.require('waeup.viewStudent')
852
853    def update(self):
854        students_utils = getUtility(IStudentsUtils)
855        msg, mnumber = students_utils.setMatricNumber(self.context)
856        if msg:
857            self.flash(msg, type="danger")
858        else:
859            self.flash(_('Matriculation number %s assigned.' % mnumber))
[11602]860            self.context.writeLogMessage(self, '%s assigned' % mnumber)
[11597]861        self.redirect(self.url(self.context))
862        return
863
864    def render(self):
[11607]865        return
866
[13059]867class ExportPDFMatricNumberSlip(UtilityView, grok.View):
[11607]868    """Deliver a PDF notification slip.
869    """
870    grok.context(ICustomStudent)
871    grok.name('matric_number_slip.pdf')
872    grok.require('waeup.viewStudent')
873    prefix = 'form'
874
875    form_fields = grok.AutoFields(ICustomStudent).select(
876        'student_id', 'matric_number')
[13713]877    omit_fields = ('date_of_birth', 'current_level', 'flash_notice')
[11607]878
879    @property
[13489]880    def title(self):
881        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]882        return translate(_('Matriculation Number'), 'waeup.kofa',
[13489]883            target_language=portal_language)
884
885    @property
[11607]886    def label(self):
887        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]888        return translate(_('Matriculation Number Slip\n'),
889            target_language=portal_language) \
[11607]890            + ' %s' % self.context.display_fullname
891
892    def render(self):
893        if self.context.state not in (PAID,) or not self.context.is_fresh \
894            or not self.context.matric_number:
895            self.flash('Not allowed.', type="danger")
896            self.redirect(self.url(self.context))
897            return
898        students_utils = getUtility(IStudentsUtils)
[11609]899        pre_text = _('Congratulations! Your acceptance fee and school fees ' +
900                     'payments have been received and your matriculation ' +
901                     'number generated with details as follows.')
[11607]902        return students_utils.renderPDFAdmissionLetter(self,
903            self.context.student, omit_fields=self.omit_fields,
[13353]904            pre_text=pre_text, post_text='')
905
[13489]906class ExportPersonalDataSlip(UtilityView, grok.View):
907    """Deliver a PDF notification slip.
908    """
909    grok.context(ICustomStudent)
910    grok.name('personal_data_slip.pdf')
911    grok.require('waeup.viewStudent')
912    prefix = 'form'
913    note = None
914
915    form_fields = grok.AutoFields(ICustomStudentPersonal).omit('personal_updated')
[13713]916    omit_fields = ('suspended', 'suspended_comment', 'adm_code',
917                   'certificate', 'flash_notice')
[13489]918
919    @property
920    def title(self):
921        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]922        return translate(_('Personal Data'), 'waeup.kofa',
[13489]923            target_language=portal_language)
924
925    @property
926    def label(self):
927        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
[13866]928        return translate(_('Personal Data Slip\n'),
929            target_language=portal_language) \
[13489]930            + ' %s' % self.context.display_fullname
931
932    def render(self):
933        studentview = StudentBasePDFFormPage(self.context.student,
934            self.request, self.omit_fields)
935        students_utils = getUtility(IStudentsUtils)
936        return students_utils.renderPDF(self, 'personal_data_slip.pdf',
937            self.context.student, studentview, note=self.note,
938            omit_fields=self.omit_fields)
939
[13462]940class CustomAccommodationManageFormPage(NigeriaAccommodationManageFormPage):
941    """ Page to manage bed tickets.
942    This manage form page is for both students and students officers.
943    """
944    with_hostel_selection = True
945
[13353]946class CustomBedTicketAddPage(BedTicketAddPage):
[13360]947    with_ac = False
[13380]948
949class CustomStudentFilesUploadPage(StudentFilesUploadPage):
950    """ View to upload files by student. Inherit from same class in
951    base package, not from kofacustom.nigeria which
952    requires that no application slip exists.
[13770]953    """
954
955class CustomCourseTicketDisplayFormPage(CourseTicketDisplayFormPage):
956    """ Page to display course tickets
957    """
958
[14453]959    @property
960    def show_results(self):
961        isStudent = getattr(
962            self.request.principal, 'user_type', None) == 'student'
963        if isStudent:
964            return False
965        return True
966
967    @property
968    def form_fields(self):
969        if self.show_results:
970            return grok.AutoFields(ICustomCourseTicket)
971        else:
972            return grok.AutoFields(ICustomCourseTicket).omit('score').omit('ca')
973
[13770]974class CustomCourseTicketManageFormPage(CourseTicketManageFormPage):
975    """ Page to manage course tickets
976    """
977    form_fields = grok.AutoFields(ICustomCourseTicket)
978    form_fields['title'].for_display = True
979    form_fields['fcode'].for_display = True
980    form_fields['dcode'].for_display = True
981    form_fields['semester'].for_display = True
982    form_fields['passmark'].for_display = True
983    form_fields['credits'].for_display = True
984    form_fields['mandatory'].for_display = False
985    form_fields['automatic'].for_display = True
986    form_fields['carry_over'].for_display = True
[15205]987    form_fields['ticket_session'].for_display = True
[15226]988    form_fields['imported_ts'].for_display = True
[13770]989
990class CustomEditScoresPage(EditScoresPage):
991    """Page that filters and lists students.
992    """
993    grok.template('editscorespage')
994
[14700]995    def _searchCatalog(self, session):
996        cat = queryUtility(ICatalog, name='coursetickets_catalog')
997        coursetickets = cat.searchResults(
998            session=(session, session),
999            code=(self.context.code, self.context.code)
1000            )
1001        try:
1002            score_editing_enabled = grok.getSite()[
1003                'configuration'][str(session)].score_editing_enabled
1004        except KeyError:
1005            return []
[14707]1006        coursetickets_list = [courseticket for courseticket in coursetickets
1007            if courseticket.student.current_mode in score_editing_enabled]
[14700]1008        return coursetickets_list
[13937]1009
1010    def _extract_uploadfile(self, uploadfile):
1011        """Get a mapping of student-ids to scores.
1012
1013        The mapping is constructed by reading contents from `uploadfile`.
1014
1015        We expect uploadfile to be a regular CSV file with columns
1016        ``student_id``, ``score`` and ``ca`` (other cols are ignored).
1017        """
1018        result = dict()
1019        data = StringIO(uploadfile.read())  # ensure we have something seekable
1020        reader = csv.DictReader(data)
1021        for row in reader:
1022            if not ('student_id' in row and 'score' in row and 'ca' in row):
1023                continue
1024            result[row['student_id']] = (row['score'], row['ca'])
1025        return result
1026
[14288]1027    def _update_scores(self, form):
[13937]1028        ob_class = self.__implemented__.__name__.replace('waeup.kofa.', '')
[14288]1029        error = ''
[13937]1030        if 'UPDATE_FILE' in form:
1031            if form['uploadfile']:
1032                try:
1033                    formvals = self._extract_uploadfile(form['uploadfile'])
1034                except:
1035                    self.flash(
1036                        _('Uploaded file contains illegal data. Ignored'),
1037                        type="danger")
[14288]1038                    return False
[13937]1039            else:
1040                self.flash(
1041                    _('No file provided.'), type="danger")
[14288]1042                return False
[13937]1043        else:
1044            formvals = dict(zip(form['sids'], zip(form['scores'], form['cas'])))
[14149]1045        for ticket in self.editable_tickets:
[13937]1046            ticket_error = False
1047            score = ticket.score
1048            ca = ticket.ca
1049            sid = ticket.student.student_id
1050            if formvals[sid][0] == '':
1051                score = None
1052            if formvals[sid][1] == '':
1053                ca = None
1054            try:
1055                if formvals[sid][0]:
1056                    score = int(formvals[sid][0])
1057                if formvals[sid][1]:
1058                    ca = int(formvals[sid][1])
1059            except ValueError:
1060                error += '%s, ' % ticket.student.display_fullname
1061                ticket_error = True
1062            if not ticket_error and ticket.score != score:
[14113]1063                try:
1064                    ticket.score = score
1065                except TooBig:
1066                    error += '%s, ' % ticket.student.display_fullname
1067                    ticket_error = True
1068                    pass
[13937]1069                ticket.student.__parent__.logger.info(
1070                    '%s - %s %s/%s score updated (%s)' %
1071                    (ob_class, ticket.student.student_id,
1072                     ticket.level, ticket.code, score))
1073            if not ticket_error and ticket.ca != ca:
[14113]1074                try:
1075                    ticket.ca = ca
1076                except TooBig:
1077                    error += '%s, ' % ticket.student.display_fullname
1078                    pass
[13937]1079                ticket.student.__parent__.logger.info(
1080                    '%s - %s %s/%s ca updated (%s)' %
1081                    (ob_class, ticket.student.student_id,
1082                     ticket.level, ticket.code, ca))
1083        if error:
1084            self.flash(_('Error: Score(s) and CA(s) of %s have not be updated. '
[14113]1085              % error.strip(', ')), type="danger")
[14288]1086        return True
1087
1088class EditPreviousSessionScoresPage(CustomEditScoresPage):
1089
1090    grok.name('edit_prev_scores')
1091
1092    def update(self,  *args, **kw):
1093        form = self.request.form
1094        self.current_academic_session = grok.getSite()[
1095            'configuration'].current_academic_session
1096        if self.context.__parent__.__parent__.score_editing_disabled:
1097            self.flash(_('Score editing disabled.'), type="warning")
1098            self.redirect(self.url(self.context))
[13939]1099            return
[14288]1100        if not self.current_academic_session:
1101            self.flash(_('Current academic session not set.'), type="warning")
1102            self.redirect(self.url(self.context))
1103            return
1104        previous_session = self.current_academic_session - 1
1105        self.session_title = academic_sessions_vocab.getTerm(
1106            previous_session).title
1107        self.tickets = self._searchCatalog(previous_session)
1108        if not self.tickets:
1109            self.flash(_('No student found.'), type="warning")
1110            self.redirect(self.url(self.context))
1111            return
1112        self.editable_tickets = [
1113            ticket for ticket in self.tickets if ticket.editable_by_lecturer]
1114        if not 'UPDATE_TABLE' in form and not 'UPDATE_FILE' in form:
1115            return
1116        if not self.editable_tickets:
1117            return
1118        success = self._update_scores(form)
1119        if success:
1120            self.flash(_('You successfully updated course results.'))
[13900]1121        return
1122
1123class CustomExportPDFScoresSlip(ExportPDFScoresSlip):
1124    """Deliver a PDF slip of course tickets for a lecturer.
1125    """
1126
[15247]1127    note = u'\nUpgraded scores are in asterisks.'
1128
[14315]1129    def data(self, session):
[14704]1130        #site = grok.getSite()
[13900]1131        cat = queryUtility(ICatalog, name='coursetickets_catalog')
1132        coursetickets = cat.searchResults(
1133            session=(session, session),
1134            code=(self.context.code, self.context.code)
1135            )
[14707]1136        # Apply filter
1137        try:
1138            score_editing_enabled = grok.getSite()[
1139                'configuration'][str(session)].score_editing_enabled
1140            coursetickets_filtered = [courseticket
1141                for courseticket in coursetickets
[15006]1142                if courseticket.student.current_mode in score_editing_enabled
[15236]1143                and courseticket.total_score is not None
1144                and courseticket.__parent__.__parent__.is_current]
[14707]1145        except KeyError:
1146            coursetickets_filtered = coursetickets
[14149]1147        # In AAUE only editable tickets can be printed
1148        editable_tickets = [
[14707]1149            ticket for ticket in coursetickets_filtered
1150            if ticket.editable_by_lecturer]
[13963]1151        header = [[_(''),
[15006]1152                   _('Student Id'),
[13963]1153                   _('Matric No.'),
[14703]1154                   #_('Reg. No.'),
1155                   #_('Fullname'),
1156                   #_('Status'),
1157                   #_('Course of\nStudies'),
[14704]1158                   _('Department'),
[13900]1159                   _('Level'),
[15201]1160                   _(' CA  '),
1161                   _('Exam\nScore'),
[13964]1162                   _('Total '),
[13963]1163                   _('Grade'),
1164                   ],]
[14288]1165        sorted_tickets = sorted(editable_tickets,
[15199]1166            key=lambda ticket: ticket.student.depcode
1167                               + ticket.student.faccode
[14704]1168                               + ticket.student.matric_number)
[14288]1169        no = 1
[13907]1170        tickets = []
[14315]1171        passed = 0
1172        failed = 0
[15229]1173        with_ca = False
[14149]1174        # In AAUE only editable tickets can be printed
[14288]1175        for ticket in sorted_tickets:
[15229]1176            if ticket.ca > 0:
1177                with_ca = True
[15006]1178            total = ticket.total_score
[15232]1179            if getattr(ticket, 'imported_ts', None):
[15245]1180                total = "**%s**" % ticket.imported_ts
[15006]1181            grade = ticket._getGradeWeightFromScore[0]
1182            if grade in ('F', '-'):
1183                failed += 1
[13963]1184            else:
[15006]1185                passed += 1
[13964]1186            fullname = textwrap.fill(ticket.student.display_fullname, 30)
[14704]1187            #deptitle = site['faculties'][ticket.student.faccode][
1188            #    ticket.student.depcode].longtitle
[15240]1189            row = [str(no),
[15006]1190                  ticket.student.student_id,
[13963]1191                  ticket.student.matric_number,
[14703]1192                  #ticket.student.reg_number,
1193                  #fullname,
1194                  #ticket.student.translated_state,
1195                  #ticket.student.certcode,
[14704]1196                  ticket.student.faccode + ' / ' + ticket.student.depcode,
[13900]1197                  ticket.level,
[15201]1198                  ticket.ca,
1199                  ticket.score,
[13963]1200                  total,
[13964]1201                  grade,
[13963]1202                  ]
[13907]1203            tickets.append(row)
[13963]1204            no += 1
[14317]1205        total = passed + failed
[14320]1206        passed_perc = 0
1207        failed_perc = 0
[14317]1208        if total:
[14320]1209            passed_perc = 100 * passed / total
1210            failed_perc = 100 * failed / total
[14710]1211        dep = self.context.__parent__.__parent__.longtitle
1212        fac = self.context.__parent__.__parent__.__parent__.longtitle
[15229]1213        # remove CA column if not necessary
1214        if not with_ca:
1215            header = [[_(''),
1216                       _('Student Id'),
1217                       _('Matric No.'),
1218                       #_('Reg. No.'),
1219                       #_('Fullname'),
1220                       #_('Status'),
1221                       #_('Course of\nStudies'),
1222                       _('Department'),
1223                       _('Level'),
1224                       #_(' CA  '),
1225                       _('Exam\nScore'),
1226                       _('Total '),
1227                       _('Grade'),
1228                       ],]
1229            for ticket in tickets:
1230                del(ticket[5])
[14320]1231        return header + tickets, [
[14710]1232            dep, fac, total, passed, passed_perc, failed, failed_perc]
[14288]1233
[14703]1234    def render(self):
1235        session = grok.getSite()['configuration'].current_academic_session
1236        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
1237                     if i['local_role'] == 'waeup.local.Lecturer']
1238        lecturers =  ', '.join(lecturers)
1239        students_utils = getUtility(IStudentsUtils)
1240        # only orientation is different
1241        return students_utils.renderPDFCourseticketsOverview(
[15247]1242            self, session, self.data(session), lecturers, '', 45, self.note)
[14703]1243
[14288]1244class DownloadPreviousSessionScoresView(DownloadScoresView):
1245    """View that exports scores.
1246    """
1247    grok.name('download_prev_scores')
1248
1249    def update(self):
1250        self.current_academic_session = grok.getSite()[
1251            'configuration'].current_academic_session
1252        if self.context.__parent__.__parent__.score_editing_disabled:
1253            self.flash(_('Score editing disabled.'), type="warning")
1254            self.redirect(self.url(self.context))
1255            return
1256        if not self.current_academic_session:
1257            self.flash(_('Current academic session not set.'), type="warning")
1258            self.redirect(self.url(self.context))
1259            return
1260        site = grok.getSite()
1261        exporter = getUtility(ICSVExporter, name='lecturer')
1262        self.csv = exporter.export_filtered(site, filepath=None,
1263                                 catalog='coursetickets',
1264                                 session=self.current_academic_session-1,
1265                                 level=None,
1266                                 code=self.context.code)
[14306]1267        return
1268
1269class AlumniRequestPasswordPage(StudentRequestPasswordPage):
1270    """Captcha'd request password page for students.
1271    """
1272    grok.name('alumni_requestpw')
1273    grok.require('waeup.Anonymous')
1274    grok.template('alumni_requestpw')
1275    form_fields = grok.AutoFields(IStudentRequestPW).select(
1276        'lastname','number','email')
1277    label = _('Search student record and send password for first-time login')
1278
1279    def _redirect_no_student(self):
1280        self.flash(_('No student record found.'), type="warning")
1281        self.redirect(self.application_url() + '/applicants/trans2017/register')
[14288]1282        return
Note: See TracBrowser for help on using the repository browser.