edupsyadmin 10.2.1__tar.gz → 10.3.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.
Files changed (100) hide show
  1. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/PKG-INFO +19 -1
  2. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/README.md +18 -0
  3. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/pyproject.toml +1 -1
  4. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/pyproject.toml.orig +1 -1
  5. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/__version__.py +1 -1
  6. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/fill_form.py +1 -1
  7. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/managers.py +157 -98
  8. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/get_clients.py +5 -0
  9. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/new_client.py +128 -91
  10. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/tui.py +4 -0
  11. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/clients_overview.py +3 -0
  12. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/clients_overview_app.py +3 -0
  13. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/edupsyadmintui.py +2 -0
  14. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/__init__.py +0 -0
  15. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/__main__.py +0 -0
  16. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/README +0 -0
  17. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/env.py +0 -0
  18. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/script.py.mako +0 -0
  19. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_02_21_0453-4087c43f0c7c_initial_migration.py +0 -0
  20. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_03_02_1222-635a9d68fbe8_add_case_active_column_to_clients.py +0 -0
  21. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_03_13_0545-ea4c3f900604_encrypt_class_columns.py +0 -0
  22. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_03_13_0620-515a72d06f10_encrypt_derived_dates.py +0 -0
  23. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_03_16_0900-d7e8f9a0b1c2_add_metadata_table.py +0 -0
  24. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_03_23_1030-e2b4c6d8f0a1_encrypt_sensitive_text_fields.py +0 -0
  25. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_04_10_1200-f3a5b7c9d1e2_set_encrypted_text_fields_non_nullable.py +0 -0
  26. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_06_12_0509-0f1497df963e_add_class_int_override.py +0 -0
  27. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic/versions/2026_09_09_1057-91edbee23274_add_record_academic_year.py +0 -0
  28. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/alembic.ini +0 -0
  29. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/__init__.py +0 -0
  30. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/cft_report.py +0 -0
  31. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/client_view.py +0 -0
  32. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/display_client_details.py +0 -0
  33. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/exceptions.py +0 -0
  34. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/flatten_pdf.py +0 -0
  35. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/flattening/__init__.py +0 -0
  36. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/flattening/api.py +0 -0
  37. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/flattening/base.py +0 -0
  38. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/flattening/pypdf_backend.py +0 -0
  39. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/lgvt.py +0 -0
  40. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/migration.py +0 -0
  41. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/migration_fs.py +0 -0
  42. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/reports.py +0 -0
  43. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/setup_demo.py +0 -0
  44. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/taetigkeitsbericht_from_db.py +0 -0
  45. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/api/types.py +0 -0
  46. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/__init__.py +0 -0
  47. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/__main__.py +0 -0
  48. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/check_shredding.py +0 -0
  49. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/copy_client.py +0 -0
  50. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/create_documentation.py +0 -0
  51. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/delete_client.py +0 -0
  52. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/edit_config.py +0 -0
  53. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/flatten_pdfs.py +0 -0
  54. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/info.py +0 -0
  55. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/mk_report.py +0 -0
  56. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/rotate_key.py +0 -0
  57. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/set_client.py +0 -0
  58. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/setup_demo.py +0 -0
  59. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/commands/taetigkeitsbericht.py +0 -0
  60. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/cli/utils.py +0 -0
  61. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/core/__init__.py +0 -0
  62. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/core/config.py +0 -0
  63. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/core/encrypt.py +0 -0
  64. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/core/enums.py +0 -0
  65. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/core/logger.py +0 -0
  66. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/core/paths.py +0 -0
  67. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/Faecher_BfsEV.txt +0 -0
  68. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/Faecher_BfsKi.txt +0 -0
  69. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/Faecher_Faks.txt +0 -0
  70. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/LiberationSans-Bold.ttf +0 -0
  71. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/LiberationSans-Regular.ttf +0 -0
  72. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/OFL.txt +0 -0
  73. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/sampleconfig.yml +0 -0
  74. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/data/taetigkeitsbericht_categories.csv +0 -0
  75. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/db/__init__.py +0 -0
  76. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/db/clients.py +0 -0
  77. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/db/column_types.py +0 -0
  78. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/db/converters.py +0 -0
  79. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/info.py +0 -0
  80. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/py.typed +0 -0
  81. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/__init__.py +0 -0
  82. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/dialogs.py +0 -0
  83. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/edit_client.py +0 -0
  84. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/edit_client_app.py +0 -0
  85. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/editconfig.py +0 -0
  86. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/editconfig.tcss +0 -0
  87. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/editconfig_app.py +0 -0
  88. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/edupsyadmintui.tcss +0 -0
  89. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/fill_form_app.py +0 -0
  90. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/fill_form_widget.py +0 -0
  91. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/tui/suggesters.py +0 -0
  92. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/__init__.py +0 -0
  93. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/academic_year.py +0 -0
  94. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/convert_measures.py +0 -0
  95. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/datediff.py +0 -0
  96. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/int_from_str.py +0 -0
  97. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/path_utils.py +0 -0
  98. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/python_type.py +0 -0
  99. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/rounding.py +0 -0
  100. {edupsyadmin-10.2.1 → edupsyadmin-10.3.0}/src/edupsyadmin/utils/taetigkeitsbericht_check_key.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: edupsyadmin
3
- Version: 10.2.1
3
+ Version: 10.3.0
4
4
  Summary: edupsyadmin provides tools to help school psychologists with their documentation
5
5
  Author: Lukas Liebermann
6
6
  License: MIT
@@ -168,6 +168,24 @@ See an overview of all clients in the database:
168
168
  edupsyadmin get-clients
169
169
  ```
170
170
 
171
+ See only active clients in the database:
172
+
173
+ ```text
174
+ edupsyadmin get-clients --active
175
+ ```
176
+
177
+ Copy a client record to a new academic year:
178
+
179
+ ```text
180
+ edupsyadmin copy-client 42 --to-academic-year 2026/27
181
+ ```
182
+
183
+ Check which client files are due for document shredding:
184
+
185
+ ```text
186
+ edupsyadmin check-shredding
187
+ ```
188
+
171
189
  Fill a PDF form for the database entry with `client_id=42`:
172
190
 
173
191
  ```text
@@ -136,6 +136,24 @@ See an overview of all clients in the database:
136
136
  edupsyadmin get-clients
137
137
  ```
138
138
 
139
+ See only active clients in the database:
140
+
141
+ ```text
142
+ edupsyadmin get-clients --active
143
+ ```
144
+
145
+ Copy a client record to a new academic year:
146
+
147
+ ```text
148
+ edupsyadmin copy-client 42 --to-academic-year 2026/27
149
+ ```
150
+
151
+ Check which client files are due for document shredding:
152
+
153
+ ```text
154
+ edupsyadmin check-shredding
155
+ ```
156
+
139
157
  Fill a PDF form for the database entry with `client_id=42`:
140
158
 
141
159
  ```text
@@ -4,7 +4,7 @@ requires = ["uv-build>=0.13.6,<0.14"]
4
4
 
5
5
  [project]
6
6
  name = "edupsyadmin"
7
- version = "10.2.1"
7
+ version = "10.3.0"
8
8
  description = "edupsyadmin provides tools to help school psychologists with their documentation"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.15"
@@ -4,7 +4,7 @@ requires = [ "uv-build>=0.13.6,<0.14" ]
4
4
 
5
5
  [project]
6
6
  name = "edupsyadmin"
7
- version = "10.2.1"
7
+ version = "10.3.0"
8
8
  description = "edupsyadmin provides tools to help school psychologists with their documentation"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -18,4 +18,4 @@ and backwards compatibility is not guaranteed for minor versions.
18
18
 
19
19
  __all__ = ["__version__"]
20
20
 
21
- __version__ = "10.2.1"
21
+ __version__ = "10.3.0"
@@ -243,7 +243,7 @@ def write_form_md(fn: Path, out_fn: Path, data: Mapping[str, Any]) -> None:
243
243
  raise
244
244
 
245
245
  try:
246
- msg = template.render(**data)
246
+ msg = template.render(data)
247
247
  except LiquidError as e:
248
248
  e.add_note(
249
249
  "The template could be parsed, but there was an issue with "
@@ -3,8 +3,8 @@ import logging # just for interaction with the sqlalchemy logger
3
3
  from datetime import date
4
4
  from typing import Any
5
5
 
6
- from sqlalchemy import create_engine, func, inspect, or_, select
7
- from sqlalchemy.orm import sessionmaker
6
+ from sqlalchemy import ColumnElement, create_engine, func, inspect, or_, select
7
+ from sqlalchemy.orm import Session, sessionmaker
8
8
 
9
9
  from edupsyadmin.api.client_view import ClientView
10
10
  from edupsyadmin.api.exceptions import ClientNotFoundError
@@ -18,6 +18,99 @@ from edupsyadmin.core.config import config
18
18
  from edupsyadmin.core.logger import logger
19
19
  from edupsyadmin.db import clients as clients_db
20
20
 
21
+ # Query column configurations for client overview
22
+ DEFAULT_OVERVIEW_BASE_COLUMNS: tuple[str, ...] = (
23
+ "client_id",
24
+ "case_active",
25
+ "last_name_encr",
26
+ "first_name_encr",
27
+ "class_name_encr",
28
+ )
29
+
30
+ DEFAULT_OVERVIEW_EXTRA_COLUMNS: tuple[str, ...] = (
31
+ "school",
32
+ "notenschutz",
33
+ "nachteilsausgleich",
34
+ "lrst_diagnosis_encr",
35
+ "keyword_taet_encr",
36
+ )
37
+
38
+ OVERVIEW_YIELD_PER: int = 100
39
+ SHREDDING_YIELD_PER: int = 100
40
+
41
+ # Names of all keyword arguments accepted by Client.__init__ (excluding self
42
+ # and primary key). copy_client() uses them to find out which attributes of an
43
+ # existiung client have to be passed to the constructor to create a copy.
44
+ _CLIENT_INIT_PARAMS: frozenset[str] = frozenset(
45
+ k
46
+ for k in py_inspect.signature(clients_db.Client.__init__).parameters
47
+ if k not in ("self", "client_id")
48
+ )
49
+
50
+
51
+ def _resolve_overview_columns(
52
+ columns: list[str] | str | None,
53
+ colmap: dict[str, Any],
54
+ ) -> list[str]:
55
+ """Resolve and validate requested overview columns into an ordered list of names.
56
+
57
+ :param columns: Columns requested by caller ("all", list, single str, or None).
58
+ :param colmap: Mapping of available column names to SQLAlchemy column attributes.
59
+ :return: Ordered, deduplicated list of column names including base columns.
60
+ :raises ValueError: If any specified extra column name is not in colmap.
61
+ """
62
+ if columns in ("all", ["all"]):
63
+ return list(colmap.keys())
64
+
65
+ if columns is None or (isinstance(columns, list) and not columns):
66
+ extras = list(DEFAULT_OVERVIEW_EXTRA_COLUMNS)
67
+ elif isinstance(columns, str):
68
+ extras = [columns]
69
+ else:
70
+ extras = list(columns)
71
+
72
+ invalid = set(extras) - set(colmap.keys())
73
+ if invalid:
74
+ allowed = ", ".join(sorted(colmap.keys()))
75
+ raise ValueError(
76
+ f"Invalid column names: {', '.join(sorted(invalid))}. Allowed: {allowed}",
77
+ )
78
+
79
+ # Merge base + extras, de-duplicating while preserving order
80
+ return list(dict.fromkeys((*DEFAULT_OVERVIEW_BASE_COLUMNS, *extras)))
81
+
82
+
83
+ def _build_overview_conditions(
84
+ nta_nos: bool = False,
85
+ schools: list[str] | None = None,
86
+ academic_years: list[str] | str | None = None,
87
+ active: bool = False,
88
+ ) -> list[ColumnElement[bool]]:
89
+ """Build SQLAlchemy where conditions for the clients overview query.
90
+
91
+ :param nta_nos: Whether to filter for clients with Notenschutz or NTA.
92
+ :param schools: Optional list of school names to filter by.
93
+ :param academic_years: Academic year(s) to filter by, or "all" for no filter.
94
+ :param active: Whether to filter only active cases.
95
+ :return: List of SQLAlchemy binary expressions to apply as WHERE filters.
96
+ """
97
+ conditions: list[ColumnElement[bool]] = []
98
+ if nta_nos:
99
+ conditions.append(
100
+ or_(
101
+ clients_db.Client.notenschutz.is_(True),
102
+ clients_db.Client.nachteilsausgleich.is_(True),
103
+ ),
104
+ )
105
+ if schools:
106
+ conditions.append(clients_db.Client.school.in_(schools))
107
+ if academic_years and academic_years not in ("all", ["all"]):
108
+ years = [academic_years] if isinstance(academic_years, str) else academic_years
109
+ conditions.append(clients_db.Client.record_academic_year.in_(years))
110
+ if active:
111
+ conditions.append(clients_db.Client.case_active.is_(True))
112
+ return conditions
113
+
21
114
 
22
115
  class ClientsManager:
23
116
  def __init__(
@@ -42,6 +135,23 @@ class ClientsManager:
42
135
 
43
136
  logger.debug(f"created connection to database at {database_url}")
44
137
 
138
+ def _get_client_or_raise(
139
+ self,
140
+ session: Session,
141
+ client_id: int,
142
+ ) -> clients_db.Client:
143
+ """Retrieve a Client by ID from an active session or raise ClientNotFoundError.
144
+
145
+ :param session: The active SQLAlchemy session.
146
+ :param client_id: Primary key of the client to retrieve.
147
+ :return: The loaded Client ORM instance.
148
+ :raises ClientNotFoundError: If no client with the given client_id exists.
149
+ """
150
+ client = session.get(clients_db.Client, client_id)
151
+ if client is None:
152
+ raise ClientNotFoundError(client_id)
153
+ return client
154
+
45
155
  def add_client(self, **client_data: Any) -> int:
46
156
  logger.debug("trying to add client")
47
157
  with self.Session() as session:
@@ -55,18 +165,14 @@ class ClientsManager:
55
165
  def get_decrypted_client(self, client_id: int) -> ClientRecord:
56
166
  logger.debug(f"trying to access client (client_id = {client_id})")
57
167
  with self.Session() as session:
58
- client = session.get(clients_db.Client, client_id)
59
- if client is None:
60
- raise ClientNotFoundError(client_id)
168
+ client = self._get_client_or_raise(session, client_id)
61
169
  return ClientRecord.model_validate(client)
62
170
 
63
171
  def get_client_view(self, client_id: int) -> ClientView:
64
172
  """Get a ClientView for the given client_id."""
65
173
  logger.debug(f"trying to access client view (client_id = {client_id})")
66
174
  with self.Session() as session:
67
- client = session.get(clients_db.Client, client_id)
68
- if client is None:
69
- raise ClientNotFoundError(client_id)
175
+ client = self._get_client_or_raise(session, client_id)
70
176
  return ClientView.model_validate(client)
71
177
 
72
178
  def get_clients_overview(
@@ -75,75 +181,28 @@ class ClientsManager:
75
181
  schools: list[str] | None = None,
76
182
  columns: list[str] | str | None = None,
77
183
  academic_years: list[str] | str | None = None,
184
+ active: bool = False,
78
185
  ) -> list[dict[str, Any]]:
79
186
  logger.debug("trying to query client data for overview")
80
187
 
81
- # Always-present base columns
82
- required_columns = [
83
- "client_id",
84
- "case_active",
85
- "last_name_encr",
86
- "first_name_encr",
87
- "class_name_encr",
88
- ]
89
-
90
- if columns in ("all", ["all"]):
91
- final_columns = list(self._colmap.keys())
92
- else:
93
- # Defaults for extra columns when none provided
94
- default_extras = [
95
- "school",
96
- "notenschutz",
97
- "nachteilsausgleich",
98
- "lrst_diagnosis_encr",
99
- "keyword_taet_encr",
100
- ]
101
-
102
- if columns is None or (isinstance(columns, list) and not columns):
103
- extras = default_extras
104
- elif isinstance(columns, str):
105
- extras = [columns]
106
- else:
107
- extras = columns
108
-
109
- # Validate extras against available columns
110
- invalid = set(extras) - set(self._colmap.keys())
111
- if invalid:
112
- allowed = ", ".join(sorted(self._colmap.keys()))
113
- raise ValueError(
114
- f"Invalid column names: {', '.join(sorted(invalid))}. "
115
- f"Allowed: {allowed}",
116
- )
117
-
118
- # Merge required + extras, de-duplicate while preserving order
119
- final_columns = list(dict.fromkeys(required_columns + extras))
120
-
121
- # Build SELECT
188
+ final_columns = _resolve_overview_columns(columns, self._colmap)
122
189
  selected_cols = [self._colmap[name].label(name) for name in final_columns]
123
190
  stmt = select(*selected_cols)
124
191
 
125
- # Optional filters
126
- conditions = []
127
- if nta_nos:
128
- conditions.append(
129
- or_(
130
- clients_db.Client.notenschutz.is_(True),
131
- clients_db.Client.nachteilsausgleich.is_(True),
132
- ),
133
- )
134
- if schools:
135
- conditions.append(clients_db.Client.school.in_(schools))
136
- if academic_years and academic_years not in ("all", ["all"]):
137
- if isinstance(academic_years, str):
138
- academic_years = [academic_years]
139
- conditions.append(
140
- clients_db.Client.record_academic_year.in_(academic_years)
141
- )
192
+ conditions = _build_overview_conditions(
193
+ nta_nos=nta_nos,
194
+ schools=schools,
195
+ academic_years=academic_years,
196
+ active=active,
197
+ )
142
198
  if conditions:
143
199
  stmt = stmt.where(*conditions)
144
200
 
145
201
  with self.Session() as session:
146
- result = session.execute(stmt, execution_options={"yield_per": 100})
202
+ result = session.execute(
203
+ stmt,
204
+ execution_options={"yield_per": OVERVIEW_YIELD_PER},
205
+ )
147
206
  return [dict(row) for row in result.mappings()]
148
207
 
149
208
  def copy_client(
@@ -164,26 +223,20 @@ class ClientsManager:
164
223
  f"to academic year {target_academic_year}",
165
224
  )
166
225
  with self.Session() as session:
167
- client = session.get(clients_db.Client, client_id)
168
- if client is None:
169
- raise ClientNotFoundError(client_id)
170
-
171
- init_params = set(
172
- py_inspect.signature(clients_db.Client.__init__).parameters.keys(),
173
- )
174
- data: dict[str, Any] = {
175
- k: getattr(client, k)
176
- for k in init_params
177
- if k not in ("self", "client_id") and hasattr(client, k)
178
- }
179
- data["record_academic_year"] = target_academic_year
180
- if reset_sessions:
181
- data["min_sessions"] = 0
182
- data["n_sessions"] = 0
183
-
184
- new_client = clients_db.Client(**data)
185
- session.add(new_client)
186
- session.commit()
226
+ with session.begin():
227
+ client = self._get_client_or_raise(session, client_id)
228
+ data: dict[str, Any] = {
229
+ k: getattr(client, k)
230
+ for k in _CLIENT_INIT_PARAMS
231
+ if hasattr(client, k)
232
+ }
233
+ data["record_academic_year"] = target_academic_year
234
+ if reset_sessions:
235
+ data["min_sessions"] = 0
236
+ data["n_sessions"] = 0
237
+
238
+ new_client = clients_db.Client(**data)
239
+ session.add(new_client)
187
240
 
188
241
  logger.info(
189
242
  f"copied client {client_id} to {new_client.client_id} "
@@ -192,12 +245,18 @@ class ClientsManager:
192
245
  return new_client.client_id
193
246
 
194
247
  def edit_client(self, client_ids: list[int], new_data: dict[str, Any]) -> None:
248
+ """Batch update attributes across one or more client records.
249
+
250
+ :param client_ids: List of client IDs to update.
251
+ :param new_data: Dictionary mapping Client attribute names to new values.
252
+ :raises ValueError: If new_data contains any unrecognized attribute keys.
253
+ """
195
254
  logger.debug(f"editing clients (ids = {client_ids})")
196
255
 
197
256
  # Validate keys
198
257
  invalid_keys = set(new_data.keys()) - self._valid_keys
199
258
  if invalid_keys:
200
- raise ValueError(f"Invalid keys found: {', '.join(invalid_keys)}")
259
+ raise ValueError(f"Invalid keys found: {', '.join(sorted(invalid_keys))}")
201
260
 
202
261
  with self.Session() as session, session.begin():
203
262
  stmt = select(clients_db.Client).where(
@@ -223,18 +282,15 @@ class ClientsManager:
223
282
  def delete_client(self, client_id: int) -> None:
224
283
  logger.debug(f"deleting client {client_id}")
225
284
  with self.Session() as session, session.begin():
226
- client = session.get(clients_db.Client, client_id)
227
- if not client:
228
- raise ClientNotFoundError(client_id)
285
+ client = self._get_client_or_raise(session, client_id)
229
286
  session.delete(client)
230
287
 
231
288
  def get_total_count(self) -> int:
232
289
  """Get the total number of clients in the database."""
233
290
  logger.debug("querying total client count from database")
234
291
  with self.Session() as session:
235
- return (
236
- session.scalar(select(func.count()).select_from(clients_db.Client)) or 0
237
- )
292
+ count = session.scalar(select(func.count()).select_from(clients_db.Client))
293
+ return count or 0
238
294
 
239
295
  def get_shredding_report(
240
296
  self,
@@ -265,7 +321,10 @@ class ClientsManager:
265
321
  unset_clients: list[ShreddingUnsetRecord] = []
266
322
 
267
323
  with self.Session() as session:
268
- result = session.execute(stmt, execution_options={"yield_per": 100})
324
+ result = session.execute(
325
+ stmt,
326
+ execution_options={"yield_per": SHREDDING_YIELD_PER},
327
+ )
269
328
  for row in result:
270
329
  shred_date = row.document_shredding_date_encr
271
330
  if shred_date is None:
@@ -275,7 +334,7 @@ class ClientsManager:
275
334
  record_academic_year=row.record_academic_year,
276
335
  school=row.school,
277
336
  class_name_encr=row.class_name_encr or "",
278
- )
337
+ ),
279
338
  )
280
339
  elif shred_date <= cutoff:
281
340
  due_clients.append(
@@ -284,11 +343,11 @@ class ClientsManager:
284
343
  record_academic_year=row.record_academic_year,
285
344
  school=row.school,
286
345
  document_shredding_date_encr=shred_date,
287
- )
346
+ ),
288
347
  )
289
348
 
290
349
  due_clients.sort(
291
- key=lambda c: (c.document_shredding_date_encr, c.school, c.client_id)
350
+ key=lambda c: (c.document_shredding_date_encr, c.school, c.client_id),
292
351
  )
293
352
  unset_clients.sort(key=lambda c: (c.school, c.client_id))
294
353
 
@@ -68,6 +68,9 @@ def add_arguments(parser: ArgumentParser) -> None:
68
68
  action="store_true",
69
69
  help="show entries from all academic years (overrides default filtering)",
70
70
  )
71
+ parser.add_argument(
72
+ "--active", action="store_true", help="show only active clients"
73
+ )
71
74
  parser.add_argument("--out", help="path for an output file", type=normalize_path)
72
75
  parser.add_argument(
73
76
  "--client-id",
@@ -108,6 +111,7 @@ def execute(args: Namespace) -> None:
108
111
  schools=args.schools,
109
112
  columns=args.columns,
110
113
  academic_years=academic_years,
114
+ active=args.active,
111
115
  ).run()
112
116
  else:
113
117
  if args.client_id:
@@ -120,6 +124,7 @@ def execute(args: Namespace) -> None:
120
124
  schools=args.schools,
121
125
  columns=args.columns,
122
126
  academic_years=academic_years,
127
+ active=args.active,
123
128
  )
124
129
  # Sort manually
125
130
  data.sort(key=lambda x: (x.get("school", ""), x.get("last_name_encr", "")))
@@ -1,9 +1,7 @@
1
1
  import os
2
2
  import textwrap
3
3
  from argparse import ArgumentParser, Namespace
4
- from datetime import datetime
5
4
  from inspect import signature
6
- from typing import TYPE_CHECKING, Any
7
5
 
8
6
  from sqlalchemy import inspect as sa_inspect
9
7
  lazy import pandas as pd
@@ -12,10 +10,6 @@ from edupsyadmin.core.config import config
12
10
  from edupsyadmin.core.logger import logger
13
11
  from edupsyadmin.db import clients
14
12
  from edupsyadmin.utils.path_utils import normalize_path
15
-
16
- if TYPE_CHECKING:
17
- from edupsyadmin.api.managers import ClientsManager
18
-
19
13
  lazy from edupsyadmin.api.managers import ClientsManager
20
14
  lazy from edupsyadmin.tui.edit_client_app import EditClientApp
21
15
 
@@ -36,29 +30,10 @@ COMMAND_EPILOG = textwrap.dedent(
36
30
  --names "Client1Name" "Client2Name" --school MySchool --keep-file
37
31
  """,
38
32
  )
33
+ _CITY_COLUMNS = frozenset({"postCode", "city"})
39
34
 
40
35
 
41
- def _enter_client_csv(
42
- clients_manager: ClientsManager,
43
- csv_path: str | os.PathLike[str],
44
- school: str | None,
45
- name: list[str],
46
- import_config_name: str | None = None,
47
- ) -> int:
48
- """
49
- Read client(s) from a csv file and add them to the database.
50
-
51
- :param clients_manager: a ClientsManager instance used to add the client to the db
52
- :param csv_path: path to a csv file
53
- :param school: short name of the school as set in the config file
54
- :param name: name(s) of the client(s) as specified in the "name" column of the csv
55
- :param import_config_name: name of the csv import configuration from the config
56
- :raises ValueError: if the import config is unknown, the lookup column is
57
- missing, a name is not found, or no school/name is available
58
- :return: client_id of the last client that was created
59
- """
60
- client_cls = clients.Client
61
-
36
+ def _get_import_config(import_config_name: str | None) -> tuple[str, dict[str, str]]:
62
37
  if import_config_name:
63
38
  try:
64
39
  import_conf = config.csv_import[import_config_name]
@@ -86,6 +61,22 @@ def _enter_client_csv(
86
61
  "address.phone": "telephone2_encr",
87
62
  "address.email": "email_encr",
88
63
  }
64
+ return separator, column_mapping
65
+
66
+
67
+ def _allowed_client_keys() -> set[str]:
68
+ client_cls = clients.Client
69
+ valid_keys = {c.key for c in sa_inspect(client_cls).column_attrs}
70
+ valid_init_keys = set(signature(client_cls.__init__).parameters)
71
+ return valid_keys | valid_init_keys
72
+
73
+
74
+ def _read_clients_csv(
75
+ csv_path: str | os.PathLike[str],
76
+ import_config_name: str | None,
77
+ ) -> tuple[str, pd.DataFrame]:
78
+ """Read a client csv and apply the column mapping."""
79
+ separator, column_mapping = _get_import_config(import_config_name)
89
80
 
90
81
  # keep_default_na: Empty cells become "" (the defaults used by
91
82
  # Client.__init__), and values like "NA" or "Null" stay strings.
@@ -107,15 +98,6 @@ def _enter_client_csv(
107
98
 
108
99
  df = raw_df.rename(columns=column_mapping)
109
100
 
110
- # Telephone numbers must be strings so that they can be encrypted.
111
- for phone_col in ("telephone1_encr", "telephone2_encr"):
112
- if phone_col in df.columns:
113
- df[phone_col] = df[phone_col].fillna("").astype(str)
114
- else:
115
- logger.warning(
116
- "No column was mapped to '%s'; it will be left empty.", phone_col
117
- )
118
-
119
101
  # The 'name' column is used for lookup; it may itself have been renamed.
120
102
  lookup_col = "name" if "name" in df.columns else column_mapping.get("name", "name")
121
103
  if lookup_col not in df.columns:
@@ -124,24 +106,14 @@ def _enter_client_csv(
124
106
  f"the column mapping. Available columns: {list(df.columns)}",
125
107
  )
126
108
 
127
- # Use the first school from the config if none was passed.
128
- if school is None:
129
- try:
130
- school = next(iter(config.school))
131
- except StopIteration:
132
- raise ValueError(
133
- "No school passed and none defined in the config."
134
- ) from None
109
+ allowed_keys = _allowed_client_keys()
135
110
 
136
- # Only keep keys that the Client model accepts.
137
- valid_keys = {c.key for c in sa_inspect(client_cls).column_attrs}
138
- valid_init_keys = set(signature(client_cls.__init__).parameters)
139
- allowed_keys = valid_keys | valid_init_keys
140
- # postCode/city are merged into city_encr below, so they are valid targets.
111
+ # postCode/city (_CITY_COLUMNS) are merged into city_encr later, so
112
+ # they are valid targets.
141
113
  unknown_targets = sorted(
142
114
  target
143
115
  for target in set(column_mapping.values())
144
- if target not in allowed_keys and target not in {"postCode", "city"}
116
+ if target not in allowed_keys and target not in _CITY_COLUMNS
145
117
  )
146
118
  if unknown_targets:
147
119
  logger.debug(
@@ -149,53 +121,118 @@ def _enter_client_csv(
149
121
  unknown_targets,
150
122
  )
151
123
 
152
- client_id: int | None = None
153
- for this_name in name:
154
- client_series = df[df[lookup_col] == this_name]
124
+ keep = allowed_keys | _CITY_COLUMNS | {lookup_col}
125
+ return lookup_col, df[[col for col in df.columns if col in keep]]
155
126
 
156
- if client_series.empty:
157
- raise ValueError(
158
- f"The name '{this_name}' was not found in column '{lookup_col}' "
159
- f"of the CSV file '{csv_path}'.",
160
- )
161
127
 
162
- client_data = client_series.iloc[0].to_dict()
128
+ def _resolve_school(school: str | None) -> str:
129
+ """Return the specified school or the first one defined in the config."""
130
+ if school is not None:
131
+ return school
132
+ try:
133
+ return next(iter(config.school))
134
+ except StopIteration:
135
+ raise ValueError("No school passed and none defined in the config.") from None
163
136
 
164
- # Combine address fields if they exist
165
- if "postCode" in client_data and "city" in client_data:
166
- client_data["city_encr"] = (
167
- str(client_data.pop("postCode", ""))
168
- + " "
169
- + str(client_data.pop("city", ""))
170
- )
171
137
 
172
- # Handle date formatting
173
- for date_col in ("entry_date_encr", "birthday_encr"):
174
- if date_col in client_data and isinstance(client_data[date_col], str):
175
- try:
176
- client_data[date_col] = datetime.strptime(
177
- client_data[date_col],
178
- "%d.%m.%Y",
179
- ).date()
180
- except ValueError:
181
- logger.error(
182
- "Could not parse date '%s' for column '%s'. "
183
- "Please ensure the format is DD.MM.YYYY.",
184
- client_data[date_col],
185
- date_col,
186
- )
187
- client_data[date_col] = None
188
-
189
- client_data["school"] = school
190
-
191
- final_client_data: dict[str, Any] = {
192
- str(k): v for k, v in client_data.items() if k in allowed_keys
193
- }
194
- client_id = clients_manager.add_client(**final_client_data)
138
+ def _enter_client_csv(
139
+ clients_manager: ClientsManager,
140
+ csv_path: str | os.PathLike[str],
141
+ school: str | None,
142
+ name: list[str],
143
+ import_config_name: str | None = None,
144
+ ) -> list[int]:
145
+ """
146
+ Read client(s) from a csv file and add them to the database.
195
147
 
196
- if client_id is None:
148
+ :param clients_manager: a ClientsManager instance used to add the client to the db
149
+ :param csv_path: path to a csv file
150
+ :param school: short name of the school as set in the config file
151
+ :param name: name(s) of the client(s) as specified in the "name" column of the csv
152
+ :param import_config_name: name of the csv import configuration from the config
153
+ :raises ValueError: if the import config is unknown, the lookup column is
154
+ missing, a name is not found, or no school/name is available
155
+ :return: list of client_ids that were created
156
+ """
157
+ if not name:
197
158
  raise ValueError("No client names were given; nothing was added.")
198
- return client_id
159
+
160
+ lookup_col, df = _read_clients_csv(csv_path, import_config_name)
161
+
162
+ # Telephone numbers must be strings so that they can be encrypted.
163
+ for phone_col in ("telephone1_encr", "telephone2_encr"):
164
+ if phone_col in df.columns:
165
+ df[phone_col] = df[phone_col].fillna("").astype(str)
166
+ else:
167
+ logger.warning(
168
+ "No column was mapped to '%s'; it will be left empty.", phone_col
169
+ )
170
+
171
+ school_name = _resolve_school(school)
172
+
173
+ # Resolve every name first so a typo in the last name does not leave
174
+ # the earlier clients half-imported.
175
+ available = set(df[lookup_col])
176
+ missing = [this_name for this_name in name if this_name not in available]
177
+ if missing:
178
+ raise ValueError(
179
+ f"The name(s) {missing} were not found in column '{lookup_col}' "
180
+ f"of the CSV file '{csv_path}'.",
181
+ )
182
+
183
+ # drop_duplicates keeps the first match per name;
184
+ # .loc[name] returns the rows in the order the names were given.
185
+ selected = (
186
+ df.drop_duplicates(subset=lookup_col)
187
+ .set_index(lookup_col, drop=False)
188
+ .loc[name]
189
+ )
190
+ records = _preprocess_client_csv_data(selected, school_name).to_dict(
191
+ orient="records"
192
+ )
193
+ return [
194
+ clients_manager.add_client(**{str(k): v for k, v in record.items()})
195
+ for record in records
196
+ ]
197
+
198
+
199
+ def _preprocess_client_csv_data(df: pd.DataFrame, school: str) -> pd.DataFrame:
200
+ """Prepare the selected csv rows for ``ClientsManager.add_client``.
201
+
202
+ Merges ``postCode`` and ``city`` into ``city_encr``, parses dates
203
+ (``DD.MM.YYYY``, unparsable values become None), sets the school and drops
204
+ all columns that are not ``Client`` fields.
205
+
206
+ :param df: the selected rows of the csv dataframe
207
+ :param school: short name of the school
208
+ :return: dataframe whose columns are valid ``add_client`` keyword arguments
209
+ """
210
+ df = df.copy()
211
+
212
+ # Combine address fields if they exist
213
+ if {"postCode", "city"} <= set(df.columns):
214
+ df["city_encr"] = df.pop("postCode") + " " + df.pop("city")
215
+
216
+ # Handle date formatting
217
+ for date_col in ("entry_date_encr", "birthday_encr"):
218
+ if date_col not in df.columns:
219
+ continue
220
+ parsed = pd.to_datetime(df[date_col], format="%d.%m.%Y", errors="coerce")
221
+ failed = parsed.isna()
222
+ for bad_value in df.loc[failed, date_col]:
223
+ if bad_value:
224
+ logger.error(
225
+ "Could not parse date '%s' for column '%s'. "
226
+ "Please ensure the format is DD.MM.YYYY.",
227
+ bad_value,
228
+ date_col,
229
+ )
230
+ df[date_col] = parsed.dt.date.where(~failed, None)
231
+
232
+ df["school"] = school
233
+
234
+ allowed_keys = _allowed_client_keys()
235
+ return df[[col for col in df.columns if col in allowed_keys]]
199
236
 
200
237
 
201
238
  def add_arguments(parser: ArgumentParser) -> None:
@@ -53,6 +53,9 @@ def add_arguments(parser: ArgumentParser) -> None:
53
53
  action="store_true",
54
54
  help="show entries from all academic years (overrides default filtering)",
55
55
  )
56
+ parser.add_argument(
57
+ "--active", action="store_true", help="show only active clients"
58
+ )
56
59
 
57
60
 
58
61
  def _suppress_console_logging() -> None:
@@ -97,5 +100,6 @@ def execute(args: Namespace) -> None:
97
100
  schools=args.schools,
98
101
  columns=args.columns,
99
102
  academic_years=academic_years,
103
+ active=args.active,
100
104
  )
101
105
  app.run()
@@ -116,6 +116,7 @@ class ClientsOverview(Static):
116
116
  schools: list[str] | None = None,
117
117
  columns: list[str] | None = None,
118
118
  academic_years: list[str] | None = None,
119
+ active: bool = False,
119
120
  name: str | None = None,
120
121
  id: str | None = None,
121
122
  classes: str | None = None,
@@ -126,6 +127,7 @@ class ClientsOverview(Static):
126
127
  self.schools = schools
127
128
  self.columns = columns
128
129
  self.academic_years = academic_years
130
+ self.active = active
129
131
  self._last_applied_sort: tuple[tuple[str, ...], bool] = ((), False)
130
132
  self._reverse_states: dict[str, bool] = {}
131
133
 
@@ -154,6 +156,7 @@ class ClientsOverview(Static):
154
156
  schools=self.schools,
155
157
  columns=self.columns,
156
158
  academic_years=self.academic_years,
159
+ active=self.active,
157
160
  )
158
161
  self.post_message(self._DataLoaded(data))
159
162
 
@@ -22,6 +22,7 @@ class ClientsOverviewApp(App):
22
22
  schools: list[str] | None = None,
23
23
  columns: list[str] | None = None,
24
24
  academic_years: list[str] | None = None,
25
+ active: bool = False,
25
26
  **kwargs,
26
27
  ) -> None:
27
28
  super().__init__(**kwargs)
@@ -30,6 +31,7 @@ class ClientsOverviewApp(App):
30
31
  self.schools = schools
31
32
  self.columns = columns
32
33
  self.academic_years = academic_years
34
+ self.active = active
33
35
 
34
36
  def compose(self) -> ComposeResult:
35
37
  yield Header()
@@ -39,5 +41,6 @@ class ClientsOverviewApp(App):
39
41
  schools=self.schools,
40
42
  columns=self.columns,
41
43
  academic_years=self.academic_years,
44
+ active=self.active,
42
45
  )
43
46
  yield Footer()
@@ -57,6 +57,7 @@ class EdupsyadminTui(App[None]):
57
57
  schools: list[str] | None = None,
58
58
  columns: list[str] | None = None,
59
59
  academic_years: list[str] | None = None,
60
+ active: bool = False,
60
61
  ) -> None:
61
62
  super().__init__()
62
63
  self.manager = manager
@@ -65,6 +66,7 @@ class EdupsyadminTui(App[None]):
65
66
  self.schools = schools
66
67
  self.columns = columns
67
68
  self.academic_years = academic_years
69
+ self.active = active
68
70
 
69
71
  def compose(self) -> ComposeResult:
70
72
  yield Header()