bb_api.py
4.98 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
from datetime import (
date,
datetime,
timedelta,
)
from time import time
import requests
from logging import getLogger
import transaction
from opensipkd.waktu import create_datetime
from ..models import Pkb
from ..common import BaseApp
from ..tools import (
plain_values,
update,
)
one_day = timedelta(1)
CHANNELS = {'Non Tunai Tranfer': 'TRANSFER'}
def create_data(d):
w = ' '.join([d['tgl_pay_flag'], d['jam_pay_flag']])
w = datetime.strptime(w, '%d/%m/%Y %H:%M:%S')
waktu = create_datetime(w.year, w.month, w.day, w.hour, w.minute, w.second)
channel = d['chanel_pembayaran']
channel = CHANNELS.get(channel, channel.split()[-1].upper())
return dict(
waktu=waktu,
tgl=waktu.date(),
no_polisi=d['no_polisi'],
nominal=float(d['nominal']),
kode_nominal=int(d['kode']),
channel=channel,
pemilik=d['nm_pemilik'],
merek=d['nm_merek_kb'],
jenis_kb=d['nm_jenis_kb'],
jenis_trx=d['nm_jen_trans'],
kasir=d['nm_kasir'],
kode_lokasi=d['kd_lokasi'],
nama_lokasi=d['nm_lokasi'],
kode_kabupaten=d['kd_kabkota'],
nama_kabupaten=d['wilayah_nm'])
class App(BaseApp):
report_orm = Pkb
conf_name = 'pkb api last date'
def get_report(self, d):
session = self.get_session_for_save()
q = session.query(self.report_orm).filter_by(
waktu=d['waktu'], no_polisi=d['no_polisi'])
return q.first()
def do_sync(self, tgl):
d = dict(tanggal=tgl.strftime('%Y-%m-%d'))
headers = {'X-Authorization': self.conf['key']}
data = dict(
tanggal=tgl.strftime('%d/%m/%Y'),
kd_lokasi=self.conf['kd_lokasi'],
kode=self.conf['kode'])
r = requests.post(self.conf['url'], headers=headers, json=data)
if r.status_code != 200:
print('HTTP error', r.status_code)
print(r.text)
return
log = getLogger('do_sync()')
d = r.json()
no = 0
self.last_pay = None
rows = []
for trx in d.get('data', []):
if not trx['flagging']:
continue
for key, value in trx['flagging'].items():
value['kode'] = self.conf['kode']
value['kd_lokasi'] = trx['kd_lokasi']
value['nm_lokasi'] = trx['nm_lokasi']
value['kd_kabkota'] = trx['kd_kabkota']
value['wilayah_nm'] = trx['wilayah_nm'].rstrip()
rows.append(value)
self.count = len(rows)
for value in rows:
source = create_data(value)
self.invoice_id = ' '.join([
value['no_polisi'], source['tgl'].strftime('%Y-%m-%d')])
no += 1
d = plain_values(source)
rpt = self.get_report(source)
if rpt:
target = rpt.to_dict()
target_update, log_msg = update(source, target)
if target_update:
s = ', '.join(log_msg)
msg = f'UPDATE {d} change {s}'
rpt.from_dict(target_update)
else:
msg = f'ALREADY SAME {d}'
rpt = None
if self.count == 1 and self.last: # Hemat log
print(msg)
print('Log yang sama, abaikan.')
return
else:
msg = f'INSERT {d}'
rpt = self.report_orm(**source)
e = self.get_estimate(no)
prefix = self.get_prefix_log()
log.info(f'#{no}/{self.count} {prefix} {msg}, estimate {e}')
if rpt:
session = self.get_session_for_save()
with transaction.manager:
session.add(rpt)
self.last_pay = source
return self.count
def get_last_time(self): # Override
return self.last_pay['waktu'].strftime('%d-%m-%Y')
def prepare_query_filter(self):
if 'tgl_awal' in self.conf:
self.last = None
self.tgl_awal = self.conf['tgl_awal']
if isinstance(self.tgl_awal, datetime):
self.tgl_awal = self.tgl_awal.date()
else:
self.last = self.get_last_id(self.conf_name)
self.tgl_awal = self.last.as_date()
if 'tgl_akhir' in self.conf:
self.tgl_akhir = self.conf['tgl_akhir']
if isinstance(self.tgl_akhir, datetime):
self.tgl_akhir = self.tgl_akhir.date()
else:
self.tgl_akhir = date.today()
def run(self): # dipanggil sync.py
self.prepare_query_filter()
tgl = self.tgl_awal
while True:
tgl += one_day
self.start_time = time()
self.do_sync(tgl)
if self.last_pay and self.last:
self.update_last()
if tgl > self.tgl_akhir:
break