## $Id: browser.py 17924 2024-09-12 10:14:59Z henrik $
##
## Copyright (C) 2012 Uli Fouquet & Henrik Bettermann
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##
import grok
from zope.i18n import translate
from zope.schema.interfaces import ConstraintNotSatisfied
from zope.component import getUtility
from zope.security import checkPermission
from hurry.workflow.interfaces import IWorkflowInfo
from waeup.kofa.interfaces import REQUESTED, IExtFileStore, IKofaUtils
from waeup.kofa.widgets.datewidget import FriendlyDatetimeDisplayWidget
from waeup.kofa.browser.layout import KofaEditFormPage
from waeup.kofa.browser.layout import action, jsaction
from waeup.kofa.students.workflow import (CREATED, ADMITTED, PAID,
    CLEARANCE, REQUESTED, RETURNING, CLEARED, REGISTERED, VALIDATED,
    GRADUATED, TRANSREQ, TRANSVAL, TRANSREL, FORBIDDEN_POSTGRAD_TRANS)
from waeup.kofa.students.browser import (
    StudyLevelEditFormPage, StudyLevelDisplayFormPage, StudyLevelManageFormPage,
    StudentBasePDFFormPage, ExportPDFCourseRegistrationSlip,
    CourseTicketDisplayFormPage, CourseTicketManageFormPage,
    StudentTriggerTransitionFormPage,
    ExportPDFAdmissionSlip,
    ExportAttendanceSlip,
    PaymentsManageFormPage, msave, emit_lock_message)
from waeup.kofa.students.interfaces import IStudentsUtils, ICourseTicket, IStudentBase
from waeup.kofa.students.workflow import FORBIDDEN_POSTGRAD_TRANS
from kofacustom.nigeria.students.browser import (
    NigeriaOnlinePaymentDisplayFormPage,
    NigeriaStudentBaseDisplayFormPage,
    NigeriaStudentBaseManageFormPage,
    NigeriaStudentClearanceEditFormPage,
    NigeriaOnlinePaymentAddFormPage,
    NigeriaExportPDFPaymentSlip,
    NigeriaExportPDFClearanceSlip,
    NigeriaBedTicketAddPage,
    NigeriaAccommodationDisplayFormPage,
    NigeriaAccommodationManageFormPage,
    )
from kofacustom.unidel.students.interfaces import (
    ICustomStudent,
    ICustomStudentBase,
    ICustomStudentOnlinePayment,
    ICustomStudentStudyCourse,
    ICustomStudentStudyLevel,
    ICustomUGStudentClearance,
    ICustomPGStudentClearance,
    ICustomCourseTicket)
from kofacustom.unidel.interfaces import MessageFactory as _

class CustomStudentBaseDisplayFormPage(NigeriaStudentBaseDisplayFormPage):
    """ Page to display student base data
    """
    form_fields = grok.AutoFields(ICustomStudentBase).omit(
        'password', 'suspended', 'suspended_comment',
        'flash_notice', 'provisionally_cleared')
    form_fields[
        'financial_clearance_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields[
        'final_clearance_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

class CustomStudentBaseManageFormPage(NigeriaStudentBaseManageFormPage):
    """ View to manage student base data
    """
    form_fields = grok.AutoFields(ICustomStudentBase).omit(
        'student_id', 'adm_code', 'suspended',
        'financially_cleared_by', 'financial_clearance_date',
        'finally_cleared_by', 'final_clearance_date')

class CustomBedTicketAddPage(NigeriaBedTicketAddPage):
    with_ac = False

class CustomAccommodationDisplayFormPage(NigeriaAccommodationDisplayFormPage):
    """ Page to view bed tickets.
    """
    with_hostel_selection = True

class CustomAccommodationManageFormPage(NigeriaAccommodationManageFormPage):
    """ Page to manage bed tickets.
    This manage form page is for both students and students officers.
    """
    with_hostel_selection = True

class CustomPaymentsManageFormPage(PaymentsManageFormPage):
    """ Page to manage the student payments. This manage form page is for
    both students and students officers. UNIDEL does not allow students
    to remove any payment ticket.
    """
    @property
    def manage_payments_allowed(self):
        return checkPermission('waeup.manageStudent', self.context)

class CustomStudentClearanceEditFormPage(NigeriaStudentClearanceEditFormPage):
    """ View to edit student clearance data by student
    """
    @property
    def form_fields(self):
        if self.context.is_postgrad:
            form_fields = grok.AutoFields(ICustomPGStudentClearance).omit(
            'clearance_locked', 'nysc_location', 'clr_code', 'officer_comment',
            'physical_clearance_date')
        else:
            form_fields = grok.AutoFields(ICustomUGStudentClearance).omit(
            'clearance_locked', 'clr_code', 'officer_comment',
            'physical_clearance_date')
            form_fields['date_of_birth'].for_display = True
            form_fields['nationality'].for_display = True
            form_fields['lga'].for_display = True
        return form_fields

class CustomOnlinePaymentDisplayFormPage(NigeriaOnlinePaymentDisplayFormPage):
    """ Page to view an online payment ticket
    """
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).omit(
        'provider_amt', 'gateway_amt', 'thirdparty_amt', 'p_item','p_combi',
        'net_amt')
    form_fields[
        'creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields[
        'payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

class CustomExportPDFPaymentSlip(NigeriaExportPDFPaymentSlip):
    """Deliver a PDF slip of the context.
    """
    form_fields = grok.AutoFields(ICustomStudentOnlinePayment).omit(
        'provider_amt', 'gateway_amt', 'thirdparty_amt', 'p_item',
        'p_split_data','p_combi', 'net_amt')
    form_fields['creation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    form_fields['payment_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

class CustomStudyLevelDisplayFormPage(StudyLevelDisplayFormPage):
    """ Page to display student study levels
    """
    #grok.template('studylevelpage')
    grok.context(ICustomStudentStudyLevel)

    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit(
        'level',)
    form_fields[
        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')

class CustomStudyLevelManageFormPage(StudyLevelManageFormPage):
    """ Page to edit the student study level data
    """
    grok.context(ICustomStudentStudyLevel)

    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit(
        'validation_date', 'validated_by', 'total_credits', 'gpa', 'level',
        'total_credits_s1', 'total_credits_s2')

class CustomExportPDFCourseRegistrationSlip(ExportPDFCourseRegistrationSlip):
    """Deliver a PDF slip of the context.
    """
    grok.context(ICustomStudentStudyLevel)
    form_fields = grok.AutoFields(ICustomStudentStudyLevel).omit(
        'level', 'gpa', 'transcript_remark')
    form_fields[
        'validation_date'].custom_widget = FriendlyDatetimeDisplayWidget('le')
    #prefix = 'form'
    omit_fields = (
        'password', 'suspended', 'phone', 'date_of_birth',
        'adm_code', 'sex', 'suspended_comment', 'current_level',
        'flash_notice')

    def _signatures(self):
        return (
            [_('Student\'s Signature')],
            [_('Academic Adviser\'s Signature')],
            [_('Head of Department\'s Signature')],
            [_('Dean of Faculty\'s Signature')],
            )

                
    def render(self):
        if not self.context.student.current_mode:
            self.flash('No certificate assigned.', type="danger")
            self.redirect(self.url(self.context))
            return
        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
        Sem = translate(_('Term'), target_language=portal_language)
        Code = translate(_('Code'), target_language=portal_language)
        Title = translate(_('Title'), target_language=portal_language)
        Cred = translate(_('Cred.'), target_language=portal_language)
        CC = translate(_('Cat.'), target_language=portal_language)
        TotalScore = translate(_('Total Score'), target_language=portal_language)
        #CA = translate(_('CA'), target_language=portal_language)
        Grade = translate(_('Grade'), target_language=portal_language)
        Signature = translate(_('Lecturer\'s Signature'), 'waeup.aaue',
            target_language=portal_language)
        studentview = StudentBasePDFFormPage(self.context.student,
            self.request, self.omit_fields)
        students_utils = getUtility(IStudentsUtils)
        tabledata = []
        tableheader = []
        contenttitle = []
        for i in range(1,7):
            tabledata.append(sorted(
                [value for value in self.context.values()
                 if value.semester == i and not value.outstanding],
                 key=lambda value: str(value.semester) + value.code))
            tableheader.append([(Code,'code', 2.0),
                               (Title,'title', 7),
                               (Cred, 'credits', 1.4),
                               #(CC, 'course_category', 1.2),
                               (TotalScore, 'total_score', 1.4),
                               #(CA, 'ca', 1.4),
                               (Grade, 'grade', 1.4),
                               (Signature, 'dummy', 3),
                               ])
        return students_utils.renderPDF(
            self, 'course_registration_slip.pdf',
            self.context.student, studentview,
            tableheader=tableheader,
            tabledata=tabledata,
            omit_fields=self.omit_fields,
            signatures=self._signatures(),
            sigs_in_footer=self._sigsInFooter(),
            )

class CustomCourseTicketDisplayFormPage(CourseTicketDisplayFormPage):
    """ Page to display course tickets
    """

    @property
    def form_fields(self):
        return grok.AutoFields(ICustomCourseTicket).omit('course_category',
            'ticket_session')

class CustomCourseTicketManageFormPage(CourseTicketManageFormPage):
    """ Page to manage course tickets
    """
    
    form_fields = grok.AutoFields(ICustomCourseTicket).omit('course_category')
    form_fields['title'].for_display = True
    form_fields['fcode'].for_display = True
    form_fields['dcode'].for_display = True
    form_fields['semester'].for_display = True
    form_fields['passmark'].for_display = True
    form_fields['credits'].for_display = True
    form_fields['mandatory'].for_display = False
    form_fields['automatic'].for_display = True
    form_fields['carry_over'].for_display = True
    form_fields['ticket_session'].for_display = True


class ExaminationClearanceSlip(NigeriaExportPDFClearanceSlip):
    """Deliver a PDF slip of the context.
    """

    grok.name('examclearance_slip.pdf')
    grok.require('waeup.handleStudent')
    omit_fields = (
        'suspended',
        #'phone',
        'email',
        'adm_code', 'suspended_comment',
        'date_of_birth',
        #'current_level',
        #'current_mode',
        #'entry_session',
        'flash_notice',
        'parents_email',
        'certificate',
        #'faculty',
        #'department',
        'reg_number')
    form_fields = None

    @property
    def note(self):
        return '''


    
You have been cleared to write second semester examination for %s/%s session.
''' % (self.context.current_session, self.context.current_session + 1)

    def update(self):
            # disabled 05/07/24
            return
        #if not  self.context.state in (VALIDATED, REGISTERED, PAID):
        #    self.flash(_('Your course list has not yet been registered.'),
        #        type="warning")
        #    self.redirect(self.url(self.context))
        #    return

    @property
    def label(self):
        portal_language = getUtility(IKofaUtils).PORTAL_LANGUAGE
        return translate(_('Examination Clearance Slip of'),
            'waeup.kofa', target_language=portal_language) \
            + ' %s' % self.context.display_fullname

    def _sigsInFooter(self):
        #isStudent = getattr(
        #    self.request.principal, 'user_type', None) == 'student'
        #if not isStudent and self.context.state in (CLEARED, RETURNING):

        return (_('Date, DICT Signature'),
                _('Date, Dean\'s Signature'),
                    )
    def render(self):
        studentview = StudentBasePDFFormPage(self.context.student,
            self.request, self.omit_fields)
        students_utils = getUtility(IStudentsUtils)
        return students_utils.renderPDF(
            self, 'examclearance_slip.pdf',
            self.context.student, studentview, signatures=None,
            sigs_in_footer=self._sigsInFooter(), show_scans=False,
            omit_fields=self.omit_fields,
            note=self.note)


class CustomExportAttendanceSlip(ExportAttendanceSlip):
    """
    """

    #def _signatures(self):
    #    return ([_('Student Signature')],
    #            [_('Clearance Officer Signature')])

    @property
    def note(self):
        return """

        
Faculty: __________________________________________________________

Department: ______________________________________________________

Date of Examination: _______________________________________________

Time of Examination: _______________________________________________

Venue of Examination: ______________________________________________

Names of Supervisors:

______________________________________________

______________________________________________

______________________________________________

______________________________________________

______________________________________________
        """

    def render(self):
        lecturers = [i['user_title'] for i in self.getUsersWithLocalRoles()
                     if i['local_role'] == 'waeup.local.Lecturer']
        lecturers =  ', '.join(lecturers)
        students_utils = getUtility(IStudentsUtils)
        return students_utils.renderPDFCourseticketsOverview(
            self, 'attendance', self.current_academic_session,
            self.data(self.current_academic_session),
            lecturers, '', 65, self.note)