@wilm-ai/wilma-client 1.3.0 → 1.4.1

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wilm.ai
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.
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Exam, Message, MessageFolder, NewsItem, OverviewData, WilmaProfile, StudentInfo } from "./types.js";
1
+ import type { Exam, Message, MessageFolder, NewsItem, OverviewData, WilmaProfile, StudentInfo, LessonNote } from "./types.js";
2
2
  export type MfaCallback = (formkey: string) => Promise<string>;
3
3
  export declare class WilmaClient {
4
4
  private session;
@@ -19,6 +19,11 @@ export declare class WilmaClient {
19
19
  end?: string;
20
20
  }) => Promise<Exam[]>;
21
21
  };
22
+ attendance: {
23
+ list: (opts?: {
24
+ date?: string;
25
+ }) => Promise<LessonNote[]>;
26
+ };
22
27
  overview: {
23
28
  get: () => Promise<OverviewData>;
24
29
  };
package/dist/client.js CHANGED
@@ -3,6 +3,7 @@ import { parseWilmaTimestamp } from "./parsers/dates.js";
3
3
  import { parseMessagesList, parseMessageDetailHtml } from "./parsers/messages.js";
4
4
  import { parseNewsDetailHtml, parseNewsDetailJson, parseNewsList, parseNewsListHtml, } from "./parsers/news.js";
5
5
  import { parseExamsHtml } from "./parsers/exams.js";
6
+ import { parseAttendanceHtml } from "./parsers/attendance.js";
6
7
  import { parseOverview } from "./parsers/overview.js";
7
8
  import { parseStudentsFromHome } from "./parsers/students.js";
8
9
  export class WilmaClient {
@@ -124,6 +125,19 @@ export class WilmaClient {
124
125
  return parseExamsHtml(text);
125
126
  },
126
127
  };
128
+ attendance = {
129
+ list: async (opts) => {
130
+ const params = new URLSearchParams();
131
+ if (opts?.date) {
132
+ params.set("date", opts.date);
133
+ }
134
+ const query = params.toString();
135
+ const path = query ? `/attendance/view?${query}` : "/attendance/view";
136
+ const resp = await this.session.get(path);
137
+ const text = await resp.text();
138
+ return parseAttendanceHtml(text, opts?.date ?? "");
139
+ },
140
+ };
127
141
  overview = {
128
142
  get: async () => {
129
143
  const resp = await this.session.get("/overview");
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type { Exam, ExamGrade, HomeworkItem, Message, MessageFolder, Municipality, NewsItem, OverviewData, ScheduleLesson, TenantDiscoveryResponse, TenantInfo, UpcomingExam, WilmaProfile, StudentInfo, } from "./types.js";
1
+ export type { Exam, ExamGrade, HomeworkItem, LessonNote, Message, MessageFolder, Municipality, NewsItem, OverviewData, ScheduleLesson, TenantDiscoveryResponse, TenantInfo, UpcomingExam, WilmaProfile, StudentInfo, } from "./types.js";
2
2
  export { WilmaClient } from "./client.js";
3
3
  export type { MfaCallback } from "./client.js";
4
4
  export { WilmaSession, AuthenticationError, MfaRequiredError, APIError } from "./session.js";
@@ -0,0 +1,18 @@
1
+ import type { LessonNote } from "../types.js";
2
+ /**
3
+ * Parse Wilma's /attendance/view HTML page into structured LessonNote objects.
4
+ *
5
+ * The attendance table is a fine-grained grid: <thead> declares hour-group
6
+ * headers like `<th colspan="3">9</th>`, and tbody rows mix `<td>` cells with
7
+ * varying colspans (filler `<td colspan="2">`, event `<td colspan="3">`, etc).
8
+ * To map an event `<td>` to its hour, we walk cumulative grid columns (sum of
9
+ * colspans) within the row and look up the column's hour group from the thead.
10
+ *
11
+ * Counting `<td>` indices alone is wrong: a `<td colspan="3">` filler skips
12
+ * three grid columns but consumes one index, so by the third or fourth cell
13
+ * the index has drifted from the true grid column.
14
+ *
15
+ * Title attribute on event cells: "TypeLabel /TeacherName" or
16
+ * "SubjectCode; TypeLabel /TeacherName".
17
+ */
18
+ export declare function parseAttendanceHtml(html: string, date: string): LessonNote[];
@@ -0,0 +1,121 @@
1
+ import * as cheerio from "cheerio";
2
+ /**
3
+ * Parse Wilma's /attendance/view HTML page into structured LessonNote objects.
4
+ *
5
+ * The attendance table is a fine-grained grid: <thead> declares hour-group
6
+ * headers like `<th colspan="3">9</th>`, and tbody rows mix `<td>` cells with
7
+ * varying colspans (filler `<td colspan="2">`, event `<td colspan="3">`, etc).
8
+ * To map an event `<td>` to its hour, we walk cumulative grid columns (sum of
9
+ * colspans) within the row and look up the column's hour group from the thead.
10
+ *
11
+ * Counting `<td>` indices alone is wrong: a `<td colspan="3">` filler skips
12
+ * three grid columns but consumes one index, so by the third or fourth cell
13
+ * the index has drifted from the true grid column.
14
+ *
15
+ * Title attribute on event cells: "TypeLabel /TeacherName" or
16
+ * "SubjectCode; TypeLabel /TeacherName".
17
+ */
18
+ export function parseAttendanceHtml(html, date) {
19
+ const $ = cheerio.load(html);
20
+ const notes = [];
21
+ const targetFinnish = dateToFinnish(date);
22
+ $("table").each((_, table) => {
23
+ const $table = $(table);
24
+ // Build a flat array indexed by grid-column whose value is the hour.
25
+ // thead has hour-labeled <th>s with colspans (e.g. <th colspan="3">9</th>);
26
+ // replicate each hour by its colspan to get a column->hour lookup.
27
+ // Non-numeric headers (Päivämäärä, Yhteensä, Huomioita) are skipped.
28
+ const hourMap = [];
29
+ $table.find("thead th").each((_, th) => {
30
+ const text = $(th).text().trim();
31
+ const hour = parseInt(text, 10);
32
+ if (!Number.isNaN(hour) && hour >= 0 && hour <= 23) {
33
+ const colspan = parseInt($(th).attr("colspan") ?? "1", 10) || 1;
34
+ for (let i = 0; i < colspan; i++)
35
+ hourMap.push(hour);
36
+ }
37
+ });
38
+ if (hourMap.length === 0)
39
+ return; // not the attendance table (e.g. legend)
40
+ $table.find("tbody tr").each((_, row) => {
41
+ const cells = $(row).find("td").toArray();
42
+ if (cells.length < 3)
43
+ return; // need at least weekday, date, and one slot
44
+ const rowDate = $(cells[1]).text().trim();
45
+ if (!rowDate || rowDate !== targetFinnish)
46
+ return;
47
+ // Walk event-grid cells. Indices 0..1 are weekday + date (outside grid).
48
+ let gridCol = 0;
49
+ for (let i = 2; i < cells.length; i++) {
50
+ const $cell = $(cells[i]);
51
+ const colspan = parseInt($cell.attr("colspan") ?? "1", 10) || 1;
52
+ const tpClass = (($cell.attr("class") ?? "").match(/\bat-tp\d+\b/) ?? [])[0];
53
+ if (tpClass) {
54
+ const title = ($cell.attr("title") ?? "").trim();
55
+ const cellText = $cell.text().trim();
56
+ // Title formats observed:
57
+ // "TypeLabel /TeacherFullName"
58
+ // "SubjectCode; TypeLabel /TeacherFullName"
59
+ // "SubjectCode; TypeLabel; ExtraNote /TeacherFullName"
60
+ let subject = "";
61
+ let typeLabel = "";
62
+ let teacher = cellText;
63
+ if (title) {
64
+ let rest = title;
65
+ const semiIdx = rest.indexOf(";");
66
+ if (semiIdx > 0) {
67
+ subject = rest.slice(0, semiIdx).trim();
68
+ rest = rest.slice(semiIdx + 1).trim();
69
+ }
70
+ const slashIdx = rest.lastIndexOf(" /");
71
+ if (slashIdx > 0) {
72
+ const afterSlash = rest.slice(slashIdx + 2);
73
+ const spaceAfter = afterSlash.startsWith(" ") ? 1 : 0;
74
+ typeLabel = rest.slice(0, slashIdx).trim();
75
+ teacher = rest.slice(slashIdx + 2 + spaceAfter).trim();
76
+ }
77
+ }
78
+ // Map cell's grid range to start/end via the thead-derived map.
79
+ // start = hour at the cell's first grid column.
80
+ // end = hour at the cell's last grid column + 45 min.
81
+ // If the cell extends past the mapped grid (shouldn't happen with
82
+ // well-formed tables), report null so consumers don't see a wrong time.
83
+ const startHour = hourMap[gridCol];
84
+ const endHour = hourMap[gridCol + colspan - 1];
85
+ let start = null;
86
+ let end = null;
87
+ if (startHour !== undefined && endHour !== undefined) {
88
+ start = `${pad(startHour)}:00`;
89
+ end = `${pad(endHour)}:45`;
90
+ }
91
+ notes.push({
92
+ date,
93
+ start,
94
+ end,
95
+ subject,
96
+ typeLabel: typeLabel || tpClass.replace("at-tp", "Type "),
97
+ typeClass: tpClass,
98
+ teacher,
99
+ });
100
+ }
101
+ gridCol += colspan;
102
+ }
103
+ });
104
+ });
105
+ return notes;
106
+ }
107
+ function pad(n) {
108
+ return String(n).padStart(2, "0");
109
+ }
110
+ function dateToFinnish(date) {
111
+ // Convert YYYY-MM-DD to D.M.YYYY (Finnish format, no leading zeros).
112
+ if (!date)
113
+ return "";
114
+ const parts = date.split("-");
115
+ if (parts.length !== 3)
116
+ return date;
117
+ const day = parseInt(parts[2], 10);
118
+ const month = parseInt(parts[1], 10);
119
+ const year = parts[0];
120
+ return `${day}.${month}.${year}`;
121
+ }
@@ -79,9 +79,53 @@ export function parseMessageDetailHtml(html, messageId) {
79
79
  });
80
80
  }
81
81
  let content = null;
82
- const hidden = $("div.ckeditor.hidden").first();
83
- if (hidden.length) {
84
- content = hidden.text().trim();
82
+ const replyBoxes = $("div.m-replybox.hidden");
83
+ if (replyBoxes.length > 0) {
84
+ const otherReplies = replyBoxes.filter(function () {
85
+ return !$(this).hasClass("m-replybox-me");
86
+ });
87
+ if (otherReplies.length > 0) {
88
+ const latest = otherReplies.last();
89
+ const inner = latest.find("div.inner.hidden");
90
+ if (inner.length) {
91
+ content = inner.text().trim();
92
+ const replyHeaderText = latest.find("h2").first().text().trim();
93
+ const replySender = latest.find("a.profile-link").first();
94
+ if (replySender.length) {
95
+ senderName = replySender.text().trim();
96
+ sendersJson = {
97
+ senders: [
98
+ {
99
+ Name: senderName,
100
+ Href: replySender.attr("href"),
101
+ },
102
+ ],
103
+ };
104
+ }
105
+ else {
106
+ const replySenderName = extractReplySenderName(replyHeaderText);
107
+ if (replySenderName) {
108
+ senderName = replySenderName;
109
+ sendersJson = {
110
+ senders: [
111
+ {
112
+ Name: senderName,
113
+ },
114
+ ],
115
+ };
116
+ }
117
+ }
118
+ if (replyHeaderText) {
119
+ sentAt = parseWilmaTimestamp(extractReplyTimestampText(replyHeaderText));
120
+ }
121
+ }
122
+ }
123
+ }
124
+ if (!content) {
125
+ const hidden = $("div.ckeditor.hidden").first();
126
+ if (hidden.length) {
127
+ content = hidden.text().trim();
128
+ }
85
129
  }
86
130
  if (!content && panelBody.length) {
87
131
  const clone = cheerio.load(panelBody.html() ?? "");
@@ -138,3 +182,12 @@ export function debugMessageFields(data) {
138
182
  function compactText(value) {
139
183
  return value.replace(/\s+/g, " ").trim();
140
184
  }
185
+ function extractReplyTimestampText(headerText) {
186
+ const absoluteDateTime = /(\d{1,2}\.\d{1,2}\.\d{4}\s+\d{1,2}:\d{2})/.exec(headerText);
187
+ return absoluteDateTime?.[1] ?? headerText;
188
+ }
189
+ function extractReplySenderName(headerText) {
190
+ const match = /^(.+?)\s+(?:vastasi|svarade|replied)\b/i.exec(compactText(headerText));
191
+ const sender = match?.[1]?.trim();
192
+ return sender || null;
193
+ }
package/dist/types.d.ts CHANGED
@@ -110,3 +110,18 @@ export interface OverviewData {
110
110
  homework: HomeworkItem[];
111
111
  fetchedAt: Date;
112
112
  }
113
+ /**
114
+ * A lesson note from the attendance/lesson notes page.
115
+ * start/end are string | null — null when time-slot derivation
116
+ * falls outside the assumed 08:00–15:00 range (see parseAttendanceHtml).
117
+ */
118
+ export interface LessonNote {
119
+ /** YYYY-MM-DD */
120
+ date: string;
121
+ start: string | null;
122
+ end: string | null;
123
+ subject: string;
124
+ typeLabel: string;
125
+ typeClass: string;
126
+ teacher: string;
127
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wilm-ai/wilma-client",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -14,13 +14,6 @@
14
14
  "dist",
15
15
  "tenant_list.json"
16
16
  ],
17
- "scripts": {
18
- "build": "tsc -p tsconfig.json",
19
- "lint": "echo 'add lint'",
20
- "test": "echo 'add tests'",
21
- "test:smoke": "tsc -p tsconfig.json && node test/smoke.mjs",
22
- "test:live": "tsc -p tsconfig.json && node test/live.spec.mjs"
23
- },
24
17
  "dependencies": {
25
18
  "cheerio": "^1.0.0-rc.12",
26
19
  "tough-cookie": "^4.1.4",
@@ -29,5 +22,12 @@
29
22
  "devDependencies": {
30
23
  "typescript": "^5.6.3",
31
24
  "@types/tough-cookie": "^4.0.5"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "lint": "echo 'add lint'",
29
+ "test": "pnpm run build && node test/parser-messages.mjs",
30
+ "test:smoke": "tsc -p tsconfig.json && node test/smoke.mjs",
31
+ "test:live": "tsc -p tsconfig.json && node test/live.spec.mjs"
32
32
  }
33
- }
33
+ }