python-mytnb 0.5.3__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.3 → python_mytnb-0.6.0}/.github/workflows/publish.yml +1 -1
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/PKG-INFO +58 -15
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/README.md +53 -13
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/pyproject.toml +6 -1
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/__init__.py +4 -0
- python_mytnb-0.6.0/src/mytnb/bill.py +93 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/cli.py +108 -1
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/client/client.py +149 -13
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/models.py +72 -3
- 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.3 → python_mytnb-0.6.0}/tests/test_cli.py +61 -1
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/tests/test_client.py +89 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/uv.lock +443 -3
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/.github/workflows/ci.yml +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/.gitignore +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/LICENSE +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/__main__.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/auth.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/client/__init__.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/client/auth.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/client/config.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/client/legacy.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/client/rest.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/client/retry.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/crypto.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/src/mytnb/exceptions.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/tests/test_auth.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/tests/test_crypto.py +0 -0
- {python_mytnb-0.5.3 → python_mytnb-0.6.0}/tests/test_models.py +0 -0
- {python_mytnb-0.5.3 → 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)
|
|
@@ -73,13 +76,46 @@ async def main():
|
|
|
73
76
|
for month in usage.by_month.months:
|
|
74
77
|
print(f"{month.month} {month.year}: {month.usage_total} kWh — RM {month.amount_total}")
|
|
75
78
|
|
|
76
|
-
# Bill history & due amount
|
|
79
|
+
# Bill history, payment history & due amount
|
|
77
80
|
history = await client.get_bill_history("220123456789")
|
|
81
|
+
payments = await client.get_payment_history("220123456789")
|
|
78
82
|
due = await client.get_account_due_amount("220123456789")
|
|
79
83
|
|
|
84
|
+
# Most account-scoped methods also accept a CustomerAccount directly
|
|
85
|
+
# (is_owner and account_type are derived automatically)
|
|
86
|
+
for acc in accounts:
|
|
87
|
+
if acc.is_smart_meter:
|
|
88
|
+
usage = await client.get_account_usage_smart(acc)
|
|
89
|
+
|
|
80
90
|
asyncio.run(main())
|
|
81
91
|
```
|
|
82
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
|
+
|
|
83
119
|
## CLI
|
|
84
120
|
|
|
85
121
|
The `mytnb` command-line tool requires the optional `cli` extra (it pulls in
|
|
@@ -115,7 +151,10 @@ mytnb usage --daily <account> # Daily usage breakdown
|
|
|
115
151
|
mytnb usage --json <account> # Full usage data as JSON
|
|
116
152
|
mytnb current-usage <account> # Simplified current usage summary
|
|
117
153
|
mytnb due-amount <account> # Outstanding balance
|
|
118
|
-
mytnb bill-history <account> #
|
|
154
|
+
mytnb bill-history <account> # Bill history (bills issued)
|
|
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)
|
|
119
158
|
```
|
|
120
159
|
|
|
121
160
|
Global options: `--debug` for full tracebacks, `--version`.
|
|
@@ -140,17 +179,21 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
|
|
|
140
179
|
|
|
141
180
|
## Data Models
|
|
142
181
|
|
|
143
|
-
| Model
|
|
144
|
-
|
|
|
145
|
-
| `CustomerAccount`
|
|
146
|
-
| `AccountUsage`
|
|
147
|
-
| `UsageMetric`
|
|
148
|
-
| `CostMetric`
|
|
149
|
-
| `BillingMonth`
|
|
150
|
-
| `DailyUsage`
|
|
151
|
-
| `TariffBlock`
|
|
152
|
-
| `
|
|
153
|
-
| `
|
|
182
|
+
| Model | Description |
|
|
183
|
+
| --------------------- | ---------------------------------------------------- |
|
|
184
|
+
| `CustomerAccount` | Linked account: number, owner, address, SMR status |
|
|
185
|
+
| `AccountUsage` | Full usage response: metrics, monthly and daily data |
|
|
186
|
+
| `UsageMetric` | Current/average usage (kWh) |
|
|
187
|
+
| `CostMetric` | Current/projected cost (RM) |
|
|
188
|
+
| `BillingMonth` | Monthly billing record with tariff blocks |
|
|
189
|
+
| `DailyUsage` | Daily consumption and cost |
|
|
190
|
+
| `TariffBlock` | Tariff pricing block details |
|
|
191
|
+
| `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
|
|
192
|
+
| `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
|
|
193
|
+
| `AccountDueAmount` | Outstanding balance and due date |
|
|
194
|
+
| `MeterReading` | One meter register's readings from a bill PDF |
|
|
195
|
+
| `SMRAccount` | Smart Meter Reading eligibility status |
|
|
196
|
+
| `BREligibility` | Bill rendering opt-in status |
|
|
154
197
|
|
|
155
198
|
## Geographic Restrictions
|
|
156
199
|
|
|
@@ -39,13 +39,46 @@ async def main():
|
|
|
39
39
|
for month in usage.by_month.months:
|
|
40
40
|
print(f"{month.month} {month.year}: {month.usage_total} kWh — RM {month.amount_total}")
|
|
41
41
|
|
|
42
|
-
# Bill history & due amount
|
|
42
|
+
# Bill history, payment history & due amount
|
|
43
43
|
history = await client.get_bill_history("220123456789")
|
|
44
|
+
payments = await client.get_payment_history("220123456789")
|
|
44
45
|
due = await client.get_account_due_amount("220123456789")
|
|
45
46
|
|
|
47
|
+
# Most account-scoped methods also accept a CustomerAccount directly
|
|
48
|
+
# (is_owner and account_type are derived automatically)
|
|
49
|
+
for acc in accounts:
|
|
50
|
+
if acc.is_smart_meter:
|
|
51
|
+
usage = await client.get_account_usage_smart(acc)
|
|
52
|
+
|
|
46
53
|
asyncio.run(main())
|
|
47
54
|
```
|
|
48
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
|
+
|
|
49
82
|
## CLI
|
|
50
83
|
|
|
51
84
|
The `mytnb` command-line tool requires the optional `cli` extra (it pulls in
|
|
@@ -81,7 +114,10 @@ mytnb usage --daily <account> # Daily usage breakdown
|
|
|
81
114
|
mytnb usage --json <account> # Full usage data as JSON
|
|
82
115
|
mytnb current-usage <account> # Simplified current usage summary
|
|
83
116
|
mytnb due-amount <account> # Outstanding balance
|
|
84
|
-
mytnb bill-history <account> #
|
|
117
|
+
mytnb bill-history <account> # Bill history (bills issued)
|
|
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)
|
|
85
121
|
```
|
|
86
122
|
|
|
87
123
|
Global options: `--debug` for full tracebacks, `--version`.
|
|
@@ -106,17 +142,21 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
|
|
|
106
142
|
|
|
107
143
|
## Data Models
|
|
108
144
|
|
|
109
|
-
| Model
|
|
110
|
-
|
|
|
111
|
-
| `CustomerAccount`
|
|
112
|
-
| `AccountUsage`
|
|
113
|
-
| `UsageMetric`
|
|
114
|
-
| `CostMetric`
|
|
115
|
-
| `BillingMonth`
|
|
116
|
-
| `DailyUsage`
|
|
117
|
-
| `TariffBlock`
|
|
118
|
-
| `
|
|
119
|
-
| `
|
|
145
|
+
| Model | Description |
|
|
146
|
+
| --------------------- | ---------------------------------------------------- |
|
|
147
|
+
| `CustomerAccount` | Linked account: number, owner, address, SMR status |
|
|
148
|
+
| `AccountUsage` | Full usage response: metrics, monthly and daily data |
|
|
149
|
+
| `UsageMetric` | Current/average usage (kWh) |
|
|
150
|
+
| `CostMetric` | Current/projected cost (RM) |
|
|
151
|
+
| `BillingMonth` | Monthly billing record with tariff blocks |
|
|
152
|
+
| `DailyUsage` | Daily consumption and cost |
|
|
153
|
+
| `TariffBlock` | Tariff pricing block details |
|
|
154
|
+
| `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
|
|
155
|
+
| `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
|
|
156
|
+
| `AccountDueAmount` | Outstanding balance and due date |
|
|
157
|
+
| `MeterReading` | One meter register's readings from a bill PDF |
|
|
158
|
+
| `SMRAccount` | Smart Meter Reading eligibility status |
|
|
159
|
+
| `BREligibility` | Bill rendering opt-in status |
|
|
120
160
|
|
|
121
161
|
## Geographic Restrictions
|
|
122
162
|
|
|
@@ -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,7 +10,9 @@ from mytnb.models import (
|
|
|
10
10
|
CostMetric,
|
|
11
11
|
CustomerAccount,
|
|
12
12
|
DailyUsage,
|
|
13
|
+
MeterReading,
|
|
13
14
|
Metric,
|
|
15
|
+
PaymentHistoryEntry,
|
|
14
16
|
TariffBlock,
|
|
15
17
|
TariffBlockLegendGroup,
|
|
16
18
|
TariffBlockLegendItem,
|
|
@@ -28,7 +30,9 @@ __all__ = [
|
|
|
28
30
|
"CostMetric",
|
|
29
31
|
"CustomerAccount",
|
|
30
32
|
"DailyUsage",
|
|
33
|
+
"MeterReading",
|
|
31
34
|
"Metric",
|
|
35
|
+
"PaymentHistoryEntry",
|
|
32
36
|
"TariffBlock",
|
|
33
37
|
"TariffBlockLegendGroup",
|
|
34
38
|
"TariffBlockLegendItem",
|
|
@@ -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
|
|
|
@@ -313,7 +314,7 @@ def due_amount(ctx, account, as_json):
|
|
|
313
314
|
@click.option("--json", "as_json", is_flag=True, help="Output full JSON.")
|
|
314
315
|
@click.pass_context
|
|
315
316
|
def bill_history(ctx, account, as_json):
|
|
316
|
-
"""Get bill
|
|
317
|
+
"""Get bill history (bills issued)."""
|
|
317
318
|
|
|
318
319
|
async def _history():
|
|
319
320
|
client = await _get_client(ctx)
|
|
@@ -340,6 +341,112 @@ def bill_history(ctx, account, as_json):
|
|
|
340
341
|
_run_async(_history())
|
|
341
342
|
|
|
342
343
|
|
|
344
|
+
@cli.command("payment-history")
|
|
345
|
+
@click.argument("account")
|
|
346
|
+
@click.option("--json", "as_json", is_flag=True, help="Output full JSON.")
|
|
347
|
+
@click.pass_context
|
|
348
|
+
def payment_history(ctx, account, as_json):
|
|
349
|
+
"""Get bill & payment history."""
|
|
350
|
+
|
|
351
|
+
async def _history():
|
|
352
|
+
client = await _get_client(ctx)
|
|
353
|
+
async with client:
|
|
354
|
+
with console.status("[bold green]Fetching..."):
|
|
355
|
+
result = await client.get_payment_history(account)
|
|
356
|
+
|
|
357
|
+
if as_json:
|
|
358
|
+
_print_json(result)
|
|
359
|
+
return
|
|
360
|
+
|
|
361
|
+
table = Table(title=f"Bill & Payment History — {account}")
|
|
362
|
+
table.add_column("Date", style="cyan")
|
|
363
|
+
table.add_column("Type")
|
|
364
|
+
table.add_column("Amount (RM)", justify="right", style="green")
|
|
365
|
+
table.add_column("Method / Ref")
|
|
366
|
+
for entry in result:
|
|
367
|
+
style = "green" if entry.is_payment else "red"
|
|
368
|
+
table.add_row(
|
|
369
|
+
entry.date.isoformat() if entry.date else "--",
|
|
370
|
+
entry.history_type_text or entry.history_type or "--",
|
|
371
|
+
f"[{style}]--[/{style}]" if entry.amount is None
|
|
372
|
+
else f"[{style}]{entry.amount:,.2f}[/{style}]",
|
|
373
|
+
entry.paid_via or entry.reference_number or "--",
|
|
374
|
+
)
|
|
375
|
+
console.print(table)
|
|
376
|
+
|
|
377
|
+
_run_async(_history())
|
|
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
|
+
|
|
343
450
|
@cli.command("init-config")
|
|
344
451
|
@click.option("-o", "--output", default="mytnb.json", help="Output path.")
|
|
345
452
|
def init_config(output):
|