Commit 4bb08032 by solo
2 parents fbf2423c 05afc654
......@@ -2,7 +2,8 @@ kode,path,nama,status,type
api-merchant-home,/api/merchant/home,Api Merchant Home,1,0
api-merchant,/api/merchant,Api Merchant,1,1
api-vendor-notify,/api/vendor/{name}/notify,Api Vendor Notify,1,0
api-merchant/payment,/api/merchant/payment,Api Merchant Payment,1,0
api-merchant-register,/api/merchant/register,Api Merchant Payment,1,0
api-merchant-payment,/api/merchant/payment,Api Merchant Payment,1,0
api-merchant-list,/api/merchant/list,Test Api Merchant,1,0
api-merchant-add,/api/merchant/add,Add Api Merchant,1,0
......
# from datetime import datetime
#
# import colander
# from agratek.api.merchant.views.api_merchant import get_vendor_produk
# from datatables import ColumnDT
# from deform import widget, Form, ValidationFailure
# from opensipkd.base.views import DataTables
# from pyramid.httpexceptions import HTTPFound
# from pyramid.view import view_config
#
# from . import BaseView # , save_file_upload
# from ..models import (DBSession, flush_row, Satuan)
# # from ..models import (H2hArInvoice, H2hArInvoiceDet)
# from ..models import (Produk, Partner, PartnerLog, PartnerProduk, H2hArInvoice, H2hArInvoiceDet)
# from ..tools import (btn_reset,
# btn_cancel, btn_delete, btn_save, auth_from_rpc, get_settings, os)
# from opensipkd.pasar.models.views import (deferred_produk, deferred_vendor,
# deferred_customer)
#
# class Payment(colander.Schema):
# """
# timeStamp Y N 14 API Request Date
# tXid Y AN 30 Transaction ID
# callBackUrl Y AN 255 Payment result forward url (on browser) direplace oleh systen
# merchantToken Y AN 255 merchantToken (dibuat oleh system)
# """
#
# time_stamp = colander.SchemaNode(
# colander.String(),
# oid="time_stamp",
# )
#
# tx_id = colander.SchemaNode(
# colander.String(), title='Customer',
# oid="tx_id",
# widget=widget.PasswordWidget(min_length=30, max_length=30)
# )
#
# callback_url = colander.SchemaNode(
# colander.String(), title='Callback URL',
# oid="callback_url",
# widget=widget.TextInputWidget()
# )
#
# class CcPay(Payment):
# """
# cardNo Y N 20 Full card number
# cardExpYymm Y N 4 card expiry(YYMM)
# cardCvv Y N 4 card CVV
# cardHolderNm Y (CIMB) AN 50 Card Holder Name
# :return:
# """
# card_name = colander.SchemaNode(
# colander.String(), title='Card Expired',
# oid="card_no",
# widget=widget.TextInputWidget(min_length=30, max_length=30)
# )
# card_no = colander.SchemaNode(
# colander.String(), title='Card Number',
# oid="card_no",
# widget=widget.TextInputWidget(min_length=16, max_length=16)
# )
# card_exp = colander.SchemaNode(
# colander.String(), title='Card Expired',
# oid="card_no",
# widget=widget.TextInputWidget(min_length=4, max_length=4)
# )
# card_cvv = colander.SchemaNode(
# colander.String(), title='Card Expired',
# oid="card_no",
# widget=widget.PasswordWidget(min_length=3, max_length=3)
# )
#
# class ClickPay(Payment):
# """
# clickPayNo Y N 16 ClickPay number
# dataField3 Y N 16 Token input 3 for clickpay
# clickPayToken Y N 6 Code response from token
# :return:
# """
# pay_no = colander.SchemaNode(
# colander.String(), title='Click Pay No',
# oid="pay_no",
# widget=widget.TextInputWidget(min_length=16, max_length=16)
# )
#
# data_field_3 = colander.SchemaNode(
# colander.String(), title='Click Pay No',
# oid="data_field_3",
# widget=widget.TextInputWidget(min_length=16, max_length=16)
# )
# token = colander.SchemaNode(
# colander.String(), title='Click Pay No',
# oid="token",
# widget=widget.TextInputWidget(min_length=6, max_length=6)
# )
#
# class AddSchema(Payment):
# customer_id = colander.SchemaNode(
# colander.Integer(), title='Customer',
# oid="customer_id", widget=deferred_customer)
#
# produk_id = colander.SchemaNode(
# colander.Integer(), title='Produk',
# oid="produk_id", widget=deferred_produk)
#
#
# def WalletPay(Payment):
# pass
#
#
#
# def payment_validator(form, values):
# pass
#
# def get_form(request, class_form, buttons=None, row=None, validator=payment_validator):
# schema = class_form(validator=validator)
# schema = schema.bind(vendor=Partner.get_vendor_list(),
# produk=Produk.get_e_list(),
# customer=Partner.get_customer_list())
# schema.request = request
# if row:
# schema.deserialize(row)
# if not buttons:
# buttons = (btn_save, btn_reset)
# return Form(schema, buttons=buttons)
#
#
# def route_list(request):
# return HTTPFound(location=request.route_url('api-customer-list'))
#
#
# def save(values, row):
# # if not row:
# # row = H2hArInvoice()
# # row.create_uid = values['uid']
# # row.created = datetime.now()
# # else:
# # row.update_uid = values['uid']
# # row.updated = datetime.now()
#
# row.from_dict(values)
# flush_row(row)
# return row
#
#
# # def save_request(request, values, values_det, row=None):
# # if not row:
# # row = H2hArInvoice()
# # values['uid'] = request.user.id
# # values['status'] = 'status' in values and values['status'] and 1 or 0
# # else:
# # values['update_uid'] = request.user.id
# # values['updated'] = datetime.now()
# # DBSession.query(H2hArInvoiceDet).filter(H2hArInvoiceDet.ar_invoice_id == row.id).delete()
# #
# # row = save(values, row)
# #
# # row_det = H2hArInvoiceDet()
# # row_det.id_pel = values['id_pel']
# # row_det.ar_invoice_id = row.id
# # row_det = save(values_det, row_det)
# # request.session.flash('Data %s Berhasil disimpan' % values['kode'])
# # # return row
# #
# #
# # form_params_edit = dict(scripts="""
# # $(document).ready(function(){
# # });
# # """)
# #
# # form_params_view = dict(scripts="""
# # $(document).ready(function(){
# # });
# # """)
# #
# # def session_failed(request, session_name):
# # r = dict(form=request.session[session_name])
# # del request.session[session_name]
# # return r
# #
# # def id_not_found(request):
# # id = request.matchdict['id']
# # request.session.flash('Data %s Tidak Ditemukan' % id, 'error')
# # return route_list(request)
# #
# #
# # def query_id(request):
# # id = request.matchdict['id']
# # return H2hArInvoice.query_id(id)
# #
# #
#
#
# class ViewData(BaseView):
# @view_config(route_name='api-merchant-payment',
# # permission="api-customer-admin",
# renderer='templates/form.pt')
# def view_payment(self):
# request = self.req
# # form = get_form(request, AddSchema)
# # form_params = dict(scripts=None)
# form = get_form(request, Payment)
# settings = get_settings()
# if request.POST:
# controls = request.POST.items()
# try:
# c = form.validate(controls)
# except ValidationFailure as e:
# form.set_appstruct(e.cstruct)
# return
# # dict(form=form, params=form_params_edit)
#
# values = dict(c.items())
# registrasi = PartnerPay.query_tx_id(values["tx_id"]).first()
# if not registrasi:
# request.session.flash("Registrasi Payment Tidak Ditemukan", "error")
# return
#
# vendor_produk = PartnerProduk.get_produk(registrasi.vendor_id, registrasi.produk_id).first()
# if not vendor_produk:
# request.session.flash("Produk Tidak Ditemukan", "error")
# return
# url = os.path.join(settings["np_url"], "payment")
# return HTTPFound(location=url, par)
#
# return dict(form=form, params=form_params_edit)
#
......@@ -65,13 +65,14 @@ def register(request, data, **kwargs):
r_data = []
log.info("%s Payment Request: %s" % (customer.kode, data))
for dat in data:
if "invoice_no" not in dat or "produk" not in dat or not dat["produk"] or \
if "invoice_no" not in dat or \
'amount' not in dat or not dat['amount']:
dat["status"] = "FAILED"
dat["message"] = "Parameter tidak lengkap"
dat['code'] = -1
else:
inv_no = dat["invoice_no"]
produk = dat["produk"]
produk = 'produk' in dat and dat["produk"] or ''
# todo cek apakah invoice sudah ada atau belum
ar_invoice = PartnerPay.query().filter_by(cust_inv_no=inv_no).first()
if ar_invoice:
......@@ -86,10 +87,10 @@ def register(request, data, **kwargs):
values = dict(
customer_id=customer.id,
id_pel=dat['id_pel'],
cart=produk,
cart=produk or '{}',
cust_inv_no=inv_no,
amt_sell=dat['amount'],
notes=dat['notes'],
notes=dat['goods_nm'],
inv_cust_nm=dat['cust_nm'],
inv_cust_phone=dat['cust_phone'],
inv_cust_email=dat['cust_email'],
......@@ -104,10 +105,6 @@ def register(request, data, **kwargs):
inv_cust_ip=dat['cust_ip'],
inv_cust_session=dat['cust_session_id'],
description=dat['description'],
inv_valid_date=dat['valid_date'],
inv_valid_time=dat['valid_time'],
inv_time_stamp=dat['time_stamp'],
inv_cust_va=dat['cust_va'],
delivery_addr=dat['delivery_addr'],
delivery_city=dat['delivery_city'],
delivery_country=dat['delivery_country'],
......@@ -116,25 +113,34 @@ def register(request, data, **kwargs):
delivery_pos=dat['delivery_pos'],
delivery_state=dat['delivery_state'],
fee=dat['fee'],
instmnt_mon=dat['instmnt_mon'],
instmnt_type=dat['instmnt_type'],
m_ref_no=dat['m_ref_no'],
notax_amt=dat['notax_amt'],
pay_valid_dt=dat['pay_valid_dt'],
pay_valid_tm=dat['pay_valid_tm'],
recurr_opt=dat['recurr_opt'],
vat=dat['vat'],
req_dt=dat['req_dt'],
req_tm=dat['req_tm'],
vat=dat['vat'],
tx_id=dat['tx_id'],
trans_dt=dat['trans_dt'],
trans_tm=dat['trans_tm'],
inv_time_stamp=dat['time_stamp'] or '',
# va
inv_valid_date='valid_date' in dat and dat['valid_date'] or '',
inv_valid_time='valid_time' in dat and dat['valid_time'] or '',
inv_cust_va='cust_va' in dat and dat['cust_va'] or '',
# cc
instmnt_mon='instmnt_mon' in dat and dat['instmnt_mon'] or '',
instmnt_type='instmnt_type' in dat and dat['instmnt_type'] or '',
recurr_opt='recurr_opt' in dat and dat['recurr_opt'] or 0,
# m_ref_no=dat['m_ref_no'] or '',
# notax_amt=dat['notax_amt'],
# pay_valid_dt=dat['pay_valid_dt'],
# pay_valid_tm=dat['pay_valid_tm'],
# out
# tx_id=dat['tx_id'],
# trans_dt=dat['trans_dt'],
# trans_tm=dat['trans_tm'],
)
ar_invoice = save_partner_pay(values, vendor_produk)
result = build_register(vendor_produk, ar_invoice)
dat.update(result["f_result"])
r_data.append(dat)
data = is_list and r_data or r_data[0]
log.info("%s Payment Response: %s " % (customer.kode, data))
return data
......
import json
import logging
from datetime import datetime
from importlib import import_module
import requests
import xmltodict
......@@ -30,65 +31,6 @@ def update_harga(p, k, v):
return True
def proses_odeo(data):
settings = get_settings()
mid = 'odeo_mid' in settings and settings["odeo_mid"] or None
key = 'odeo_key' in settings and settings["odeo_key"] or None
partner = Partner.query_kode("ODEO").first()
status = str(data["status"])
if status == "BROADCAST_NEW_PRICE":
signature = sha256("{mid}{key}{status}".format(
mid=mid, key=key, status=status))
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature different")
new_price = data["new_prices"]
for k in new_price:
v = new_price[k]
update_harga(partner, k, v)
return dict(success=True)
else:
order_id = str(data["order_id"])
signature = sha256("{order_id}{mid}{key}{status}".format(
order_id=order_id, mid=mid, key=key, status=status))
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature Different")
order = H2hArInvoiceDet.query() \
.filter(H2hArInvoiceDet.vendor_id == partner.id,
H2hArInvoiceDet.vend_inv_no == str(order_id)).first()
if order:
if status == "COMPLETED":
order.status = 1
else:
order.status = -3
order.notify = dict(post=data)
if "sn" in data and data["sn"]:
order.serial_number = data["sn"]
else:
message = 'message' in data and data["message"] or ""
if message:
loc = message.find("SN: ")
if loc>-1:
sn = message[loc+4:loc+28]
order.serial_number=sn
flush_row(order)
# todo: add to customer notify table
# todo: create cron for notify
# proses jika status 1 notify ada isinya tapi belum ada field result
# todo: create cron torecurring order to other vendor
# jika status = -2 proses vendor yang lain
callback_merchant(order)
return order
def callback_merchant(order):
# Callback to merchant
invoice = order.invoice
......@@ -121,19 +63,35 @@ def callback_merchant(order):
dat.update(produk=produk)
data.append(dat)
js = get_jsonrpc(method="notify", params=dict(data=data))
log.info("Notify: %s %s" %(url, js))
log.info("Notify: %s %s" % (url, js))
try:
requests.post(url, data=js, timeout=10)
except:
pass
def proses_np(data):
# todo:
pass
@view_config(route_name='api-vendor-notify', renderer='json')
def api_vendor_notify(request):
vendor_nm = request.matchdict['name']
if vendor_nm == "odeo":
data = json.loads(request.text)
order = proses_odeo(data)
elif vendor_nm == "np":
data = json.loads(request.text)
modul = '.notify'
pckgs = 'agratek.api.merchant.views.{}'.format(vendor_nm)
moduls = import_module(modul, pckgs)
typ = 'proses'
# moduls(data)
cls = hasattr(moduls, typ) and getattr(moduls, typ) or None
if cls:
order = cls(data)
@view_config(route_name='api-vendor-test', renderer="string")
......
......@@ -113,7 +113,8 @@ class Vendor(VendorClass): #VendorClass
# Nicepay.set('merchantKey', self.key)
Nicepay.merchantKey = self.key
Nicepay.set('merchantToken', Nicepay.merchantToken())
Nicepay.set("userLanguage", "ko-KR,en-US;q=0.8,ko;q=0.6,en;q=0.4")
# Nicepay.set("userLanguage", "en-US")
Nicepay.set("userLanguage", "")
Nicepay.set('reqClientVer', '2.0')
return True
......@@ -150,21 +151,32 @@ class Vendor(VendorClass): #VendorClass
Nicepay.set('deliveryState', self.invoice_det.delivery_state)
Nicepay.set('deliveryPostCd', self.invoice_det.delivery_pos)
Nicepay.set('deliveryCountry', self.invoice_det.delivery_country)
Nicepay.set('vat', str(self.invoice_det.vat))
Nicepay.set('fee', str(self.invoice_det.fee))
Nicepay.set('notaxAmt', str(self.invoice_det.notax_amt))
Nicepay.set('reqDt', self.invoice_det.req_dt) # Format (YYYYMMDD)
Nicepay.set('reqTm', self.invoice_det.req_tm) # Format (HHiiss)\
# print('>>> INVOICE DET:', self.invoice_det.vat, type(self.invoice_det.vat),
# self.invoice_det.fee, type(self.invoice_det.fee),
# self.invoice_det.notax_amt, type(self.invoice_det.notax_amt))
Nicepay.set('vat', self.invoice_det.vat and int(self.invoice_det.vat) > 0 and \
str(self.invoice_det.vat) or '')
Nicepay.set('fee', self.invoice_det.fee and int(self.invoice_det.fee) > 0 and \
str(self.invoice_det.fee) or '')
no_tax_amt = self.invoice_det.notax_amt and int(self.invoice_det.notax_amt) > 0 and\
str(self.invoice_det.notax_amt) or ''
Nicepay.set('notaxAmt', no_tax_amt)
# Nicepay.set('reqDt', self.invoice_det.req_dt) # Format (YYYYMMDD)
# Nicepay.set('reqTm', self.invoice_det.req_tm) # Format (HHiiss)
Nicepay.set('reqDt', '') # Format (YYYYMMDD)
Nicepay.set('reqTm', '') # Format (HHiiss)
Nicepay.set('reqClientVer', '')
Nicepay.set('recurrOpt', str(self.invoice_det.recurr_opt))
Nicepay.set('instmntMon', self.invoice_det.instmnt_mon)
Nicepay.set('instmntType', self.invoice_det.instmnt_type)
Nicepay.set('mRefNo', self.invoice_det.m_ref_no)
Nicepay.set('payValidDt', self.invoice_det.pay_valid_dt)
Nicepay.set('payValidTm', self.invoice_det.pay_valid_tm)
Nicepay.set('tXid', self.invoice_det.tx_id)
Nicepay.set('transDt', self.invoice_det.trans_dt)
Nicepay.set('transTm', self.invoice_det.trans_tm)
Nicepay.set('instmntType', '')
Nicepay.set('instmntMon', '')
Nicepay.set('mRefNo', '')
# result dari nicepay
# Nicepay.set('tXid', '')
# Nicepay.set('transDt', '')
# Nicepay.set('transTm', '')
Nicepay.set('payValidDt', '')
Nicepay.set('payValidTm', '')
Nicepay.set('recurrOpt', '')
def register(self):
Nicepay.requestData = {}
......@@ -174,15 +186,23 @@ class Vendor(VendorClass): #VendorClass
# Nicepay.set('merchantToken', 'a20e500ecd7eb786fcda1761765ca59f344a25716ff0b576f3b42ff4ac9f7224')
data = str(json.dumps(self.invoice_det.cart))
# Nicepay.set('cartData', self.invoice_det.cart)
Nicepay.set('cartData', '{}'.format(data))
cart_data = data and '{}'.format(data) or '{}'
Nicepay.set('cartData', cart_data)
self.set_optional_param()
# For Credit Card (Don't forgot change payMethod to '01')
if self.pay_method == '01':
Nicepay.set('instmntType', self.invoice_det.instmnt_type)
Nicepay.set('instmntMon', self.invoice_det.instmnt_mon)
# if self.reccuring:
# # For Credit Card Reccuring Only
Nicepay.set('recurrOpt', '2')
# Nicepay.set('recurrOpt', '2')
# cc
print('>>>> NP INIT:', self.invoice_det.to_dict())
Nicepay.set('recurrOpt', str(self.invoice_det.recurr_opt))
Nicepay.set('instmntMon', str(self.invoice_det.instmnt_mon) or '')
Nicepay.set('instmntType', str(self.invoice_det.instmnt_type) or '')
# Nicepay.set('payValidDt', self.invoice_det.pay_valid_dt or '')
# Nicepay.set('payValidTm', self.invoice_det.pay_valid_tm or '')
# Nicepay.set('mRefNo', self.invoice_det.m_ref_no or '')
# For Virtual Account (Don't forgot change payMethod to '02')
elif self.pay_method == '02':
......@@ -194,30 +214,36 @@ class Vendor(VendorClass): #VendorClass
if self.invoice_det.inv_cust_va:
self.va_typ = 'fixed'
Nicepay.set('merFixAcctId', self.invoice_det.inv_cust_va)
Nicepay.set('vacctValidDt', '')
Nicepay.set('vacctValidTm', '')
# if self.va_typ == "fixed":
# # For Virtual Account Fix Account
# Nicepay.set('merFixAcctId', '12345679')
# # length value of merFixAcctId setting By Mid. Contact
# # Nicepay IT for Information
else:
self.va_typ = 'float'
Nicepay.set('merFixAcctId', '')
elif self.pay_method in ['03', '04', '05']:
elif self.pay_method in ['03', '05']:
# For CVS,ClickPay or E-Wallet
# (Don't forgot change payMethod to '03'/'04'/'05')
Nicepay.set('mitraCd', self.bank_cd)
if self.pay_method == '03':
# For CVS Only
Nicepay.set('payValidDt', self.invoice_det.inv_valid_date) # Format (YYYYMMDD)
Nicepay.set('payValidTm', self.invoice_det.inv_valid_time) # Format (HHiiss)
elif self.pay_method == '04':
# For ClickPay Only
Nicepay.set('mRefNo', self.cust_inv_no)
Nicepay.set('bankCd', self.bank_cd)
elif self.pay_method == '05':
Nicepay.set('mitraCd', self.bank_cd)
elif self.pay_method == '06':
Nicepay.set('recurrOpt', str(self.invoice_det.recurr_opt))
Nicepay.set('instmntMon', str(self.invoice_det.instmnt_mon) or '')
Nicepay.set('instmntType', str(self.invoice_det.instmnt_type) or '')
Nicepay.set('mitraCd', self.bank_cd)
Nicepay.set('payValidDt', self.invoice_det.inv_valid_date) # Format (YYYYMMDD)
Nicepay.set('payValidTm', self.invoice_det.inv_valid_time) # Format (HHiiss)
self.set_optional_param()
self.request = Nicepay.requestData
log.info("REQUEST: {}".format(json.dumps(self.request)))
self.save_log('inquiry')
......@@ -239,18 +265,58 @@ class Vendor(VendorClass): #VendorClass
result_code = int(response['resultCd'])
result["code"] = result_code
result["message"] = response['resultMsg']
if result_code == 0:
if result_code == 0 or self.pay_method == '01':
result["currency"] = response['currency']
result["tx_id"] = response['tXid']
result['trans_dt'] = response['transDt']
result['trans_tm'] = response['transTm']
result["amount"] = response['amt']
result["invoice_no"] = response['referenceNo']
result["description"] = response['description']
# Jika kartu kredit
# if self.pay_method == '01':
# # C-Card
# # payment = self.request_payment(response)
# elif response['payMethod'] == "02":
if response['payMethod'] == "02":
result['pay_method'] = self.pay_method
if result['pay_method'] == "01":
result["code"] = 0
result["message"] = 'SUCCESS'
request_data = Nicepay.requestData
settings = get_settings()
call_back_url = settings['switcher_call_back_url']
result.update(dict(
time_stamp=request_data['timeStamp'],
tx_id=result['tx_id'],
merchant_token=request_data['merchantToken'],
call_back_url=call_back_url,
))
# form = """
# <input type="text" name="timeStamp" value="{time_stamp}">
# <input type="text" name="tXid" value="{tx_id}">
# <input type="text" name="merchantToken" value="{merchant_token}">
# <input type="text" name="cardNo" value="{card_no}">
# <input type="text" name="cardExpYymm" value="{card_exp_yymm}">
# <input type="text" name="cardCvv" value="{card_cvv}">
# <input type="text" name="cardHolderNm" value="{card_holder_nm}">
# <input type="text" name="callBackUrl" value="{call_back_url}">
# """.format(
# time_stamp=request_data['timeStamp'],
# tx_id=result['tx_id'],
# merchant_token=request_data['merchantToken'],
# card_no='',
# card_exp_yymm='',
# card_cvv='',
# card_holder_nm='',
# call_back_url=call_back_url,
# )
# result['form'] = form
elif response['payMethod'] == "02":
# VA
result["vacct_no"]=response['vacctNo']
result["bank_cd"]=response['bankCd']
# result["vacct_valid_dt"]=response['vacctValidDt']
# result["vacct_valid_tm"]=response['vacctValidTm']
# result["mer_fix_acct_id"]=response['merFixAcctId']
......@@ -259,13 +325,13 @@ class Vendor(VendorClass): #VendorClass
result["pay_no"]=response['payNo']
# result["pay_valid_dt"]=response['payValidDt']
# result["pay_valid_tm"]=response['payValidTm']
elif result['payMethod'] == "04":
elif response['payMethod'] == "04":
# clickpay
result["receipt_code"]=response['receiptCode']
elif result['payMethod'] == "05":
elif response['payMethod'] == "05":
# e-wallet
result["receipt_code"]='receiptCode' in response and response['receiptCode'] or ''
elif result['payMethod'] == "06":
elif response['payMethod'] == "06":
# akulaku
pass
......
from _sha256 import sha256
import logging
from agratek.api.merchant.views.notify_vendor import callback_merchant, update_harga
from opensipkd.base import get_settings
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import H2hArInvoiceDet
log = logging.getLogger(__name__)
def proses(data):
# todo:
"""
change settig from odeo to np
"""
settings = get_settings()
mid = 'odeo_mid' in settings and settings["odeo_mid"] or None
key = 'odeo_key' in settings and settings["odeo_key"] or None
partner = Partner.query_kode("ODEO").first()
status = str(data["status"])
if status == "BROADCAST_NEW_PRICE":
signature = sha256("{mid}{key}{status}".format(
mid=mid, key=key, status=status))
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature different")
new_price = data["new_prices"]
for k in new_price:
v = new_price[k]
update_harga(partner, k, v)
return dict(success=True)
else:
order_id = str(data["order_id"])
signature = sha256("{order_id}{mid}{key}{status}".format(
order_id=order_id, mid=mid, key=key, status=status))
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature Different")
order = H2hArInvoiceDet.query() \
.filter(H2hArInvoiceDet.vendor_id == partner.id,
H2hArInvoiceDet.vend_inv_no == str(order_id)).first()
if order:
if status == "COMPLETED":
order.status = 1
else:
order.status = -3
order.notify = dict(post=data)
if "sn" in data and data["sn"]:
order.serial_number = data["sn"]
else:
message = 'message' in data and data["message"] or ""
if message:
loc = message.find("SN: ")
if loc>-1:
sn = message[loc+4:loc+28]
order.serial_number=sn
flush_row(order)
# todo: add to customer notify table
# todo: create cron for notify
# proses jika status 1 notify ada isinya tapi belum ada field result
# todo: create cron torecurring order to other vendor
# jika status = -2 proses vendor yang lain
callback_merchant(order)
return order
......@@ -13,6 +13,7 @@ import logging
log = logging.getLogger(__name__)
import urllib3
from . import notify
urllib3.disable_warnings()
......
from _sha256 import sha256
import logging
from agratek.api.merchant.views.notify_vendor import callback_merchant, update_harga
from opensipkd.base import get_settings
from opensipkd.base.models import Partner, flush_row
from opensipkd.pasar.models import H2hArInvoiceDet
log = logging.getLogger(__name__)
def proses(data):
settings = get_settings()
mid = 'odeo_mid' in settings and settings["odeo_mid"] or None
key = 'odeo_key' in settings and settings["odeo_key"] or None
partner = Partner.query_kode("ODEO").first()
status = str(data["status"])
if status == "BROADCAST_NEW_PRICE":
signature = sha256("{mid}{key}{status}".format(
mid=mid, key=key, status=status))
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature different")
new_price = data["new_prices"]
for k in new_price:
v = new_price[k]
update_harga(partner, k, v)
return dict(success=True)
else:
order_id = str(data["order_id"])
signature = sha256("{order_id}{mid}{key}{status}".format(
order_id=order_id, mid=mid, key=key, status=status))
if signature != data["signature"]:
log.info("Signature Vendor Different")
log.info("local %s, vendor %s" % (signature, data["signature"]))
return dict(error="Signature Different")
order = H2hArInvoiceDet.query() \
.filter(H2hArInvoiceDet.vendor_id == partner.id,
H2hArInvoiceDet.vend_inv_no == str(order_id)).first()
if order:
if status == "COMPLETED":
order.status = 1
else:
order.status = -3
order.notify = dict(post=data)
if "sn" in data and data["sn"]:
order.serial_number = data["sn"]
else:
message = 'message' in data and data["message"] or ""
if message:
loc = message.find("SN: ")
if loc>-1:
sn = message[loc+4:loc+28]
order.serial_number=sn
flush_row(order)
# todo: add to customer notify table
# todo: create cron for notify
# proses jika status 1 notify ada isinya tapi belum ada field result
# todo: create cron torecurring order to other vendor
# jika status = -2 proses vendor yang lain
callback_merchant(order)
return order
<html metal:use-macro="load: ../base.pt">
<div metal:fill-slot="content">
<style>
button {
margin:0px 3px;
}
#main{min-height: 1px;
padding-bottom: 1px;}
</style>
</div>
<div metal:fill-slot="scripts">
<div class="panel-body col-md-12">
<div class="col-md-6 col-md-offset-3 col-xs-12 well">
<!-- Proses Template Form -->
<form method="post" accept-charset="utf-8" id="deform" class="form-horizontal"
enctype="multipart/form-data" tal:define="field form"
style="background-color:white;"
autocomplete="off">
<input type="hidden" name="_charset_">
<input type="hidden" value="deform" name="__formid__">
<!-- Tampilan untuk general error -->
<div class="alert alert-danger" tal:condition="field.error">
<div class="errorMsgLbl" i18n:translate="">
Terdapat kesalahan pengisian
</div>
<p class="errorMsg">${field.errormsg}</p>
</div>
<!-- END Tampilan untuk general error -->
<div class="col-md-12">
<!-- Looping Semua Field-->
<div tal:repeat="f form">
<div tal:condition="f.widget.hidden">
<!-- Proses Saat Field hidden-->
${structure:f.serialize()}
</div>
<div tal:condition="not f.widget.hidden and not f.children"
class="form-group f-${f.name}" >
<!-- Proses Saat Field Normal dan bukan Children-->
<!-- Field Reqired menggunakan class required -->
<label for="${f.oid}"
class="control-label col-md-4 ${f.required and 'required' or ''}"
id="req-${f.oid}">
${f.title}</label>
<div class="col-md-8">
${structure:f.serialize()}
<p tal:condition="f.error" id="error-${f.oid}" class="help-block"
tal:repeat="error f.error.messages()">
${error}</p>
</div>
</div>
<div tal:condition="f.children and f.name=='upload_files'">
<!-- Proses saat Form Adalah File Upload-->
${f.start_sequence()}
${structure:f.serialize()}
${f.end_sequence()}
</div>
<div tal:condition="f.children and f.name!='upload_files'">
<!-- Proses saat Form Adalah Children -->
${f.start_mapping()}
<div tal:repeat="g f.children" class="form-group" >
<label for="${g.oid}"
class="control-label col-md-4 ${g.required and 'required' or ''}"
id="req-${g.oid}">
${g.title}</label>
<div class="col-md-8">
${structure:g.serialize()}
<p tal:condition="g.error" id="error-${g.oid}" class="help-block"
tal:repeat="error g.error.messages()">
${error}</p>
</div>
</div>
${f.end_mapping()}
</div>
</div>
<div class="input-group-btn">
<button tal:repeat="fb form.buttons" type="${fb.type}"
class="btn ${fb.css_class} pull-right"
name="${fb.name}">${fb.title}</button>
</div>
</div>
</form>
<!-- End Template Form -->
<!-- </div> -->
</div>
</div>
</div>
</html>
<html metal:use-macro="load: ../base.pt">
<div metal:fill-slot="content">
<style>
button {
margin:0px 3px;
}
#main{min-height: 1px;
padding-bottom: 1px;}
</style>
</div>
<div metal:fill-slot="scripts">
<div class="panel-body col-md-12">
<div class="col-md-6 col-md-offset-3 col-xs-12 well">
<!-- Proses Template Form -->
<form method="post" accept-charset="utf-8" id="deform" class="form-horizontal"
enctype="multipart/form-data" tal:define="field form"
style="background-color:white;"
autocomplete="off">
<input type="hidden" name="_charset_">
<input type="hidden" value="deform" name="__formid__">
<!-- Tampilan untuk general error -->
<div class="alert alert-danger" tal:condition="field.error">
<div class="errorMsgLbl" i18n:translate="">
Terdapat kesalahan pengisian
</div>
<p class="errorMsg">${field.errormsg}</p>
</div>
<!-- END Tampilan untuk general error -->
<div class="col-md-12">
<!-- Looping Semua Field-->
<div tal:repeat="f form">
<div tal:condition="f.widget.hidden">
<!-- Proses Saat Field hidden-->
${structure:f.serialize()}
</div>
<div tal:condition="not f.widget.hidden and not f.children"
class="form-group f-${f.name}" >
<!-- Proses Saat Field Normal dan bukan Children-->
<!-- Field Reqired menggunakan class required -->
<label for="${f.oid}"
class="control-label col-md-4 ${f.required and 'required' or ''}"
id="req-${f.oid}">
${f.title}</label>
<div class="col-md-8">
${structure:f.serialize()}
<p tal:condition="f.error" id="error-${f.oid}" class="help-block"
tal:repeat="error f.error.messages()">
${error}</p>
</div>
</div>
<div tal:condition="f.children and f.name=='upload_files'">
<!-- Proses saat Form Adalah File Upload-->
${f.start_sequence()}
${structure:f.serialize()}
${f.end_sequence()}
</div>
<div tal:condition="f.children and f.name!='upload_files'">
<!-- Proses saat Form Adalah Children -->
${f.start_mapping()}
<div tal:repeat="g f.children" class="form-group" >
<label for="${g.oid}"
class="control-label col-md-4 ${g.required and 'required' or ''}"
id="req-${g.oid}">
${g.title}</label>
<div class="col-md-8">
${structure:g.serialize()}
<p tal:condition="g.error" id="error-${g.oid}" class="help-block"
tal:repeat="error g.error.messages()">
${error}</p>
</div>
</div>
${f.end_mapping()}
</div>
</div>
<div class="input-group-btn">
<button tal:repeat="fb form.buttons" type="${fb.type}"
class="btn ${fb.css_class} pull-right"
name="${fb.name}">${fb.title}</button>
</div>
</div>
</form>
<!-- End Template Form -->
<!-- </div> -->
</div>
</div>
<script>
${params.scripts}
</script>
</div>
</html>
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!