naturgy-cli 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Naturgy CLI contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,431 @@
1
+ Metadata-Version: 2.4
2
+ Name: naturgy-cli
3
+ Version: 0.1.0
4
+ Summary: JSON-first CLI for your own Naturgy España (Omega) account
5
+ Keywords: naturgy,naturgy-espana,omega,luz,gas,cli,json
6
+ Author: Naturgy CLI contributors
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: POSIX
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Utilities
21
+ Requires-Dist: httpx>=0.28.1
22
+ Requires-Dist: pydantic>=2.9
23
+ Requires-Dist: typer>=0.15
24
+ Requires-Python: >=3.12
25
+ Project-URL: Homepage, https://github.com/Jotis86/naturgy_cli
26
+ Project-URL: Source, https://github.com/Jotis86/naturgy_cli
27
+ Project-URL: Issues, https://github.com/Jotis86/naturgy_cli/issues
28
+ Project-URL: Security, https://github.com/Jotis86/naturgy_cli/security/advisories/new
29
+ Description-Content-Type: text/markdown
30
+
31
+ # naturgy-cli
32
+
33
+ A JSON-first command-line client for **your own** Naturgy España account, over the Área Clientes
34
+ "Omega" API (`omegav2.naturgy.es`). It talks directly to Naturgy's REST API over HTTPS, so no
35
+ browser is needed at runtime. Its JSON output is meant for scripts and coding agents.
36
+
37
+ > This is an unofficial client of an undocumented API. It is not affiliated with or endorsed by
38
+ > Naturgy. Use it only with your own account. Naturgy's terms of service may restrict automated
39
+ > access; you are responsible for how you use it.
40
+
41
+ ## Features
42
+
43
+ | Command | Description | Status |
44
+ | --- | --- | --- |
45
+ | `naturgy auth login` | Sign in with NIF/NIE + password and save the session | ✅ |
46
+ | `naturgy auth status` | Token expiry, account and optional live check | ✅ |
47
+ | `naturgy auth logout` | Revoke the session (best effort) and delete the local session | ✅ |
48
+ | `naturgy auth import` | Import a browser `sessionStorage` token export | ✅ |
49
+ | `naturgy me` | Holder, contacts, preferred contact and permissions | ✅ |
50
+ | `naturgy supplies` | Supplies, contracts, CUPS, addresses, billing accounts, rates | ✅ |
51
+ | `naturgy consumption` | Electricity, gas and solar consumption series | ✅ |
52
+ | `naturgy readings` | Meter readings per contract | ✅ |
53
+ | `naturgy invoices list` | Invoices across supplies, newest first | ✅ |
54
+ | `naturgy invoices show` | Detail for one invoice | ✅ |
55
+ | `naturgy invoices download` | Invoice PDFs: one, the latest, or all | ✅ |
56
+ | `naturgy debt` | Pending invoices and other debt | ✅ |
57
+ | `naturgy cases` | Claims and cases already filed with Naturgy | ✅ |
58
+ | `naturgy battery status` | Virtual battery balance, mode and activation dates | ✅ |
59
+ | `naturgy battery history` | Virtual battery movements (charges, discharges, expirations) | ✅ |
60
+ | `naturgy battery evolution` | Monthly evolution of the virtual battery balance | ✅ |
61
+ | `naturgy battery assignments` | Balance assigned per supply point | ✅ |
62
+ | `naturgy invoices claim` | File a bill review (**sends a claim**, after confirmation) | ✅ |
63
+
64
+ Everything is read-only except `naturgy invoices claim`.
65
+
66
+ ## Requirements
67
+
68
+ - A Naturgy España residential account you can log in to at <https://omegav2.naturgy.es>
69
+ - macOS or Linux
70
+ - Python 3.12+ and [uv](https://docs.astral.sh/uv/)
71
+
72
+ ## Installation
73
+
74
+ From a checkout (recommended while the API mapping is being validated):
75
+
76
+ ```bash
77
+ git clone https://github.com/Jotis86/naturgy_cli.git
78
+ cd naturgy-cli
79
+ ./scripts/sync.sh # uv sync + repair the macOS editable .pth
80
+ ./scripts/run.sh --help # development: live code, no editable .pth needed
81
+ # optional: install this checkout as a tool (a regular wheel, no editable .pth)
82
+ uv tool install .
83
+ ```
84
+
85
+ To install the CLI without a checkout, let uv build a wheel straight from the repository:
86
+
87
+ ```bash
88
+ uv tool install git+https://github.com/Jotis86/naturgy_cli.git
89
+ ```
90
+
91
+ `scripts/run.sh` puts `src/` on `PYTHONPATH` and runs `python -m naturgy`, so code changes apply
92
+ immediately. `scripts/sync.sh` is `uv sync` plus `scripts/fix-venv.sh`, which clears the macOS
93
+ `hidden` flag from the venv so `uv run naturgy` also works. For daily use, `uv tool install .` is
94
+ the most robust option: it installs a wheel and never depends on an editable `.pth`.
95
+
96
+ ### `ModuleNotFoundError: No module named 'naturgy'` after `uv sync`
97
+
98
+ This is a macOS/Python 3.12 issue with editable installs, not a CLI bug. The editable install is a
99
+ `.pth` file, and Python 3.12+ skips `.pth` files marked hidden (`UF_HIDDEN`). `PYTHONPATH=src` and
100
+ `scripts/run.sh` bypass it, which is why the CLI works when launched that way.
101
+
102
+ Repair the current venv:
103
+
104
+ ```bash
105
+ ./scripts/fix-venv.sh
106
+ # manual equivalent:
107
+ ls -lO .venv/lib/python*/site-packages/naturgy_cli.pth
108
+ chflags -R nohidden .venv
109
+ .venv/bin/python -c "import naturgy; print(naturgy.__file__)"
110
+ ```
111
+
112
+ If it comes back after `uv sync`, use `./scripts/sync.sh` instead, or avoid editable installs:
113
+ `uv sync --no-editable` and then `uv run --no-sync naturgy --version`. See
114
+ [astral-sh/uv#16977](https://github.com/astral-sh/uv/issues/16977).
115
+
116
+ ## Authentication
117
+
118
+ ### Sign in
119
+
120
+ ```bash
121
+ naturgy auth login
122
+ ```
123
+
124
+ It prompts for your **NIF/NIE** and password (hidden). It normalizes them the same way the web app
125
+ does: the NIF loses spaces, dots and hyphens and is uppercased, and literal spaces are removed from
126
+ the password. The password is used for one request and is never stored or logged. On success it
127
+ writes the session to the token file.
128
+
129
+ If Naturgy refuses the sign-in, the error includes its code (`PS01` means it does not recognize the
130
+ user; `CG09`/`PS04` mean the NIF or password is not valid; `CG08` means too many attempts).
131
+
132
+ `naturgy auth status` shows the token expiry (decoded from the JWT, offline) and exits `3` when the
133
+ token has expired. `naturgy auth status --check` also calls the API to prove the session works.
134
+
135
+ ### Browser token export
136
+
137
+ If you would rather not type your password into the CLI, log in at <https://omegav2.naturgy.es>,
138
+ open the developer tools and copy the `user` entry from `sessionStorage`, then:
139
+
140
+ ```bash
141
+ naturgy auth import ./session-user.json
142
+ ```
143
+
144
+ The export is the object with `token`, `idToken`, `refreshToken`, `userId`, `clientCode` and
145
+ `roleTypeId`.
146
+
147
+ ### Token file location
148
+
149
+ The CLI looks for the file in this order, and `auth login` writes to the same place:
150
+
151
+ 1. `--tokens PATH`
152
+ 2. `$NATURGY_TOKENS_FILE`
153
+ 3. An existing `./.local-secrets/tokens.json` (a checkout's local session)
154
+ 4. An existing `~/.config/naturgy-cli/tokens.json`, or
155
+ `$XDG_CONFIG_HOME/naturgy-cli/tokens.json`
156
+ 5. A source checkout without a session yet: `./.local-secrets/tokens.json`
157
+ 6. An installed copy without a session yet: `~/.config/naturgy-cli/tokens.json`
158
+
159
+ The file is written atomically with mode `0600`. Concurrent commands hold a lock on
160
+ `tokens.json.lock` while they sign in or write.
161
+
162
+ ### No refresh token
163
+
164
+ Naturgy's Omega API exposes no refresh endpoint (the web app stores a `refreshToken` but never
165
+ exchanges it). When the access token expires you have to sign in again with `naturgy auth login` or
166
+ import a fresh browser token. `naturgy auth status` tells you when that is needed.
167
+
168
+ ## Usage
169
+
170
+ Every command writes JSON to stdout. `--version` and `--help` print plain text. Prompts and errors
171
+ go to stderr, so stdout stays valid JSON.
172
+
173
+ ```bash
174
+ naturgy --version
175
+ naturgy auth login
176
+ naturgy auth status
177
+ naturgy auth status --check
178
+
179
+ naturgy me
180
+ naturgy supplies
181
+ naturgy supplies --supply 1234 # service account, billing ref, contract, CUPS or suffix
182
+
183
+ naturgy consumption # last 12 months, monthly
184
+ naturgy consumption --period day --from 2026-01-01 --to 2026-02-01
185
+ naturgy consumption --family luz --family gas
186
+
187
+ naturgy readings
188
+ naturgy debt
189
+ naturgy cases
190
+
191
+ naturgy battery status
192
+ naturgy battery history --page 1 --limit 20
193
+ naturgy battery evolution --year 2026
194
+ naturgy battery assignments
195
+
196
+ naturgy invoices list
197
+ naturgy invoices show <invoice-id>
198
+ naturgy invoices download # latest PDF into the current directory
199
+ naturgy invoices download all --dir ~/facturas
200
+ naturgy invoices download <invoice-id>
201
+
202
+ naturgy invoices claim latest -m "No reconozco el cargo de 12,40 EUR" --reason wrong-charge
203
+ naturgy invoices claim <invoice-id> -m "..." --attach foto.png --dry-run
204
+ naturgy invoices claim <invoice-id> -m "..." --yes
205
+ naturgy invoices claim <invoice-id> -m "..." --yes --force # only when the open-claim check failed
206
+ ```
207
+
208
+ Global options:
209
+
210
+ - `--tokens PATH`: session file to use.
211
+ - `--supply SELECTOR`: limit to a supply (service account id, billing ref, contract number, CUPS
212
+ or a unique suffix).
213
+ - `--raw`: include the original API object as `source` (debugging; may contain personal data).
214
+ - `--language es`: `x-language` header.
215
+
216
+ ### Output
217
+
218
+ The CLI normalizes the API's camelCase payloads into stable snake_case shapes. Every command has a
219
+ top-level `count` where it returns a list. With `--raw`, the original object is added as `source`.
220
+
221
+ ```json
222
+ // naturgy supplies
223
+ {
224
+ "supplies": [
225
+ {
226
+ "service_account_id": "…",
227
+ "client_id": "…",
228
+ "address": "Calle Ejemplo 1 28001 Madrid",
229
+ "address_details": {"zipCode": "28001", "city": "Madrid"},
230
+ "billing_accounts": [
231
+ {"billing_account_id": "…", "ref_num": "…", "is_direct_payment": true, "iban_masked": "ES12 **** **** 3456", "pay_day": "5", "bill_delivery_method": "online"}
232
+ ],
233
+ "products": [
234
+ {"contract_id": "…", "contract_number": "…", "product_family": "luz", "product_name": "…", "product_code": "…", "status": "03", "is_active": true, "rate": "2.0TD", "cups": "ES…", "powers": {"powerPlain": 4.6, "powerValley": 4.6}, "billing_account_id": "…"}
235
+ ]
236
+ }
237
+ ],
238
+ "count": 1
239
+ }
240
+ ```
241
+
242
+ ```json
243
+ // naturgy invoices list
244
+ {
245
+ "invoices": [
246
+ {
247
+ "invoice_id": "…",
248
+ "type": "NC",
249
+ "status": "03",
250
+ "issued_date": "2026-10-01",
251
+ "billing_date": "2026-10-01",
252
+ "amount": 54.21,
253
+ "pending_amount": 0.0,
254
+ "currency": "EUR",
255
+ "is_pending": false,
256
+ "pdf_document_id": "…",
257
+ "has_pdf": true,
258
+ "service_account_id": "…",
259
+ "billing_account_id": "…",
260
+ "ref_num": "…",
261
+ "product_family": "luz",
262
+ "relations": [{"contract_number": "…", "product_family_id": "luz", "invoice_atr_id": "…"}]
263
+ }
264
+ ],
265
+ "count": 1,
266
+ "is_contingency_mode": false
267
+ }
268
+ ```
269
+
270
+ Invoice PDFs are saved as `factura_YYYY-MM_<id>.pdf`. Existing files are never overwritten; a file
271
+ appears under its final name only when it is complete, and it is written with mode `0600`.
272
+
273
+ `unlimited`/missing numeric values are `null` rather than a made-up zero. Dates are passed through
274
+ as Naturgy sends them (usually ISO `YYYY-MM-DD`).
275
+
276
+ ### Virtual battery
277
+
278
+ `naturgy battery status` reads the current balance, whether the discount mode is automatic and the
279
+ activation dates. `history` lists charges, discharges and expirations one page at a time (`--page`
280
+ starts at 1; `--limit` is 1–100). `evolution --year YYYY` shows the monthly balance by origin, and
281
+ `assignments` shows the balance reserved for each supply point.
282
+
283
+ These commands are read-only. Changing the mode or assigning balance is not exposed. `--supply`
284
+ filters `history` and `assignments` by contract, supply id or address. In `history` the filter
285
+ applies to the requested page, so a supply that only appears on another page will show no results.
286
+
287
+ ```json
288
+ // naturgy battery status
289
+ {
290
+ "balance": 12.34,
291
+ "currency": "EUR",
292
+ "is_active": true,
293
+ "is_automatic": false,
294
+ "date_enabled": "2025-02-03T00:00:00.000Z",
295
+ "date_disabled": null,
296
+ "breakdown": [
297
+ {"code": "01", "total": 12.34, "date_enabled": "2025-02-03T00:00:00.000Z", "date_disabled": null}
298
+ ]
299
+ }
300
+ ```
301
+
302
+ `history` returns `movements` with `concept`, `kind` (`charge`, `discharge`, `expired` or
303
+ `adjustment`), `amount`, `invoice_id`, `contract`, `is_self_consumption` and dates, plus
304
+ `page`/`total_pages`/`total_items`.
305
+
306
+ ### Bill reviews (claims)
307
+
308
+ `naturgy invoices claim TARGET --message TEXT` files a bill review ("Revisa tu factura") about one
309
+ invoice, the same request the web app sends. `TARGET` is an invoice id from `invoices list` or
310
+ `latest`. The message is limited to 4,000 characters.
311
+
312
+ Reasons (`--reason`):
313
+
314
+ | Key | Code | Meaning |
315
+ | --- | --- | --- |
316
+ | `wrong-reading` | 01 | Lectura incorrecta |
317
+ | `wrong-invoice` | 02 | Factura incorrecta |
318
+ | `wrong-charge` | 03 | Cargo incorrecto (default) |
319
+ | `others` | 05 | Otros |
320
+ | `download-invoice` | 06 | Descarga de factura |
321
+ | `sending-invoice` | 07 | Envío de factura |
322
+ | `billed-invoice` | 08 | Factura ya cobrada (contract-level; needs `--supply`) |
323
+
324
+ Attachments (`--attach`, repeatable) must be PNG, JPEG or PDF, up to 2 MB each and 10 MB total.
325
+
326
+ - `--dry-run` runs the read-only checks, prints the exact JSON body (attachment bytes redacted) and
327
+ sends nothing.
328
+ - On a terminal it shows the invoice, reason, attachments and full text, then asks
329
+ `¿Enviar esta reclamación a Naturgy? [s/N]`. Only `s` / `si` / `sí` sends it.
330
+ - Without a terminal it refuses unless `--yes` is passed.
331
+ - A claim is sent once and never retried. If the outcome is uncertain (timeout, 5xx, or a response
332
+ without a ticket), it exits `5` with `outcome_unknown`; run `naturgy cases` before trying again.
333
+ - If the invoice's account already has an open claim, it exits `5` with `claim_already_open` and
334
+ sends nothing.
335
+ - Before sending, it checks `naturgy cases` for an open claim. If that check cannot be completed
336
+ (timeout, 5xx or bot protection), it exits `5` with `claim_check_failed` and sends nothing.
337
+ Pass `--force` to send anyway; a check that *did* confirm an open claim still blocks.
338
+
339
+ ## Errors and exit codes
340
+
341
+ Errors go to stderr as JSON:
342
+
343
+ ```json
344
+ {"error":{"type":"auth_expired","message":"not signed in: run `naturgy auth login`","exit_code":3}}
345
+ ```
346
+
347
+ | Exit code | Types | Meaning |
348
+ | --- | --- | --- |
349
+ | 0 | | Success |
350
+ | 1 | `internal` | Unexpected error (only the exception type is reported) |
351
+ | 2 | `usage` | Invalid arguments, dates, reasons or attachments |
352
+ | 2 | `cancelled` | The claim was not confirmed; nothing was sent |
353
+ | 3 | `auth_expired` | Not signed in, or the session expired/was rejected |
354
+ | 3 | `login_failed` | Sign-in refused (NIF/password or another check); the `code` says which |
355
+ | 3 | `access_denied` | That account or supply was refused, not the session |
356
+ | 5 | `blocked`, `upstream_unavailable` | Bot protection, rate limit, timeout or Naturgy 5xx |
357
+ | 5 | `claim_already_open` | The invoice's account already has an open claim; nothing was sent |
358
+ | 5 | `claim_check_failed` | The open-claim check failed; nothing was sent (use `--force` to send anyway) |
359
+ | 5 | `outcome_unknown` | A claim may or may not have been filed; check `naturgy cases` |
360
+ | 7 | `api_changed` | Unexpected status or response shape; the API probably changed |
361
+
362
+ Requests are sent one at a time with a short delay and are never retried automatically. A claim
363
+ checks `naturgy cases` before sending; the initial `/clients` lookup scopes the session.
364
+
365
+ ## Limitations
366
+
367
+ - The API is undocumented and may change without notice. `--raw` and `scripts/probe.py` exist to
368
+ make the mapping easy to update.
369
+ - The API requires a W3C `traceparent` header and the account/contact ids that `/authorization`
370
+ returns; the CLI generates the header and fetches the ids after login. A `403`, `429` or an empty
371
+ `200` is still reported as `blocked` (exit 5).
372
+ - There is no token refresh; see above.
373
+ - `readings` passes through what Naturgy returns. For some accounts `readingDetailList` is `null`,
374
+ so `items` is an empty list; that is the API's answer, not a CLI error.
375
+ - The client document number and tokens are sensitive. The token file is `0600` and values are
376
+ never printed. Output may contain personal data (names, addresses, CUPS, invoice ids); do not
377
+ commit it. `--raw` may include the full IBAN; the normalized output masks it.
378
+ - This project is not affiliated with Naturgy.
379
+
380
+ ## Development
381
+
382
+ ```bash
383
+ ./scripts/sync.sh # uv sync + the macOS editable-install repair
384
+ ./scripts/check.sh # ruff + pytest with coverage
385
+ uv run --no-sync pytest # tests only
386
+ ```
387
+
388
+ The tests are offline and use synthetic fixtures. Live read-only tests are opt-in:
389
+
390
+ ```bash
391
+ NATURGY_LIVE=1 uv run --no-sync pytest -m live
392
+ ```
393
+
394
+ ### Discovery probe
395
+
396
+ To validate the wire shapes against a real account without sharing personal data:
397
+
398
+ ```bash
399
+ ./scripts/run.sh auth login # once; saves .local-secrets/tokens.json
400
+ uv run python scripts/probe.py # reuses that session
401
+ ```
402
+
403
+ If there is no usable session it prompts for NIF/NIE and password once. `--save-tokens` also saves
404
+ the session in that case. The probe calls the read-only endpoints and writes
405
+ `.local-secrets/shapes.json` with **only keys, types, array lengths and sample shapes**. It never
406
+ sends a claim, never stores the password and never prints a token. The file is gitignored and mode
407
+ `0600`.
408
+
409
+ ```
410
+ src/naturgy/
411
+ cli.py Typer app: commands and exit codes
412
+ auth.py sign-in, status, logout, browser token import
413
+ client.py OmegaClient: headers, pacing, error mapping, WAF detection
414
+ api.py read operations, battery, normalization, PDFs and claims
415
+ models.py token-set model
416
+ output.py JSON rendering
417
+ tokens.py token file, lock, JWT expiry
418
+ errors.py typed errors and exit codes
419
+ config.py hosts, headers, token-file lookup
420
+ scripts/
421
+ run.sh run this checkout with src/ on PYTHONPATH
422
+ check.sh ruff + pytest with coverage
423
+ sync.sh uv sync + fix the macOS editable .pth
424
+ fix-venv.sh clear hidden flags and verify `import naturgy`
425
+ probe.py read-only shape discovery
426
+ tests/ offline unit tests and opt-in live tests
427
+ ```
428
+
429
+ ## License
430
+
431
+ MIT. See [LICENSE](LICENSE).