## $Id: helpers.py 16167 2020-07-15 09:00:00Z henrik $
##
## Copyright (C) 2017 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
##
"""General helper functions for the etranzact module in custom packages.
"""
import grok
import re
from datetime import datetime
from urllib import urlencode
from urllib2 import urlopen
from urlparse import parse_qs
import httplib
import hashlib
import json
from zope.event import notify
from waeup.kofa.utils.helpers import extract_formvars
from kofacustom.nigeria.interfaces import MessageFactory as _

ERROR_PART1 = (
        'PayeeName=N/A~'
        + 'Faculty=N/A~'
        + 'Department=N/A~'
        + 'Level=N/A~'
        + 'ProgrammeType=N/A~'
        + 'StudyType=N/A~'
        + 'Session=N/A~'
        + 'PayeeID=N/A~'
        + 'Amount=N/A~'
        + 'FeeStatus=')
ERROR_PART2 = (
        '~Semester=N/A~'
        + 'PaymentType=N/A~'
        + 'MatricNumber=N/A~'
        + 'Email=N/A~'
        + 'PhoneNumber=N/A')

def write_payments_log(id, payment):
    payment.logger.info(
        '%s,%s,%s,%s,%s,%s,%s,%s,,,' % (
        id, payment.p_id, payment.p_category,
        payment.amount_auth, payment.r_code,
        payment.provider_amt, payment.gateway_amt,
        payment.thirdparty_amt))

def query_history(host, terminal_id, transaction_id, https):
    headers={"Content-type": "application/x-www-form-urlencoded",
             "Accept": "text/plain"}
    url = "/webconnect/v3/query.jsp"
    if https:
        h = httplib.HTTPSConnection(host)
    else:
        h = httplib.HTTPConnection(host)
    args = {'TERMINAL_ID': terminal_id,
            'TRANSACTION_ID': transaction_id,
            }
    #args['RESPONSE_URL'] = responseurl
    h.request('POST', url, urlencode(args), headers)
    response = h.getresponse()
    if response.status!=200:
        return 'Connection error (%s, %s)' % (response.status, response.reason), None
    raw = response.read()
    return raw, extract_formvars(raw)

 # A sample caller response sent to the RESPONSE_URL

 # http://salsa:8080/app/applicants/cbt2015/449072/p5679522929425/receive_etranzact?
 # AMOUNT=3333.0&
 # DESCRIPTION=&
 # CHECKSUM=8aab3904652f8ba69ebed42d3bae80a2&
 # EMAIL=aa%40aa.de&
 # SUCCESS=C&
 # MESSAGE=Cancel&
 # LOGO_URL=https%3A%2F%2Fiuokada.waeup.org%2Fstatic_custom%2Fiou_logo.png&
 # RESPONSE_URL=http%3A%2F%2Fsalsa%3A8080%2Fapp%2Fapplicants%2Fcbt2015%2F449072%2Fp5679522929425%2Freceive_etranzact&
 # CURRENCY_CODE=NGN&
 # TERMINAL_ID=0000000001&
 # TRANSACTION_ID=p5679522929425&
 # MERCHANT_CODE=0339990001&
 # RESPONSE_CODE=C&
 # FINAL_CHECKSUM=E524590DBFAB719EEE428C778FFF1650&
 # STATUS_REASON=Cancel&
 # TRANS_NUM=01ESA20190913062149AHGUHQ&
 # CARD_NO=null&
 # CARD_TYPE=null

 # A sample query response

 # <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 #     "http://www.w3.org/TR/html4/loose.dtd">
 # <script language='javascript'>
 # var spanId = document.getElementById("message_container");
 # spanId.textContent = 'Redirecting...';</script>
 # <form method="GET" id="redirect_form" name="redirect_form"
 # action="http://localhost:81/projects/Webconnect/response.php" target="_top">
 # <input type="hidden" name = "LOGO_URL"
 # value="http://localhost:81/projects/Webconnect/images/elogo.fw.png">
 # <input type="hidden" name = "RESPONSE_URL"
 # value="http://localhost:81/projects/Webconnect/response.php">
 # <input type="hidden" name = "CURRENCY_CODE" value="NGN">
 # <input type="hidden" name = "TERMINAL_ID" value="0000000001">
 # <input type="hidden" name = "TRANSACTION_ID" value="etz1568638104web">
 # <input type="hidden" name = "AMOUNT" value="100">
 # <input type="hidden" name = "DESCRIPTION" value="Payment Description">
 # <input type="hidden" name = "CHECKSUM"
 # value="5be04064f4bb250f73650059a8e921cc">
 # <input type="hidden" name = "MERCHANT_CODE" value="0339990001">
 # <input type="hidden" name = "EMAIL" value="xyz@yahoo.com">
 # <input type="hidden" name = "SUCCESS" value="0">
 # <input type="hidden" name = "FINAL_CHECKSUM"
 # value="FD67A4CCC39E2C8DEEEC78D6C64A61FE">
 # <input type="hidden" name = "STATUS_REASON" value="Approved">
 # <input type="hidden" name = "TRANS_NUM" value="01ESA20190916134824YA3YJ8">
 # <input type="hidden" name = "CARD_NO" value="506066XXXXXXXXX6666">
 # <input type="hidden" name = "CARD_TYPE" value="Verve">
 # </form>
 # <script language='javascript'>
 # var fom = document.forms["redirect_form"];
 # fom.submit();</script>

 # A sample query response sent to the RESPONSE_URL after the browser has
 # automatically executed the Javascript above (we don't use this response)

 # http://salsa:8080/app/applicants/cbt2015/449072/p5686487280654/receive_etranzact?
 # LOGO_URL=https%3A%2F%2Fiuokada.waeup.org%2Fstatic_custom%2Fiou_logo.png&
 # RESPONSE_URL=http%3A%2F%2Fsalsa%3A8080%2Fapp%2Fapplicants%2Fcbt2015%2F449072%2Fp5686487280654%2Freceive_etranzact&
 # CURRENCY_CODE=NGN&
 # TERMINAL_ID=0000000001&
 # TRANSACTION_ID=p5686487280654&
 # AMOUNT=3333.0&
 # DESCRIPTION=&
 # CHECKSUM=3886118fcd91a376cc95c48c94dc499a&
 # MERCHANT_CODE=0339990001&
 # EMAIL=aa%40aa.de&
 # SUCCESS=0&
 # FINAL_CHECKSUM=EE105B703F84B1D67D0A4234622C03E8&
 # STATUS_REASON=Approved&
 # TRANS_NUM=01ESA20190916164636L2UTU7&
 # CARD_NO=506066XXXXXXXXX6666&
 # CARD_TYPE=Verve

def process_response(payment, form, view, verify):
    if not form or not form.get('SUCCESS', None):
        msg = _('No (valid) response from Etranzact.')
        log = 'invalid response for payment %s' % payment.p_id
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    success = form.get('SUCCESS', None)
    # Compute final checksum
    transaction_id = payment.p_id
    amount = "%.1f" % payment.amount_auth
    responseurl = view.url(payment, 'receive_etranzact')
    hashargs = 	success + amount + view.terminal_id + transaction_id \
        + responseurl + view.secret_key
    final_checksum = hashlib.md5(hashargs).hexdigest().upper()
    if form.get('FINAL_CHECKSUM', None) != final_checksum:
        msg = _('Wrong checksum.')
        log = 'wrong checksum for %s payment %s: %s' % (
            payment.p_category, payment.p_id, str(form))
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    payment.r_code = form.get('SUCCESS', None)
    payment.r_desc = form.get('STATUS_REASON', None) # MESSAGE also available
    payment.r_amount_approved = float(form.get('AMOUNT', None))
    payment.r_pay_reference = form.get('TRANS_NUM', None)
    payment.r_card_num = "%s %s" % (form.get('CARD_TYPE', None),
                                    form.get('CARD_NO', None))
    if payment.r_code != '0':
        msg = _('Unsuccessful response: ${a}', mapping = {'a': payment.r_desc})
        log = 'unsuccessful response for %s payment %s: %s' % (
            payment.p_category, payment.p_id, payment.r_desc)
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    if round(payment.r_amount_approved/10.0, 0) != round(
        payment.amount_auth/10.0, 0):
        msg = _('Response amount does not match.')
        log = 'wrong response for %s payment %s: %s' % (
            payment.p_category, payment.p_id, str(form))
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    transaction_id = form.get('TRANSACTION_ID', None)
    if transaction_id != payment.p_id:
        msg = _('Response transaction id does not match.')
        log = 'wrong response for %s payment %s: %s' % (
            payment.p_category, payment.p_id, str(form))
        payment.p_state = 'failed'
        notify(grok.ObjectModifiedEvent(payment))
        return False, msg, log
    payment.p_state = 'paid'
    if not verify:
        payment.payment_date = datetime.utcnow()
    msg = _('Successful response received')
    log = 'valid response for %s payment %s: %s' % (
        payment.p_category, payment.p_id, str(form))
    notify(grok.ObjectModifiedEvent(payment))
    return True, msg, log

# Requerying Etranzact Payoutlet payments

# Expected response:
# RECEIPT_NO=500191030486&PAYMENT_CODE=500854291572447457669&MERCHANT_CODE=700602WDUB
# &TRANS_AMOUNT=200000.0&TRANS_DATE=2019/10/30
# 15:13:47&TRANS_DESCR=Test%20Test%20Test-CLEARANCE%20-001-p5723474039401
# &CUSTOMER_ID=p5723474039401&BANK_CODE=500&BRANCH_CODE=001
# &SERVICE_ID=p5723474039401&CUSTOMER_NAME=Test%20Test%20Test
# &CUSTOMER_ADDRESS=ASS-ENG&TELLER_ID=etzbankteller&USERNAME=%20
# &PASSWORD=%20&BANK_NAME=eTranzact%20Intl%20Plc
# &BRANCH_NAME=ETRANZACT&CHANNEL_NAME=Bank&PAYMENT_METHOD_NAME=Cash
# &PAYMENT_CURRENCY=566&TRANS_TYPE=101&TRANS_FEE=0.0
# &TYPE_NAME=CLEARANCE&LEAD_BANK_CODE=700&LEAD_BANK_NAME=eTranzact%20Intl%20Plc
# COL1=2018/2019&COL2=Acceptance
# Fee&COL3=ASS&COL4=ENG&COL5=BARTENL&COL6=400&COL7=ug_ft&COL8=N/A&COL9=11/12345
# &COL10=damms005@gmail.com&COL11=None&COL12=&COL13=

def query_payoutlet(host, terminal_id, confirmation_number, payment, https):
    headers={"Content-type": "application/x-www-form-urlencoded",
             "Accept": "text/plain"}
    url = "/WebConnectPlus/query.jsp"
    if https:
        h = httplib.HTTPSConnection(host)
    else:
        h = httplib.HTTPConnection(host)
    args = {'TERMINAL_ID': terminal_id,
            'CONFIRMATION_NO': confirmation_number,
            }
    h.request('POST', url, urlencode(args), headers)
    response = h.getresponse()
    if response.status!=200:
        return False, 'Connection error (%s, %s)' % (response.status, response.reason), None
    raw = response.read()
    # Remove empty lines
    raw = raw.replace('\r\n','')
    success = parse_qs(raw)
    if not success.get('CUSTOMER_ID'):
        msg = _('Invalid or unsuccessful callback: ${a}',
            mapping = {'a': raw})
        log = 'invalid callback for payment %s: %s' % (payment.p_id, raw)
        payment.p_state = 'failed'
        return False, msg, log
    # We expect at least two parameters
    if len(success) < 2:
        msg = _('Invalid callback: ${a}', mapping = {'a': raw})
        log = 'invalid callback for payment %s: %s' % (payment.p_id, raw)
        payment.p_state = 'failed'
        return False, msg, log
    customer_id = success.get('CUSTOMER_ID')[0]
    if payment.p_id != customer_id:
        msg = _('Wrong payment id')
        log = 'wrong callback for payment %s: %s' % (payment.p_id, raw)
        payment.p_state = 'failed'
        return False, msg, log
    payment.r_code = u'ET'
    payment.r_desc = u'%s' % success.get('TRANS_DESCR')[0]
    payment.r_amount_approved = float(success.get('TRANS_AMOUNT')[0])
    payment.r_card_num = None
    payment.r_pay_reference = u'%s' % success.get('RECEIPT_NO')[0]
    if payment.r_amount_approved != payment.amount_auth:
        msg = _('Wrong amount')
        log = 'wrong callback for payment %s: %s' % (payment.p_id, raw)
        payment.p_state = 'failed'
        return False, msg, log
    log = 'valid callback for payment %s: %s' % (payment.p_id, raw)
    msg = _('Successful callback received')
    payment.p_state = 'paid'
    payment.payment_date = datetime.utcnow()
    return True, msg, log
