librus-python-api 1.8.4__py3-none-any.whl → 1.10.0__py3-none-any.whl

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,7 +1,7 @@
1
1
  """Independent bounded async client. General live compatibility is unqualified."""
2
2
 
3
3
  # Before the imports: config reads it for the User-Agent.
4
- __version__ = "1.8.4"
4
+ __version__ = "1.10.0"
5
5
 
6
6
  from librus_python_api.attachments import AttachmentStream, ModernAttachmentStream
7
7
  from librus_python_api.budget import RequestBudget
@@ -38,6 +38,8 @@ from librus_python_api.models import (
38
38
  AttendanceView,
39
39
  AttendanceWindow,
40
40
  Availability,
41
+ BehaviourPointEntry,
42
+ BehaviourPoints,
41
43
  ClassFreeDay,
42
44
  ClassFreeDays,
43
45
  CompletedLesson,
@@ -53,6 +55,7 @@ from librus_python_api.models import (
53
55
  FrequencyMeasure,
54
56
  GatewayAttendance,
55
57
  GatewayAttendanceRecord,
58
+ GradeCorrection,
56
59
  GradeKind,
57
60
  GradeRecords,
58
61
  Grades,
@@ -63,6 +66,9 @@ from librus_python_api.models import (
63
66
  HomeworkItem,
64
67
  HomeworkRangeRequest,
65
68
  Identity,
69
+ Justification,
70
+ Justifications,
71
+ JustificationStatus,
66
72
  LuckyNumber,
67
73
  MessageAttachment,
68
74
  MessageAttachmentReference,
@@ -258,6 +264,9 @@ __all__ = [
258
264
  "DescriptiveGradeSummary",
259
265
  "FinalGrades",
260
266
  "FormativeGrade",
267
+ "BehaviourPointEntry",
268
+ "BehaviourPoints",
269
+ "GradeCorrection",
261
270
  "GradeKind",
262
271
  "GradeRecords",
263
272
  "Grades",
@@ -265,6 +274,9 @@ __all__ = [
265
274
  "GradeView",
266
275
  "GradeWindow",
267
276
  "Identity",
277
+ "Justification",
278
+ "Justifications",
279
+ "JustificationStatus",
268
280
  "LibrusService",
269
281
  "LuckyNumber",
270
282
  "NumericGrade",
@@ -503,6 +503,17 @@ ENDPOINTS: Mapping[str, Endpoint] = MappingProxyType(
503
503
  True,
504
504
  Evidence.INDEPENDENTLY_OBSERVED,
505
505
  ),
506
+ # The e-Justifications list as the page shows it unfiltered. Both
507
+ # parent logins got it, both student logins the "Brak dostępu"
508
+ # page (2026-11-13). The filter form's POST is not used.
509
+ Endpoint(
510
+ "justifications",
511
+ "GET",
512
+ "/eusprawiedliwienia",
513
+ SideEffect.NONE,
514
+ True,
515
+ Evidence.INDEPENDENTLY_OBSERVED,
516
+ ),
506
517
  Endpoint(
507
518
  "gateway_attendance",
508
519
  "GET",
@@ -724,8 +735,10 @@ GRADE_INLINE_DETAIL_LABEL = "Ocena"
724
735
  # multi-line grade comment was observed on 2026-10-27. A formative mirror's
725
736
  # assessment text after `Ocena` also spans lines (2026-11-08, markup.py).
726
737
  TOOLTIP_MULTILINE_LABELS = frozenset({"Komentarz"})
727
- # Labels a tooltip may repeat. A grade correcting two earlier grades lists one
728
- # `Poprawa oceny` line per corrected grade in the week view (2026-11-08).
738
+ # Labels a tooltip may repeat. In the week view a correction listed
739
+ # `Poprawa oceny` twice, both naming the same original grade, the first ending
740
+ # in a comma; the all view showed it once (2026-11-08). The tooltip is no
741
+ # record of which grades were corrected: correction brackets are.
729
742
  TOOLTIP_REPEATABLE_LABELS = frozenset({"Poprawa oceny"})
730
743
  # Tooltip labels observed on grade, attendance and point pages. Diagnostics
731
744
  # show only these by name; any other label is masked as teacher-entered text.
@@ -769,6 +782,12 @@ GRADE_VIEW_FIELDS = MappingProxyType(
769
782
  )
770
783
  GRADE_CURRENT_HEADER = "Oceny bieżące"
771
784
  GRADE_EMPTY_MARKERS = frozenset({"", "-", "Brak ocen"})
785
+ # The all view wraps a corrected grade and its correction in a bare <span>
786
+ # directly in the grade cell: its text is "[", its children are the grade
787
+ # boxes in page order (original first) and the last box's tail is "]" (owner
788
+ # logins, structure-only, 2026-11-08). The week view showed no brackets, even
789
+ # with the original in the same cell. Groups of more than two are accepted.
790
+ GRADE_CORRECTION_BRACKETS = ("[", "]")
772
791
  GRADE_AVERAGE_HEADERS = MappingProxyType(
773
792
  {"Średnia ocen": 1, "Średnia ocen z drugiego okresu": 2, "Średnia roczna": 0}
774
793
  )
@@ -869,8 +888,17 @@ FORMATIVE_DETAIL_PATH_PREFIX = "/przegladaj_oceny/szczegoly/ksztaltujace/"
869
888
  BEHAVIOUR_POINTS_DETAIL_PATH_PREFIX = "/przegladaj_oceny/zachowanie_szczegoly/"
870
889
  # Tooltip labels of a behaviour grade symbol entry (#114, synthetic example).
871
890
  BEHAVIOUR_GRADE_LABELS = frozenset({"Data wystawienia", "Dodał", "Komentarz"})
891
+ # Tooltip labels after a behaviour-point entry's unlabelled first line, as the
892
+ # 1.6.2 synthetic entry has them; any other label fails the read (#138).
893
+ BEHAVIOUR_POINT_LABELS = frozenset(
894
+ {"Zakres od", "Zakres do", "Data wystawienia", "Dodał", "Komentarz"}
895
+ )
872
896
  # Recognition only: point-grade detail links are classified, never requested.
873
897
  POINT_GRADE_DETAIL_PATH_PREFIX = "/przegladaj_oceny_punktowe/szczegoly/"
898
+ # Recognition only: an ordinary grade's own detail link gives its stable grade
899
+ # ID (librus-mcp#88); the page is never requested. Formative links share this
900
+ # prefix but have no digits-only rest, so they never yield a grade ID.
901
+ GRADE_DETAIL_PATH_PREFIX = "/przegladaj_oceny/szczegoly/"
874
902
  FORMATIVE_HEADERS = (
875
903
  "przedmiot",
876
904
  "ocena kształtująca",
@@ -1022,6 +1050,35 @@ PAGE_NOTICES = MappingProxyType(
1022
1050
  )
1023
1051
  MODULE_UNAVAILABLE_PATH = "/modul_niedostepny"
1024
1052
  CLASS_FREE_DAYS_MAX_RECORDS = 4096
1053
+ # e-Justifications list (`/eusprawiedliwienia`, structure observed on two
1054
+ # parent logins on 2026-11-13). The list table's classes, its seven header
1055
+ # cells in page order (`td`, not `th`, in `thead`) and the status words. The
1056
+ # status words are the filter's options; `odrzucone` has not been seen on an
1057
+ # entry. A decided entry adds " (" + the deciding person's name + ")".
1058
+ JUSTIFICATION_TABLE_CLASSES = frozenset({"decorated", "stretch", "center"})
1059
+ JUSTIFICATION_HEADERS = (
1060
+ "Załącznik",
1061
+ "Okres usprawiedliwienia",
1062
+ "Liczba usprawiedliwionych nieobecności",
1063
+ "Treść",
1064
+ "Powiadomieni nauczyciele",
1065
+ "Data wysłania",
1066
+ "Status",
1067
+ )
1068
+ JUSTIFICATION_STATUSES = MappingProxyType(
1069
+ {"wysłane": "sent", "usprawiedliwione": "justified", "odrzucone": "rejected"}
1070
+ )
1071
+ # `Me.Account.GroupId` of the logins that may request the list: 5 on both
1072
+ # parent logins, 8 on both student logins (one school, 2026-11-13). Opening
1073
+ # the list on a student login ends its session, so any other or missing group
1074
+ # is refused before the request.
1075
+ JUSTIFICATION_ACCOUNT_GROUP = 5
1076
+ # The filter form's date inputs, filled with the window the list shows.
1077
+ JUSTIFICATION_WINDOW_FIELDS = ("data_od", "data_do")
1078
+ JUSTIFICATION_MAX_ITEMS = 512
1079
+ JUSTIFICATION_MAX_CONTENT_LENGTH = 8192
1080
+ JUSTIFICATION_MAX_TEACHERS = 64
1081
+ JUSTIFICATION_MAX_TOTAL_TEXT_LENGTH = 262144
1025
1082
  COMPLETED_LESSONS_MAX_WINDOW_DAYS = 371
1026
1083
  COMPLETED_LESSONS_MAX_PAGE_COUNT = 1000
1027
1084
  COMPLETED_LESSONS_MAX_PAGE_ITEMS = 256
@@ -245,7 +245,8 @@ def _redaction_vocabulary() -> tuple[
245
245
  # Lazy: config imports models, which this module also imports.
246
246
  from librus_python_api import config
247
247
 
248
- texts = set(config.GRADE_EMPTY_MARKERS) | {
248
+ texts = set(config.GRADE_EMPTY_MARKERS) | set(config.GRADE_CORRECTION_BRACKETS)
249
+ texts |= {
249
250
  config.GRADE_CURRENT_HEADER,
250
251
  config.GRADE_INLINE_DETAIL_LABEL,
251
252
  config.GRADE_PREDICTED_ANNUAL_HEADER,
@@ -254,6 +255,7 @@ def _redaction_vocabulary() -> tuple[
254
255
  *config.GRADE_PERIOD_HEADERS,
255
256
  *config.GRADE_PREDICTED_PERIOD_HEADERS,
256
257
  *config.GRADE_AVERAGE_HEADERS,
258
+ *config.JUSTIFICATION_HEADERS,
257
259
  }
258
260
  texts |= {label.casefold() for label in config.FORMATIVE_HEADERS}
259
261
  profile = (*config.PROFILE_LABELS, *config.PROFILE_OWNER_LABELS)
@@ -4,8 +4,10 @@ The grades page of a school on the new descriptive grading schema renders a
4
4
  subject table whose semester cells are empty; the page script then loads the
5
5
  grades from gateway JSON routes. Routes and field names come from public client
6
6
  code and the official page script. One authorized read on 2026-10-28 parsed four
7
- PartialGrades records on one school; pagination keys are still unknown, so every
8
- unexpected shape fails instead of producing a partial collection.
7
+ PartialGrades records on one school. A structure-only read on 2026-11-13 recorded
8
+ the pagination member, `{"limit", "page", "total"}` integers beside `data` or
9
+ `Users` (Subjects has none), and only that member is checked; every unexpected
10
+ shape fails instead of producing a partial collection.
9
11
 
10
12
  Another school renders the same table with plain text in its semester cells and
11
13
  no script hooks (#115, from a reporter's synthetic example). The grade record
@@ -55,29 +57,6 @@ _DATE = re.compile(
55
57
  r"(?:[T ][0-9]{2}:[0-9]{2}(?::[0-9]{2}(?:\.[0-9]{1,9})?)?"
56
58
  r"(?:Z|[+-][0-9]{2}:?[0-9]{2})?)?"
57
59
  )
58
- # Keys (lower case, without separators) that, in any object beside `data`,
59
- # show that the collection continues on another page.
60
- _TOTAL_KEYS = frozenset(
61
- {
62
- "total",
63
- "totalcount",
64
- "totalitems",
65
- "totalrecords",
66
- "totalresults",
67
- "count",
68
- "itemcount",
69
- "itemscount",
70
- "recordcount",
71
- }
72
- )
73
- _PAGE_COUNT_KEYS = frozenset(
74
- {"pages", "totalpages", "pagecount", "pagescount", "lastpage", "numberofpages"}
75
- )
76
- _NEXT_KEYS = frozenset({"next", "nextpage", "nexturl", "nextpageurl", "nextlink"})
77
- _MORE_KEYS = frozenset({"hasmore", "hasnext", "hasnextpage", "more"})
78
- _PAGE_SIZE_KEYS = frozenset(
79
- {"limit", "perpage", "pagesize", "itemsperpage", "pagelimit"}
80
- )
81
60
 
82
61
 
83
62
  class _TokenInfoWire(BaseModel):
@@ -199,52 +178,33 @@ def _decode_collection(body: bytes, key: str, maximum: int) -> dict[str, Any]:
199
178
  return data
200
179
 
201
180
 
202
- def _count(value: Any) -> int | None:
203
- if type(value) is int:
204
- return value
205
- if type(value) is str and re.fullmatch(r"[0-9]{1,18}", value):
206
- return int(value)
207
- return None
181
+ def _check_pagination(
182
+ envelope: dict[str, Any], received: int, *, required: bool
183
+ ) -> None:
184
+ """Read the recorded `pagination` member; anything else decides nothing.
208
185
 
209
-
210
- def _continues(envelope: dict[str, Any], received: int) -> bool:
211
- """Whether a pagination member shows more items than this response holds.
212
-
213
- No paginated response was observed, so its field names are unknown. Every
214
- object beside `data`, to depth three, is checked for obvious signals: a
215
- total above the items received, more than one page, a next link or page,
216
- a true has-more flag, or a full page of a stated size with no total.
186
+ Observed 2026-11-13: `{"limit": int, "page": int, "total": int}` beside
187
+ `data` (PartialGrades) or `Users`. Subjects carries no member. Only the
188
+ first page is ever read, so the member must show page 1 and a total equal
189
+ to the items received (the limit is not a fixed page size and is only
190
+ checked to be an integer). Anything else fails instead of returning a
191
+ possibly partial collection.
217
192
  """
218
- totals: list[int] = []
219
- sizes: list[int] = []
220
- more = False
221
- pending: list[tuple[dict[str, Any], int]] = [
222
- ({k: v for k, v in envelope.items() if k != "data"}, 0)
223
- ]
224
- while pending:
225
- item, depth = pending.pop()
226
- for key, value in item.items():
227
- name = re.sub(r"[^a-z]", "", str(key).lower())
228
- if name in _NEXT_KEYS:
229
- more = more or value not in (None, "", False, {}, [])
230
- continue
231
- if isinstance(value, dict):
232
- if depth < 3:
233
- pending.append((value, depth + 1))
234
- continue
235
- number = _count(value)
236
- if name in _TOTAL_KEYS and number is not None:
237
- totals.append(number)
238
- elif name in _PAGE_COUNT_KEYS and number is not None:
239
- more = more or number > 1
240
- elif name in _MORE_KEYS:
241
- more = more or value is True
242
- elif name in _PAGE_SIZE_KEYS and number is not None:
243
- sizes.append(number)
244
- if any(total > received for total in totals):
245
- return True
246
- full_page = any(0 < size <= received for size in sizes)
247
- return more or (full_page and not totals)
193
+ if "pagination" not in envelope:
194
+ if required:
195
+ raise LibrusError(ErrorKind.PARSE)
196
+ return
197
+ member = envelope["pagination"]
198
+ if not isinstance(member, dict):
199
+ raise LibrusError(ErrorKind.PARSE)
200
+ limit, page, total = member.get("limit"), member.get("page"), member.get("total")
201
+ # `type(...) is int` rejects booleans, strings and floats.
202
+ if type(limit) is not int or type(page) is not int or type(total) is not int:
203
+ raise LibrusError(ErrorKind.PARSE)
204
+ if limit < 1 or total < received:
205
+ raise LibrusError(ErrorKind.PARSE)
206
+ if page != 1 or total > received:
207
+ raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
248
208
 
249
209
 
250
210
  def parse_token_info(body: bytes) -> str:
@@ -281,9 +241,8 @@ def _day(value: str) -> date:
281
241
  def parse_partial_grades(body: bytes) -> tuple[PartialGrade, ...]:
282
242
  data = _decode_collection(body, "data", GRADE_MAX_RECORDS)
283
243
  wire = _validate(_PartialGradesWire, data)
284
- if _continues(data, len(wire.data)):
285
- # Returning the first page alone would be a silently partial result.
286
- raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
244
+ # Returning the first page alone would be a silently partial result.
245
+ _check_pagination(data, len(wire.data), required=True)
287
246
  return tuple(
288
247
  PartialGrade(
289
248
  item.subjectId,
@@ -303,8 +262,7 @@ def parse_partial_grades(body: bytes) -> tuple[PartialGrade, ...]:
303
262
  def parse_gateway_subjects(body: bytes) -> Mapping[str, GatewaySubject]:
304
263
  data = _decode_collection(body, "data", DESCRIPTIVE_MAX_SUBJECTS)
305
264
  wire = _validate(_SubjectsWire, data)
306
- if _continues(data, len(wire.data)):
307
- raise LibrusError(ErrorKind.UNSUPPORTED_CAPABILITY)
265
+ _check_pagination(data, len(wire.data), required=False)
308
266
  result: dict[str, GatewaySubject] = {}
309
267
  numeric: set[int] = set()
310
268
  for item in wire.data:
@@ -323,6 +281,7 @@ def parse_gateway_users(body: bytes) -> Mapping[str, str]:
323
281
  """Account IDs to "LastName FirstName"; a user with neither is omitted."""
324
282
  data = _decode_collection(body, "Users", DESCRIPTIVE_MAX_USERS)
325
283
  wire = _validate(_UsersWire, data)
284
+ _check_pagination(data, len(wire.Users), required=False)
326
285
  result: dict[str, str] = {}
327
286
  seen: dict[str, tuple[str | None, str | None]] = {}
328
287
  for user in wire.Users:
@@ -9,10 +9,12 @@ from lxml import html
9
9
  from librus_python_api import markup
10
10
  from librus_python_api.config import (
11
11
  BEHAVIOUR_GRADE_LABELS,
12
+ BEHAVIOUR_POINT_LABELS,
12
13
  BEHAVIOUR_POINTS_DETAIL_PATH_PREFIX,
13
14
  FORMATIVE_DETAIL_PATH_PREFIX,
14
15
  GRADE_AVERAGE_HEADERS,
15
16
  GRADE_BODY_PREFIX_COLUMNS,
17
+ GRADE_CORRECTION_BRACKETS,
16
18
  GRADE_CURRENT_HEADER,
17
19
  GRADE_EMPTY_MARKERS,
18
20
  GRADE_INLINE_DETAIL_LABEL,
@@ -44,9 +46,12 @@ from librus_python_api.grade_parsers import (
44
46
  )
45
47
  from librus_python_api.models import (
46
48
  Availability,
49
+ BehaviourPointEntry,
50
+ BehaviourPoints,
47
51
  DescriptiveGrade,
48
52
  DescriptiveGradeSummary,
49
53
  FormativeGrade,
54
+ GradeCorrection,
50
55
  GradeKind,
51
56
  GradeRecords,
52
57
  GradeSummaryValue,
@@ -216,18 +221,23 @@ class _Collection:
216
221
  )
217
222
  averages: list[SchoolAverage] = field(default_factory=list, repr=False)
218
223
  point_results: list[SchoolAverage] = field(default_factory=list, repr=False)
224
+ corrections: list[GradeCorrection] = field(default_factory=list, repr=False)
225
+ corrected: set[str] = field(default_factory=set, repr=False)
219
226
  subjects: set[tuple[bool, str]] = field(default_factory=set, repr=False)
220
227
  point_subjects: set[str] = field(default_factory=set, repr=False)
221
228
  consumed: set[html.HtmlElement] = field(default_factory=set, repr=False)
222
229
  publication_rows: set[html.HtmlElement] = field(default_factory=set, repr=False)
230
+ behaviour: list[BehaviourPoints] = field(default_factory=list, repr=False)
223
231
  formative: int = 0
224
232
 
225
- def check_size(self) -> None:
233
+ def check_size(self, pending: int = 0) -> None:
226
234
  if (
227
235
  len(self.numeric)
228
236
  + len(self.descriptive)
229
237
  + len(self.descriptive_summaries)
230
238
  + self.formative
239
+ + sum(len(item.entries) for item in self.behaviour)
240
+ + pending
231
241
  > GRADE_MAX_RECORDS
232
242
  ):
233
243
  raise LibrusError(ErrorKind.LIMIT)
@@ -254,20 +264,136 @@ class _Collection:
254
264
 
255
265
 
256
266
  def _boxes(cell: html.HtmlElement) -> list[html.HtmlElement]:
257
- return [
258
- node
259
- for node in cell.iter("span")
260
- if "grade-box" in node.get("class", "").split()
261
- ]
267
+ return [node for node in cell.iter("span") if _is_box(node)]
268
+
269
+
270
+ def _is_box(node: html.HtmlElement) -> bool:
271
+ return isinstance(node.tag, str) and "grade-box" in node.get("class", "").split()
262
272
 
263
273
 
264
- def _behaviour_points(cell: html.HtmlElement, collection: _Collection) -> bool:
265
- """Recognize and validate a behaviour-points cell; points are not grades.
274
+ def _brackets(
275
+ cell: html.HtmlElement, boxes: list[html.HtmlElement]
276
+ ) -> list[list[html.HtmlElement]]:
277
+ """The correction brackets of a grade cell, each its grade boxes in order.
266
278
 
267
- The cell holds one points tooltip (starting points or a running total; its
268
- title is not interpreted) and point entries linking to behaviour details,
269
- each with its own unlabelled tooltip. Any other content next to the points
270
- tooltip fails instead of being skipped.
279
+ A bracket is a bare <span> directly in the cell whose text is "[", whose
280
+ element children are two or more grade boxes, and whose last child's tail
281
+ is "]" (config.GRADE_CORRECTION_BRACKETS); comments are ignored. Any other
282
+ bracket text outside grade boxes, such as an unbalanced or nested bracket,
283
+ fails the read instead of dropping a correction link.
284
+ """
285
+ opening, closing = GRADE_CORRECTION_BRACKETS
286
+ inside = set(boxes)
287
+ outside = [cell.text or ""]
288
+ pending = list(cell)
289
+ while pending:
290
+ node = pending.pop()
291
+ outside.append(node.tail or "")
292
+ if node not in inside and isinstance(node.tag, str):
293
+ outside.append(node.text or "")
294
+ pending.extend(node)
295
+ marks = sum(text.count(opening) + text.count(closing) for text in outside)
296
+ if not marks:
297
+ return []
298
+ groups = []
299
+ for wrapper in cell:
300
+ if wrapper.tag != "span" or wrapper.attrib:
301
+ continue
302
+ if (wrapper.text or "").strip() != opening:
303
+ continue
304
+ children = list(wrapper)
305
+ members = [child for child in children if isinstance(child.tag, str)]
306
+ if (
307
+ len(members) < 2
308
+ or not all(member in inside for member in members)
309
+ or any((child.tail or "").strip() for child in children[:-1])
310
+ or (children[-1].tail or "").strip() != closing
311
+ ):
312
+ raise LibrusError(ErrorKind.PARSE)
313
+ groups.append(members)
314
+ if marks != 2 * len(groups):
315
+ raise LibrusError(ErrorKind.PARSE)
316
+ return groups
317
+
318
+
319
+ def _read_corrections(
320
+ groups: list[list[html.HtmlElement]],
321
+ ids: dict[html.HtmlElement, str | None],
322
+ subject: str,
323
+ period: Literal[0, 1, 2],
324
+ collection: _Collection,
325
+ *,
326
+ points: bool,
327
+ ) -> None:
328
+ for boxes in groups:
329
+ members = [ids.get(box) for box in boxes]
330
+ if any(member is None for member in members):
331
+ # Only ordinary grades with their own detail link were observed.
332
+ raise LibrusError(ErrorKind.PARSE)
333
+ correction = GradeCorrection(
334
+ subject, period, tuple(cast(str, member) for member in members)
335
+ )
336
+ if points:
337
+ # Brackets were not observed in the point table. Only a period
338
+ # grade it shows again, already read from the ordinary table, is
339
+ # accepted, as one link like its record.
340
+ if correction not in collection.corrections:
341
+ raise LibrusError(ErrorKind.PARSE)
342
+ continue
343
+ grade_ids = correction.grade_ids
344
+ if len(set(grade_ids)) != len(grade_ids) or not collection.corrected.isdisjoint(
345
+ grade_ids
346
+ ):
347
+ raise LibrusError(ErrorKind.PARSE)
348
+ collection.corrected.update(grade_ids)
349
+ collection.corrections.append(correction)
350
+
351
+
352
+ def _behaviour_point_entry(element: html.HtmlElement) -> BehaviourPointEntry:
353
+ """A point entry's link: signed points, detail ID and its tooltip.
354
+
355
+ The tooltip has an unlabelled first line, the category, then only
356
+ `config.BEHAVIOUR_POINT_LABELS`; `Data wystawienia` is required. A first
357
+ line that is a known label means the category is missing and fails.
358
+ """
359
+ detail = markup.detail_id(element.get("href"), BEHAVIOUR_POINTS_DETAIL_PATH_PREFIX)
360
+ raw = markup.text(element)
361
+ if detail is None or not re.fullmatch(r"[+-]?[0-9]{1,4}", raw):
362
+ raise LibrusError(ErrorKind.PARSE)
363
+ heading: list[str] = []
364
+ metadata = markup.tooltip_fields(element, heading)
365
+ if (
366
+ not heading
367
+ or heading[0].partition(":")[0].strip() in TOOLTIP_LABELS
368
+ or not BEHAVIOUR_POINT_LABELS >= metadata.keys()
369
+ ):
370
+ raise LibrusError(ErrorKind.PARSE)
371
+ return BehaviourPointEntry(
372
+ int(raw),
373
+ detail,
374
+ heading[0],
375
+ markup.civil_date(metadata.get("Data wystawienia")),
376
+ tuple(metadata.items()),
377
+ )
378
+
379
+
380
+ def _behaviour_points(
381
+ cell: html.HtmlElement,
382
+ period: Literal[1, 2] | None,
383
+ collection: _Collection,
384
+ *,
385
+ points: bool = False,
386
+ ) -> bool:
387
+ """Read a behaviour-points cell into `collection.behaviour`; not grades.
388
+
389
+ The cell holds one tooltip span showing an integer, the tally (its title
390
+ is not interpreted), and point entries linking to behaviour details, each
391
+ with its own tooltip. Any other content next to the tally fails instead of
392
+ being skipped. The point table may show the same cell again: an equal item
393
+ is one item, a different one for the same period fails, and only an item
394
+ that is appended counts toward `GRADE_MAX_RECORDS`. A cell spanning both
395
+ periods (`period` None) holds no entries and is validated, not recorded:
396
+ its period would be a guess.
271
397
  """
272
398
  tallies = [
273
399
  node
@@ -278,15 +404,20 @@ def _behaviour_points(cell: html.HtmlElement, collection: _Collection) -> bool:
278
404
  return False
279
405
  elements = [node for node in cell if isinstance(node.tag, str)]
280
406
  boxes = [node for node in elements if node not in tallies]
407
+ tally = markup.text(tallies[0])
281
408
  if (
282
409
  len(tallies) != 1
283
410
  or len(tallies[0])
284
- or not re.fullmatch(r"-?[0-9]{1,4}", markup.text(tallies[0]))
411
+ or not re.fullmatch(r"-?[0-9]{1,4}", tally)
285
412
  or (cell.text or "").strip()
286
413
  or any((node.tail or "").strip() for node in cell)
287
414
  or _boxes(cell) != boxes
288
415
  ):
289
416
  raise LibrusError(ErrorKind.PARSE)
417
+ same = [known for known in collection.behaviour if known.semester == period]
418
+ if same and not points:
419
+ raise LibrusError(ErrorKind.PARSE)
420
+ entries = []
290
421
  for box in boxes:
291
422
  anchors = [node for node in box if isinstance(node.tag, str)]
292
423
  if (
@@ -294,14 +425,20 @@ def _behaviour_points(cell: html.HtmlElement, collection: _Collection) -> bool:
294
425
  or len(anchors) != 1
295
426
  or anchors[0].tag != "a"
296
427
  or len(anchors[0])
297
- or markup.detail_id(
298
- anchors[0].get("href"), BEHAVIOUR_POINTS_DETAIL_PATH_PREFIX
299
- )
300
- is None
301
- or not re.fullmatch(r"[+-]?[0-9]{1,4}", markup.text(anchors[0]))
302
428
  ):
303
429
  raise LibrusError(ErrorKind.PARSE)
304
- collection.consumed.add(box)
430
+ entries.append(_behaviour_point_entry(anchors[0]))
431
+ if not same:
432
+ collection.check_size(len(entries))
433
+ elif len(entries) > len(same[0].entries):
434
+ raise LibrusError(ErrorKind.PARSE)
435
+ if period is not None:
436
+ item = BehaviourPoints(period, int(tally), tuple(entries))
437
+ if not same:
438
+ collection.behaviour.append(item)
439
+ elif same != [item]:
440
+ raise LibrusError(ErrorKind.PARSE)
441
+ collection.consumed.update(boxes)
305
442
  return True
306
443
 
307
444
 
@@ -314,8 +451,11 @@ def _entries(
314
451
  kind: GradeKind = GradeKind.CURRENT,
315
452
  descriptive: bool = False,
316
453
  require_empty_marker: bool = True,
454
+ points: bool = False,
317
455
  ) -> None:
318
456
  boxes = _boxes(cell)
457
+ groups = _brackets(cell, boxes) if boxes else []
458
+ ids: dict[html.HtmlElement, str | None] = {}
319
459
  if (
320
460
  not boxes
321
461
  and require_empty_marker
@@ -376,14 +516,17 @@ def _entries(
376
516
  href,
377
517
  )
378
518
  )
519
+ ids[box] = collection.descriptive[-1].grade_id
379
520
  else:
380
521
  collection.numeric.append(record)
522
+ ids[box] = record.grade_id
381
523
  else:
382
524
  collection.descriptive.append(
383
525
  _descriptive(box, descriptions[0], subject, period, kind)
384
526
  )
385
527
  collection.consumed.add(box)
386
528
  collection.check_size()
529
+ _read_corrections(groups, ids, subject, period, collection, points=points)
387
530
 
388
531
 
389
532
  def _descriptive_row(cells: list[html.HtmlElement]) -> bool:
@@ -475,18 +618,28 @@ def _read_numeric_table(
475
618
  )
476
619
  )
477
620
  averages.append(SchoolAverage(subject, period, value))
478
- if columns[current[0]] is columns[current[1]] and _boxes(columns[current[0]]):
621
+ spanning = columns[current[0]] is columns[current[1]]
622
+ if spanning and _boxes(columns[current[0]]):
479
623
  raise LibrusError(ErrorKind.PARSE)
480
624
  seen: set[html.HtmlElement] = set()
481
625
  for period, index in enumerate(current, start=1):
482
626
  if columns[index] not in seen:
483
627
  if not (
484
628
  subject in GRADE_MERGED_SUBJECTS
485
- and _behaviour_points(columns[index], collection)
629
+ and _behaviour_points(
630
+ columns[index],
631
+ None if spanning else cast(Literal[1, 2], period),
632
+ collection,
633
+ points=points,
634
+ )
486
635
  ):
487
636
  start = len(collection.numeric)
488
637
  _entries(
489
- columns[index], subject, cast(Literal[1, 2], period), collection
638
+ columns[index],
639
+ subject,
640
+ cast(Literal[1, 2], period),
641
+ collection,
642
+ points=points,
490
643
  )
491
644
  # A point entry without its detail link would pass as a
492
645
  # grade symbol; an unseen link layout fails instead. The
@@ -509,6 +662,7 @@ def _read_numeric_table(
509
662
  collection,
510
663
  kind=kind,
511
664
  require_empty_marker=False,
665
+ points=points,
512
666
  )
513
667
  collection.numeric[start:] = [
514
668
  record for record in collection.numeric[start:] if record not in prior
@@ -674,4 +828,6 @@ def read_grade_records(document: html.HtmlElement) -> GradeRecords:
674
828
  tuple(collection.descriptive_summaries),
675
829
  formative,
676
830
  tuple(collection.point_results),
831
+ tuple(collection.corrections),
832
+ tuple(collection.behaviour),
677
833
  )