python-mytnb 0.5.4__tar.gz → 0.6.0__tar.gz
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.
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/.github/workflows/publish.yml +1 -1
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/PKG-INFO +34 -2
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/README.md +29 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/pyproject.toml +6 -1
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/__init__.py +2 -0
- python_mytnb-0.6.0/src/mytnb/bill.py +93 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/cli.py +71 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/client/client.py +69 -1
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/models.py +16 -0
- python_mytnb-0.6.0/tests/bill_pdf.py +49 -0
- python_mytnb-0.6.0/tests/test_bill.py +74 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/tests/test_cli.py +61 -1
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/tests/test_client.py +89 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/uv.lock +443 -3
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/.github/workflows/ci.yml +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/.gitignore +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/LICENSE +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/__main__.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/auth.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/client/__init__.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/client/auth.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/client/config.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/client/legacy.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/client/rest.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/client/retry.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/crypto.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/src/mytnb/exceptions.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/tests/test_auth.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/tests/test_crypto.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/tests/test_models.py +0 -0
- {python_mytnb-0.5.4 → python_mytnb-0.6.0}/tests/test_retry.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
2
|
Name: python-mytnb
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.6.0
|
|
4
4
|
Summary: Python library to interface with the myTNB API (Tenaga Nasional Berhad)
|
|
5
5
|
Project-URL: Repository, https://github.com/danieyal/python-mytnb
|
|
6
6
|
License-Expression: MIT
|
|
@@ -25,11 +25,14 @@ Requires-Dist: click>=8.3.3; extra == 'cli'
|
|
|
25
25
|
Requires-Dist: rich>=15.0.0; extra == 'cli'
|
|
26
26
|
Provides-Extra: dev
|
|
27
27
|
Requires-Dist: click>=8.3.3; extra == 'dev'
|
|
28
|
+
Requires-Dist: pdfplumber>=0.11; extra == 'dev'
|
|
28
29
|
Requires-Dist: pylint>=3.0; extra == 'dev'
|
|
29
30
|
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
|
|
30
31
|
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
31
32
|
Requires-Dist: rich>=15.0.0; extra == 'dev'
|
|
32
33
|
Requires-Dist: ruff>=0.6; extra == 'dev'
|
|
34
|
+
Provides-Extra: pdf
|
|
35
|
+
Requires-Dist: pdfplumber>=0.11; extra == 'pdf'
|
|
33
36
|
Description-Content-Type: text/markdown
|
|
34
37
|
|
|
35
38
|
[](https://badge.fury.io/py/python-mytnb)
|
|
@@ -87,6 +90,32 @@ async def main():
|
|
|
87
90
|
asyncio.run(main())
|
|
88
91
|
```
|
|
89
92
|
|
|
93
|
+
## Bills and meter readings
|
|
94
|
+
|
|
95
|
+
`get_bill_pdf()` downloads a bill as PDF, the latest one unless you pass a
|
|
96
|
+
billing number from `get_bill_history()`. It returns `None` when the account has
|
|
97
|
+
no bills or myTNB has no PDF for the bill.
|
|
98
|
+
|
|
99
|
+
No endpoint returns the meter's own register (odometer) readings; they are only
|
|
100
|
+
printed on the bill, in its "Maklumat Meter" table. `get_meter_readings()`
|
|
101
|
+
downloads the bill and reads that table. It needs the optional `pdf` extra
|
|
102
|
+
(pdfplumber):
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
pip install "python-mytnb[pdf]"
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
readings = await client.get_meter_readings("220123456789")
|
|
110
|
+
for reading in readings: # one per register: kWh, and kW/kVARh on some tariffs
|
|
111
|
+
print(reading.meter_number, reading.unit, reading.previous_reading, reading.current_reading)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
The table's layout is TNB's and can change without notice. When the parser does
|
|
115
|
+
not recognise it, `get_meter_readings()` returns an empty list rather than
|
|
116
|
+
guessing. `mytnb meter-readings <account>` shows what it finds, and
|
|
117
|
+
`mytnb bill-pdf <account>` saves the PDF so you can compare.
|
|
118
|
+
|
|
90
119
|
## CLI
|
|
91
120
|
|
|
92
121
|
The `mytnb` command-line tool requires the optional `cli` extra (it pulls in
|
|
@@ -124,6 +153,8 @@ mytnb current-usage <account> # Simplified current usage summary
|
|
|
124
153
|
mytnb due-amount <account> # Outstanding balance
|
|
125
154
|
mytnb bill-history <account> # Bill history (bills issued)
|
|
126
155
|
mytnb payment-history <account> # Bill & payment history
|
|
156
|
+
mytnb bill-pdf <account> # Save the latest bill as PDF (--billing-no, -o)
|
|
157
|
+
mytnb meter-readings <account> # Meter readings from the latest bill (needs the pdf extra)
|
|
127
158
|
```
|
|
128
159
|
|
|
129
160
|
Global options: `--debug` for full tracebacks, `--version`.
|
|
@@ -160,6 +191,7 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
|
|
|
160
191
|
| `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
|
|
161
192
|
| `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
|
|
162
193
|
| `AccountDueAmount` | Outstanding balance and due date |
|
|
194
|
+
| `MeterReading` | One meter register's readings from a bill PDF |
|
|
163
195
|
| `SMRAccount` | Smart Meter Reading eligibility status |
|
|
164
196
|
| `BREligibility` | Bill rendering opt-in status |
|
|
165
197
|
|
|
@@ -53,6 +53,32 @@ async def main():
|
|
|
53
53
|
asyncio.run(main())
|
|
54
54
|
```
|
|
55
55
|
|
|
56
|
+
## Bills and meter readings
|
|
57
|
+
|
|
58
|
+
`get_bill_pdf()` downloads a bill as PDF, the latest one unless you pass a
|
|
59
|
+
billing number from `get_bill_history()`. It returns `None` when the account has
|
|
60
|
+
no bills or myTNB has no PDF for the bill.
|
|
61
|
+
|
|
62
|
+
No endpoint returns the meter's own register (odometer) readings; they are only
|
|
63
|
+
printed on the bill, in its "Maklumat Meter" table. `get_meter_readings()`
|
|
64
|
+
downloads the bill and reads that table. It needs the optional `pdf` extra
|
|
65
|
+
(pdfplumber):
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
pip install "python-mytnb[pdf]"
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
readings = await client.get_meter_readings("220123456789")
|
|
73
|
+
for reading in readings: # one per register: kWh, and kW/kVARh on some tariffs
|
|
74
|
+
print(reading.meter_number, reading.unit, reading.previous_reading, reading.current_reading)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
The table's layout is TNB's and can change without notice. When the parser does
|
|
78
|
+
not recognise it, `get_meter_readings()` returns an empty list rather than
|
|
79
|
+
guessing. `mytnb meter-readings <account>` shows what it finds, and
|
|
80
|
+
`mytnb bill-pdf <account>` saves the PDF so you can compare.
|
|
81
|
+
|
|
56
82
|
## CLI
|
|
57
83
|
|
|
58
84
|
The `mytnb` command-line tool requires the optional `cli` extra (it pulls in
|
|
@@ -90,6 +116,8 @@ mytnb current-usage <account> # Simplified current usage summary
|
|
|
90
116
|
mytnb due-amount <account> # Outstanding balance
|
|
91
117
|
mytnb bill-history <account> # Bill history (bills issued)
|
|
92
118
|
mytnb payment-history <account> # Bill & payment history
|
|
119
|
+
mytnb bill-pdf <account> # Save the latest bill as PDF (--billing-no, -o)
|
|
120
|
+
mytnb meter-readings <account> # Meter readings from the latest bill (needs the pdf extra)
|
|
93
121
|
```
|
|
94
122
|
|
|
95
123
|
Global options: `--debug` for full tracebacks, `--version`.
|
|
@@ -126,6 +154,7 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
|
|
|
126
154
|
| `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
|
|
127
155
|
| `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
|
|
128
156
|
| `AccountDueAmount` | Outstanding balance and due date |
|
|
157
|
+
| `MeterReading` | One meter register's readings from a bill PDF |
|
|
129
158
|
| `SMRAccount` | Smart Meter Reading eligibility status |
|
|
130
159
|
| `BREligibility` | Bill rendering opt-in status |
|
|
131
160
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "python-mytnb"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.6.0"
|
|
8
8
|
description = "Python library to interface with the myTNB API (Tenaga Nasional Berhad)"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -29,6 +29,10 @@ dependencies = [
|
|
|
29
29
|
]
|
|
30
30
|
|
|
31
31
|
[project.optional-dependencies]
|
|
32
|
+
# Reading bill PDFs (MyTNBClient.get_meter_readings).
|
|
33
|
+
pdf = [
|
|
34
|
+
"pdfplumber>=0.11",
|
|
35
|
+
]
|
|
32
36
|
cli = [
|
|
33
37
|
"click>=8.3.3",
|
|
34
38
|
"rich>=15.0.0",
|
|
@@ -40,6 +44,7 @@ dev = [
|
|
|
40
44
|
"ruff>=0.6",
|
|
41
45
|
"click>=8.3.3",
|
|
42
46
|
"rich>=15.0.0",
|
|
47
|
+
"pdfplumber>=0.11",
|
|
43
48
|
]
|
|
44
49
|
|
|
45
50
|
[project.scripts]
|
|
@@ -10,6 +10,7 @@ from mytnb.models import (
|
|
|
10
10
|
CostMetric,
|
|
11
11
|
CustomerAccount,
|
|
12
12
|
DailyUsage,
|
|
13
|
+
MeterReading,
|
|
13
14
|
Metric,
|
|
14
15
|
PaymentHistoryEntry,
|
|
15
16
|
TariffBlock,
|
|
@@ -29,6 +30,7 @@ __all__ = [
|
|
|
29
30
|
"CostMetric",
|
|
30
31
|
"CustomerAccount",
|
|
31
32
|
"DailyUsage",
|
|
33
|
+
"MeterReading",
|
|
32
34
|
"Metric",
|
|
33
35
|
"PaymentHistoryEntry",
|
|
34
36
|
"TariffBlock",
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Meter readings from myTNB bill PDFs.
|
|
2
|
+
|
|
3
|
+
No myTNB endpoint returns a meter's register (odometer) readings. The usage
|
|
4
|
+
endpoints only give consumption derived from them. The readings are printed in
|
|
5
|
+
the bill PDF's meter information table ("Maklumat Meter"), one row per register:
|
|
6
|
+
|
|
7
|
+
M SIE1052308047669 9,750 10,319 569 kWh
|
|
8
|
+
|
|
9
|
+
kWh (energy) is on every bill; kW (maximum demand) and kVARh (reactive energy)
|
|
10
|
+
appear on some tariffs. Reading the PDF's text needs the optional ``pdf`` extra:
|
|
11
|
+
``pip install "python-mytnb[pdf]"``. The layout is TNB's and can change without
|
|
12
|
+
notice; when the parser does not recognise it, it returns no readings rather
|
|
13
|
+
than guessing.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import io
|
|
19
|
+
import re
|
|
20
|
+
|
|
21
|
+
from mytnb.models import MeterReading
|
|
22
|
+
|
|
23
|
+
PDF_EXTRA_HINT = 'Reading bill PDFs needs the pdf extra: pip install "python-mytnb[pdf]"'
|
|
24
|
+
|
|
25
|
+
# Headings that open the meter table (bills are bilingual).
|
|
26
|
+
_SECTION_RE = re.compile(r"Maklumat\s+Meter|Meter\s+Information", re.IGNORECASE)
|
|
27
|
+
|
|
28
|
+
_NUMBER = r"\d[\d,]*(?:\.\d+)?"
|
|
29
|
+
# meter number, previous reading, current reading, usage, unit. The leading "M"
|
|
30
|
+
# column is optional, and numbers may carry thousands separators or decimals.
|
|
31
|
+
# A meter number is upper-case letters and digits, with at least one digit.
|
|
32
|
+
_ROW_RE = re.compile(
|
|
33
|
+
rf"(?:^|\s)(?:M\s+)?((?=[A-Z]*\d)[A-Z0-9]{{6,}})"
|
|
34
|
+
rf"\s+({_NUMBER})\s+({_NUMBER})\s+({_NUMBER})\s+((?i:kwh|kw|kvarh))\b"
|
|
35
|
+
)
|
|
36
|
+
_UNITS = {"kwh": "kWh", "kw": "kW", "kvarh": "kVARh"}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def require_pdf_support() -> None:
|
|
40
|
+
"""Raise ImportError with an install hint when the ``pdf`` extra is missing."""
|
|
41
|
+
try:
|
|
42
|
+
import pdfplumber # noqa: F401 # pylint: disable=import-outside-toplevel,unused-import
|
|
43
|
+
except ImportError as err:
|
|
44
|
+
raise ImportError(PDF_EXTRA_HINT) from err
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def extract_text(pdf: bytes) -> str:
|
|
48
|
+
"""Return the text of every page of a PDF, one line per printed line.
|
|
49
|
+
|
|
50
|
+
Blocking (pdfplumber is synchronous); run it in a thread from async code.
|
|
51
|
+
"""
|
|
52
|
+
require_pdf_support()
|
|
53
|
+
import pdfplumber # pylint: disable=import-outside-toplevel
|
|
54
|
+
|
|
55
|
+
with pdfplumber.open(io.BytesIO(pdf)) as document:
|
|
56
|
+
return "\n".join(page.extract_text() or "" for page in document.pages)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def parse_meter_readings(text: str) -> list[MeterReading]:
|
|
60
|
+
"""Parse the meter information table out of a bill's text.
|
|
61
|
+
|
|
62
|
+
Returns an empty list when the text has no meter table, so text from other
|
|
63
|
+
documents (or other parts of the bill) never yields readings.
|
|
64
|
+
"""
|
|
65
|
+
section = _SECTION_RE.search(text)
|
|
66
|
+
if section is None:
|
|
67
|
+
return []
|
|
68
|
+
|
|
69
|
+
readings = []
|
|
70
|
+
for line in text[section.end():].splitlines():
|
|
71
|
+
match = _ROW_RE.search(line)
|
|
72
|
+
if match is None:
|
|
73
|
+
continue
|
|
74
|
+
meter_number, previous, current, usage, unit = match.groups()
|
|
75
|
+
readings.append(
|
|
76
|
+
MeterReading(
|
|
77
|
+
meter_number=meter_number,
|
|
78
|
+
previous_reading=_to_float(previous),
|
|
79
|
+
current_reading=_to_float(current),
|
|
80
|
+
usage=_to_float(usage),
|
|
81
|
+
unit=_UNITS[unit.lower()],
|
|
82
|
+
)
|
|
83
|
+
)
|
|
84
|
+
return readings
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def read_meter_readings(pdf: bytes) -> list[MeterReading]:
|
|
88
|
+
"""Extract and parse the meter readings from a bill PDF (blocking)."""
|
|
89
|
+
return parse_meter_readings(extract_text(pdf))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _to_float(value: str) -> float:
|
|
93
|
+
return float(value.replace(",", ""))
|
|
@@ -15,6 +15,7 @@ from rich.panel import Panel
|
|
|
15
15
|
from rich.table import Table
|
|
16
16
|
|
|
17
17
|
from mytnb.auth import Credentials, DeviceInfo, UserInfo
|
|
18
|
+
from mytnb.bill import require_pdf_support
|
|
18
19
|
from mytnb.client import MyTNBClient
|
|
19
20
|
from mytnb.exceptions import MyTNBError
|
|
20
21
|
|
|
@@ -376,6 +377,76 @@ def payment_history(ctx, account, as_json):
|
|
|
376
377
|
_run_async(_history())
|
|
377
378
|
|
|
378
379
|
|
|
380
|
+
@cli.command("bill-pdf")
|
|
381
|
+
@click.argument("account")
|
|
382
|
+
@click.option("--billing-no", help="Bill number (see bill-history). Defaults to the latest bill.")
|
|
383
|
+
@click.option("-o", "--output", help="Output path. Defaults to bill-<account>-<billing no>.pdf.")
|
|
384
|
+
@click.pass_context
|
|
385
|
+
def bill_pdf(ctx, account, billing_no, output):
|
|
386
|
+
"""Download a bill as PDF."""
|
|
387
|
+
|
|
388
|
+
async def _download():
|
|
389
|
+
client = await _get_client(ctx)
|
|
390
|
+
async with client:
|
|
391
|
+
number = billing_no
|
|
392
|
+
with console.status("[bold green]Downloading..."):
|
|
393
|
+
if number is None:
|
|
394
|
+
bills = await client.get_bill_history(account)
|
|
395
|
+
number = next((bill.billing_no for bill in bills if bill.billing_no), None)
|
|
396
|
+
if number is None:
|
|
397
|
+
raise click.ClickException(f"No bills found for {account}")
|
|
398
|
+
pdf = await client.get_bill_pdf(account, number)
|
|
399
|
+
if pdf is None:
|
|
400
|
+
raise click.ClickException(f"myTNB has no PDF for bill {number}")
|
|
401
|
+
target = Path(output or f"bill-{account}-{number}.pdf")
|
|
402
|
+
target.write_bytes(pdf)
|
|
403
|
+
console.print(f"[green]Saved bill {number} to[/] {target}")
|
|
404
|
+
|
|
405
|
+
_run_async(_download())
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
@cli.command("meter-readings")
|
|
409
|
+
@click.argument("account")
|
|
410
|
+
@click.option("--billing-no", help="Bill number (see bill-history). Defaults to the latest bill.")
|
|
411
|
+
@click.option("--json", "as_json", is_flag=True, help="Output full JSON.")
|
|
412
|
+
@click.pass_context
|
|
413
|
+
def meter_readings(ctx, account, billing_no, as_json):
|
|
414
|
+
"""Show the meter readings printed on a bill (needs the pdf extra)."""
|
|
415
|
+
require_pdf_support() # fail before logging in
|
|
416
|
+
|
|
417
|
+
async def _readings():
|
|
418
|
+
client = await _get_client(ctx)
|
|
419
|
+
async with client:
|
|
420
|
+
with console.status("[bold green]Reading bill..."):
|
|
421
|
+
result = await client.get_meter_readings(account, billing_no)
|
|
422
|
+
|
|
423
|
+
if as_json:
|
|
424
|
+
_print_json(result)
|
|
425
|
+
return
|
|
426
|
+
|
|
427
|
+
if not result:
|
|
428
|
+
console.print("[yellow]No meter readings found on the bill.[/]")
|
|
429
|
+
return
|
|
430
|
+
|
|
431
|
+
table = Table(title=f"Meter Readings — {account}")
|
|
432
|
+
table.add_column("Meter", style="cyan")
|
|
433
|
+
table.add_column("Previous", justify="right")
|
|
434
|
+
table.add_column("Current", justify="right", style="bold")
|
|
435
|
+
table.add_column("Usage", justify="right", style="green")
|
|
436
|
+
table.add_column("Unit")
|
|
437
|
+
for reading in result:
|
|
438
|
+
table.add_row(
|
|
439
|
+
reading.meter_number,
|
|
440
|
+
f"{reading.previous_reading:,g}",
|
|
441
|
+
f"{reading.current_reading:,g}",
|
|
442
|
+
f"{reading.usage:,g}",
|
|
443
|
+
reading.unit,
|
|
444
|
+
)
|
|
445
|
+
console.print(table)
|
|
446
|
+
|
|
447
|
+
_run_async(_readings())
|
|
448
|
+
|
|
449
|
+
|
|
379
450
|
@cli.command("init-config")
|
|
380
451
|
@click.option("-o", "--output", default="mytnb.json", help="Output path.")
|
|
381
452
|
def init_config(output):
|
|
@@ -2,6 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import binascii
|
|
5
8
|
import logging
|
|
6
9
|
from typing import Any, Optional
|
|
7
10
|
|
|
@@ -9,8 +12,14 @@ import httpx
|
|
|
9
12
|
from curl_cffi import requests as curl_requests
|
|
10
13
|
|
|
11
14
|
from mytnb.auth import Credentials
|
|
15
|
+
from mytnb.bill import read_meter_readings, require_pdf_support
|
|
12
16
|
from mytnb.client.auth import login
|
|
13
|
-
from mytnb.client.config import
|
|
17
|
+
from mytnb.client.config import (
|
|
18
|
+
AWS_API_BASE_URL,
|
|
19
|
+
DEFAULT_SECURE_KEY_K1,
|
|
20
|
+
USER_AGENT,
|
|
21
|
+
_check_http_status,
|
|
22
|
+
)
|
|
14
23
|
from mytnb.client.legacy import _LegacyTransport
|
|
15
24
|
from mytnb.client.rest import _RestTransport
|
|
16
25
|
from mytnb.crypto import encrypt_request
|
|
@@ -21,6 +30,7 @@ from mytnb.models import (
|
|
|
21
30
|
BillHistoryEntry,
|
|
22
31
|
BREligibility,
|
|
23
32
|
CustomerAccount,
|
|
33
|
+
MeterReading,
|
|
24
34
|
PaymentHistoryEntry,
|
|
25
35
|
SMRAccount,
|
|
26
36
|
)
|
|
@@ -347,6 +357,64 @@ class MyTNBClient:
|
|
|
347
357
|
histories.append(PaymentHistoryEntry.model_validate(item))
|
|
348
358
|
return histories
|
|
349
359
|
|
|
360
|
+
async def get_bill_pdf(
|
|
361
|
+
self,
|
|
362
|
+
account: str | CustomerAccount,
|
|
363
|
+
billing_no: str | None = None,
|
|
364
|
+
*,
|
|
365
|
+
is_owner: bool | None = None,
|
|
366
|
+
) -> bytes | None:
|
|
367
|
+
"""Download a bill as PDF, the latest one unless ``billing_no`` is given.
|
|
368
|
+
|
|
369
|
+
Bill numbers come from :meth:`get_bill_history`. Returns ``None`` when
|
|
370
|
+
the account has no bills or myTNB has no PDF for the bill.
|
|
371
|
+
"""
|
|
372
|
+
acc_no, owner, _ = _resolve_account(account, is_owner)
|
|
373
|
+
if billing_no is None:
|
|
374
|
+
bills = await self.get_bill_history(account, is_owner=is_owner)
|
|
375
|
+
billing_no = next((bill.billing_no for bill in bills if bill.billing_no), None)
|
|
376
|
+
if billing_no is None:
|
|
377
|
+
return None
|
|
378
|
+
|
|
379
|
+
data = {
|
|
380
|
+
"apiKeyID": DEFAULT_SECURE_KEY_K1,
|
|
381
|
+
"contractAccount": acc_no,
|
|
382
|
+
"billingNo": billing_no,
|
|
383
|
+
"isOwnerBill": owner,
|
|
384
|
+
"lang": "EN",
|
|
385
|
+
}
|
|
386
|
+
result = await self._legacy_transport.post("GetBillMaskingPDFV2", data)
|
|
387
|
+
blob = result.get("binaryBill")
|
|
388
|
+
if not blob and isinstance(result.get("data"), dict):
|
|
389
|
+
blob = result["data"].get("binaryBill")
|
|
390
|
+
if not blob:
|
|
391
|
+
logger.debug("GetBillMaskingPDFV2 returned no PDF for bill %s", billing_no)
|
|
392
|
+
return None
|
|
393
|
+
try:
|
|
394
|
+
return base64.b64decode(blob)
|
|
395
|
+
except (binascii.Error, ValueError) as err:
|
|
396
|
+
raise APIError(message=f"Bill {billing_no} PDF is not valid base64") from err
|
|
397
|
+
|
|
398
|
+
async def get_meter_readings(
|
|
399
|
+
self,
|
|
400
|
+
account: str | CustomerAccount,
|
|
401
|
+
billing_no: str | None = None,
|
|
402
|
+
*,
|
|
403
|
+
is_owner: bool | None = None,
|
|
404
|
+
) -> list[MeterReading]:
|
|
405
|
+
"""Return the meter register readings printed on a bill.
|
|
406
|
+
|
|
407
|
+
Reads the latest bill unless ``billing_no`` is given, and returns an
|
|
408
|
+
empty list when there is no bill PDF or it has no meter table. Needs the
|
|
409
|
+
``pdf`` extra (``pip install "python-mytnb[pdf]"``); without it this
|
|
410
|
+
raises ``ImportError`` before downloading anything.
|
|
411
|
+
"""
|
|
412
|
+
require_pdf_support()
|
|
413
|
+
pdf = await self.get_bill_pdf(account, billing_no, is_owner=is_owner)
|
|
414
|
+
if pdf is None:
|
|
415
|
+
return []
|
|
416
|
+
return await asyncio.to_thread(read_meter_readings, pdf)
|
|
417
|
+
|
|
350
418
|
async def get_current_usage(self, account_number: str) -> dict:
|
|
351
419
|
"""Get a simplified summary of current usage."""
|
|
352
420
|
usage = await self.get_account_usage_smart(account_number)
|
|
@@ -545,3 +545,19 @@ class AccountDueAmount(BaseModel):
|
|
|
545
545
|
if isinstance(inner, dict):
|
|
546
546
|
return cls.model_validate(inner)
|
|
547
547
|
return cls()
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
class MeterReading(BaseModel):
|
|
551
|
+
"""One register row from a bill's meter information table ("Maklumat Meter").
|
|
552
|
+
|
|
553
|
+
``previous_reading`` and ``current_reading`` are the meter's register
|
|
554
|
+
(odometer) values at the start and end of the billing period, and ``usage``
|
|
555
|
+
is the difference billed. ``unit`` is ``kWh`` (energy), ``kW`` (maximum
|
|
556
|
+
demand) or ``kVARh`` (reactive energy).
|
|
557
|
+
"""
|
|
558
|
+
|
|
559
|
+
meter_number: str
|
|
560
|
+
previous_reading: float
|
|
561
|
+
current_reading: float
|
|
562
|
+
usage: float
|
|
563
|
+
unit: str
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Build small PDFs for bill-parsing tests."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
# A bill's meter table: each cell is printed at its own x position, as on a real bill.
|
|
6
|
+
METER_TABLE = [
|
|
7
|
+
[(40, "Bil Terperinci Anda")],
|
|
8
|
+
[(40, "Maklumat Meter")],
|
|
9
|
+
[(40, "No. Meter"), (220, "Dahulu"), (300, "Semasa"), (380, "Penggunaan"), (470, "Unit")],
|
|
10
|
+
[(40, "M"), (60, "SIE1052308047669"), (220, "9,750"), (300, "10,319"), (380, "569"), (470, "kWh")],
|
|
11
|
+
[(40, "M"), (60, "SIE1052308047669"), (220, "76"), (300, "81"), (380, "5"), (470, "kW")],
|
|
12
|
+
[(40, "M"), (60, "SIE1052308047669"), (220, "1,174"), (300, "1,265"), (380, "91"), (470, "kVARh")],
|
|
13
|
+
[(40, "Perlu Bantuan?")],
|
|
14
|
+
]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _escape(text: str) -> str:
|
|
18
|
+
return text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def make_pdf(rows: list[list[tuple[int, str]]]) -> bytes:
|
|
22
|
+
"""Return a one-page PDF printing each row's (x, text) cells on its own line."""
|
|
23
|
+
ops = ["BT /F1 10 Tf"]
|
|
24
|
+
for index, row in enumerate(rows):
|
|
25
|
+
y = 800 - 16 * index
|
|
26
|
+
for x, text in row:
|
|
27
|
+
ops.append(f"1 0 0 1 {x} {y} Tm ({_escape(text)}) Tj")
|
|
28
|
+
ops.append("ET")
|
|
29
|
+
stream = "\n".join(ops)
|
|
30
|
+
|
|
31
|
+
objects = [
|
|
32
|
+
"<< /Type /Catalog /Pages 2 0 R >>",
|
|
33
|
+
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
|
34
|
+
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842]"
|
|
35
|
+
" /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
|
|
36
|
+
f"<< /Length {len(stream)} >>\nstream\n{stream}\nendstream",
|
|
37
|
+
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
|
38
|
+
]
|
|
39
|
+
out = bytearray(b"%PDF-1.4\n")
|
|
40
|
+
offsets = []
|
|
41
|
+
for number, body in enumerate(objects, start=1):
|
|
42
|
+
offsets.append(len(out))
|
|
43
|
+
out += f"{number} 0 obj\n{body}\nendobj\n".encode("latin-1")
|
|
44
|
+
xref = len(out)
|
|
45
|
+
out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()
|
|
46
|
+
for offset in offsets:
|
|
47
|
+
out += f"{offset:010d} 00000 n \n".encode()
|
|
48
|
+
out += f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()
|
|
49
|
+
return bytes(out)
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"""Tests for mytnb.bill (meter readings from bill PDFs)."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
import pytest
|
|
6
|
+
from bill_pdf import METER_TABLE, make_pdf
|
|
7
|
+
|
|
8
|
+
from mytnb.bill import extract_text, parse_meter_readings, read_meter_readings, require_pdf_support
|
|
9
|
+
from mytnb.models import MeterReading
|
|
10
|
+
|
|
11
|
+
BILL_TEXT = """
|
|
12
|
+
Bil Terperinci Anda
|
|
13
|
+
Maklumat Meter
|
|
14
|
+
No. Meter Dahulu Semasa Penggunaan Unit
|
|
15
|
+
M SIE1052308047669 9,750 10,319 569 kWh
|
|
16
|
+
M SIE1052308047669 76 81 5 kW
|
|
17
|
+
M SIE1052308047669 1,174 1,265 91 kVARh
|
|
18
|
+
Perlu Bantuan?
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
EXPECTED = [
|
|
22
|
+
MeterReading(meter_number="SIE1052308047669", previous_reading=9750, current_reading=10319, usage=569, unit="kWh"),
|
|
23
|
+
MeterReading(meter_number="SIE1052308047669", previous_reading=76, current_reading=81, usage=5, unit="kW"),
|
|
24
|
+
MeterReading(meter_number="SIE1052308047669", previous_reading=1174, current_reading=1265, usage=91, unit="kVARh"),
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TestParseMeterReadings:
|
|
29
|
+
def test_parses_every_register(self):
|
|
30
|
+
assert parse_meter_readings(BILL_TEXT) == EXPECTED
|
|
31
|
+
|
|
32
|
+
def test_needs_the_meter_section(self):
|
|
33
|
+
assert not parse_meter_readings("M SIE1052308047669 9,750 10,319 569 kWh")
|
|
34
|
+
|
|
35
|
+
def test_ignores_rows_before_the_section(self):
|
|
36
|
+
text = "M OTHER0000001 1 2 1 kWh\n" + BILL_TEXT
|
|
37
|
+
assert [r.meter_number for r in parse_meter_readings(text)] == ["SIE1052308047669"] * 3
|
|
38
|
+
|
|
39
|
+
def test_english_heading(self):
|
|
40
|
+
text = "Meter Information\nM SIE1052308047669 9,750 10,319 569 kWh"
|
|
41
|
+
assert parse_meter_readings(text) == EXPECTED[:1]
|
|
42
|
+
|
|
43
|
+
def test_thousands_and_decimals(self):
|
|
44
|
+
text = "Maklumat Meter\n12345678 98,765 99,999 1,234 kWh\n12345678 10.5 12.25 1.75 kW"
|
|
45
|
+
readings = parse_meter_readings(text)
|
|
46
|
+
assert [(r.previous_reading, r.current_reading, r.usage) for r in readings] == [
|
|
47
|
+
(98765, 99999, 1234),
|
|
48
|
+
(10.5, 12.25, 1.75),
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
def test_normalises_unit_case(self):
|
|
52
|
+
text = "Maklumat Meter\nM SIE1052308047669 9,750 10,319 569 KWH"
|
|
53
|
+
assert parse_meter_readings(text)[0].unit == "kWh"
|
|
54
|
+
|
|
55
|
+
def test_ignores_summary_lines(self):
|
|
56
|
+
"""A label without digits is not a meter number."""
|
|
57
|
+
text = "Maklumat Meter\nJumlah 9,750 10,319 569 kWh\nPENGGUNAAN 9,750 10,319 569 kWh"
|
|
58
|
+
assert not parse_meter_readings(text)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class TestPdf:
|
|
62
|
+
def test_reads_a_bill_pdf(self):
|
|
63
|
+
assert read_meter_readings(make_pdf(METER_TABLE)) == EXPECTED
|
|
64
|
+
|
|
65
|
+
def test_extract_text_keeps_rows_on_one_line(self):
|
|
66
|
+
text = extract_text(make_pdf(METER_TABLE))
|
|
67
|
+
assert "M SIE1052308047669 9,750 10,319 569 kWh" in text.splitlines()
|
|
68
|
+
|
|
69
|
+
def test_missing_extra(self, monkeypatch):
|
|
70
|
+
monkeypatch.setitem(sys.modules, "pdfplumber", None)
|
|
71
|
+
with pytest.raises(ImportError, match=r"python-mytnb\[pdf\]"):
|
|
72
|
+
require_pdf_support()
|
|
73
|
+
with pytest.raises(ImportError, match=r"python-mytnb\[pdf\]"):
|
|
74
|
+
extract_text(b"%PDF-1.4")
|
|
@@ -9,7 +9,7 @@ import pytest
|
|
|
9
9
|
from click.testing import CliRunner
|
|
10
10
|
|
|
11
11
|
from mytnb.cli import _build_credentials, _load_config, cli, main
|
|
12
|
-
from mytnb.models import CustomerAccount
|
|
12
|
+
from mytnb.models import BillHistoryEntry, CustomerAccount, MeterReading
|
|
13
13
|
|
|
14
14
|
|
|
15
15
|
class TestLoadConfig:
|
|
@@ -145,3 +145,63 @@ class TestAccountsCommand:
|
|
|
145
145
|
)
|
|
146
146
|
assert result.exit_code == 0
|
|
147
147
|
assert "No linked accounts" in result.output
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _mock_client(**methods) -> MagicMock:
|
|
151
|
+
client = MagicMock()
|
|
152
|
+
for name, value in methods.items():
|
|
153
|
+
setattr(client, name, AsyncMock(return_value=value))
|
|
154
|
+
client.__aenter__ = AsyncMock(return_value=client)
|
|
155
|
+
client.__aexit__ = AsyncMock(return_value=None)
|
|
156
|
+
return client
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
class TestBillCommands:
|
|
160
|
+
"""Tests for `mytnb bill-pdf` and `mytnb meter-readings`."""
|
|
161
|
+
|
|
162
|
+
def test_bill_pdf_saves_the_latest_bill(self, tmp_path, monkeypatch):
|
|
163
|
+
monkeypatch.chdir(tmp_path)
|
|
164
|
+
client = _mock_client(
|
|
165
|
+
get_bill_history=[BillHistoryEntry(billing_no="502"), BillHistoryEntry(billing_no="501")],
|
|
166
|
+
get_bill_pdf=b"%PDF-1.4 bill",
|
|
167
|
+
)
|
|
168
|
+
with patch("mytnb.cli._get_client", AsyncMock(return_value=client)):
|
|
169
|
+
result = CliRunner().invoke(cli, ["bill-pdf", "220123456789"])
|
|
170
|
+
|
|
171
|
+
assert result.exit_code == 0, result.output
|
|
172
|
+
assert (tmp_path / "bill-220123456789-502.pdf").read_bytes() == b"%PDF-1.4 bill"
|
|
173
|
+
client.get_bill_pdf.assert_awaited_once_with("220123456789", "502")
|
|
174
|
+
|
|
175
|
+
def test_bill_pdf_without_pdf(self, tmp_path):
|
|
176
|
+
client = _mock_client(get_bill_pdf=None)
|
|
177
|
+
with patch("mytnb.cli._get_client", AsyncMock(return_value=client)):
|
|
178
|
+
result = CliRunner().invoke(
|
|
179
|
+
cli, ["bill-pdf", "220123456789", "--billing-no", "500", "-o", str(tmp_path / "b.pdf")]
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
assert result.exit_code != 0
|
|
183
|
+
assert "no PDF for bill 500" in result.output
|
|
184
|
+
assert not (tmp_path / "b.pdf").exists()
|
|
185
|
+
|
|
186
|
+
def test_meter_readings_json(self):
|
|
187
|
+
reading = MeterReading(
|
|
188
|
+
meter_number="SIE1052308047669", previous_reading=9750, current_reading=10319, usage=569, unit="kWh"
|
|
189
|
+
)
|
|
190
|
+
client = _mock_client(get_meter_readings=[reading])
|
|
191
|
+
with patch("mytnb.cli._get_client", AsyncMock(return_value=client)):
|
|
192
|
+
result = CliRunner().invoke(cli, ["meter-readings", "220123456789", "--json"])
|
|
193
|
+
|
|
194
|
+
assert result.exit_code == 0, result.output
|
|
195
|
+
assert json.loads(result.output)[0]["current_reading"] == 10319
|
|
196
|
+
client.get_meter_readings.assert_awaited_once_with("220123456789", None)
|
|
197
|
+
|
|
198
|
+
def test_meter_readings_table(self):
|
|
199
|
+
reading = MeterReading(
|
|
200
|
+
meter_number="SIE1052308047669", previous_reading=9750, current_reading=10319, usage=569, unit="kWh"
|
|
201
|
+
)
|
|
202
|
+
client = _mock_client(get_meter_readings=[reading])
|
|
203
|
+
with patch("mytnb.cli._get_client", AsyncMock(return_value=client)):
|
|
204
|
+
result = CliRunner().invoke(cli, ["meter-readings", "220123456789"])
|
|
205
|
+
|
|
206
|
+
assert result.exit_code == 0, result.output
|
|
207
|
+
assert "10,319" in result.output
|