__init__.py 16.4 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
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

from .dummy import Lolable, kirim_notify

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)

        print('masuk vendor odeo >>')

        # 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 = 'odeo_url' in settings and settings['odeo_url'] or None
        key = ":".join([self.mid, self.key]).encode()
        self.auth = base64.b64encode(key).decode()

    def get_headers(self):
        return {'Authorization': 'Bearer {key}'.format(key=self.auth)}

    def get_url(self, url=None):
        return url and self.url + url or self.url

    def _inquiry(self):
        print('masuk inquiry odeo>>>')
        if self.v_produk_kd[:3] == 'PLN' and self.v_produk_kd != 'PLNPASCA':
            params = dict(
                number=self.id_pel,
                denom=self.v_produk_kd,
            )
            url = self.get_url('/prepaid/pln/inquiry')
        else:
            params = dict(
                denom=self.v_produk_kd,
                number=self.id_pel
            )
            url = self.get_url('/postpaid/inquiry')

        self.request = params
        log.info("Inquiry Request: url: %s params %s" % (url, params))
        self.save_log("inquiry")

        # try:
        #     lolable = Lolable(self.vendor_produk, self.invoice_det)
        #     # resp = lolable.stupeed(json.dumps(params))

        #     resp = lolable.inquat(json.dumps(params))

        #     print('resp_inquat >>')
        #     print(resp_dummy)

        #     # resp = requests.get(url, params=params, verify=False,
        #     #                     headers=self.get_headers())
        # except Exception as e:
        #     log.info(e)
        #     print('error lolable >>')
        #     print(e)
        #     return

        lolable = Lolable(self.vendor_produk, self.invoice_det)

        resp = lolable.inquat(json.dumps(params))

        print('resp_inquat >>')
        print(resp)

        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 = "data" in result and result["data"] or None
            parsd = self.pars_data(data)
            return self.set_success(parsd, "inquiry")  # parsd

        elif resp.status_code == 400:
            data = "data" in result and result["data"] or None
            message = ""
            if data and "errors" in data:
                msg = data["errors"][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")

        return self.set_failed(typ="inquiry")


        # parsd = self._inquiry()
        # if not parsd:
        #     return self.set_failed()  # parsd

    def payment(self):
        # Jika kategory bukan e-pulsa Call Inquiry First
        parsd = None
        print('masuk payment odeo >>')
        if self.vendor_produk.produk.kategori.kode != "e-pulsa":
            print('bukan kategori odeo e-pulsa >>')

            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_pending(typ="inquiry")

            self.response = result
            log.info("Inquiry Response: %s" % self.response)
            if resp.status_code == 200:
                self.status = 1  # sukses
                data = "data" in result and result["data"] or None
                parsd = self.pars_data(data)

            elif resp.status_code == 400:
                data = "data" in result and result["data"] or None
                message = ""
                if data and "errors" in data:
                    msg = data["errors"][0]
                    pos = msg.find("Sisa saldo")
                    message = pos > -1 and msg[:pos] or msg
                parsd = self.pars_data(data)
                return self.set_pending(parsd, message=message, typ="inquiry")
            else:
                return self.set_pending(typ="inquiry")

            if not parsd:
                return self.set_pending(typ="inquiry")

        print('kategori odeo e-pulsa >>')
        params = dict(
            data=dict(
                denom=self.v_produk_kd,
                number=self.id_pel
            )
        )
        self.request = params
        log.info("Payment Request: %s" % self.request)
        self.save_log("payment")
        if not parsd:
            parsd = self.get_price()

        url = self.get_url("/prepaid/purchase")
        try:
            # resp = requests.post(url, data=json.dumps(params), verify=False,
                                 # headers=self.get_headers(), timeout=timeout)

            lolable = Lolable(self.vendor_produk, self.invoice_det)
            resp = lolable.stupeed(json.dumps(params))
        except Exception as e:
            print(e)
            resp = None

        if resp is None or not resp.text:
            return self.set_pending(parsd, typ="payment")

        try:
            result = json.loads(resp.text)
        except:
            self.response = resp.text
            log.info("Payment Response: %s" % self.response)
            return self.set_pending(parsd, typ="payment")

        self.response = result
        log.info("Payment Response: %s" % self.response)

        # odeo mengembalikan result dalam bentuk status
        # 0200 ok
        # 0400 bad request
        # 0401 auth error
        if resp.status_code == 200 and type(result) is dict:  # 0200
            data = "data" in result and result["data"] or {}
            if not data:
                self.status = 0
                return self.set_pending(parsd, typ="payment")

            self.vend_inv_no = "order_id" in data and data["order_id"] or self.vend_inv_no
            self.amt_buy = "price" in data and data["price"] or self.amt_buy
            if "rc" in data:
                if data["rc"] == "13":  # Gagal
                    return self.set_failed(parsd, typ="payment")
                elif data["rc"] == "67":  # Gagal Double
                    return self.set_failed(parsd, typ="payment")
                elif data["rc"] == "68":  # Pending
                    return self.set_pending(parsd, typ="payment")
            else:
                self.serial_number = 'serial_number' in data and data["serial_number"] \
                                     or self.serial_number

            kirim_notify(self.invoice_det.h2h_ar_invoice.cust_inv_no)
            
            return self.set_success(parsd, typ="payment")
        elif resp.status_code == 400:
            data = "data" in result and result["data"] or None
            message = ""
            if data and "errors" in data:
                msg = data["errors"][0]
                pos = msg.find("Sisa saldo")
                message = pos > -1 and msg[:pos] or msg

            pos = message.find("SN: ")
            sn = ""
            if pos > -1:
                sn_spl = message[pos:].split(" ")
                sn = len(sn_spl) > 1 and sn_spl[1] or ""
            parsd["serial_number"] = sn
            return self.set_failed(parsd, message=message, typ="payment")

        elif resp.status_code == 401:
            return self.set_failed(parsd, typ="payment")
        else:
            return

    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')

        if self.kategori == 'e-payment':
            order_id = self.invoice_det.vend_inv_no
            url = self.get_url('/order/{order_id}'.format(order_id=order_id))
            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('/prepaid/purchase-get')

        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('pars_data, data >>')
        print(data)
        if not data:
            return result

        if "subscriber_id" in data and data["subscriber_id"]:
            result['id_pel'] = data["subscriber_id"]
        if "name" in data and data["name"]:
            result['nama'] = data["name"]
        if "subscriber_name" in data and data["subscriber_name"]:
            result['nama'] = data["subscriber_name"]

        rincian = {}
        if "tariff" in data and data["tariff"]:
            rincian['tarif'] = data["tariff"]
        if "number" in data:
            rincian['no_meter'] = data["number"]
        if "power" in data:
            rincian['power'] = data["power"]
        if self.v_produk_kd[:3] == "PLN" and self.v_produk_kd != "PLNPASCA":
            # 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 == "PLNPASCA":
            if 'tarif' in rincian and rincian['tarif']:
                p = rincian['tarif'].split('/')
                if len(p) > 1:
                    rincian["power"] = p[1][:-2]
            if "subscriber_id" in data and data["subscriber_id"]:
                rincian['no_meter'] = data["subscriber_id"]

        i = 1

        inquiries = 'inquiries' in data and data['inquiries'] \
                    or 'inquiry' in data and data['inquiry'] 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 "tariff" in inquiries and inquiries["tariff"]:
                rincian['tarif'] = inquiries["tariff"]
            if "number" in inquiries:
                rincian['no_meter'] = inquiries["number"]
            if "power" in inquiries:
                rincian['power'] = inquiries["power"]
            if "subscriber_id" in inquiries and inquiries["subscriber_id"]:
                result['id_pel'] = inquiries["subscriber_id"]
            if "name" in inquiries and inquiries["name"]:
                result['nama'] = inquiries["name"]
            if "subscriber_name" in inquiries and inquiries["subscriber_name"]:
                result['nama'] = inquiries["subscriber_name"]

            if "base_price" in inquiries:
                pokok += int(inquiries["base_price"])
            if "fine" in inquiries:
                denda += int(inquiries["fine"])
            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 "period" in inquiries:
                period += " " + inquiries["period"]

            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 "due_date" in inquiries:
                if "jth_tempo" in rincian:
                    rincian['jth_tempo'] += " " + inquiries["due_date"]
                else:
                    rincian['jth_tempo'] = inquiries["due_date"]

            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 = "total" in data and data["total"] or 0
        rincian["pokok"] = pokok
        rincian["denda"] = denda
        if self.v_produk_kd == "TELKOMSELHALO":
            admin = self.vendor_produk.produk.harga
        else:
            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