## Script (Python) "getPaymentsFolderInfo"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
# $Id: getPaymentsFolderInfo.py 2480 2007-10-30 15:23:25Z joachim $
"""
Info for the PaymentsFolder
"""
from Products.AdvancedQuery import Eq, Between, Le,In

mtool = context.portal_membership
wftool = context.portal_workflow
member = mtool.getAuthenticatedMember()
payments_catalog = context.payments_catalog
aq_payments = payments_catalog.evalAdvancedQuery
if mtool.isAnonymousUser():
    return None
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass

import DateTime
request = context.REQUEST
#students = context.portal_url.getPortalObject().campus.students
student_id = context.getStudentId()
if student_id is None:
    return context.REQUEST.RESPONSE.redirect("%s/srp_anonymous_view" % context.portal_url())
#student = getattr(students,student_id)
student_record = context.students_catalog.getRecordByKey(student_id)


info = {}
is_so = info['is_so'] = context.isSectionOfficer()
is_student = info['is_student'] = context.isStudent()
info['student_name'] = student_record.name
info['query_url'] = "https://webpay.interswitchng.com/paydirect/services/TransactionQueryURL.aspx"
review_state = info['review_state'] = student_record.review_state
parttime = student_record.mode and student_record.mode.endswith('_pt')
fulltime = student_record.mode and student_record.mode.endswith('_ft')


session = student_record.session
next_info = context.getNextInfo(student_record)
info['next_session'] = next_info['next_session_id']
info['next_session_str'] = next_info['next_session_str']
info['payment_method'] = ""
info['reasons'] = next_info['reasons']

# begin customization

if review_state in ('returning',) and info['next_session'] != session:
    if session in ('06','07','08'):
        info['payment_method'] = "online_payment"
    else:
        info['payment_method'] = "first_instalment"
elif review_state in ('cleared_and_validated',):
    if session in ('06','07','08','09'):
        info['payment_method'] = "online_payment"
    else:
        info['payment_method'] = "first_instalment"
elif session in ('09','10','11',) and review_state in ('school_fee_paid','courses_registered','courses_validated',):
    second_instalment_records = aq_payments(Eq('student_id',student_id) & Eq('category','schoolfee2') & Eq('session_id',session) & Eq('status','paid'))
    if not second_instalment_records:
        info['payment_method'] = "second_instalment"
    else:    
        pass
info['prod_id'] = '119'

# end customization

info['student_name'] = student_record.name
payments_path = "%s/campus/students/%s/payments" % (context.portal_url(),student_id)
payments = []
payment_records = aq_payments(Eq('student_id',student_id)) # & Eq('session_id',student_record.session))
vocabularies = context.portal_vocabularies
paid_fees = []
for payment in payment_records:
    if payment.status == "paid":
        paid_fees += "%s_%s" % (payment.category,payment.session_id),
#info['pf'] = paid_fees
for payment in payment_records:
    row = {}
    row['id'] = payment.key
    if payment.status == 'invalid':
        row['title'] = "Invalid Payment, Naira %s, %s" % (payment.amount,
                                                          payment.date.strftime("%d/%m/%y %H:%M:%S"))
    elif payment.type == 'request' and payment.resp_approved_amount:
        row['title'] = "%s for Session %s, Naira %s, %s" % (vocabularies.payment_categories.get(payment.category),
                                                            vocabularies.sessions.get(payment.session_id),
                                                            payment.resp_approved_amount,
                                                            payment.date.strftime("%d/%m/%y %H:%M:%S"))
    elif payment.type == 'request':
        row['title'] = "%s for Session %s, %s" % (vocabularies.payment_categories.get(payment.category),
                                                            vocabularies.sessions.get(payment.session_id),
                                                            payment.date.strftime("%d/%m/%y %H:%M:%S"))                                                            
    else:
        row['title'] = "%s for Session %s, Naira %s, %s" % (vocabularies.payment_categories.get(payment.category),
                                                            vocabularies.sessions.get(payment.session_id),
                                                            payment.amount,
                                                            payment.date.strftime("%d/%m/%y %H:%M:%S"))
    oid = payment.order_id
    onr = oid.rfind('-')+1
    if onr > 0:
        start_pos = onr
    else:
        start_pos = 6
    url = row['url'] = "%s/p%s" % (payments_path,oid[start_pos:])
    row['is_requeryable'] = "%s_%s" % (payment.category,payment.session_id) not in paid_fees and (not payment.resp_desc or str(member) in ('admin','isouaba')) and payment.type == 'online'   # customized too
    row['is_requestable'] = "%s_%s" % (payment.category,payment.session_id) not in paid_fees and (not payment.resp_desc or str(member) in ('admin','isouaba')) and payment.type == 'request'  # customized too
    row['is_approvable'] = is_so and (row['is_requeryable'] or row['is_requestable']) and payment.category == 'schoolfee' # does not make sense for maintenance
    row['resp_desc'] = payment.resp_desc or 'Payment Process Interrupted'
    row['trans_ref'] = payment.order_id
    if row['is_requeryable']:
        if payment.category == 'schoolfee':
            row['callback_url'] = "%(url)s/interswitch_cb" % row
        elif payment.category == 'schoolfee2':
            row['callback_url'] = "%(url)s/interswitch_cb2" % row             
#        if payment.category == 'schoolfee':
#            row['callback_url'] = "%(url)s/interswitch_cb" % row
#        elif payment.category == 'hostel_maintenance':
#            row['callback_url'] = "%(url)s/interswitch_acco_cb" % row
#        else:
        href = '%(query_url)s' % info
        href += '?transRef=%(trans_ref)s' % row
        href += '&prodID=%(prod_id)s' % info
        href += '&redirectURL=%(callback_url)s' % row
        row['href'] = href
    elif row['is_requestable']:
        if payment.category == 'schoolfee':
            row['callback_url'] = "%(url)s/interswitch_request_cb" % row
        elif payment.category == 'schoolfee2':
            row['callback_url'] = "%(url)s/interswitch_request_cb2" % row      
        #href = '%(query_url)s' % info
        #href = "http://testwebpay.interswitchng.com/CollegepayService/TransactionQueryURL.aspx"
        href = "http://webpay.interswitchng.com/CollegepayService/TransactionQueryURL.aspx "
        href += '?redirectURL=%(callback_url)s' % row
        #href += '&productid=%(prod_id)s' % info
        href += '&productid=53'
        href += '&merchantref=ignore'
        href += '&custNumber=%s' % student_id
        href += '&session=%s' % info['next_session_str']
        href += '&semester=Semester 1'
        if payment.category == 'schoolfee2':    
            href += '&semester=Semester 2'         
        row['href'] = href        
    if payment.status == 'paid':
        row['confirmed'] = 'active'
    else:
        row['confirmed'] = 'unsuccessful'
    row['is_editable'] = is_so and (row['confirmed'] == 'active')
    payments.append(row)

payments.sort(cmp=lambda x,y: cmp(x['trans_ref'],y['trans_ref']))
info['payments'] = payments
return info

