api_payment.py 16.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472
import logging
from importlib import import_module

from agratek.api.merchant.views.api_merchant import get_vendor_produk, build_request
from opensipkd.base.models import Partner, flush_row
from opensipkd.base.tools.api import (auth_from_rpc,
                                      JsonRpcProdukNotFoundError, JsonRpcCustomerNotFoundError,
                                      JsonRpcParameterNotFound)
from opensipkd.base.views import BaseView
from opensipkd.pasar.models import Produk, PartnerProduk
from opensipkd.pasar.models.produk import H2hArInvoice, H2hArInvoiceDet, PartnerLog, PartnerPay
from pyramid.httpexceptions import HTTPFound
from pyramid.view import view_config
from pyramid_rpc.jsonrpc import jsonrpc_method
from ..tools import JsonRpcInvoiceFoundError, JsonRpcError, get_settings

log = logging.getLogger(__name__)


def save_partner_pay(values, vendor_produk, row=None):
    if not row:
        row = PartnerPay()

    row.from_dict(values)
    row.vendor_id = vendor_produk.partner_id
    row.produk_id = vendor_produk.produk.id
    flush_row(row)
    return row


def build_register(vendor_produk, partner_log=None, **kwargs):
    return build_request('register', vendor_produk, partner_log, **kwargs)


def set_register_values(dat, customer):
    billing = dat["customer"]
    deliver_to = dat["deliver_to"]
    server = dat["server"]
    produk = 'produk' in dat and dat["produk"] or ''
    values = dict(
        customer_id=customer.id,
        # id_pel=dat['id_pel'],
        cart=produk or '{}',
        cust_inv_no=dat["invoice_no"],
        amt_sell=dat['amount'],
        notes=dat['description'],
        inv_cust_nm=billing['name'],
        inv_cust_phone=billing['phone'],
        inv_cust_email=billing['email'],
        inv_cust_city=billing['city'],
        inv_cust_state=billing['state'],
        inv_cust_pos=billing['post_code'],
        inv_cust_country=billing['country'],
        inv_cust_addr=billing['address'],
        inv_cust_agent=billing['agent'],
        inv_cust_ip=billing['ip'],
        inv_cust_session=billing['session_id'],

        domain=server['domain'],
        server_ip=server['ip'],
        description=dat['description'],

        delivery_addr=deliver_to['address'],
        delivery_city=deliver_to['city'],
        delivery_country=deliver_to['country'],
        delivery_nm=deliver_to['name'],
        delivery_phone=deliver_to['phone'],
        delivery_pos=deliver_to['post_code'],
        delivery_state=deliver_to['state'],

        fee=dat['fee'],
        vat=dat['vat'],
        req_dt=dat['req_dt'],
        req_tm=dat['req_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 '',

        # 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'],
    )
    return values


@jsonrpc_method(method='register', endpoint='api-merchant')
def register(request, data, **kwargs):
    """
    Digunakan untuk mendapatkan daftar produk
    :param request:
    :param data:
        {
            denom: string,
            id_pel:string
            inv_no: string optional
        }
    :param token:
        user_token
    :return:
      {
        product_nm:string,
        denom: string,
        id_pel:string
        inv_no: string optional
        denom:string,
        harga:integer,
        admin:integer,
        discount:integer,
        total:integer,
        status:success/pending/failed
    """
    user = auth_from_rpc(request)
    i = 0
    if not data:
        raise JsonRpcParameterNotFound

    is_list = type(data) == list
    data = is_list and data or [data]
    customer = Partner.query_user(user).first()
    if not customer:
        raise JsonRpcCustomerNotFoundError

    r_data = []
    log.info("%s Payment Request: %s" % (customer.kode, data))
    for dat in data:
        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"]
            row = PartnerPay.query().filter_by(cust_inv_no=inv_no).first()
            if row and row.status>0:
                raise JsonRpcInvoiceFoundError()

            vendor_kd = "vendor_kd" in dat and dat["vendor_kd"] or None
            produk_kd = 'denom' in dat and dat['denom'] or None
            vendor_produk = get_vendor_produk(produk_kd, vendor_kd=vendor_kd)
            if not vendor_produk:
                raise JsonRpcProdukNotFoundError

            values = set_register_values(dat, customer)
            credit_card = "credit_card" in dat and dat["credit_card"] or {}
            if credit_card:
                values.update(dict(
                    instmnt_mon = 'instmnt_mon' in credit_card and credit_card['instmnt_mon'] or '',
                    instmnt_type = 'instmnt_type' in credit_card and credit_card['instmnt_type'] or '',
                    recurr_opt = 'recurr_opt' in credit_card and credit_card['recurr_opt'] or 0,
                    card_no = 'card_no' in credit_card and credit_card['card_no'] or 0,
                ))
                ccard = (dict(
                    card_cvv=credit_card["card_cvv"],
                    card_exp=credit_card["card_exp"],
                    card_name=credit_card["card_name"]
                ))
            else:
                ccard = None

            va = "va" in dat and dat["va"] or {}
            if va:
                values.update(dict(
                    inv_valid_date='valid_date' in va and va['valid_date'] or '',
                    inv_valid_time='valid_time' in va and va['valid_time'] or '',
                    inv_cust_va='fix_acct_id' in va and va['fix_acct_id'] or '',
                ))

            ar_invoice = save_partner_pay(values, vendor_produk, row)
            result = build_register(vendor_produk, ar_invoice, ccard=ccard)
            #table payment di update lagi

            dat.update(result["f_result"])
            if "form" in result:
                dat.update(dict(form=result["form"]))
                # request.environ["application"]="text/html"
                # request.response()
                # return request.response

        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


class ViewData(BaseView):
    @view_config(route_name='api-merchant-payment',
                 renderer='templates/form-clean.pt')
    def view_form(self):
        # request = self.req
        # flash = request.session.flash
        # print(">>>>>", request.environ)
        # print(">>>>", request.POST, request)
        # if request.POST:
        #     data = dict(request.POST.items())
        #     if "tXid" in "data":
        #         row = PartnerPay.query_id(data["tXid"]).first()
        #         if not row:
        #             flash('Pembayaran tidak ditemukan', "error")
        #             return dict()
        #         vendor = row.vendor
        #         produk_vendor = PartnerProduk.query()\
        #             .filter_by(partner_id=row.vendor_id,
        #                        produk_id = row.produk_id,)\
        #             .first()
        #
        # else:
        #     flash('Method POST Required', "error")
        #     return dict()

        settings = get_settings()
        url = settings["np_url"]+'/payment'
        return HTTPFound(url)
# @jsonrpc_method(method='advice', endpoint='api-merchant')
# def advice(request, data):
#     """
#     Digunakan untuk mendapatkan daftar produk
#     :param request:
#     :param data:
#         {
#             denom: string,
#             id_pel:string
#             inv_no: string optional
#         }
#     :param token:
#         user_token
#     :return:
#       {
#         product_nm:string,
#         denom: string,
#         id_pel:string
#         inv_no: string optional
#         denom:string,
#         harga:integer,
#         admin:integer,
#         discount:integer,
#         total:integer,
#         status:success/pending/failed
#     """
#     user = auth_from_rpc(request)
#     i = 0
#     is_list = type(data) == list
#     data = is_list and data or [data]
#     customer = Partner.query_user(user).first()
#     if not customer:
#         raise JsonRpcCustomerNotFoundError
#     r_data = []
#     for dat in data:
#         if "invoice_no" not in dat:
#             dat["status"] = "FAILED"
#             dat["message"] = "Parameter tidak lengkap"
#         else:
#             inv_no = dat["invoice_no"]
#             invoice = H2hArInvoice.query() \
#                 .filter_by(cust_inv_no=inv_no,
#                            customer_id=customer.id).first()
#             if not invoice:
#                 dat["status"] = "FAILED"
#                 dat["message"] = "Invoice %s Tidak Ditemukan" % inv_no
#             else:
#                 qry = H2hArInvoiceDet.query().filter_by(ar_invoice_id=invoice.id)
#                 r_prod = []
#                 if "produk" in dat:
#                     prods = []
#                     for p in dat["produk"]:
#                         row = qry.join(Produk, Produk.id == H2hArInvoiceDet.produk_id) \
#                             .filter(Produk.kode == p["denom"],
#                                     H2hArInvoiceDet.id_pel == p["id_pel"]).first()
#                         if not row:
#                             status = "FAILED"
#                             message = "Produk tidak ada"
#                             p.update(dict(status=status,
#                                           message=message))
#                         else:
#                             status = row.status == -1 and 'PENDING' or row.status == 1 and 'SUCCESS' \
#                                      or row.status == -2 and 'PENDING' or "FAILED"
#                             p.update(dict(
#                                 subtotal=(row.amt_sell or 0) + (row.discount or 0),
#                                 discount=row.discount or 0,
#                                 total=row.amt_sell,
#                                 status=status,
#                                 serial_number=row.serial_number or "", )
#                             )
#                         r_prod.append(p)
#                 else:
#                     for p in qry.all():
#                         produk = Produk.query(). \
#                             filter(Produk.id == p.produk_id).first()
#                         status = p.status == -1 and 'PENDING' or p.status == 1 and 'SUCCESS' \
#                                  or p.status == -2 and 'PENDING' or "FAILED"
#                         r_prod.append(dict(denom=produk.kode,
#                                            id_pel=p.id_pel,
#                                            subtotal=(p.amt_sell or 0) + (p.discount or 0),
#                                            discount=p.discount or 0,
#                                            total=p.amt_sell,
#                                            status=status,
#                                            serial_number=p.serial_number or "", )
#                                       )
#                 dat["produk"] = r_prod
#             r_data.append(dat)
#             i += 1
#     data = is_list and r_data or r_data[0]
#     return data
#
# @jsonrpc_method(method='payment', endpoint='api-merchant')
# def payment(request, token, data):
#     """
#     Digunakan untuk mendapatkan daftar produk
#     :param request:
#     :param data:
#         {
#             denom: string,
#             id_pel:string
#             inv_no: string optional
#         }
#     :param token:
#         user_token
#     :return:
#       {
#         product_nm:string,
#
#         denom: string,
#         id_pel:string
#         inv_no: string optional
#         denom:string,
#         harga:integer,
#         admin:integer,
#         discount:integer,
#         total:integer,
#         status:success/pending/failed 00/01/02
#     """
#     user = auth_from_rpc(request, token)
#     i = 0
#     dat = data is list and data or [data]
#     costumer = Partner.query_user(user)
#     for dat in data:
#         produk_kd = 'denom' in dat and dat['denom'] or None
#         if not produk_kd :
#             raise JsonRpcProdukNotFound(message="Produk harus diisi")
#
#         produk = Produk.query_kode(produk_kd).first()
#         if not produk:
#             raise JsonRpcProdukNotFound(message="Produk %s tidak ditemukan" % produk_kd)
#
#         # todo: search product lowest price
#         vend_kd = 'ODEO'
#
#         qry = PartnerProduk.query() \
#             .filter(Partner.kode == vend_kd) \
#             .filter(Produk.kode == produk_kd).first()
#
#         r_data = dat
#         r_data.update(dict(data=result))
#         data[i] = r_data
#         i += 1
#     return data
#
#
# @jsonrpc_method(method='get_product', endpoint='api-merchant')
# def get_product(request, token, data ):
#     """
#     Digunakan untuk mendapatkan daftar produk
#     :param request:
#     :param data:
#         {
#             product_kd: string, //optional
#             page:integer, //optional
#             length:integer, //optional
#             category:string, //optional
#             search:string //optional
#         }
#     :return: [
#       {
#         product_kd:string,
#         product_nm:string,
#         harga:integer
#       }
#
#     ]
#     """
#     auth_from_rpc(request)
#     i =0
#     qry = DepartemenProduk.query() \
#         .filter(Departemen.kode == '100000')
#     for dat in data:
#         page = 'page' in dat and dat['page'] or 1
#         length = 'length' in dat and dat['length'] or 5
#         product_kd = 'product_kd' in dat and dat['product_kd'] or None
#         search = 'search' in dat and dat['search'] or None
#         category = 'category' in dat and dat['category'] or None
#         if product_kd :
#             rst = qry.join(Produk).filter(Produk.kode == product_kd)
#         elif search:
#             rst = qry.join(Produk).filter(Produk.nama.ilike("".join(['%',search,'%' ])))
#         elif category:
#             rst = qry.join(Produk).join(ProdukKategori) \
#                 .filter(ProdukKategori.nama.ilike("".join(['%', category, '%'])))
#         else:
#              rst = qry
#
#         rst = rst.limit(length).offset((page-1)*length)
#         result = []
#         for row in rst.all():
#             result.append(dict(product_kd=row.produk.kode,
#                                produk_nm=row.produk.nama,
#                                harga=row.harga ))
#         r_data = dat
#         r_data.update(dict(data=result))
#         data[i]=r_data
#         i += 1
#     return data
#
# @jsonrpc_method(method='get_biaya', endpoint='api-merchant')
# def get_biaya(request, data, token=None):
#     """
#         Digunakan untuk mencari methode pembayaran dan biaya layanan
#         :param request:
#         :param data:
#             {
#                 biaya_kd: string,
#                 harga:integer,
#                 cname:string,
#                 cid:string,
#                 cvv:string, optional
#             }
#         :param token:
#             user_token
#         :return:
#           {
#             product_kd:string,
#             product_nm:string,
#             harga:integer
#           }
#         """
#
#     user = auth_from_rpc(request, token)
#     i =0
#     qry = DepartemenProduk.query() \
#         .filter(Departemen.kode == '100000')
#     for dat in data:
#         product_kd = 'biaya_kd' in dat and dat['biaya_kd'] or None
#         cid  = 'cid' in dat and dat['cid'] or None
#         if not product_kd :
#             raise JsonRpcParameterNotFound(message='Paramter product_kd wajib di isi')
#
#         rst = qry.join(Produk).filter(Produk.kode == product_kd)
#         result = []
#         for row in rst.all():
#             if row.is_cid and not cid:
#                 raise JsonRpcParameterNotFound(message="Parameter cid wajib di isi")
#             if row.produk.fixed:
#                 harga = row.harga
#             else:
#                 harga = dat['harga']*row.harga
#
#             result.append(dict(biaya_kd=row.produk.kode,
#                                produk_nm=row.produk.nama,
#                                harga=harga))
#
#         r_data = dat
#         r_data.update(dict(data=result))
#         data[i]=r_data
#         i += 1
#     return data