myorlen-ebok-api 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,66 @@
1
+ """Unofficial Python SDK for the myORLEN gas eBOK (ebok.myorlen.pl, formerly PGNiG eBOK)."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .client import BASE_URL, MyorlenClient
6
+ from .exceptions import ApiError, AuthenticationError, MyorlenError, NotFoundError, ParseError
7
+ from .models import (
8
+ Address,
9
+ Agreement,
10
+ BillingSummary,
11
+ CollectionPoint,
12
+ ConsumptionEntry,
13
+ ContactMessage,
14
+ DownloadedFile,
15
+ EmailSettings,
16
+ HistoryEntry,
17
+ Invoice,
18
+ InvoiceFilter,
19
+ InvoicePage,
20
+ MeterPoint,
21
+ Notification,
22
+ Payment,
23
+ Reading,
24
+ ReadingPage,
25
+ RelatedAccount,
26
+ User,
27
+ YearConsumption,
28
+ YearlyConsumption,
29
+ )
30
+
31
+ try:
32
+ __version__ = version("myorlen-ebok-api")
33
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
34
+ __version__ = "0.0.0"
35
+
36
+ __all__ = [
37
+ "BASE_URL",
38
+ "Address",
39
+ "Agreement",
40
+ "ApiError",
41
+ "AuthenticationError",
42
+ "BillingSummary",
43
+ "CollectionPoint",
44
+ "ConsumptionEntry",
45
+ "ContactMessage",
46
+ "DownloadedFile",
47
+ "EmailSettings",
48
+ "HistoryEntry",
49
+ "Invoice",
50
+ "InvoiceFilter",
51
+ "InvoicePage",
52
+ "MeterPoint",
53
+ "MyorlenClient",
54
+ "MyorlenError",
55
+ "NotFoundError",
56
+ "Notification",
57
+ "ParseError",
58
+ "Payment",
59
+ "Reading",
60
+ "ReadingPage",
61
+ "RelatedAccount",
62
+ "User",
63
+ "YearConsumption",
64
+ "YearlyConsumption",
65
+ "__version__",
66
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,184 @@
1
+ """``myorlen-ebok-api`` command line interface. Prints JSON to stdout; files are written to disk.
2
+
3
+ Credentials come from ``MYORLEN_USER`` / ``MYORLEN_PASS`` (environment or a ``.env`` file in
4
+ the current directory); the old ``PGNIG_USER`` / ``PGNIG_PASS`` names are accepted too.
5
+ The session token is cached in ``~/.cache/myorlen-ebok-api/session.json``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import os
13
+ import sys
14
+ from collections.abc import Sequence
15
+ from datetime import date
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from . import __version__
20
+ from .client import MyorlenClient
21
+ from .exceptions import MyorlenError
22
+ from .models import DownloadedFile, InvoiceFilter, to_jsonable
23
+
24
+ DEFAULT_SESSION_FILE = Path("~/.cache/myorlen-ebok-api/session.json")
25
+
26
+
27
+ def load_dotenv(path: Path) -> None:
28
+ """Minimal .env loader: KEY=VALUE lines, existing environment wins."""
29
+ if not path.is_file():
30
+ return
31
+ for line in path.read_text().splitlines():
32
+ line = line.strip()
33
+ if not line or line.startswith("#") or "=" not in line:
34
+ continue
35
+ key, value = line.split("=", 1)
36
+ os.environ.setdefault(key.strip(), value.strip().strip("'\""))
37
+
38
+
39
+ def _print(data: Any) -> None:
40
+ json.dump(to_jsonable(data), sys.stdout, indent=2, ensure_ascii=False)
41
+ sys.stdout.write("\n")
42
+
43
+
44
+ def _save(file: DownloadedFile, out: str) -> Path:
45
+ dest = Path(out)
46
+ if dest.is_dir() or out.endswith(("/", os.sep)):
47
+ dest.mkdir(parents=True, exist_ok=True)
48
+ dest = dest / (file.filename or "download.bin")
49
+ dest.write_bytes(file.content)
50
+ return dest
51
+
52
+
53
+ def build_parser() -> argparse.ArgumentParser:
54
+ ap = argparse.ArgumentParser(
55
+ prog="myorlen-ebok-api", description="Unofficial myORLEN (formerly PGNiG) eBOK client"
56
+ )
57
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
58
+ ap.add_argument("--ppg", help="meter point id (needed only when the account has several)")
59
+ ap.add_argument(
60
+ "--session-file",
61
+ default=os.environ.get("MYORLEN_SESSION_FILE", str(DEFAULT_SESSION_FILE)),
62
+ help="where to cache the session token ('' disables)",
63
+ )
64
+ sub = ap.add_subparsers(dest="cmd", required=True, metavar="COMMAND")
65
+
66
+ def dates(p: argparse.ArgumentParser) -> None:
67
+ p.add_argument("--from", dest="date_from", type=date.fromisoformat, help="YYYY-MM-DD")
68
+ p.add_argument("--to", dest="date_to", type=date.fromisoformat, help="YYYY-MM-DD")
69
+
70
+ sub.add_parser("user", help="logged-in user with balance and amount to pay")
71
+ sub.add_parser("balance", help="balance, amount to pay and dashboard payment status")
72
+ sub.add_parser("accounts", help="customer accounts linked to the login")
73
+
74
+ p = sub.add_parser("agreements", help="supply agreements")
75
+ p.add_argument("--all", action="store_true", help="include inactive agreements")
76
+ p = sub.add_parser("agreement", help="details of one agreement")
77
+ p.add_argument("number", nargs="?", help="agreement number (default: the only active one)")
78
+
79
+ sub.add_parser("meter-points", help="gas meter points (PPG) with the last reading")
80
+
81
+ p = sub.add_parser("invoices", help="invoices, forecast instalments and interest notes")
82
+ dates(p)
83
+ p.add_argument("--filter", choices=[f.value for f in InvoiceFilter], default="all")
84
+ p.add_argument("--agreement", help="agreement number")
85
+ p.add_argument("--limit", type=int, default=0, help="max rows (0 = all)")
86
+ p = sub.add_parser("invoice", help="details of one invoice / interest note")
87
+ p.add_argument("number", help="e.g. P/1234567/0001/26 or NO/1234567/000001/26")
88
+ p = sub.add_parser("pdf", help="download an invoice PDF")
89
+ p.add_argument("number")
90
+ p.add_argument("--out", default=".", help="file or directory (default: current directory)")
91
+
92
+ sub.add_parser("payments", help="payments booked on the account")
93
+ p = sub.add_parser("history", help="eBOK action history")
94
+ p.add_argument("--limit", type=int, default=30)
95
+
96
+ p = sub.add_parser("readings", help="meter readings (m³)")
97
+ dates(p)
98
+ p.add_argument("--xlsx", metavar="PATH", help="save the portal's Excel export instead of printing")
99
+ p = sub.add_parser("monthly", help="consumption per settlement period")
100
+ p.add_argument("--months", type=int, default=24)
101
+ sub.add_parser("yearly", help="this year vs previous year consumption")
102
+
103
+ sub.add_parser("notifications", help="in-app notifications")
104
+ sub.add_parser("contacts", help="contact form history")
105
+ sub.add_parser("email-settings", help="e-mail notification settings")
106
+ return ap
107
+
108
+
109
+ def run(args: argparse.Namespace, client: MyorlenClient) -> None:
110
+ ppg = args.ppg
111
+ cmd = args.cmd
112
+ if cmd == "user":
113
+ _print(client.get_user())
114
+ elif cmd == "balance":
115
+ user = client.get_user()
116
+ summary = client.get_billing_summary()
117
+ _print({"balance": user.balance, "amount_to_pay": user.amount_to_pay, **summary.to_dict()})
118
+ elif cmd == "accounts":
119
+ _print(client.get_related_accounts())
120
+ elif cmd == "agreements":
121
+ _print(client.get_agreements(include_inactive=args.all))
122
+ elif cmd == "agreement":
123
+ _print(client.get_agreement(args.number))
124
+ elif cmd == "meter-points":
125
+ _print(client.get_meter_points())
126
+ elif cmd == "invoices":
127
+ invoices = []
128
+ for inv in client.iter_invoices(
129
+ filter=args.filter,
130
+ date_from=args.date_from,
131
+ date_to=args.date_to,
132
+ agreement_number=args.agreement,
133
+ ):
134
+ invoices.append(inv)
135
+ if args.limit and len(invoices) >= args.limit:
136
+ break
137
+ _print(invoices)
138
+ elif cmd == "invoice":
139
+ _print(client.get_invoice(args.number))
140
+ elif cmd == "pdf":
141
+ print(_save(client.download_invoice(args.number), args.out))
142
+ elif cmd == "payments":
143
+ _print(client.get_payments())
144
+ elif cmd == "history":
145
+ _print(client.get_account_history(page_size=args.limit))
146
+ elif cmd == "readings":
147
+ if args.xlsx:
148
+ print(_save(client.export_readings(ppg), args.xlsx))
149
+ else:
150
+ _print(list(client.iter_readings(ppg, date_from=args.date_from, date_to=args.date_to)))
151
+ elif cmd == "monthly":
152
+ _print(client.get_monthly_consumption(ppg, months=args.months))
153
+ elif cmd == "yearly":
154
+ _print(client.get_yearly_consumption(ppg))
155
+ elif cmd == "notifications":
156
+ _print(client.get_notifications())
157
+ elif cmd == "contacts":
158
+ _print(list(client.iter_contact_history()))
159
+ elif cmd == "email-settings":
160
+ _print(client.get_email_settings())
161
+ else: # pragma: no cover - argparse rejects unknown commands
162
+ raise SystemExit(f"unknown command {cmd}")
163
+
164
+
165
+ def main(argv: Sequence[str] | None = None) -> int:
166
+ args = build_parser().parse_args(argv)
167
+ load_dotenv(Path.cwd() / ".env")
168
+ user = os.environ.get("MYORLEN_USER") or os.environ.get("PGNIG_USER")
169
+ password = os.environ.get("MYORLEN_PASS") or os.environ.get("PGNIG_PASS")
170
+ session_file = args.session_file or None
171
+ if not (user and password) and not (session_file and Path(session_file).expanduser().exists()):
172
+ print("error: set MYORLEN_USER and MYORLEN_PASS (environment or .env)", file=sys.stderr)
173
+ return 2
174
+ try:
175
+ with MyorlenClient(user, password, session_file=session_file) as client:
176
+ run(args, client)
177
+ except MyorlenError as e:
178
+ print(f"error: {e}", file=sys.stderr)
179
+ return 1
180
+ return 0
181
+
182
+
183
+ if __name__ == "__main__": # pragma: no cover
184
+ raise SystemExit(main())