api_merchant.py
18.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
import logging
from importlib import import_module
from opensipkd.base.models import Partner, flush_row
from opensipkd.base.tools.api import (auth_from_rpc,
JsonRpcProdukNotFoundError, JsonRpcCustomerNotFoundError,
JsonRpcParameterNotFound)
from opensipkd.pasar.models import Produk, PartnerProduk
from opensipkd.pasar.models.produk import H2hArInvoice, H2hArInvoiceDet, PartnerLog
from pyramid_rpc.jsonrpc import jsonrpc_method
from ..tools import JsonRpcInvoiceFoundError, JsonRpcError
log = logging.getLogger(__name__)
def build_request(typ, vendor_produk, partner_log=None):
# produk_id = values['produk_id']
# vendor_id = values['vendor_id']
# bill_no = values['destination']
# customer_id = 'customer_id' in values and values['customer_id'] or None
# cust_trx_id = 'cust_trx_id' in values and values['cust_trx_id'] or None
pckgs = 'agratek.api.merchant.views'
moduls = vendor_produk.modules.split('.')
if len(moduls) > 1:
pckg = ".".join(moduls[:-1])
pckgs = ".".join([pckgs, pckg])
moduls = moduls[-1:]
modul = moduls[0]
log.info("Module: %s Pckgs: %s" % (modul, pckgs))
modul = '.' + modul
modules = import_module(modul, pckgs)
cls_module = modules.Vendor(vendor_produk, partner_log)
cls = hasattr(cls_module, typ) and getattr(cls_module, typ) or None
if cls:
result = cls()
# log.info("Build Req: mod %s rslt: %s" % (vendor_produk.modules, data))
log.info("Request %s" % cls_module.request)
log.info("Response %s" % cls_module.response)
log.info("Result %s" % cls_module.result)
result = {}
result["f_response"] = cls_module.response
result["f_result"] = cls_module.result
result["f_request"] = cls_module.request
else:
log.info("Module %s Not Found" % vendor_produk.modules)
data = dict(message='Fungsi %s tidak ada' % typ,
code=9999)
result = {"f_result": data}
# dict(data=)
return result
def save_partner_log(values, vendor_produk):
partner_log = PartnerLog()
partner_log.vendor_id = vendor_produk.partner_id
partner_log.produk_id = vendor_produk.produk.id
partner_log.customer_id = values["customer_id"]
partner_log.id_pel = values["id_pel"]
flush_row(partner_log)
return partner_log
def qry_vendor_produk():
return PartnerProduk.query() \
.join(Partner, Partner.id == PartnerProduk.partner_id) \
.join(Produk, Produk.id == PartnerProduk.produk_id)
def get_vendor_produk(produk_kd, vendor_kd=None, harga=None):
"""
Fungsi ini digunakan untuk mencari vendor yang paling murah
:param produk_kd: String Kode Produk
:param vendor_kd: Kode Vendor
:return: row objek dari Partner Produk
"""
qry = qry_vendor_produk().filter(Produk.kode == produk_kd)
# Jika parameter vendor_kd disebutkan maka secara explisit mengambil dari
# data vendor parameter secara default mengambil dari yang statusnya=1
if vendor_kd:
qry = qry.filter(Partner.kode == vendor_kd)
else:
qry = qry.filter(PartnerProduk.status == 1)
row = qry.first()
return row
@jsonrpc_method(method='inquiry', endpoint='api-merchant')
def inquiry(request, data, **kwargs):
"""
Digunakan untuk mendapatkan data tagihan
:param request:
:param data:
{
denom: string,
id_pel:string
}
:param token:
user_token
:return:
{
"data": [{
"nopel": "530678910981",
"nama": "SUBCRIBER NAME",
"refno": "25641544",
"rincian":{
"pokok": 300000,
"denda": 0,
"admin": 2500,
"tarif": "R1\/1300VA",
"no_meter": "530678910012",
"power": "1300VA"
},
"subtotal": 302500,
"discount": 800,
"total": 301700
}]
}
"""
user = auth_from_rpc(request)
i = 0
is_list = type(data) == list
data = is_list and data or [data]
customer = Partner.query_user(user).filter(Partner.is_customer == 1).first()
if not customer:
raise JsonRpcCustomerNotFoundError()
r_data = []
for prod in data:
# prods = "produk" in dat and dat["produk"] or None
# for prod in prods:
# log.info(prod)
produk_kd = 'denom' in prod and prod['denom'] or None
if not produk_kd:
raise JsonRpcProdukNotFoundError(message="Produk harus diisi")
vendor_kd = 'vendor_kd' in prod and prod['vendor_kd'] or None
vendor_produk = get_vendor_produk(produk_kd, vendor_kd=vendor_kd)
if not vendor_produk:
raise JsonRpcProdukNotFoundError(
message="Produk %s tidak ditemukan" % produk_kd)
log.info("Vendor %s Produk %s Module %s" % (vendor_produk.partner.kode,
vendor_produk.produk.kode,
vendor_produk.modules))
values = dict(customer_id=customer.id,
id_pel=prod["id_pel"])
partner_log = save_partner_log(values, vendor_produk)
result = build_request('inquiry', vendor_produk, partner_log)
result_code = "code" in result["f_result"] and result["f_result"]["code"] or None
if result_code:
raise JsonRpcError(message=result["f_result"]["message"])
if result["f_result"]["code"] == 0:
prod.update(result)
else:
prod.update(dict(status="FAILED",
message=result["message"]))
r_data.append(prod)
data = is_list and r_data or r_data[0]
return data
def build_purchase(vendor_produk, partner_log=None):
return build_request('payment', vendor_produk, partner_log)
@jsonrpc_method(method='purchase', endpoint='api-merchant')
def purchase(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 "produk" not in dat or not dat["produk"]:
dat["status"] = "FAILED"
dat["message"] = "Parameter tidak lengkap"
else:
inv_no = dat["invoice_no"]
produk = dat["produk"]
# todo cek apakah invoice sudah ada atau belum
ar_invoice = H2hArInvoice.query().filter_by(cust_inv_no=inv_no).first()
if ar_invoice:
raise JsonRpcInvoiceFoundError()
ar_invoice = H2hArInvoice()
ar_invoice.customer_id = customer.id
ar_invoice.cust_inv_no = inv_no
ar_invoice.cust_inv_no = inv_no
ar_invoice.payment = dict(request=dat)
flush_row(ar_invoice)
r_prod = []
for prod in produk:
produk_kd = 'denom' in prod and prod['denom'] or None
id_pel = 'id_pel' in prod and prod['id_pel'] or None
if not produk_kd or not id_pel:
prod["status"] = "FAILED"
prod["message"] = "Denom atau id pelanggan tidak diisi"
else:
# produk = Produk.query_kode(produk_kd).first()
# todo: search product lowest price
vendor_produk = get_vendor_produk(produk_kd)
if not vendor_produk:
prod["status"] = "FAILED"
prod["message"] = "Data tidak ditemukan"
else:
ar_invoice_det = H2hArInvoiceDet()
ar_invoice_det.vendor_id = vendor_produk.partner_id
ar_invoice_det.produk_id = vendor_produk.produk.id
ar_invoice_det.ar_invoice_id = ar_invoice.id
ar_invoice_det.id_pel = prod["id_pel"]
ar_invoice_det.amt_sell = vendor_produk.produk.harga
flush_row(ar_invoice_det)
result = build_purchase(vendor_produk, ar_invoice_det)
total = "total" in result and result["total"] or 0
prod.update(result)
# Perhitungan Total
# Jika harga jual lebih besar dari harga beli jual dipakai harga jual
# jika harga lebih kecil dari harga beli maka harga beli ditambah admin_fee
if total:
if vendor_produk.produk.harga < total:
total += vendor_produk.produk.harga
elif vendor_produk.produk.harga > total:
total = vendor_produk.produk.harga
prod.update(dict(total=total))
r_prod.append(prod)
ar_invoice.payment["response"] = r_prod
dat["produk"] = r_prod
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
@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