-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhep_info.py
More file actions
217 lines (193 loc) · 9 KB
/
hep_info.py
File metadata and controls
217 lines (193 loc) · 9 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
import configparser
import requests
import json
import textwrap
import base64
import os
from decimal import Decimal
# Read config
config = configparser.ConfigParser()
config.read('hep_settings.ini')
username = config['Credentials']['username']
password = config['Credentials']['password']
barcode_json = config.getboolean('Settings', 'barcode_json', fallback=False)
barcode_save = config.getboolean('Settings', 'barcode_save', fallback=False)
save_bills_api = config.getboolean('Settings', 'save_bills_api', fallback=False)
output_dir = config.get('Settings', 'output_dir', fallback='.')
# Ensure output directory exists
os.makedirs(output_dir, exist_ok=True)
# Create session
session = requests.Session()
# Headers
headers = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json",
"Origin": "https://mojracun.hep.hr",
"Referer": "https://mojracun.hep.hr/elektra/promet",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin"
}
# Login
login_url = "https://mojracun.hep.hr/elektra/v1/api/korisnik/prijava"
payload = {"username": username, "password": password}
response = session.post(login_url, json=payload, headers=headers, timeout=10)
if response.status_code != 200:
print(f"Login failed. Status: {response.status_code}")
exit(1)
json_response = response.json()
print("Login successful.\n")
# Prepare hep_sve.json
sve_data = {"user": json_response, "accounts": []}
# Extract accounts
accounts = []
for kupac in json_response['kupci']:
account = {
"customer_id": kupac['kupacId'],
"contract_account": kupac['ugovorniRacun'].strip(),
"address": kupac['adresa'],
"name": kupac['naziv']
}
accounts.append(account)
token = json_response.get('token')
headers["Authorization"] = f"Bearer {token}"
# Prepare hep_light.json and hep_superlite.json
light_data = {}
superlite_data = {}
# Fetch bills and barcodes
barcode_url = "https://mojracun.hep.hr/elektra/v1/api/barcode"
for account in accounts:
customer_id = account['customer_id']
contract_account = account['contract_account']
bills_url = f"https://mojracun.hep.hr/elektra/v1/api/promet/{customer_id}"
print(f"Fetching bills for account: {contract_account} (Customer ID: {customer_id})")
response = session.get(bills_url, headers=headers, timeout=10)
if save_bills_api:
bills_file = os.path.join(output_dir, f"bills_api_response_{contract_account}.json")
with open(bills_file, "w", encoding="utf-8") as f:
f.write(response.text)
print(f"Saved bills to {bills_file}")
if response.status_code == 200:
bills_data = response.json()
account_data = {
"contract_account": contract_account,
"customer_id": customer_id,
"address": account['address'],
"bills": bills_data
}
# Prepare light data
light_data[contract_account] = {
"customer_id": customer_id,
"address": account['address'],
"amount": bills_data.get('saldo', {}).get('iznos', 'N/A'),
"amount_currency": bills_data.get('saldo', {}).get('iznosVal', 'N/A'),
"description": bills_data.get('saldo', {}).get('opis', 'N/A'),
"red_transactions": [],
"green_invoices": []
}
# Prepare superlite data
superlite_data[contract_account] = {
"customer_id": customer_id,
"address": account['address'],
"description": bills_data.get('saldo', {}).get('opis', 'N/A'),
"amount": bills_data.get('saldo', {}).get('iznos', 'N/A')
}
# Filter transactions
red_transactions = [bill for bill in bills_data.get('promet', []) if bill['status'] == 'RED']
green_invoices = sorted(
[bill for bill in bills_data.get('promet', []) if bill['opis'] == 'Račun' and bill['status'] == 'GREEN'],
key=lambda x: x['datum'], reverse=True
)[:3]
print(f"\nBalance for {contract_account}:")
print(f" Amount: {bills_data.get('saldo', {}).get('iznos', 'N/A')} {bills_data.get('saldo', {}).get('iznosVal', 'N/A')}")
print(f" Description: {bills_data.get('saldo', {}).get('opis', 'N/A')}")
print(f"\nRED Transactions for {contract_account}:")
if red_transactions:
first_red = red_transactions[0]
light_data[contract_account]["red_transactions"].append({
"date": first_red['datum'],
"amount": first_red['iznosIspis'],
"pnb": first_red.get('pnb', 'N/A'),
"status": first_red['status']
})
print(f"- Date: {first_red['datum']}")
print(f" Amount: {first_red['iznosIspis']} EUR")
print(f" PNB: {first_red.get('pnb', 'N/A')}")
print(f" Status: {first_red['status']}")
else:
print(" None")
print(f"\nLatest GREEN Invoices for {contract_account}:")
for invoice in green_invoices:
light_data[contract_account]["green_invoices"].append({
"date": invoice['datum'],
"amount": invoice['iznosIspis'],
"pnb": invoice.get('pnb', 'N/A'),
"status": invoice['status']
})
print(f"- Date: {invoice['datum']}")
print(f" Amount: {invoice['iznosIspis']} EUR")
print(f" PNB: {invoice.get('pnb', 'N/A')}")
print(f" Status: {invoice['status']}")
# Fetch barcode for first RED transaction if barcode_json or barcode_save is True
if red_transactions and (barcode_json or barcode_save):
print(f"\nFetching barcode for {contract_account} (first RED transaction)...")
first_red = red_transactions[0]
pnb = first_red.get('pnb', 'N/A')
amount = first_red.get('iznosIspis', 0)
opis = first_red.get('opis', 'N/A')
amount_cents = int(Decimal(str(amount)) * 100)
amount_padded = f"{amount_cents:015d}"
barcode_payload = {
"data": textwrap.dedent(f"""\
HRVHUB30
EUR
{amount_padded}
{account['name']}
{account['address']}
HEP ELEKTRA D.O.O.
ULICA GRADA VUKOVARA 37
ZAGREB
HR4924070001500325331
HR01
{pnb}
ELEC
{opis}
""")
}
barcode_response = session.post(barcode_url, json=barcode_payload, headers=headers, timeout=10)
print(f"Barcode API status for RED (PNB: {pnb}): {barcode_response.status_code}")
if barcode_response.status_code == 200:
barcode_data = barcode_response.json()
base64_data = barcode_data.get('data', 'N/A')
if base64_data != 'N/A':
# Include QR code in JSON if barcode_json is True
if barcode_json:
light_data[contract_account]["red_transactions"][0]["qr_code"] = base64_data
# Save PNG and include png_path if barcode_save is True
if barcode_save:
png_filename = f"barcode_{contract_account}_{pnb}.png"
png_file = os.path.join(output_dir, png_filename)
light_data[contract_account]["red_transactions"][0]["png_path"] = png_filename
superlite_data[contract_account]["png_path"] = png_filename
account_data["png_path"] = png_filename
with open(png_file, "wb") as f:
f.write(base64.b64decode(base64_data))
print(f"Barcode for RED (PNB: {pnb}):")
print(f" Base64 Data: {base64_data[:50]}...")
print(f"Saved barcode as {png_file}")
else:
print(f"Barcode for RED (PNB: {pnb}): No barcode data")
else:
print(f"Failed to fetch barcode for RED (PNB: {pnb}). Status: {barcode_response.status_code}")
sve_data["accounts"].append(account_data)
# Save JSON files
with open(os.path.join(output_dir, "hep_sve.json"), "w", encoding="utf-8") as f:
json.dump(sve_data, f, ensure_ascii=False, indent=2)
print(f"\nSaved all data to {os.path.join(output_dir, 'hep_sve.json')}")
with open(os.path.join(output_dir, "hep_light.json"), "w", encoding="utf-8") as f:
json.dump(light_data, f, ensure_ascii=False, indent=2)
print(f"Saved light data to {os.path.join(output_dir, 'hep_light.json')}")
with open(os.path.join(output_dir, "hep_superlite.json"), "w", encoding="utf-8") as f:
json.dump(superlite_data, f, ensure_ascii=False, indent=2)
print(f"Saved superlite data to {os.path.join(output_dir, 'hep_superlite.json')}")