leancpms-cli 0.1.2__tar.gz → 0.1.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: leancpms-cli
3
- Version: 0.1.2
3
+ Version: 0.1.4
4
4
  Summary: The cpms command alone: a client of a LeanCPMS instance's JSON API
5
5
  License-Expression: AGPL-3.0-or-later
6
6
  License-File: LICENSE
@@ -13,7 +13,7 @@ Description-Content-Type: text/markdown
13
13
  # `cpms`, the LeanCPMS command line
14
14
 
15
15
  `cpms` manages an organization in a LeanCPMS instance from your own
16
- machine: live state, sessions, the monthly statement, and the declared
16
+ machine: live state, sessions, the monthly settlements, and the declared
17
17
  state (organization, price list, sites) as YAML documents you can keep in
18
18
  a git repository. It talks to the instance's JSON API over HTTPS with an
19
19
  API key, and the same commands work for people and for AI agents.
@@ -34,8 +34,8 @@ Until then, from a GitHub release (a tag `cli-v<version>`) or straight
34
34
  from the repository:
35
35
 
36
36
  ```bash
37
- gh release download cli-v0.1.2 --repo forsslund/leancpms --pattern '*.whl'
38
- uv tool install ./leancpms_cli-0.1.2-py3-none-any.whl
37
+ gh release download cli-v0.1.4 --repo forsslund/leancpms --pattern '*.whl'
38
+ uv tool install ./leancpms_cli-0.1.4-py3-none-any.whl
39
39
  # or
40
40
  uv tool install "git+https://github.com/forsslund/leancpms#subdirectory=cli"
41
41
  ```
@@ -113,7 +113,7 @@ A networked command that has neither exits 2 and says what to set.
113
113
  ```bash
114
114
  cpms # live state: sites, fuse groups, outlets, current per phase
115
115
  cpms sessions --since 2026-10-01
116
- cpms report statement --month 2026-10 # receipts incl./excl. VAT, sessions without one
116
+ cpms report settlements --month 2026-10 # the month's settlements per site, with bookkeeping proposals
117
117
  cpms manifest export kvartersel > all.yaml
118
118
  cpms manifest export kvartersel --site odalvagen > sites/odalvagen.yaml
119
119
  cpms manifest validate sites/odalvagen.yaml # offline: the schema
@@ -194,7 +194,7 @@ Raise `version` in both `cli/pyproject.toml` and the root `pyproject.toml`
194
194
  (a test keeps them equal), then tag and push:
195
195
 
196
196
  ```bash
197
- git tag cli-v0.1.2 && git push origin cli-v0.1.2
197
+ git tag cli-v0.1.4 && git push origin cli-v0.1.4
198
198
  ```
199
199
 
200
200
  `.github/workflows/release-cli.yml` builds the wheel and sdist, smoke-tests
@@ -1,7 +1,7 @@
1
1
  # `cpms`, the LeanCPMS command line
2
2
 
3
3
  `cpms` manages an organization in a LeanCPMS instance from your own
4
- machine: live state, sessions, the monthly statement, and the declared
4
+ machine: live state, sessions, the monthly settlements, and the declared
5
5
  state (organization, price list, sites) as YAML documents you can keep in
6
6
  a git repository. It talks to the instance's JSON API over HTTPS with an
7
7
  API key, and the same commands work for people and for AI agents.
@@ -22,8 +22,8 @@ Until then, from a GitHub release (a tag `cli-v<version>`) or straight
22
22
  from the repository:
23
23
 
24
24
  ```bash
25
- gh release download cli-v0.1.2 --repo forsslund/leancpms --pattern '*.whl'
26
- uv tool install ./leancpms_cli-0.1.2-py3-none-any.whl
25
+ gh release download cli-v0.1.4 --repo forsslund/leancpms --pattern '*.whl'
26
+ uv tool install ./leancpms_cli-0.1.4-py3-none-any.whl
27
27
  # or
28
28
  uv tool install "git+https://github.com/forsslund/leancpms#subdirectory=cli"
29
29
  ```
@@ -101,7 +101,7 @@ A networked command that has neither exits 2 and says what to set.
101
101
  ```bash
102
102
  cpms # live state: sites, fuse groups, outlets, current per phase
103
103
  cpms sessions --since 2026-10-01
104
- cpms report statement --month 2026-10 # receipts incl./excl. VAT, sessions without one
104
+ cpms report settlements --month 2026-10 # the month's settlements per site, with bookkeeping proposals
105
105
  cpms manifest export kvartersel > all.yaml
106
106
  cpms manifest export kvartersel --site odalvagen > sites/odalvagen.yaml
107
107
  cpms manifest validate sites/odalvagen.yaml # offline: the schema
@@ -182,7 +182,7 @@ Raise `version` in both `cli/pyproject.toml` and the root `pyproject.toml`
182
182
  (a test keeps them equal), then tag and push:
183
183
 
184
184
  ```bash
185
- git tag cli-v0.1.2 && git push origin cli-v0.1.2
185
+ git tag cli-v0.1.4 && git push origin cli-v0.1.4
186
186
  ```
187
187
 
188
188
  `.github/workflows/release-cli.yml` builds the wheel and sdist, smoke-tests
@@ -12,10 +12,8 @@ import csv
12
12
  import json
13
13
  import os
14
14
  import sys
15
- from datetime import datetime
16
15
  from pathlib import Path
17
16
  from typing import Any, Callable
18
- from zoneinfo import ZoneInfo
19
17
 
20
18
  from cpms.manifest.documents import ManifestError, diff, json_schema, parse_yaml, to_data, to_yaml
21
19
 
@@ -241,72 +239,79 @@ def cmd_events(api: Api, a: argparse.Namespace) -> int:
241
239
  # --- reports -------------------------------------------------------------------------------
242
240
 
243
241
 
244
- _RECEIPT_FIGURES = ["SESSIONS", "KWH (RECEIPTS)", "INCL VAT", "EXCL VAT", "VAT"]
245
- _SESSION_FIGURES = ["SESSIONS", "KWH (SESSIONS)"]
242
+ def _kwh(wh: int | None) -> str:
243
+ return "" if wh is None else f"{wh / 1000:.3f}"
246
244
 
247
245
 
248
- def _figures(f: dict[str, Any], receipts: bool) -> list[Any]:
249
- if not receipts:
250
- return [f["sessions"], f["kwh"]]
251
- return [f["sessions"], f["kwh_on_receipts"], f["amount_incl_vat"], f["amount_excl_vat"], f["vat_amount"]]
252
-
253
-
254
- def _local(ts: str, tz: str) -> str:
255
- """An ISO time with offset as local wall time, for people only."""
256
- return datetime.fromisoformat(ts).astimezone(ZoneInfo(tz)).strftime("%Y-%m-%d %H:%M")
257
-
258
-
259
- def _statement_part(part: dict[str, Any], receipts: bool) -> None:
260
- label = "collected_by" if receipts else "reason"
261
- figs = _RECEIPT_FIGURES if receipts else _SESSION_FIGURES
262
- lines, cps, sites = [], [], []
263
- for site in part["sites"]:
264
- sites.append([site["key"], site["name"], *_figures(site, receipts)])
265
- for cp in site["charge_points"]:
266
- cps.append([site["key"], cp["key"], cp["ocpp_id"], *_figures(cp, receipts)])
267
- for o in cp["outlets"]:
268
- for x in o["by_channel"]:
269
- lines.append([site["key"], cp["key"], o["key"], x["channel"], x[label],
270
- *_figures(x, receipts)])
271
- table(lines, ["SITE", "CP", "OUTLET", "CHANNEL", label.replace("_", " ").upper(), *figs], right=5)
272
- if receipts:
273
- _print()
274
- table(cps, ["SITE", "CP", "OCPP ID", *figs], right=3)
275
- _print()
276
- table(sites, ["SITE", "NAME", *figs], right=2)
277
- _print()
278
- table([[x["channel"], x[label], *_figures(x, receipts)] for x in part["by_channel"]]
279
- + [["total", "", *_figures(part, receipts)]], ["CHANNEL", label.replace("_", " ").upper(), *figs], right=2)
246
+ def _bookkeeping(s: dict[str, Any]) -> None:
247
+ """A settlement's bookkeeping proposals: account, what it is, project, debit, credit."""
248
+ for v in s["bookkeeping"]:
249
+ when = v["date"] or "on the date of the invoice"
250
+ _print(f"bookkeeping proposal {when}" + (f", {v['kind']}" if v["kind"] in ("accrual", "reversal") else ""))
251
+ if not v["entries"]:
252
+ _print("nothing to book")
253
+ continue
254
+ blank = {"0.00": ""}
255
+ table([[e["account"], e["role"], e["project"], blank.get(e["debit"], e["debit"]),
256
+ blank.get(e["credit"], e["credit"])] for e in v["entries"]] + [["sum", "", "", v["debit"], v["credit"]]],
257
+ ["ACCOUNT", "WHAT", "PROJECT", "DEBIT", "CREDIT"], right=3)
258
+
259
+
260
+ def _settlement(s: dict[str, Any]) -> None:
261
+ """One settlement as the portal's sheet says it: its rows per site, then its bookkeeping proposal."""
262
+ issued = f"issued {s['issued']}" if s["issued"] else "not final"
263
+ if s["kind"] == "billing":
264
+ what = f"roaming invoice basis, {s['partner']}" if s["source"] == "roaming" else f"billing, {s['source']}"
265
+ _print(f"{s['number']} {what}: {s['documents']} {'sessions' if s['source'] == 'roaming' else 'receipts'} ({issued})")
266
+ rows = [[x["project"], x["name"], _kwh(x["wh"]), x["amount_excl_vat"]] for x in s["sites"]]
267
+ rows.append(["sum excl. VAT", "", _kwh(s["wh"]), s["amount_excl_vat"]])
268
+ for v in s["vat"]:
269
+ rate = f" {float(v['rate']) * 100:g} %" if v["rate"] is not None else ""
270
+ rows.append([f"VAT{rate}", "", "", v["amount"]])
271
+ rows.append(["to invoice, incl. VAT" if s["source"] == "roaming" else "sum incl. VAT", "", "", s["amount_incl_vat"]])
272
+ table(rows, ["PROJECT", "SITE", "KWH", "EXCL VAT"], right=2)
273
+ elif s["kind"] == "payment":
274
+ _print(f"{s['number']} payment, {s['provider']} ({issued})")
275
+ table([[u["source"] or "sum", u["unpaid_before_incl_vat"], u["charged_incl_vat"], u["paid_in_incl_vat"],
276
+ u["unpaid_after_incl_vat"], u["difference"]] for u in [*s["unpaid"], s["unpaid_total"]]],
277
+ ["INCL VAT", "UNPAID BEFORE", "CHARGED", "PAID IN", "UNPAID AFTER", "DIFFERENCE"], right=1)
278
+ table([[f["project"], f["name"], f["amount_excl_vat"]] for f in s["fees"]] + [["sum", "", s["fees_excl_vat"]]],
279
+ ["PROJECT", "SITE", "FEE EXCL VAT"], right=2)
280
+ _print(f"reached the balance: {s['reached_balance']}")
281
+ if s["unclassified"]:
282
+ _print("not in this settlement (booked by hand):")
283
+ table([[u["what"], u["count"], u["amount"]] for u in s["unclassified"]], ["BALANCE TRANSACTION", "COUNT", "AMOUNT"],
284
+ right=1)
285
+ if not s["reconciles"]:
286
+ _print(f"DOES NOT RECONCILE: {', '.join(s['problems'])}")
287
+ else:
288
+ _print(f"{s['number']} accrual basis: sessions ended in the month, billed after it ({issued})")
289
+ sources = s["sources"]
290
+ table([[x["project"], x["name"], _kwh(x["wh"]), *(x["by_source_excl_vat"].get(src, "") for src in sources),
291
+ x["amount_excl_vat"]] for x in s["sites"]]
292
+ + [["sum", "", _kwh(s["wh"]), *(s["by_source_excl_vat"][src] for src in sources), s["amount_excl_vat"]]],
293
+ ["PROJECT", "SITE", "KWH", *(src.upper() for src in sources), "EXCL VAT"], right=2)
294
+ _bookkeeping(s)
280
295
 
281
296
 
282
- def cmd_statement(api: Api, a: argparse.Namespace) -> int:
283
- body = api.get("/reports/statement", month=a.month, organization=a.org)
297
+ def cmd_settlements(api: Api, a: argparse.Namespace) -> int:
298
+ body = api.get("/reports/settlements", month=a.month, organization=a.org)
284
299
  if a.json:
285
300
  _dump(body)
286
301
  return 0
287
- p, tz = body["period"], body["period"]["timezone"]
288
- _print(f"Statement {p['month']} {body['organization']} ({body['organization_name']})")
289
- _print(f"{_local(p['from'], tz)} to {_local(p['to'], tz)} {tz}; amounts in {body['currency']}")
290
- _print()
291
- receipts, none = body["receipts"], body["no_receipt"]
292
- _print("Receipts issued in the month (money by document date; kWh is the energy on the receipts, "
293
- "not energy delivered in the month)")
294
- if receipts["sessions"]:
295
- _statement_part(receipts, True)
296
- else:
297
- _print("no receipts")
298
- _print()
299
- _print("No receipt: sessions that ended in the month without one (cancelled, unpaid, or pending capture); "
300
- "no money")
301
- if none["sessions"]:
302
- _statement_part(none, False)
303
- else:
304
- _print("none")
305
- if body["active_sessions"]:
302
+ p = body["period"]
303
+ _print(f"Settlements {p['month']} {body['organization']} ({body['organization_name']}); amounts in {body['currency']}")
304
+ if body["not_final"] == "month_not_ended":
305
+ _print("NOT FINAL: the month has not ended")
306
+ elif body["not_final"]:
307
+ _print(f"NOT FINAL: {', '.join(body['providers_not_read'])} has not been read to the end since the month ended")
308
+ if body["roaming_without_cdr"]:
309
+ _print(f"left out: {body['roaming_without_cdr']} roaming sessions that ended in the month without a CDR yet")
310
+ if body["receipts_without_session"]:
311
+ _print(f"{body['receipts_without_session']} receipts have no session; placed by the site name on the receipt")
312
+ for s in body["settlements"]:
306
313
  _print()
307
- _print(f"{body['active_sessions']} session(s) still active")
308
- for w in body["warnings"]:
309
- _err(f"warning: {w}")
314
+ _settlement(s)
310
315
  return 0
311
316
 
312
317
 
@@ -820,13 +825,14 @@ def parser() -> argparse.ArgumentParser:
820
825
  s.add_argument("--event")
821
826
  s.add_argument("--limit", type=int, default=100)
822
827
 
823
- r = sub.add_parser("report", parents=[common], help="reports: the monthly statement")
828
+ r = sub.add_parser("report", parents=[common], help="reports: the monthly settlements")
824
829
  rsub = r.add_subparsers(dest="report_command", parser_class=_Parser, required=True)
825
- s = rsub.add_parser("statement", parents=[common], help="a month's receipts (incl./excl. VAT) and sessions without one, per site, "
826
- "charge point and outlet",
827
- description="The monthly statement (PRD §6.1), from this system's sessions and ledger.")
828
- s.set_defaults(fn=cmd_statement)
829
- s.add_argument("--month", help="YYYY-MM in the organization's time zone (default: this month so far)")
830
+ s = rsub.add_parser("settlements", parents=[common],
831
+ help="a month's settlements: drop-in, roaming invoice basis, payment provider, accrual basis",
832
+ description="The monthly settlements (PRD §6.1): per site, each with its bookkeeping proposal. "
833
+ "The same figures as the portal's sheets, which are the ones to print.")
834
+ s.set_defaults(fn=cmd_settlements)
835
+ s.add_argument("--month", help="YYYY-MM in the organization's time zone (default: the last month that has ended)")
830
836
  s.add_argument("--org", help="operator: which organization (an organization key knows its own)")
831
837
 
832
838
  m = sub.add_parser("manifest", parents=[common], help="declared state: export, plan, apply, history, diff, validate, schema")
@@ -116,6 +116,27 @@ DriverOrigin = Annotated[
116
116
  ]
117
117
 
118
118
 
119
+ # A ledger account in the organization's bookkeeping, as its chart of accounts writes it.
120
+ Account = Annotated[str, StringConstraints(pattern=r"^[0-9A-Za-z][0-9A-Za-z.-]{0,15}$")]
121
+
122
+
123
+ class BookkeepingAccounts(Strict):
124
+ """The accounts the monthly settlements' bookkeeping proposals name (architecture §8).
125
+
126
+ The defaults are suggestions from the Swedish BAS chart, for the organization's accountant to
127
+ confirm. Revenue has one account per source; the project on each row is the site's key.
128
+ """
129
+
130
+ receivables: Account = "1510"
131
+ accrued_revenue: Account = "1790"
132
+ provider_balance: Account = "1940" # the balance at the payment provider, treated as a bank account
133
+ output_vat: Account = "2611"
134
+ bank_charges: Account = "6570" # the payment provider's fees
135
+ revenue_dropin: Account = "3001"
136
+ revenue_subscription: Account = "3002"
137
+ revenue_roaming: Account = "3003"
138
+
139
+
119
140
  class Organization(Strict):
120
141
  key: OrganizationKey
121
142
  name: str
@@ -134,6 +155,8 @@ class Organization(Strict):
134
155
  # The organization's own driver front ends, on domains of its own: they may call the driver API's
135
156
  # start and session endpoints from a browser, and payment may return to them (architecture §3.1).
136
157
  driver_origins: list[DriverOrigin] = []
158
+ # The accounts in the monthly settlements' bookkeeping proposals; left out, the suggested ones.
159
+ bookkeeping_accounts: BookkeepingAccounts = BookkeepingAccounts()
137
160
 
138
161
  @model_validator(mode="after")
139
162
  def _unique_hosts(self): # type: ignore[no-untyped-def]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "leancpms-cli"
3
- version = "0.1.2"
3
+ version = "0.1.4"
4
4
  description = "The cpms command alone: a client of a LeanCPMS instance's JSON API"
5
5
  readme = "README.md"
6
6
  license = "AGPL-3.0-or-later"
File without changes
File without changes