python-mytnb 0.5.3__tar.gz → 0.5.4__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.
Files changed (28) hide show
  1. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/PKG-INFO +25 -14
  2. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/README.md +24 -13
  3. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/pyproject.toml +1 -1
  4. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/__init__.py +2 -0
  5. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/cli.py +37 -1
  6. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/client/client.py +80 -12
  7. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/models.py +56 -3
  8. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/uv.lock +1 -1
  9. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/.github/workflows/ci.yml +0 -0
  10. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/.github/workflows/publish.yml +0 -0
  11. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/.gitignore +0 -0
  12. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/LICENSE +0 -0
  13. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/__main__.py +0 -0
  14. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/auth.py +0 -0
  15. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/client/__init__.py +0 -0
  16. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/client/auth.py +0 -0
  17. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/client/config.py +0 -0
  18. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/client/legacy.py +0 -0
  19. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/client/rest.py +0 -0
  20. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/client/retry.py +0 -0
  21. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/crypto.py +0 -0
  22. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/src/mytnb/exceptions.py +0 -0
  23. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/tests/test_auth.py +0 -0
  24. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/tests/test_cli.py +0 -0
  25. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/tests/test_client.py +0 -0
  26. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/tests/test_crypto.py +0 -0
  27. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/tests/test_models.py +0 -0
  28. {python_mytnb-0.5.3 → python_mytnb-0.5.4}/tests/test_retry.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-mytnb
3
- Version: 0.5.3
3
+ Version: 0.5.4
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
@@ -73,10 +73,17 @@ async def main():
73
73
  for month in usage.by_month.months:
74
74
  print(f"{month.month} {month.year}: {month.usage_total} kWh — RM {month.amount_total}")
75
75
 
76
- # Bill history & due amount
76
+ # Bill history, payment history & due amount
77
77
  history = await client.get_bill_history("220123456789")
78
+ payments = await client.get_payment_history("220123456789")
78
79
  due = await client.get_account_due_amount("220123456789")
79
80
 
81
+ # Most account-scoped methods also accept a CustomerAccount directly
82
+ # (is_owner and account_type are derived automatically)
83
+ for acc in accounts:
84
+ if acc.is_smart_meter:
85
+ usage = await client.get_account_usage_smart(acc)
86
+
80
87
  asyncio.run(main())
81
88
  ```
82
89
 
@@ -115,7 +122,8 @@ mytnb usage --daily <account> # Daily usage breakdown
115
122
  mytnb usage --json <account> # Full usage data as JSON
116
123
  mytnb current-usage <account> # Simplified current usage summary
117
124
  mytnb due-amount <account> # Outstanding balance
118
- mytnb bill-history <account> # Payment history
125
+ mytnb bill-history <account> # Bill history (bills issued)
126
+ mytnb payment-history <account> # Bill & payment history
119
127
  ```
120
128
 
121
129
  Global options: `--debug` for full tracebacks, `--version`.
@@ -140,17 +148,20 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
140
148
 
141
149
  ## Data Models
142
150
 
143
- | Model | Description |
144
- | ----------------- | ---------------------------------------------------- |
145
- | `CustomerAccount` | Linked account: number, owner, address, SMR status |
146
- | `AccountUsage` | Full usage response: metrics, monthly and daily data |
147
- | `UsageMetric` | Current/average usage (kWh) |
148
- | `CostMetric` | Current/projected cost (RM) |
149
- | `BillingMonth` | Monthly billing record with tariff blocks |
150
- | `DailyUsage` | Daily consumption and cost |
151
- | `TariffBlock` | Tariff pricing block details |
152
- | `SMRAccount` | Smart Meter Reading eligibility status |
153
- | `BREligibility` | Bill rendering opt-in status |
151
+ | Model | Description |
152
+ | --------------------- | ---------------------------------------------------- |
153
+ | `CustomerAccount` | Linked account: number, owner, address, SMR status |
154
+ | `AccountUsage` | Full usage response: metrics, monthly and daily data |
155
+ | `UsageMetric` | Current/average usage (kWh) |
156
+ | `CostMetric` | Current/projected cost (RM) |
157
+ | `BillingMonth` | Monthly billing record with tariff blocks |
158
+ | `DailyUsage` | Daily consumption and cost |
159
+ | `TariffBlock` | Tariff pricing block details |
160
+ | `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
161
+ | `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
162
+ | `AccountDueAmount` | Outstanding balance and due date |
163
+ | `SMRAccount` | Smart Meter Reading eligibility status |
164
+ | `BREligibility` | Bill rendering opt-in status |
154
165
 
155
166
  ## Geographic Restrictions
156
167
 
@@ -39,10 +39,17 @@ 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
 
@@ -81,7 +88,8 @@ mytnb usage --daily <account> # Daily usage breakdown
81
88
  mytnb usage --json <account> # Full usage data as JSON
82
89
  mytnb current-usage <account> # Simplified current usage summary
83
90
  mytnb due-amount <account> # Outstanding balance
84
- mytnb bill-history <account> # Payment history
91
+ mytnb bill-history <account> # Bill history (bills issued)
92
+ mytnb payment-history <account> # Bill & payment history
85
93
  ```
86
94
 
87
95
  Global options: `--debug` for full tracebacks, `--version`.
@@ -106,17 +114,20 @@ Request encryption for the ASMX API is automatic — just pass plaintext paramet
106
114
 
107
115
  ## Data Models
108
116
 
109
- | Model | Description |
110
- | ----------------- | ---------------------------------------------------- |
111
- | `CustomerAccount` | Linked account: number, owner, address, SMR status |
112
- | `AccountUsage` | Full usage response: metrics, monthly and daily data |
113
- | `UsageMetric` | Current/average usage (kWh) |
114
- | `CostMetric` | Current/projected cost (RM) |
115
- | `BillingMonth` | Monthly billing record with tariff blocks |
116
- | `DailyUsage` | Daily consumption and cost |
117
- | `TariffBlock` | Tariff pricing block details |
118
- | `SMRAccount` | Smart Meter Reading eligibility status |
119
- | `BREligibility` | Bill rendering opt-in status |
117
+ | Model | Description |
118
+ | --------------------- | ---------------------------------------------------- |
119
+ | `CustomerAccount` | Linked account: number, owner, address, SMR status |
120
+ | `AccountUsage` | Full usage response: metrics, monthly and daily data |
121
+ | `UsageMetric` | Current/average usage (kWh) |
122
+ | `CostMetric` | Current/projected cost (RM) |
123
+ | `BillingMonth` | Monthly billing record with tariff blocks |
124
+ | `DailyUsage` | Daily consumption and cost |
125
+ | `TariffBlock` | Tariff pricing block details |
126
+ | `BillHistoryEntry` | Single bill issued (date, amount, billing number) |
127
+ | `PaymentHistoryEntry` | Bill or payment entry with type, method, reference |
128
+ | `AccountDueAmount` | Outstanding balance and due date |
129
+ | `SMRAccount` | Smart Meter Reading eligibility status |
130
+ | `BREligibility` | Bill rendering opt-in status |
120
131
 
121
132
  ## Geographic Restrictions
122
133
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "python-mytnb"
7
- version = "0.5.3"
7
+ version = "0.5.4"
8
8
  description = "Python library to interface with the myTNB API (Tenaga Nasional Berhad)"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -11,6 +11,7 @@ from mytnb.models import (
11
11
  CustomerAccount,
12
12
  DailyUsage,
13
13
  Metric,
14
+ PaymentHistoryEntry,
14
15
  TariffBlock,
15
16
  TariffBlockLegendGroup,
16
17
  TariffBlockLegendItem,
@@ -29,6 +30,7 @@ __all__ = [
29
30
  "CustomerAccount",
30
31
  "DailyUsage",
31
32
  "Metric",
33
+ "PaymentHistoryEntry",
32
34
  "TariffBlock",
33
35
  "TariffBlockLegendGroup",
34
36
  "TariffBlockLegendItem",
@@ -313,7 +313,7 @@ def due_amount(ctx, account, as_json):
313
313
  @click.option("--json", "as_json", is_flag=True, help="Output full JSON.")
314
314
  @click.pass_context
315
315
  def bill_history(ctx, account, as_json):
316
- """Get bill payment history."""
316
+ """Get bill history (bills issued)."""
317
317
 
318
318
  async def _history():
319
319
  client = await _get_client(ctx)
@@ -340,6 +340,42 @@ def bill_history(ctx, account, as_json):
340
340
  _run_async(_history())
341
341
 
342
342
 
343
+ @cli.command("payment-history")
344
+ @click.argument("account")
345
+ @click.option("--json", "as_json", is_flag=True, help="Output full JSON.")
346
+ @click.pass_context
347
+ def payment_history(ctx, account, as_json):
348
+ """Get bill & payment history."""
349
+
350
+ async def _history():
351
+ client = await _get_client(ctx)
352
+ async with client:
353
+ with console.status("[bold green]Fetching..."):
354
+ result = await client.get_payment_history(account)
355
+
356
+ if as_json:
357
+ _print_json(result)
358
+ return
359
+
360
+ table = Table(title=f"Bill & Payment History — {account}")
361
+ table.add_column("Date", style="cyan")
362
+ table.add_column("Type")
363
+ table.add_column("Amount (RM)", justify="right", style="green")
364
+ table.add_column("Method / Ref")
365
+ for entry in result:
366
+ style = "green" if entry.is_payment else "red"
367
+ table.add_row(
368
+ entry.date.isoformat() if entry.date else "--",
369
+ entry.history_type_text or entry.history_type or "--",
370
+ f"[{style}]--[/{style}]" if entry.amount is None
371
+ else f"[{style}]{entry.amount:,.2f}[/{style}]",
372
+ entry.paid_via or entry.reference_number or "--",
373
+ )
374
+ console.print(table)
375
+
376
+ _run_async(_history())
377
+
378
+
343
379
  @cli.command("init-config")
344
380
  @click.option("-o", "--output", default="mytnb.json", help="Output path.")
345
381
  def init_config(output):
@@ -21,12 +21,30 @@ from mytnb.models import (
21
21
  BillHistoryEntry,
22
22
  BREligibility,
23
23
  CustomerAccount,
24
+ PaymentHistoryEntry,
24
25
  SMRAccount,
25
26
  )
26
27
 
27
28
  logger = logging.getLogger(__name__)
28
29
 
29
30
 
31
+ def _resolve_account(
32
+ account: str | CustomerAccount,
33
+ is_owner: bool | None = None,
34
+ ) -> tuple[str, bool, str]:
35
+ """Resolve account identifier + metadata from a string or CustomerAccount.
36
+
37
+ Returns ``(account_number, is_owner, account_type)``.
38
+ """
39
+ if isinstance(account, CustomerAccount):
40
+ return (
41
+ account.account_number,
42
+ is_owner if is_owner is not None else account.is_owned_bool,
43
+ "RE" if account.account_category_id == "2" else "UTIL",
44
+ )
45
+ return (account, is_owner if is_owner is not None else True, "UTIL")
46
+
47
+
30
48
  class MyTNBClient:
31
49
  """Client for interacting with the myTNB API.
32
50
 
@@ -163,14 +181,15 @@ class MyTNBClient:
163
181
 
164
182
  async def get_account_usage_smart(
165
183
  self,
166
- account_number: str,
184
+ account: str | CustomerAccount,
167
185
  *,
168
- is_owner: bool = True,
186
+ is_owner: bool | None = None,
169
187
  ) -> AccountUsage:
170
188
  """Get smart meter account usage data."""
189
+ acc_no, owner, _ = _resolve_account(account, is_owner)
171
190
  data = {
172
- "contractAccount": account_number,
173
- "isOwner": "true" if is_owner else "false",
191
+ "contractAccount": acc_no,
192
+ "isOwner": "true" if owner else "false",
174
193
  "metercode": "",
175
194
  "usrInf": self._legacy_transport.base_user_info(),
176
195
  }
@@ -236,14 +255,15 @@ class MyTNBClient:
236
255
 
237
256
  async def get_account_due_amount(
238
257
  self,
239
- account_number: str,
258
+ account: str | CustomerAccount,
240
259
  *,
241
- is_owner: bool = True,
260
+ is_owner: bool | None = None,
242
261
  ) -> AccountDueAmount:
243
262
  """Get account due amount as a typed model."""
263
+ acc_no, owner, _ = _resolve_account(account, is_owner)
244
264
  data = {
245
- "contractAccount": account_number,
246
- "isOwnedAccount": "true" if is_owner else "false",
265
+ "contractAccount": acc_no,
266
+ "isOwnedAccount": "true" if owner else "false",
247
267
  "usrInf": self._legacy_transport.base_user_info(),
248
268
  }
249
269
  result = await self._legacy_transport.post("GetAccountDueAmount", data)
@@ -251,14 +271,15 @@ class MyTNBClient:
251
271
 
252
272
  async def get_bill_history(
253
273
  self,
254
- account_number: str,
274
+ account: str | CustomerAccount,
255
275
  *,
256
- is_owner: bool = True,
276
+ is_owner: bool | None = None,
257
277
  ) -> list[BillHistoryEntry]:
258
278
  """Get bill payment history as typed models (most recent first)."""
279
+ acc_no, owner, _ = _resolve_account(account, is_owner)
259
280
  data = {
260
- "contractAccount": account_number,
261
- "isOwnedAccount": "true" if is_owner else "false",
281
+ "contractAccount": acc_no,
282
+ "isOwnedAccount": "true" if owner else "false",
262
283
  "usrInf": self._legacy_transport.base_user_info(),
263
284
  }
264
285
  result = await self._legacy_transport.post("GetBillHistory", data)
@@ -279,6 +300,53 @@ class MyTNBClient:
279
300
  )
280
301
  return []
281
302
 
303
+ async def get_payment_history(
304
+ self,
305
+ account: str | CustomerAccount,
306
+ *,
307
+ is_owner: bool | None = None,
308
+ account_type: str | None = None,
309
+ ) -> list[PaymentHistoryEntry]:
310
+ """Get bill & payment history as typed models (most recent first).
311
+
312
+ Uses the GetAccountBillPayHistoryV4 endpoint which returns both bills
313
+ and payments. Each entry has a ``history_type`` field ("PAYMENT",
314
+ "BILL", or "ADVICE") so callers can filter as needed.
315
+
316
+ When ``account`` is a ``CustomerAccount``, ``is_owner`` and
317
+ ``account_type`` are derived automatically (unless explicitly
318
+ overridden).
319
+ """
320
+ acc_no, owner, derived_type = _resolve_account(account, is_owner)
321
+ if account_type is None:
322
+ account_type = derived_type
323
+ data = {
324
+ "contractAccount": acc_no,
325
+ "isOwnedAccount": owner,
326
+ "accountType": account_type,
327
+ "usrInf": self._legacy_transport.base_user_info(),
328
+ }
329
+ result = await self._legacy_transport.post(
330
+ "GetAccountBillPayHistoryV4", data
331
+ )
332
+ inner = result.get("data", result)
333
+ histories: list[PaymentHistoryEntry] = []
334
+ if isinstance(inner, dict):
335
+ for group in inner.get("BillPayHistories", []):
336
+ if not isinstance(group, dict):
337
+ continue
338
+ for item in group.get("BillPayHistoryData", []):
339
+ if isinstance(item, dict):
340
+ histories.append(PaymentHistoryEntry.model_validate(item))
341
+ elif isinstance(inner, list):
342
+ for group in inner:
343
+ if not isinstance(group, dict):
344
+ continue
345
+ for item in group.get("BillPayHistoryData", []):
346
+ if isinstance(item, dict):
347
+ histories.append(PaymentHistoryEntry.model_validate(item))
348
+ return histories
349
+
282
350
  async def get_current_usage(self, account_number: str) -> dict:
283
351
  """Get a simplified summary of current usage."""
284
352
  usage = await self.get_account_usage_smart(account_number)
@@ -2,8 +2,9 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  from datetime import date as date_cls
6
- from datetime import datetime
7
+ from datetime import datetime, timezone
7
8
  from typing import Any, Optional
8
9
 
9
10
  from pydantic import AliasChoices, BaseModel, Field, field_validator
@@ -11,9 +12,12 @@ from pydantic import AliasChoices, BaseModel, Field, field_validator
11
12
  # myTNB returns dates as DD/MM/YYYY; keep ISO variants as fallbacks.
12
13
  _API_DATE_FORMATS = ("%d/%m/%Y", "%Y-%m-%d", "%d-%m-%Y")
13
14
 
15
+ # Microsoft JSON date format: /Date(1782921600000)/
16
+ _MS_DATE_RE = re.compile(r"/Date\((\d+)\)/")
17
+
14
18
 
15
19
  def parse_api_date(value: Any) -> Optional[date_cls]:
16
- """Parse a myTNB date string (typically DD/MM/YYYY) into a date.
20
+ """Parse a myTNB date string (DD/MM/YYYY or /Date(ms)/) into a date.
17
21
 
18
22
  Returns None for empty/None/unparseable input so a single bad field never
19
23
  breaks an entire response.
@@ -24,6 +28,15 @@ def parse_api_date(value: Any) -> Optional[date_cls]:
24
28
  return value
25
29
  if not isinstance(value, str) or not value.strip():
26
30
  return None
31
+ # Microsoft /Date(1782921600000)/ format (ms since epoch UTC)
32
+ ms_match = _MS_DATE_RE.fullmatch(value.strip())
33
+ if ms_match:
34
+ try:
35
+ return datetime.fromtimestamp(
36
+ int(ms_match.group(1)) / 1000, tz=timezone.utc
37
+ ).date()
38
+ except (ValueError, OSError):
39
+ return None
27
40
  for fmt in _API_DATE_FORMATS:
28
41
  try:
29
42
  return datetime.strptime(value.strip(), fmt).date()
@@ -436,7 +449,7 @@ class CustomerAccount(BaseModel):
436
449
 
437
450
 
438
451
  class BillHistoryEntry(BaseModel):
439
- """A single bill payment history entry from GetBillHistory.
452
+ """A single bill entry from GetBillHistory (bills *issued*, not payments).
440
453
 
441
454
  Raw shape: {"DtBill": "31/05/2026", "AmPayable": "87.50", "BillingNo": "12345"}
442
455
  """
@@ -463,6 +476,46 @@ class BillHistoryEntry(BaseModel):
463
476
  return "" if v is None else str(v)
464
477
 
465
478
 
479
+ class PaymentHistoryEntry(BaseModel):
480
+ """A single payment-or-bill entry from GetAccountBillPayHistoryV4.
481
+
482
+ Raw shape:
483
+ {"BillOrPaymentDate":"15/01/2026","HistoryType":"Payment","Amount":"100.50",…}
484
+ """
485
+
486
+ date: Optional[date_cls] = Field(default=None, alias="BillOrPaymentDate")
487
+ history_type: str = Field(default="", alias="HistoryType")
488
+ date_and_history_type: str = Field(default="", alias="DateAndHistoryType")
489
+ amount: Optional[float] = Field(default=None, alias="Amount")
490
+ reference_number: str = Field(default="", alias="DetailedInfoNumber")
491
+ paid_via: str = Field(default="", alias="PaidVia")
492
+ history_type_text: str = Field(default="", alias="HistoryTypeText")
493
+ is_payment_pending: bool = Field(default=False, alias="IsPaymentPending")
494
+
495
+ model_config = {"populate_by_name": True, "extra": "ignore"}
496
+
497
+ @field_validator("date", mode="before")
498
+ @classmethod
499
+ def _parse_date(cls, v: Any) -> Optional[date_cls]:
500
+ return parse_api_date(v)
501
+
502
+ @field_validator("amount", mode="before")
503
+ @classmethod
504
+ def _parse_amount(cls, v: Any) -> Optional[float]:
505
+ return _parse_optional_float(v)
506
+
507
+ @field_validator("history_type", "date_and_history_type", "reference_number",
508
+ "paid_via", "history_type_text", mode="before")
509
+ @classmethod
510
+ def _coerce_str(cls, v: Any) -> str:
511
+ return "" if v is None else str(v)
512
+
513
+ @property
514
+ def is_payment(self) -> bool:
515
+ """True when this entry is a payment (not a bill or advice)."""
516
+ return self.history_type.upper() == "PAYMENT" # pylint: disable=no-member
517
+
518
+
466
519
  class AccountDueAmount(BaseModel):
467
520
  """Outstanding balance for an account from GetAccountDueAmount.
468
521
 
@@ -600,7 +600,7 @@ wheels = [
600
600
 
601
601
  [[package]]
602
602
  name = "python-mytnb"
603
- version = "0.5.3"
603
+ version = "0.5.4"
604
604
  source = { editable = "." }
605
605
  dependencies = [
606
606
  { name = "cryptography" },
File without changes
File without changes