Commit 2f67bcc4 by yasir

update api vendor MKM

1 parent e517c07a
import base64
import json
import re
from time import sleep
import requests
from opensipkd.base import get_settings
from opensipkd.pasar.models import PartnerProduk, H2hArInvoiceDet
from ..vendor import VendorClass
import logging
log = logging.getLogger(__name__)
import urllib3
# from . import notify
urllib3.disable_warnings()
timeout = 30
class Vendor(VendorClass):
def __init__(self, vendor_produk, invoice_det):
VendorClass.__init__(self, vendor_produk, invoice_det=invoice_det)
# id_pel, customer_id, cust_trx, row
settings = get_settings()
# self.mid = 'odeo_mid' in settings and settings['odeo_mid'] or None
# self.key = 'odeo_key' in settings and settings['odeo_key'] or None
self.url = 'mkm_url' in settings and settings['mkm_url'] or None
self.userid = 'mkm_userid' in settings and settings['mkm_userid'] or None
# key = ":".join([self.mid, self.key]).encode()
# self.auth = base64.b64encode(key).decode()
def get_headers(self):
return {'Content-Type': 'application/json'}
def get_url(self, url=None):
return url and self.url + url or self.url
def _inquiry(self):
params = {}
params['Action'] = 'inquiry'
params['ClientId'] = self.userid
params['MCC'] = '6008'
params['KodeProduk'] = self.v_produk_kd
params['NomorPelanggan'] = self.id_pel
# params = dict(
# 'Action' = 'inquiry',
# 'ClientId' = self.userid,
# 'MCC' = '6008',
# 'KodeProduk' = self.v_produk_kd,
# NomorPelanggan = self.id_pel
# )
params = json.dumps(params)
self.request = params
log.info("Inquiry Request: url: %s params %s" % (self.url, params))
self.save_log("inquiry")
try:
resp = requests.post(self.url, data=params, verify=False,
headers=self.get_headers())
except Exception as e:
log.info(e)
return
return resp
def inquiry(self):
if not self.v_produk_kd or not self.id_pel:
return self.set_response(message='Parameter tidak lengkap')
resp = self._inquiry()
if resp is None or not resp.text:
log.info("Resp Tidak Ada, {}".format(resp))
return
try:
result = json.loads(resp.text)
except:
self.response = resp.text
return self.set_failed(typ="inquiry")
self.response = result
log.info("Inquiry Response: %s" % self.response)
if resp.status_code == 200:
self.status = 1 # sukses
data = self.response
parsd = self.pars_data(data)
return self.set_success(parsd, "inquiry") # parsd
elif resp.status_code == 400:
data = self.response
message = ""
if data and "ErrorMessage" in data:
msg = data["ErrorMessage"][0]
pos = msg.find("Sisa saldo")
message = pos > -1 and msg[:pos] or msg
parsd = self.pars_data(data)
return self.set_failed(parsd, message=message, typ="inquiry")
def payment(self):
parsd = None
response_inquiry = self._inquiry() #plain json type
if response_inquiry is None or not response_inquiry.text:
log.info("Resp Tidak Ada, {}".format(response_inquiry))
return
try:
result_inquiry = json.loads(response_inquiry.text) # converting to dictionary type
except:
self.response = response_inquiry.text #converting to readable string
return self.set_failed(typ="inquiry") # failing while parsing json to dictionary
log.info("Inquiry Response: %s" % self.response)
self.response = result_inquiry # should be json serializable
message_log = 'Success'
if response_inquiry.status_code == 200: #answered request
is_error = 'ErrorMessage' in result_inquiry and result_inquiry['ErrorMessage'] or ''
is_error = is_error != '' and result_inquiry['Status'] != '0000'
if is_error :
self.status = 0
error_msg = result_inquiry['ErrorMessage']
error_status = result_inquiry['Status']
message_log = '[' + error_status + '] ' + error_msg
parsd = self.pars_data(result_inquiry) # parsing to user information
return self.set_failed(parsd, message = message_log, typ = "inquiry") # error means failed
else :
# nothing goes wrong, will continue to payment sequences
self.status = 1 # sukses
parsd = self.pars_data(result_inquiry)
print('inq_sukses >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
else: # network fail or any other errors
message_log = 'Terjadi kesalahan Server Pembayaran.'
is_error = 'ErrorMessage' in result_inquiry and result_inquiry['ErrorMessage'] or ''
is_error = is_error != '' and result_inquiry['Status'] != '0000'
if is_error:
error_msg = result_inquiry['ErrorMessage']
error_status = result_inquiry['Status']
message_log = '[' + error_status + '] ' + error_msg
parsd = self.pars_data(result_inquiry)
return self.set_failed(parsd, message=message_log, typ="inquiry")
tagihan_list_inq = result_inquiry['Tagihan']
tagihan_list_pay = []
total_admin = 0
for item in tagihan_list_inq:
tagihan_pay = {}
tagihan_pay['Periode'] = item['Periode']
tagihan_pay['Total'] = item['Total']
total_admin = total_admin + item['Total']
tagihan_list_pay.append(tagihan_pay)
params = dict(
Action = "payment",
ClientId = self.userid,
KodeProduk = self.v_produk_kd,
MCC = 6008,
SessionId = result_inquiry['SessionId'],
NomorPelanggan = result_inquiry['NomorPelanggan'],
Tagihan = tagihan_list_pay,
TotalAdmin = total_admin
)
self.request = params
log.info("Payment Request: %s" % self.request)
self.save_log("payment")
url = self.get_url()
try:
response_payment = requests.post(url, data=json.dumps(params), verify=False,
headers=self.get_headers(), timeout=timeout)
except:
self.response = response_payment.text #converting to readable string
return self.set_failed(typ="payment") # failing while parsing json to dictionary
if response_payment is None or not response_payment.text:
return self.set_failed(typ="payment")
try:
result_payment = json.loads(response_payment.text)
except:
self.response = response_payment.text
log.info("Payment Response: %s" % self.response)
return self.set_failed(typ="payment")
self.response = result_payment
log.info("Payment Response: %s" % self.response)
if response_payment.status_code == 200 : #answered request
is_error = 'ErrorMessage' in result_payment and result_payment['ErrorMessage'] or ''
is_error = is_error != '' and result_payment['Status'] != '0000'
if is_error :
self.status = 0
error_msg = result_payment['ErrorMessage']
error_status = result_payment['Status']
message_log = '[' + error_status + '] ' + error_msg
parsd = self.pars_data(result_payment) # parsing to user information
return self.set_failed(parsd, message = message_log, typ = "payment") # error means failed
else :
# nothing goes wrong, the next process should be waiting for the notify ? or just checking regularly by advice request ?
# there is no notify url parameter in the payment request.
# so i set it in pending status ?
self.status = 1 # sukses
parsd = self.pars_data(result_payment)
message_log = "Request Advice untuk cek status."
return self.set_pending(parsd, message = message_log, typ = "payment")
def advice(self):
# if not self.v_produk_kd or not self.id_pel or not self.invoice_det:
# return dict(code=9999,
# message='Parameter tidak lengkap')
parsd = None
response_inquiry = self._inquiry() #plain json type
if response_inquiry is None or not response_inquiry.text:
log.info("Resp Tidak Ada, {}".format(response_inquiry))
return
try:
result_inquiry = json.loads(response_inquiry.text) # converting to dictionary type
except:
self.response = response_inquiry.text #converting to readable string
return self.set_failed(typ="inquiry") # failing while parsing json to dictionary
log.info("Inquiry Response: %s" % self.response)
self.response = result_inquiry # should be json serializable
message_log = 'Success'
if response_inquiry.status_code == 200: #answered request
is_error = 'ErrorMessage' in result_inquiry and result_inquiry['ErrorMessage'] or ''
is_error = is_error != '' and result_inquiry['Status'] != '0000'
if is_error :
self.status = 0
error_msg = result_inquiry['ErrorMessage']
error_status = result_inquiry['Status']
message_log = '[' + error_status + '] ' + error_msg
parsd = self.pars_data(result_inquiry) # parsing to user information
return self.set_failed(parsd, message = message_log, typ = "inquiry") # error means failed
else :
# nothing goes wrong, will continue to advice sequences
self.status = 1 # sukses
parsd = self.pars_data(result_inquiry)
print('inq_sukses >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
else: # network fail or any other errors
message_log = 'Terjadi kesalahan Server.'
is_error = 'ErrorMessage' in result_inquiry and result_inquiry['ErrorMessage'] or ''
is_error = is_error != '' and result_inquiry['Status'] != '0000'
if is_error:
error_msg = result_inquiry['ErrorMessage']
error_status = result_inquiry['Status']
message_log = '[' + error_status + '] ' + error_msg
parsd = self.pars_data(result_inquiry)
return self.set_failed(parsd, message=message_log, typ="inquiry")
tagihan_list_inq = result_inquiry['Tagihan']
tagihan_list_pay = []
total_admin = 0
for item in tagihan_list_inq:
tagihan_pay = {}
tagihan_pay['Periode'] = item['Periode']
tagihan_pay['Total'] = item['Total']
total_admin = total_admin + item['Total']
tagihan_list_pay.append(tagihan_pay)
params = dict(
Action = "advice",
ClientId = self.userid,
KodeProduk = self.v_produk_kd,
MCC = 6008,
SessionId = result_inquiry['SessionId'],
NomorPelanggan = result_inquiry['NomorPelanggan'],
Tagihan = tagihan_list_pay,
TotalAdmin = total_admin
)
url = self.get_url()
self.save_log("advice")
try:
response_advice = requests.post(url, data=json.dumps(params), verify=False,
headers=self.get_headers(), timeout=timeout)
except:
self.response = response_advice.text #converting to readable string
return self.set_response() # failing while parsing json to dictionary
if response_advice is None or not response_advice.text:
return self.set_failed(typ="advice")
try:
result_advice = json.loads(response_advice.text)
except:
result_advice = response_advice.text
self.response = result_advice
parsd = self.pars_data(result_advice)
save_log('advice')
return parsd
# if self.kategori == 'e-payment':
# order_id = self.invoice_det.vend_inv_no
# url = self.get_url()
# params = None
# self.request = url
# else:
# params = dict(
# data=dict(
# denom=self.v_produk_kd,
# number=self.id_pel
# )
# )
# self.request = params
# url = self.get_url()
# self.save_log("advice")
# try:
# resp = requests.get(url, params=params, verify=False,
# headers=self.get_headers(), timeout=timeout)
# except:
# return self.set_response()
# try:
# result = json.loads(resp.text)
# except:
# result = resp.text
# self.response = result
# if resp.ok:
# self.status = 1 # sukses
# data = "data" in result and result["data"] or None
# parsd = self.pars_data(data)
# return self.set_success(parsd, "payment")
# elif resp.status_code == 400:
# self.status = -3
# parsd = dict(code=resp.status_code,
# message=resp.text)
# else:
# self.status = -4
# parsd = dict(code=500,
# message="Other Error")
# self.save_log('advice')
# return parsd
def pars_data(self, data):
result = dict()
print('isi data pars data >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
print(data)
if not data:
return result
if "NomorPelanggan" in data and data["NomorPelanggan"]:
result['id_pel'] = data["NomorPelanggan"]
if "Nama" in data and data["Nama"]:
result['nama'] = data["Nama"]
if "Nama" in data and data["Nama"]:
result['nama'] = data["Nama"]
rincian = {}
if "Tarif" in data and data["Tarif"]:
rincian['tarif'] = data["Tarif"]
if "NomorMeter" in data:
rincian['no_meter'] = data["NomorMeter"]
if "Daya" in data:
rincian['power'] = data["Daya"]
print('isi vp_produk_kd >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
print(self.v_produk_kd)
# if self.v_produk_kd[:3] == "PLN" and self.v_produk_kd != "PLNPASCA":
if self.v_produk_kd == "522":
print('masuk pra bayar >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
# harga = "price" in data and data["price"] or 0
# pokok = harga and int(re.sub("\D","", self.v_produk_kd))*1000 or 0
pokok = int(self.vendor_produk.produk.harga)
admin = 0
rincian["pokok"] = pokok
rincian["admin"] = admin
rincian["denda"] = 0
rincian["total"] = pokok + admin
rincian["token"] = "token" in data and data["token"] or ""
log.info(">Rincian: {}".format(rincian))
elif self.v_produk_kd == "521":
print('masuk 521 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>')
if 'tarif' in rincian and rincian['tarif']:
p = rincian['tarif'].split('/')
if len(p) > 1:
rincian["power"] = p[1][:-2]
if "NomorPelanggan" in data and data["NomorPelanggan"]:
rincian['no_meter'] = data["NomorPelanggan"]
i = 1
inquiries = 'Tagihan' in data and data['Tagihan'] \
or 'Tagihan' in data and data['Tagihan'] or {}
if not inquiries:
result["jml_data"] = 1
result["rincian"] = rincian
return result
inquirieses = type(inquiries) is list and inquiries or [inquiries]
pokok = denda = admin = 0
period = meter = ""
jml_period = 0
i = 0
log.info(inquirieses)
for inquiries in inquirieses:
# odeo ngerubah data inquiry
if "Tarif" in inquiries and inquiries["tarif"]:
rincian['tarif'] = inquiries["tariff"]
if "NomorMeter" in inquiries:
rincian['no_meter'] = inquiries["NomorMeter"]
if "Daya" in inquiries:
rincian['power'] = inquiries["Daya"]
if "NomorPelanggan" in inquiries and inquiries["NomorPelanggan"]:
result['id_pel'] = inquiries["NomorPelanggan"]
if "Nama" in inquiries and inquiries["Nama"]:
result['nama'] = inquiries["Nama"]
if "NomorPelanggan" in inquiries and inquiries["NomorPelanggan"]:
result['nama'] = inquiries["NomorPelanggan"]
if "TagihanListrik" in inquiries:
pokok += int(inquiries["TagihanListrik"])
if "fine" in inquiries:
denda += int(inquiries["Denda"])
if "admin" in inquiries:
admin += int(inquiries["admin"])
if "admin_fee" in inquiries:
admin += int(inquiries["admin_fee"])
if "coll_fee" in inquiries:
if "coll_fee" in rincian:
rincian['coll_fee'] += int(inquiries["coll_fee"])
else:
rincian['coll_fee'] = int(inquiries["coll_fee"])
if "bill_rest" in inquiries:
if "bill_rest" in rincian:
rincian['bill_rest'] += int(inquiries["bill_rest"])
else:
rincian['bill_rest'] = int(inquiries["bill_rest"])
if "Periode" in inquiries:
period += " " + inquiries["Periode"]
if "meter_changes" in inquiries:
if "meter" in rincian:
rincian['meter'] += inquiries["meter_changes"]
else:
rincian['meter'] = inquiries["meter_changes"]
if "usages" in inquiries:
if "penggunaan" in rincian:
rincian['penggunaan'] += inquiries["usages"]
else:
rincian['penggunaan'] = inquiries["usages"]
if "installment" in inquiries:
if "installment" in rincian:
rincian['installment'] += " " + inquiries["installment"]
else:
rincian['installment'] = inquiries["installment"]
if "platform" in inquiries:
if "platform" in rincian:
rincian['platform'] += " " + inquiries["platform"]
else:
rincian['platform'] = inquiries["platform"]
if "TanggalAkhirPeriode" in inquiries:
rincian['jth_tempo'] = inquiries["TanggalAkhirPeriode"]
# if "jth_tempo" in rincian:
# rincian['jth_tempo'] += " " + inquiries["due_date"]
# else:
if "branch_code" in inquiries:
rincian['cabang'] = inquiries["branch_code"]
if "branch_name" in inquiries:
rincian['nm_cabang'] = inquiries["branch_name"]
if "month_counts" in inquiries:
rincian['jml_bulan'] = inquiries["month_counts"]
if "participant_counts" in inquiries:
rincian['anggota'] = inquiries["participant_counts"]
i += 1
self.amt_buy = "TotalTagihan" in data and data["TotalTagihan"] or 0
rincian["pokok"] = pokok
rincian["denda"] = denda
admin = int(self.vendor_produk.produk.harga * i)
rincian["admin"] = admin
rincian["total"] = pokok + denda + admin
rincian["period"] = period
if not 'jml_bulan' in rincian:
rincian["jml_bulan"] = i
result["subtotal"] = rincian["total"]
product_id = self.invoice_det.produk.id
if hasattr(self.invoice_det, "customer_id"):
partner_id = self.invoice_det.customer_id
else:
partner_id = self.invoice_det.h2h_ar_invoice.customer_id
discount = PartnerProduk.get_discount(partner_id, product_id)
self.discount = discount * i
result["discount"] = self.discount
# self.amt_sell = result["total"]
result['rincian'] = rincian
return result
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!