iobroker.time-tracker 0.2.6 → 0.3.0
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/README.md +25 -14
- package/build/lib/adapter/commands.js +18 -3
- package/build/lib/adapter/commands.js.map +2 -2
- package/build/lib/adapter/messages.js +11 -2
- package/build/lib/adapter/messages.js.map +2 -2
- package/build/lib/db/migrations.js +9 -0
- package/build/lib/db/migrations.js.map +2 -2
- package/build/lib/db/repositories/users.js +13 -7
- package/build/lib/db/repositories/users.js.map +2 -2
- package/build/lib/services/aggregation.js +2 -1
- package/build/lib/services/aggregation.js.map +2 -2
- package/build/lib/web/api.js +17 -5
- package/build/lib/web/api.js.map +2 -2
- package/build/main.js +38 -3
- package/build/main.js.map +2 -2
- package/io-package.json +27 -27
- package/package.json +1 -1
- package/src-pwa/src/i18n/de.json +4 -1
- package/src-pwa/src/i18n/en.json +4 -1
- package/src-pwa/src/i18n/es.json +4 -1
- package/src-pwa/src/i18n/fr.json +4 -1
- package/src-pwa/src/i18n/it.json +4 -1
- package/src-pwa/src/i18n/nl.json +4 -1
- package/src-pwa/src/i18n/pl.json +4 -1
- package/src-pwa/src/i18n/pt.json +4 -1
- package/src-pwa/src/i18n/ru.json +4 -1
- package/src-pwa/src/i18n/uk.json +4 -1
- package/src-pwa/src/i18n/zh-cn.json +4 -1
- package/www/assets/index-BW4HvYbk.js +119 -0
- package/www/assets/index-BW4HvYbk.js.map +1 -0
- package/www/index.html +1 -1
- package/www/sw.js +1 -1
- package/www/sw.js.map +1 -1
- package/www/assets/index-QI3wrEvW.js +0 -119
- package/www/assets/index-QI3wrEvW.js.map +0 -1
package/README.md
CHANGED
|
@@ -131,6 +131,11 @@ Everything is served on the port of the instance settings:
|
|
|
131
131
|
| `/terminal?token=…` | the kiosk screen (badge and PIN) |
|
|
132
132
|
| `/presence?token=…` | the board “who is at work right now” |
|
|
133
133
|
|
|
134
|
+
The board shows every employee with the state of the day. The **worked time of today** appears next to it
|
|
135
|
+
(`1:23`, `0:00` before the first punch of the day) once the **work profile** of that employee allows it
|
|
136
|
+
(*Arbeitszeit auf der Anwesenheitskarte*, off by default): the board is visible before the PIN is entered, so the
|
|
137
|
+
administration decides this per employee — the API only sends the minutes for employees who agreed.
|
|
138
|
+
|
|
134
139
|
### Terminal (kiosk)
|
|
135
140
|
|
|
136
141
|
Switch **Enable kiosk terminal** on, then create the device in **Administration → Terminals** and copy the device
|
|
@@ -348,6 +353,26 @@ local SQLite file, access is role-based, and every correction is written to an a
|
|
|
348
353
|
|
|
349
354
|
### **WORK IN PROGRESS**
|
|
350
355
|
|
|
356
|
+
### 0.3.0 (2026-09-22)
|
|
357
|
+
|
|
358
|
+
- (Alex) new: the presence board can show the working time of today on the employee tiles — `1:23` next to
|
|
359
|
+
`Present`/`Away` (`0:00` before the first punch), and the tile keeps counting while the employee is present. It is
|
|
360
|
+
switched on **per employee** in the work profile (*Arbeitszeit auf der Anwesenheitskarte*, off by default), because
|
|
361
|
+
the board is visible before the PIN is entered — the decision is made on the server, the API only sends the minutes
|
|
362
|
+
for employees who agreed (`/terminal/users` and `/terminal/punch`). The new column
|
|
363
|
+
`work_profiles.show_worked_time` arrives with migration 20
|
|
364
|
+
|
|
365
|
+
### 0.2.7 (2026-09-22)
|
|
366
|
+
|
|
367
|
+
- (Alex) fix: **every** punch path reaches `events.*` and the web app now. Besides the presence state (0.2.6) the
|
|
368
|
+
`commands.punch`/`quickPunch` buttons, a `sendTo` message (`punch`, `present`) and the trigger rules (Actions) wrote
|
|
369
|
+
the punch and refreshed the figures but never published an event — the event states kept the punch before. The
|
|
370
|
+
results carry `userId` and `direction` now, and `punchEvent` (like `presenceEvent`) builds the bus event for them;
|
|
371
|
+
the automation rules send the direction with their `automation.*` event
|
|
372
|
+
- (Alex) test: the end-to-end suite is deterministic again — the correction spec anchors its “forgotten day” inside the
|
|
373
|
+
local day (`now - 8h` fell on the day before when the suite ran shortly after midnight and left the employee
|
|
374
|
+
present for the specs that follow), and the presence spec puts its employee into a known state before it asserts
|
|
375
|
+
|
|
351
376
|
### 0.2.6 (2026-09-22)
|
|
352
377
|
|
|
353
378
|
- (Alex) fix: a punch from the presence state (`users.<id>.present`) is published like every other one now — it shows
|
|
@@ -369,20 +394,6 @@ local SQLite file, access is role-based, and every correction is written to an a
|
|
|
369
394
|
states — both with copy-ready examples and the two traps (buttons act on `true` only, a wrong period answers in the
|
|
370
395
|
log)
|
|
371
396
|
|
|
372
|
-
### 0.2.3 (2026-09-20)
|
|
373
|
-
|
|
374
|
-
- (Alex) fix: a corrected object definition really reaches existing installations now — `ensureObject` merges the
|
|
375
|
-
fields the adapter owns (`name`, `type`, `role`, `read`, `write`, `unit`) instead of only the name. An installation
|
|
376
|
-
created before 0.2.2 kept its old `role: "value"` on `commands.punchUserId`, so the object structure check still
|
|
377
|
-
reported `E1011`
|
|
378
|
-
|
|
379
|
-
### 0.2.2 (2026-09-20)
|
|
380
|
-
|
|
381
|
-
- (Alex) object structure check: every object name carries all **eleven languages** now (`E6001`) and the employee-id
|
|
382
|
-
command uses the role **`level`** instead of `value` (`E1011`). The names live in one place
|
|
383
|
-
(`src/lib/adapter/stateNames.ts`), a unit test keeps them complete, and existing installations receive the new
|
|
384
|
-
names on the next start (`extendObject`)
|
|
385
|
-
|
|
386
397
|
Older entries are kept in [`CHANGELOG_OLD.md`](CHANGELOG_OLD.md).
|
|
387
398
|
|
|
388
399
|
## Provenance
|
|
@@ -19,7 +19,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
19
19
|
var commands_exports = {};
|
|
20
20
|
__export(commands_exports, {
|
|
21
21
|
handleCommand: () => handleCommand,
|
|
22
|
-
punchEmployee: () => punchEmployee
|
|
22
|
+
punchEmployee: () => punchEmployee,
|
|
23
|
+
punchEvent: () => punchEvent
|
|
23
24
|
});
|
|
24
25
|
module.exports = __toCommonJS(commands_exports);
|
|
25
26
|
var import_errors = require("../errors");
|
|
@@ -86,7 +87,20 @@ function punchEmployee(deps, input) {
|
|
|
86
87
|
return {
|
|
87
88
|
ok: true,
|
|
88
89
|
message: `${target.displayName} punched ${direction} (${day.workedMin} min today, open: ${day.hasOpenEntry})`,
|
|
89
|
-
recalculated: [stored.entry.localDate]
|
|
90
|
+
recalculated: [stored.entry.localDate],
|
|
91
|
+
userId: target.id,
|
|
92
|
+
direction
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function punchEvent(result, source, atUtc) {
|
|
96
|
+
if (!result.ok || !result.direction || result.userId === void 0) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
type: "punch",
|
|
101
|
+
atUtc,
|
|
102
|
+
userId: result.userId,
|
|
103
|
+
data: { direction: result.direction, source }
|
|
90
104
|
};
|
|
91
105
|
}
|
|
92
106
|
function handleCommand(deps, id, value) {
|
|
@@ -175,6 +189,7 @@ function handleCommand(deps, id, value) {
|
|
|
175
189
|
// Annotate the CommonJS export names for ESM import in node:
|
|
176
190
|
0 && (module.exports = {
|
|
177
191
|
handleCommand,
|
|
178
|
-
punchEmployee
|
|
192
|
+
punchEmployee,
|
|
193
|
+
punchEvent
|
|
179
194
|
});
|
|
180
195
|
//# sourceMappingURL=commands.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/adapter/commands.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Command states of the adapter.\n *\n * The adapter reacts to the states below, so a script, a dashboard or another adapter can punch, close a month\n * or trigger a recalculation without the REST API. Commands are triggered from inside ioBroker, not from a\n * browser, so no session is involved; the audit trail records them with `actorId: 0` (system).\n */\n\nimport type { Db } from \"../db/database\";\nimport type { EntriesRepository } from \"../db/repositories/entries\";\nimport type { SettingsRepository } from \"../db/repositories/settings\";\nimport type { UsersRepository } from \"../db/repositories/users\";\nimport type { AggregationService } from \"../services/aggregation\";\nimport type { ClosingService } from \"../services/closing\";\nimport type { BackupService } from \"../services/backup\";\nimport { ValidationError } from \"../errors\";\nimport { buildDayPunches, nextDirection, roundToStep, type PunchEntry } from \"../domain/punch\";\nimport { localDate as resolveLocalDate } from \"../util/time\";\nimport { COMMAND_IDS } from \"./states\";\n\n/** Data sources of the command handler. */\nexport interface CommandDeps {\n\t/** Open database handle */\n\tdb: Db;\n\t/** Punch storage */\n\tentries: EntriesRepository;\n\t/** User storage */\n\tusers: UsersRepository;\n\t/** Instance settings (quick rounding, target employee) */\n\tsettings: SettingsRepository;\n\t/** Aggregation service */\n\taggregation: Pick<AggregationService, \"recalculateDay\" | \"recalculateMonth\" | \"recalculateYear\">;\n\t/** Closing service (month close) */\n\tclosing: Pick<ClosingService, \"closeMonth\">;\n\t/** Backup service (button `commands.backup`), optional */\n\tbackup?: Pick<BackupService, \"create\">;\n\t/** Instant source, defaults to the system clock */\n\tnow?: () => number;\n}\n\n/** Result of a command. */\nexport interface CommandResult {\n\t/** True when the command was executed */\n\tok: boolean;\n\t/** Human readable summary for the log */\n\tmessage: string;\n\t/** Local dates that were recalculated */\n\trecalculated: string[];\n}\n\n/** A period taken from a command value. */\ninterface Period {\n\t/** Four digit year */\n\tyear: number;\n\t/** Month (1 to 12) or `null` for a whole year */\n\tmonth: number | null;\n}\n\n/**\n * Parses a period string.\n *\n * @param value - `YYYY-MM` or `YYYY`\n * @returns the parsed period\n */\nfunction parsePeriod(value: string): Period {\n\tconst monthMatch = /^(\\d{4})-(\\d{1,2})$/.exec(value.trim());\n\tif (monthMatch) {\n\t\tconst month = Number(monthMatch[2]);\n\t\tif (month < 1 || month > 12) {\n\t\t\tthrow new ValidationError(`month must be between 1 and 12 (got ${value})`);\n\t\t}\n\t\treturn { year: Number(monthMatch[1]), month };\n\t}\n\n\tconst yearMatch = /^(\\d{4})$/.exec(value.trim());\n\tif (yearMatch) {\n\t\treturn { year: Number(yearMatch[1]), month: null };\n\t}\n\tthrow new ValidationError(`expected YYYY-MM or YYYY (got \"${value}\")`);\n}\n\n/**\n * Resolves the employee a command applies to: the only one, or the configured one.\n *\n * @param deps - data sources\n * @returns the employee\n */\nfunction targetUser(deps: CommandDeps): { id: number; displayName: string; timezone: string } {\n\tconst configured = Number(deps.settings.get(\"command_punch_user_id\") ?? Number.NaN);\n\tconst explicit = Number.isInteger(configured) ? deps.users.findById(configured) : null;\n\tif (explicit) {\n\t\treturn explicit;\n\t}\n\n\tconst candidates = deps.users.list();\n\tif (candidates.length === 1) {\n\t\treturn candidates[0];\n\t}\n\tif (candidates.length === 0) {\n\t\tthrow new ValidationError(\"no employee exists yet\");\n\t}\n\tthrow new ValidationError(\"several employees exist - set command_punch_user_id or write users.<id> commands\");\n}\n\n/** Data a punch needs: where to write, how to round and how to recalculate. */\nexport type PunchDeps = Pick<CommandDeps, \"entries\" | \"users\" | \"settings\" | \"aggregation\" | \"now\">;\n\n/**\n * Punches in or out for one employee.\n *\n * This is the single punch path of the adapter: the `commands.punch` button, a trigger rule and a `sendTo`\n * message all end up here, so direction, rounding, note and recalculation behave the same everywhere.\n *\n * @param deps - data sources\n * @param input - employee, rounding and note\n * @param input.userId - employee the punch belongs to\n * @param input.quick - true to round the instant with the configured quick rounding\n * @param input.note - note stored with the punch\n * @param input.now - instant of the punch, defaults to the system clock\n * @returns result of the punch\n */\nexport function punchEmployee(\n\tdeps: PunchDeps,\n\tinput: { userId: number; quick?: boolean; note?: string; now?: number },\n): CommandResult {\n\tconst target = deps.users.findById(input.userId);\n\tif (!target) {\n\t\tthrow new ValidationError(`employee ${input.userId} does not exist`);\n\t}\n\tif (!target.isActive) {\n\t\tthrow new ValidationError(`${target.displayName} is deactivated, no punch was written`);\n\t}\n\n\tconst now = deps.now ?? (() => Math.floor(Date.now() / 1000));\n\tconst timestamp = input.now ?? now();\n\tconst quickRound = input.quick === true ? deps.settings.getNumber(\"quick_round_minutes\", 0) : 0;\n\tconst tsUtc = quickRound > 0 ? roundToStep(timestamp, quickRound, target.timezone) : timestamp;\n\tconst today = resolveLocalDate(tsUtc, target.timezone);\n\n\tconst existing: PunchEntry[] = deps.entries\n\t\t.listByDate(target.id, today)\n\t\t.map(entry => ({ id: entry.id, tsUtc: entry.tsUtc, syncState: entry.syncState }));\n\tconst direction = nextDirection(buildDayPunches(existing));\n\n\tconst stored = deps.entries.insert({\n\t\tuserId: target.id,\n\t\ttsUtc,\n\t\ttimeZone: target.timezone,\n\t\tsource: \"api\",\n\t\tdirection,\n\t\tnote: input.note ?? null,\n\t\tnow: timestamp,\n\t});\n\tconst day = deps.aggregation.recalculateDay(target.id, stored.entry.localDate, { now: timestamp });\n\n\treturn {\n\t\tok: true,\n\t\tmessage: `${target.displayName} punched ${direction} (${day.workedMin} min today, open: ${day.hasOpenEntry})`,\n\t\trecalculated: [stored.entry.localDate],\n\t};\n}\n\n/**\n * Handles a command state.\n *\n * @param deps - data sources\n * @param id - state id that was written (without the instance prefix)\n * @param value - value that was written\n * @returns result of the command\n */\nexport function handleCommand(deps: CommandDeps, id: string, value: ioBroker.StateValue): CommandResult {\n\tconst now = deps.now ?? (() => Math.floor(Date.now() / 1000));\n\tconst timestamp = now();\n\n\tif (id === COMMAND_IDS.punchUserId) {\n\t\t// The state chooses the employee the punch commands apply to (`0` = take the only employee again).\n\t\tconst userId = Number(value ?? Number.NaN);\n\t\tif (!Number.isInteger(userId) || userId < 0) {\n\t\t\tthrow new ValidationError(`expected the id of an employee or 0 (got \"${String(value ?? \"\")}\")`);\n\t\t}\n\t\tif (userId === 0) {\n\t\t\tdeps.settings.set(\"command_punch_user_id\", 0, 0, timestamp);\n\t\t\treturn { ok: true, message: \"punch commands use the only employee again\", recalculated: [] };\n\t\t}\n\t\tconst chosen = deps.users.findById(userId);\n\t\tif (!chosen) {\n\t\t\tthrow new ValidationError(`employee ${userId} does not exist`);\n\t\t}\n\t\tdeps.settings.set(\"command_punch_user_id\", userId, 0, timestamp);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `punch commands now apply to ${chosen.displayName}`,\n\t\t\trecalculated: [],\n\t\t};\n\t}\n\n\tif (id === COMMAND_IDS.closeMonth || id === COMMAND_IDS.recalc) {\n\t\tconst period = parsePeriod(String(value ?? \"\"));\n\t\tconst target = targetUser(deps);\n\n\t\tif (id === COMMAND_IDS.recalc) {\n\t\t\tif (period.month === null) {\n\t\t\t\tdeps.aggregation.recalculateYear(target.id, period.year, { now: timestamp });\n\t\t\t\treturn { ok: true, message: `year ${period.year} recalculated`, recalculated: [] };\n\t\t\t}\n\t\t\tdeps.aggregation.recalculateMonth(target.id, period.year, period.month, { now: timestamp });\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tmessage: `month ${period.year}-${String(period.month).padStart(2, \"0\")} recalculated`,\n\t\t\t\trecalculated: [],\n\t\t\t};\n\t\t}\n\n\t\tif (period.month === null) {\n\t\t\tthrow new ValidationError(\"closing a month needs YYYY-MM\");\n\t\t}\n\t\tconst closed = deps.closing.closeMonth({\n\t\t\tuserId: target.id,\n\t\t\tyear: period.year,\n\t\t\tmonth: period.month,\n\t\t\tactorId: 0,\n\t\t\tnow: timestamp,\n\t\t});\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `month ${period.year}-${String(period.month).padStart(2, \"0\")} closed for ${target.displayName} (balance ${closed.month.balanceMin} min, overtime ${closed.month.overtimeMin} min)`,\n\t\t\trecalculated: [],\n\t\t};\n\t}\n\n\tif (id === COMMAND_IDS.punch || id === COMMAND_IDS.quickPunch) {\n\t\tif (value !== true) {\n\t\t\t// buttons only act on `true`\n\t\t\treturn { ok: false, message: \"ignored (buttons act on true)\", recalculated: [] };\n\t\t}\n\n\t\tconst target = targetUser(deps);\n\t\treturn punchEmployee(deps, {\n\t\t\tuserId: target.id,\n\t\t\tquick: id === COMMAND_IDS.quickPunch,\n\t\t\tnote: \"command.punch\",\n\t\t\tnow: timestamp,\n\t\t});\n\t}\n\n\tif (id === COMMAND_IDS.backup) {\n\t\tif (value !== true) {\n\t\t\t// buttons only act on `true`\n\t\t\treturn { ok: false, message: \"ignored (buttons act on true)\", recalculated: [] };\n\t\t}\n\t\tif (!deps.backup) {\n\t\t\tthrow new ValidationError(\"this instance has no backup service\");\n\t\t}\n\n\t\tconst created = deps.backup.create({ actorId: 0, reason: \"command state\" });\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `backup ${created.backup.name} written (${created.backup.sizeBytes} bytes, ${created.backup.entries} punches), ${created.removed.length} old file(s) removed`,\n\t\t\trecalculated: [],\n\t\t};\n\t}\n\n\tthrow new ValidationError(`unknown command state ${id}`);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;
|
|
4
|
+
"sourcesContent": ["/**\n * Command states of the adapter.\n *\n * The adapter reacts to the states below, so a script, a dashboard or another adapter can punch, close a month\n * or trigger a recalculation without the REST API. Commands are triggered from inside ioBroker, not from a\n * browser, so no session is involved; the audit trail records them with `actorId: 0` (system).\n */\n\nimport type { Db } from \"../db/database\";\nimport type { EntriesRepository } from \"../db/repositories/entries\";\nimport type { SettingsRepository } from \"../db/repositories/settings\";\nimport type { UsersRepository } from \"../db/repositories/users\";\nimport type { AggregationService } from \"../services/aggregation\";\nimport type { ClosingService } from \"../services/closing\";\nimport type { BackupService } from \"../services/backup\";\nimport type { ApiEvent } from \"../web/events\";\nimport { ValidationError } from \"../errors\";\nimport { buildDayPunches, nextDirection, roundToStep, type PunchEntry } from \"../domain/punch\";\nimport { localDate as resolveLocalDate } from \"../util/time\";\nimport { COMMAND_IDS } from \"./states\";\n\n/** Data sources of the command handler. */\nexport interface CommandDeps {\n\t/** Open database handle */\n\tdb: Db;\n\t/** Punch storage */\n\tentries: EntriesRepository;\n\t/** User storage */\n\tusers: UsersRepository;\n\t/** Instance settings (quick rounding, target employee) */\n\tsettings: SettingsRepository;\n\t/** Aggregation service */\n\taggregation: Pick<AggregationService, \"recalculateDay\" | \"recalculateMonth\" | \"recalculateYear\">;\n\t/** Closing service (month close) */\n\tclosing: Pick<ClosingService, \"closeMonth\">;\n\t/** Backup service (button `commands.backup`), optional */\n\tbackup?: Pick<BackupService, \"create\">;\n\t/** Instant source, defaults to the system clock */\n\tnow?: () => number;\n}\n\n/** Result of a command. */\nexport interface CommandResult {\n\t/** True when the command was executed */\n\tok: boolean;\n\t/** Human readable summary for the log */\n\tmessage: string;\n\t/** Local dates that were recalculated */\n\trecalculated: string[];\n\t/** Employee a written punch belongs to \u2014 unset for every other command */\n\tuserId?: number;\n\t/** Direction of a written punch \u2014 unset for every other command */\n\tdirection?: \"in\" | \"out\";\n}\n\n/** A period taken from a command value. */\ninterface Period {\n\t/** Four digit year */\n\tyear: number;\n\t/** Month (1 to 12) or `null` for a whole year */\n\tmonth: number | null;\n}\n\n/**\n * Parses a period string.\n *\n * @param value - `YYYY-MM` or `YYYY`\n * @returns the parsed period\n */\nfunction parsePeriod(value: string): Period {\n\tconst monthMatch = /^(\\d{4})-(\\d{1,2})$/.exec(value.trim());\n\tif (monthMatch) {\n\t\tconst month = Number(monthMatch[2]);\n\t\tif (month < 1 || month > 12) {\n\t\t\tthrow new ValidationError(`month must be between 1 and 12 (got ${value})`);\n\t\t}\n\t\treturn { year: Number(monthMatch[1]), month };\n\t}\n\n\tconst yearMatch = /^(\\d{4})$/.exec(value.trim());\n\tif (yearMatch) {\n\t\treturn { year: Number(yearMatch[1]), month: null };\n\t}\n\tthrow new ValidationError(`expected YYYY-MM or YYYY (got \"${value}\")`);\n}\n\n/**\n * Resolves the employee a command applies to: the only one, or the configured one.\n *\n * @param deps - data sources\n * @returns the employee\n */\nfunction targetUser(deps: CommandDeps): { id: number; displayName: string; timezone: string } {\n\tconst configured = Number(deps.settings.get(\"command_punch_user_id\") ?? Number.NaN);\n\tconst explicit = Number.isInteger(configured) ? deps.users.findById(configured) : null;\n\tif (explicit) {\n\t\treturn explicit;\n\t}\n\n\tconst candidates = deps.users.list();\n\tif (candidates.length === 1) {\n\t\treturn candidates[0];\n\t}\n\tif (candidates.length === 0) {\n\t\tthrow new ValidationError(\"no employee exists yet\");\n\t}\n\tthrow new ValidationError(\"several employees exist - set command_punch_user_id or write users.<id> commands\");\n}\n\n/** Data a punch needs: where to write, how to round and how to recalculate. */\nexport type PunchDeps = Pick<CommandDeps, \"entries\" | \"users\" | \"settings\" | \"aggregation\" | \"now\">;\n\n/**\n * Punches in or out for one employee.\n *\n * This is the single punch path of the adapter: the `commands.punch` button, a trigger rule and a `sendTo`\n * message all end up here, so direction, rounding, note and recalculation behave the same everywhere.\n *\n * @param deps - data sources\n * @param input - employee, rounding and note\n * @param input.userId - employee the punch belongs to\n * @param input.quick - true to round the instant with the configured quick rounding\n * @param input.note - note stored with the punch\n * @param input.now - instant of the punch, defaults to the system clock\n * @returns result of the punch\n */\nexport function punchEmployee(\n\tdeps: PunchDeps,\n\tinput: { userId: number; quick?: boolean; note?: string; now?: number },\n): CommandResult {\n\tconst target = deps.users.findById(input.userId);\n\tif (!target) {\n\t\tthrow new ValidationError(`employee ${input.userId} does not exist`);\n\t}\n\tif (!target.isActive) {\n\t\tthrow new ValidationError(`${target.displayName} is deactivated, no punch was written`);\n\t}\n\n\tconst now = deps.now ?? (() => Math.floor(Date.now() / 1000));\n\tconst timestamp = input.now ?? now();\n\tconst quickRound = input.quick === true ? deps.settings.getNumber(\"quick_round_minutes\", 0) : 0;\n\tconst tsUtc = quickRound > 0 ? roundToStep(timestamp, quickRound, target.timezone) : timestamp;\n\tconst today = resolveLocalDate(tsUtc, target.timezone);\n\n\tconst existing: PunchEntry[] = deps.entries\n\t\t.listByDate(target.id, today)\n\t\t.map(entry => ({ id: entry.id, tsUtc: entry.tsUtc, syncState: entry.syncState }));\n\tconst direction = nextDirection(buildDayPunches(existing));\n\n\tconst stored = deps.entries.insert({\n\t\tuserId: target.id,\n\t\ttsUtc,\n\t\ttimeZone: target.timezone,\n\t\tsource: \"api\",\n\t\tdirection,\n\t\tnote: input.note ?? null,\n\t\tnow: timestamp,\n\t});\n\tconst day = deps.aggregation.recalculateDay(target.id, stored.entry.localDate, { now: timestamp });\n\n\treturn {\n\t\tok: true,\n\t\tmessage: `${target.displayName} punched ${direction} (${day.workedMin} min today, open: ${day.hasOpenEntry})`,\n\t\trecalculated: [stored.entry.localDate],\n\t\tuserId: target.id,\n\t\tdirection,\n\t};\n}\n\n/**\n * Builds the event a written punch publishes.\n *\n * `punchEmployee` stays pure \u2014 the caller feeds the result into the event bus, exactly like the REST API does it.\n * That is what makes a punch from a command state, a script (`sendTo`) or a trigger rule show up in `events.*`\n * (`lastType`, `lastUser`, \u2026) and in the web app. `null` means: no punch was written.\n *\n * @param result - result of the punch\n * @param source - where the punch came from (`commands.punch`, `sendTo.punch`, `trigger.<id>`, \u2026)\n * @param atUtc - instant of the punch, UTC epoch seconds\n * @returns the event for the bus, or `null` when nothing was written\n */\nexport function punchEvent(result: CommandResult, source: string, atUtc: number): ApiEvent | null {\n\tif (!result.ok || !result.direction || result.userId === undefined) {\n\t\treturn null;\n\t}\n\treturn {\n\t\ttype: \"punch\",\n\t\tatUtc,\n\t\tuserId: result.userId,\n\t\tdata: { direction: result.direction, source },\n\t};\n}\n\n/**\n * Handles a command state.\n *\n * @param deps - data sources\n * @param id - state id that was written (without the instance prefix)\n * @param value - value that was written\n * @returns result of the command\n */\nexport function handleCommand(deps: CommandDeps, id: string, value: ioBroker.StateValue): CommandResult {\n\tconst now = deps.now ?? (() => Math.floor(Date.now() / 1000));\n\tconst timestamp = now();\n\n\tif (id === COMMAND_IDS.punchUserId) {\n\t\t// The state chooses the employee the punch commands apply to (`0` = take the only employee again).\n\t\tconst userId = Number(value ?? Number.NaN);\n\t\tif (!Number.isInteger(userId) || userId < 0) {\n\t\t\tthrow new ValidationError(`expected the id of an employee or 0 (got \"${String(value ?? \"\")}\")`);\n\t\t}\n\t\tif (userId === 0) {\n\t\t\tdeps.settings.set(\"command_punch_user_id\", 0, 0, timestamp);\n\t\t\treturn { ok: true, message: \"punch commands use the only employee again\", recalculated: [] };\n\t\t}\n\t\tconst chosen = deps.users.findById(userId);\n\t\tif (!chosen) {\n\t\t\tthrow new ValidationError(`employee ${userId} does not exist`);\n\t\t}\n\t\tdeps.settings.set(\"command_punch_user_id\", userId, 0, timestamp);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `punch commands now apply to ${chosen.displayName}`,\n\t\t\trecalculated: [],\n\t\t};\n\t}\n\n\tif (id === COMMAND_IDS.closeMonth || id === COMMAND_IDS.recalc) {\n\t\tconst period = parsePeriod(String(value ?? \"\"));\n\t\tconst target = targetUser(deps);\n\n\t\tif (id === COMMAND_IDS.recalc) {\n\t\t\tif (period.month === null) {\n\t\t\t\tdeps.aggregation.recalculateYear(target.id, period.year, { now: timestamp });\n\t\t\t\treturn { ok: true, message: `year ${period.year} recalculated`, recalculated: [] };\n\t\t\t}\n\t\t\tdeps.aggregation.recalculateMonth(target.id, period.year, period.month, { now: timestamp });\n\t\t\treturn {\n\t\t\t\tok: true,\n\t\t\t\tmessage: `month ${period.year}-${String(period.month).padStart(2, \"0\")} recalculated`,\n\t\t\t\trecalculated: [],\n\t\t\t};\n\t\t}\n\n\t\tif (period.month === null) {\n\t\t\tthrow new ValidationError(\"closing a month needs YYYY-MM\");\n\t\t}\n\t\tconst closed = deps.closing.closeMonth({\n\t\t\tuserId: target.id,\n\t\t\tyear: period.year,\n\t\t\tmonth: period.month,\n\t\t\tactorId: 0,\n\t\t\tnow: timestamp,\n\t\t});\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `month ${period.year}-${String(period.month).padStart(2, \"0\")} closed for ${target.displayName} (balance ${closed.month.balanceMin} min, overtime ${closed.month.overtimeMin} min)`,\n\t\t\trecalculated: [],\n\t\t};\n\t}\n\n\tif (id === COMMAND_IDS.punch || id === COMMAND_IDS.quickPunch) {\n\t\tif (value !== true) {\n\t\t\t// buttons only act on `true`\n\t\t\treturn { ok: false, message: \"ignored (buttons act on true)\", recalculated: [] };\n\t\t}\n\n\t\tconst target = targetUser(deps);\n\t\treturn punchEmployee(deps, {\n\t\t\tuserId: target.id,\n\t\t\tquick: id === COMMAND_IDS.quickPunch,\n\t\t\tnote: \"command.punch\",\n\t\t\tnow: timestamp,\n\t\t});\n\t}\n\n\tif (id === COMMAND_IDS.backup) {\n\t\tif (value !== true) {\n\t\t\t// buttons only act on `true`\n\t\t\treturn { ok: false, message: \"ignored (buttons act on true)\", recalculated: [] };\n\t\t}\n\t\tif (!deps.backup) {\n\t\t\tthrow new ValidationError(\"this instance has no backup service\");\n\t\t}\n\n\t\tconst created = deps.backup.create({ actorId: 0, reason: \"command state\" });\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `backup ${created.backup.name} written (${created.backup.sizeBytes} bytes, ${created.backup.entries} punches), ${created.removed.length} old file(s) removed`,\n\t\t\trecalculated: [],\n\t\t};\n\t}\n\n\tthrow new ValidationError(`unknown command state ${id}`);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,oBAAgC;AAChC,mBAA6E;AAC7E,kBAA8C;AAC9C,oBAA4B;AAkD5B,SAAS,YAAY,OAAuB;AAC3C,QAAM,aAAa,sBAAsB,KAAK,MAAM,KAAK,CAAC;AAC1D,MAAI,YAAY;AACf,UAAM,QAAQ,OAAO,WAAW,CAAC,CAAC;AAClC,QAAI,QAAQ,KAAK,QAAQ,IAAI;AAC5B,YAAM,IAAI,8BAAgB,uCAAuC,KAAK,GAAG;AAAA,IAC1E;AACA,WAAO,EAAE,MAAM,OAAO,WAAW,CAAC,CAAC,GAAG,MAAM;AAAA,EAC7C;AAEA,QAAM,YAAY,YAAY,KAAK,MAAM,KAAK,CAAC;AAC/C,MAAI,WAAW;AACd,WAAO,EAAE,MAAM,OAAO,UAAU,CAAC,CAAC,GAAG,OAAO,KAAK;AAAA,EAClD;AACA,QAAM,IAAI,8BAAgB,kCAAkC,KAAK,IAAI;AACtE;AAQA,SAAS,WAAW,MAA0E;AA5F9F;AA6FC,Q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E,SAAS,GAAG,GAAG,CAAC,eAAe,OAAO,WAAW,aAAa,OAAO,MAAM,UAAU,kBAAkB,OAAO,MAAM,WAAW;AAAA,MACrL,cAAc,CAAC;AAAA,IAChB;AAAA,EACD;AAEA,MAAI,OAAO,0BAAY,SAAS,OAAO,0BAAY,YAAY;AAC9D,QAAI,UAAU,MAAM;AAEnB,aAAO,EAAE,IAAI,OAAO,SAAS,iCAAiC,cAAc,CAAC,EAAE;AAAA,IAChF;AAEA,UAAM,SAAS,WAAW,IAAI;AAC9B,WAAO,cAAc,MAAM;AAAA,MAC1B,QAAQ,OAAO;AAAA,MACf,OAAO,OAAO,0BAAY;AAAA,MAC1B,MAAM;AAAA,MACN,KAAK;AAAA,IACN,CAAC;AAAA,EACF;AAEA,MAAI,OAAO,0BAAY,QAAQ;AAC9B,QAAI,UAAU,MAAM;AAEnB,aAAO,EAAE,IAAI,OAAO,SAAS,iCAAiC,cAAc,CAAC,EAAE;AAAA,IAChF;AACA,QAAI,CAAC,KAAK,QAAQ;AACjB,YAAM,IAAI,8BAAgB,qCAAqC;AAAA,IAChE;AAEA,UAAM,UAAU,KAAK,OAAO,OAAO,EAAE,SAAS,GAAG,QAAQ,gBAAgB,CAAC;AAC1E,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,SAAS,UAAU,QAAQ,OAAO,IAAI,aAAa,QAAQ,OAAO,SAAS,WAAW,QAAQ,OAAO,OAAO,cAAc,QAAQ,QAAQ,MAAM;AAAA,MAChJ,cAAc,CAAC;AAAA,IAChB;AAAA,EACD;AAEA,QAAM,IAAI,8BAAgB,yBAAyB,EAAE,EAAE;AACxD;",
|
|
6
6
|
"names": ["resolveLocalDate"]
|
|
7
7
|
}
|
|
@@ -123,7 +123,11 @@ async function handleMessage(deps, command, payload) {
|
|
|
123
123
|
now: now()
|
|
124
124
|
}
|
|
125
125
|
);
|
|
126
|
-
return {
|
|
126
|
+
return {
|
|
127
|
+
ok: true,
|
|
128
|
+
message: result.message,
|
|
129
|
+
data: { userId: user.id, direction: result.direction, message: result.message }
|
|
130
|
+
};
|
|
127
131
|
}
|
|
128
132
|
if (command === "present") {
|
|
129
133
|
const user = targetUser(body, deps.users);
|
|
@@ -139,7 +143,12 @@ async function handleMessage(deps, command, payload) {
|
|
|
139
143
|
return {
|
|
140
144
|
ok: result.ok,
|
|
141
145
|
message: result.message,
|
|
142
|
-
data: {
|
|
146
|
+
data: {
|
|
147
|
+
userId: user.id,
|
|
148
|
+
present: result.present,
|
|
149
|
+
changed: result.changed,
|
|
150
|
+
direction: result.changed ? result.present ? "in" : "out" : null
|
|
151
|
+
}
|
|
143
152
|
};
|
|
144
153
|
}
|
|
145
154
|
if (command === "status") {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/adapter/messages.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Messages of the adapter (`sendTo`).\n *\n * A script adapter, Blockly or another adapter can drive the time tracking without HTTP and without a session:\n * `sendTo(\"time-tracker.0\", \"punch\", { user: \"anna\" }, callback)`. Every command answers with an object, so the\n * caller can react on the outcome.\n *\n * | Command | Payload | Answer |\n * | --------- | ----------------------------------------- | ------------------------------------- |\n * | `punch` | `{ user, quick?, note? }` | `{ userId, message }` |\n * | `present` | `{ user, present }` | `{ userId, present, changed }` |\n * | `status` | `{ user }` | figures of the employee |\n * | `report` | `{ user, period?, format? }` | `{ fileName, mimeType, base64 }` |\n * | `backup` | \u2014 | `{ name, sizeBytes }` |\n *\n * `user` is a user id, a login or the shown name \u2014 the same resolution the trigger rules use.\n */\n\nimport type { AbsencesRepository } from \"../db/repositories/absences\";\nimport type { EntriesRepository } from \"../db/repositories/entries\";\nimport type { SettingsRepository } from \"../db/repositories/settings\";\nimport type { UserRecord, UsersRepository } from \"../db/repositories/users\";\nimport type { AggregationService } from \"../services/aggregation\";\nimport type { BackupService } from \"../services/backup\";\nimport type { SyncService } from \"../services/sync\";\nimport { ValidationError } from \"../errors\";\nimport { buildMonthStatement } from \"../reports/pdf\";\nimport { reportLabels } from \"../reports/labels\";\nimport { reportFileName, type ReportInput } from \"../reports/types\";\nimport { buildMonthReport } from \"../reports/xls\";\nimport { localDate } from \"../util/time\";\nimport { punchEmployee } from \"./commands\";\nimport { handlePresenceState } from \"./presence\";\nimport { readUserSnapshot } from \"./states\";\nimport { resolveTriggerUser } from \"./triggers\";\n\n/** Data a message needs. */\nexport interface MessageDeps {\n\t/** User storage */\n\tusers: UsersRepository;\n\t/** Punch storage */\n\tentries: EntriesRepository;\n\t/** Absences (the monthly statement shows them) */\n\tabsences: AbsencesRepository;\n\t/** Instance settings (quick rounding, font of the statements) */\n\tsettings: SettingsRepository;\n\t/** Aggregation service */\n\taggregation: AggregationService;\n\t/** Synchronisation service (open conflicts) */\n\tsync: SyncService;\n\t/** Backup service, optional: without it the command is refused */\n\tbackup?: Pick<BackupService, \"create\">;\n\t/** Version printed into a generated statement */\n\tversion?: string;\n\t/** Instant source, defaults to the system clock */\n\tnow?: () => number;\n}\n\n/** Answer of a message. */\nexport interface MessageResult {\n\t/** True when the command ran */\n\tok: boolean;\n\t/** Human readable summary */\n\tmessage: string;\n\t/** Command specific answer for the caller of `sendTo` */\n\tdata?: Record<string, unknown>;\n}\n\n/**\n * Reads a text field of a message payload.\n *\n * @param payload - payload of the message\n * @param field - field name\n * @returns the trimmed text or `null`\n */\nfunction textField(payload: Record<string, unknown>, field: string): string | null {\n\tconst value = payload[field];\n\tif (value === undefined || value === null) {\n\t\treturn null;\n\t}\n\tif (typeof value === \"number\" || typeof value === \"boolean\") {\n\t\treturn String(value);\n\t}\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(`${field} must be a string (got ${typeof value})`);\n\t}\n\treturn value.trim() || null;\n}\n\n/**\n * Reads a boolean field of a message payload.\n *\n * @param payload - payload of the message\n * @param field - field name\n * @returns the boolean, or `null` when the field is missing\n */\nfunction booleanField(payload: Record<string, unknown>, field: string): boolean | null {\n\tconst value = payload[field];\n\tif (value === undefined || value === null) {\n\t\treturn null;\n\t}\n\tif (typeof value === \"boolean\") {\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\treturn value !== 0;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value.trim().toLowerCase();\n\t\tif ([\"true\", \"1\", \"yes\", \"on\"].includes(normalized)) {\n\t\t\treturn true;\n\t\t}\n\t\tif ([\"false\", \"0\", \"no\", \"off\", \"\"].includes(normalized)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tthrow new ValidationError(`${field} must be a boolean (got ${JSON.stringify(value)})`);\n}\n\n/**\n * Resolves the employee a message names.\n *\n * @param payload - payload of the message\n * @param users - user storage\n * @returns the employee\n */\nfunction targetUser(payload: Record<string, unknown>, users: UsersRepository): UserRecord {\n\tconst raw = payload.user ?? payload.userId;\n\tif (raw === undefined || raw === null || raw === \"\") {\n\t\tthrow new ValidationError(\"user is required: pass a user id, a login or the shown name\");\n\t}\n\t// a value of another type cannot name an employee; it is only reported back\n\tconst asText = typeof raw === \"string\" || typeof raw === \"number\" ? String(raw) : JSON.stringify(raw);\n\tconst user = resolveTriggerUser(typeof raw === \"number\" ? raw : asText, users);\n\tif (!user) {\n\t\tthrow new ValidationError(`no employee matches ${asText}`);\n\t}\n\treturn user;\n}\n\n/**\n * Builds the input of a monthly statement.\n *\n * @param deps - data sources\n * @param user - employee the statement belongs to\n * @param year - four digit year\n * @param month - month, 1 to 12\n * @returns the report input including the generator line\n */\nfunction statementInput(\n\tdeps: MessageDeps,\n\tuser: UserRecord,\n\tyear: number,\n\tmonth: number,\n): ReportInput & { generator: string } {\n\tconst timestamp = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();\n\tconst prefix = `${year}-${String(month).padStart(2, \"0\")}`;\n\tconst first = `${prefix}-01`;\n\tconst lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();\n\tconst last = `${prefix}-${String(lastDay).padStart(2, \"0\")}`;\n\t// a statement has to show the current state of the month, so the range is recalculated first\n\tdeps.aggregation.recalculateRange(user.id, first, last, { now: timestamp });\n\tconst { labels, language } = reportLabels(user.locale);\n\n\treturn {\n\t\tuser: { displayName: user.displayName, login: user.login, timezone: user.timezone },\n\t\tlabels,\n\t\tlanguage,\n\t\tlocale: user.locale || \"en\",\n\t\tyear,\n\t\tmonth,\n\t\tdays: deps.aggregation.days(user.id, first, last),\n\t\tabsences: deps.absences.withTypesInRange(user.id, first, last).map(absence => ({\n\t\t\ttypeCode: absence.typeCode,\n\t\t\ttypeName: absence.typeName,\n\t\t\tdateFrom: absence.dateFrom,\n\t\t\tdateTo: absence.dateTo,\n\t\t\tdayPortion: absence.dayPortion,\n\t\t\thours: absence.hours,\n\t\t})),\n\t\tgeneratedAt: timestamp,\n\t\tgenerator: `time-tracker ${deps.version ?? \"\"}`.trim(),\n\t};\n}\n\n/**\n * Applies a message of a script, a Blockly block or another adapter.\n *\n * @param deps - data sources\n * @param command - name of the command\n * @param payload - payload of the message\n * @returns the answer for the caller\n */\nexport async function handleMessage(deps: MessageDeps, command: string, payload: unknown): Promise<MessageResult> {\n\tconst body = (payload ?? {}) as Record<string, unknown>;\n\tconst now = deps.now ?? (() => Math.floor(Date.now() / 1000));\n\n\tif (command === \"punch\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst result = punchEmployee(\n\t\t\t{ entries: deps.entries, users: deps.users, settings: deps.settings, aggregation: deps.aggregation },\n\t\t\t{\n\t\t\t\tuserId: user.id,\n\t\t\t\tquick: booleanField(body, \"quick\") === true,\n\t\t\t\tnote: textField(body, \"note\") ?? \"sendTo.punch\",\n\t\t\t\tnow: now(),\n\t\t\t},\n\t\t);\n\t\treturn { ok: true, message: result.message, data: { userId: user.id, message: result.message } };\n\t}\n\n\tif (command === \"present\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst desired = booleanField(body, \"present\");\n\t\tif (desired === null) {\n\t\t\tthrow new ValidationError(\"present is required: pass true or false\");\n\t\t}\n\t\tconst result = handlePresenceState(\n\t\t\t{ entries: deps.entries, users: deps.users, aggregation: deps.aggregation, now },\n\t\t\t`users.${user.id}.present`,\n\t\t\tdesired,\n\t\t);\n\t\treturn {\n\t\t\tok: result.ok,\n\t\t\tmessage: result.message,\n\t\t\tdata: { userId: user.id, present: result.present, changed: result.changed },\n\t\t};\n\t}\n\n\tif (command === \"status\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst snapshot = readUserSnapshot({\n\t\t\taggregation: deps.aggregation,\n\t\t\tusers: deps.users,\n\t\t\tsync: deps.sync,\n\t\t\tuserId: user.id,\n\t\t\tnow: now(),\n\t\t});\n\t\tif (!snapshot) {\n\t\t\tthrow new ValidationError(`employee ${user.id} disappeared`);\n\t\t}\n\t\treturn { ok: true, message: `figures of ${user.displayName}`, data: { ...snapshot } };\n\t}\n\n\tif (command === \"report\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst format = (textField(body, \"format\") ?? \"pdf\").toLowerCase();\n\t\tif (format !== \"pdf\" && format !== \"xlsx\") {\n\t\t\tthrow new ValidationError(`format must be pdf or xlsx (got ${format})`);\n\t\t}\n\t\tconst period = textField(body, \"period\") ?? localDate(now(), user.timezone).slice(0, 7);\n\t\tconst match = /^(\\d{4})-(\\d{2})$/.exec(period);\n\t\tif (!match) {\n\t\t\tthrow new ValidationError(`period must be YYYY-MM (got \"${period}\")`);\n\t\t}\n\t\tconst year = Number(match[1]);\n\t\tconst month = Number(match[2]);\n\t\tif (month < 1 || month > 12) {\n\t\t\tthrow new ValidationError(`month must be between 1 and 12 (got ${month})`);\n\t\t}\n\n\t\tconst input = statementInput(deps, user, year, month);\n\t\tconst file =\n\t\t\tformat === \"pdf\"\n\t\t\t\t? await buildMonthStatement({ ...input, fontPath: deps.settings.get(\"report_font_path\") ?? \"\" })\n\t\t\t\t: await buildMonthReport(input);\n\t\tconst fileName = reportFileName(user.login, year, month, format === \"pdf\" ? \"pdf\" : \"xlsx\");\n\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `${fileName} (${file.length} bytes)`,\n\t\t\tdata: {\n\t\t\t\tuserId: user.id,\n\t\t\t\tfileName,\n\t\t\t\tmimeType:\n\t\t\t\t\tformat === \"pdf\"\n\t\t\t\t\t\t? \"application/pdf\"\n\t\t\t\t\t\t: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n\t\t\t\tbytes: file.length,\n\t\t\t\tbase64: file.toString(\"base64\"),\n\t\t\t},\n\t\t};\n\t}\n\n\tif (command === \"backup\") {\n\t\tif (!deps.backup) {\n\t\t\tthrow new ValidationError(\"this instance has no backup service\");\n\t\t}\n\t\tconst created = deps.backup.create({ actorId: 0, reason: \"sendTo\" });\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `backup ${created.backup.name} written (${created.backup.sizeBytes} bytes)`,\n\t\t\tdata: { name: created.backup.name, sizeBytes: created.backup.sizeBytes, removed: created.removed },\n\t\t};\n\t}\n\n\tthrow new ValidationError(`unknown command \"${command}\": use punch, present, status, report or backup`);\n}\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,oBAAgC;AAChC,iBAAoC;AACpC,oBAA6B;AAC7B,mBAAiD;AACjD,iBAAiC;AACjC,kBAA0B;AAC1B,sBAA8B;AAC9B,sBAAoC;AACpC,oBAAiC;AACjC,sBAAmC;AAyCnC,SAAS,UAAU,SAAkC,OAA8B;AAClF,QAAM,QAAQ,QAAQ,KAAK;AAC3B,MAAI,UAAU,UAAa,UAAU,MAAM;AAC1C,WAAO;AAAA,EACR;AACA,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW;AAC5D,WAAO,OAAO,KAAK;AAAA,EACpB;AACA,MAAI,OAAO,UAAU,UAAU;AAC9B,UAAM,IAAI,8BAAgB,GAAG,KAAK,0BAA0B,OAAO,KAAK,GAAG;AAAA,EAC5E;AACA,SAAO,MAAM,KAAK,KAAK;AACxB;AASA,SAAS,aAA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,MACnG;AAAA,QACC,QAAQ,KAAK;AAAA,QACb,OAAO,aAAa,MAAM,OAAO,MAAM;AAAA,QACvC,OAAM,eAAU,MAAM,MAAM,MAAtB,YAA2B;AAAA,QACjC,KAAK,IAAI;AAAA,MACV;AAAA,IACD;AACA,WAAO,
|
|
4
|
+
"sourcesContent": ["/**\n * Messages of the adapter (`sendTo`).\n *\n * A script adapter, Blockly or another adapter can drive the time tracking without HTTP and without a session:\n * `sendTo(\"time-tracker.0\", \"punch\", { user: \"anna\" }, callback)`. Every command answers with an object, so the\n * caller can react on the outcome.\n *\n * | Command | Payload | Answer |\n * | --------- | ----------------------------------------- | ------------------------------------- |\n * | `punch` | `{ user, quick?, note? }` | `{ userId, message }` |\n * | `present` | `{ user, present }` | `{ userId, present, changed }` |\n * | `status` | `{ user }` | figures of the employee |\n * | `report` | `{ user, period?, format? }` | `{ fileName, mimeType, base64 }` |\n * | `backup` | \u2014 | `{ name, sizeBytes }` |\n *\n * `user` is a user id, a login or the shown name \u2014 the same resolution the trigger rules use.\n */\n\nimport type { AbsencesRepository } from \"../db/repositories/absences\";\nimport type { EntriesRepository } from \"../db/repositories/entries\";\nimport type { SettingsRepository } from \"../db/repositories/settings\";\nimport type { UserRecord, UsersRepository } from \"../db/repositories/users\";\nimport type { AggregationService } from \"../services/aggregation\";\nimport type { BackupService } from \"../services/backup\";\nimport type { SyncService } from \"../services/sync\";\nimport { ValidationError } from \"../errors\";\nimport { buildMonthStatement } from \"../reports/pdf\";\nimport { reportLabels } from \"../reports/labels\";\nimport { reportFileName, type ReportInput } from \"../reports/types\";\nimport { buildMonthReport } from \"../reports/xls\";\nimport { localDate } from \"../util/time\";\nimport { punchEmployee } from \"./commands\";\nimport { handlePresenceState } from \"./presence\";\nimport { readUserSnapshot } from \"./states\";\nimport { resolveTriggerUser } from \"./triggers\";\n\n/** Data a message needs. */\nexport interface MessageDeps {\n\t/** User storage */\n\tusers: UsersRepository;\n\t/** Punch storage */\n\tentries: EntriesRepository;\n\t/** Absences (the monthly statement shows them) */\n\tabsences: AbsencesRepository;\n\t/** Instance settings (quick rounding, font of the statements) */\n\tsettings: SettingsRepository;\n\t/** Aggregation service */\n\taggregation: AggregationService;\n\t/** Synchronisation service (open conflicts) */\n\tsync: SyncService;\n\t/** Backup service, optional: without it the command is refused */\n\tbackup?: Pick<BackupService, \"create\">;\n\t/** Version printed into a generated statement */\n\tversion?: string;\n\t/** Instant source, defaults to the system clock */\n\tnow?: () => number;\n}\n\n/** Answer of a message. */\nexport interface MessageResult {\n\t/** True when the command ran */\n\tok: boolean;\n\t/** Human readable summary */\n\tmessage: string;\n\t/** Command specific answer for the caller of `sendTo` */\n\tdata?: Record<string, unknown>;\n}\n\n/**\n * Reads a text field of a message payload.\n *\n * @param payload - payload of the message\n * @param field - field name\n * @returns the trimmed text or `null`\n */\nfunction textField(payload: Record<string, unknown>, field: string): string | null {\n\tconst value = payload[field];\n\tif (value === undefined || value === null) {\n\t\treturn null;\n\t}\n\tif (typeof value === \"number\" || typeof value === \"boolean\") {\n\t\treturn String(value);\n\t}\n\tif (typeof value !== \"string\") {\n\t\tthrow new ValidationError(`${field} must be a string (got ${typeof value})`);\n\t}\n\treturn value.trim() || null;\n}\n\n/**\n * Reads a boolean field of a message payload.\n *\n * @param payload - payload of the message\n * @param field - field name\n * @returns the boolean, or `null` when the field is missing\n */\nfunction booleanField(payload: Record<string, unknown>, field: string): boolean | null {\n\tconst value = payload[field];\n\tif (value === undefined || value === null) {\n\t\treturn null;\n\t}\n\tif (typeof value === \"boolean\") {\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\treturn value !== 0;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value.trim().toLowerCase();\n\t\tif ([\"true\", \"1\", \"yes\", \"on\"].includes(normalized)) {\n\t\t\treturn true;\n\t\t}\n\t\tif ([\"false\", \"0\", \"no\", \"off\", \"\"].includes(normalized)) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tthrow new ValidationError(`${field} must be a boolean (got ${JSON.stringify(value)})`);\n}\n\n/**\n * Resolves the employee a message names.\n *\n * @param payload - payload of the message\n * @param users - user storage\n * @returns the employee\n */\nfunction targetUser(payload: Record<string, unknown>, users: UsersRepository): UserRecord {\n\tconst raw = payload.user ?? payload.userId;\n\tif (raw === undefined || raw === null || raw === \"\") {\n\t\tthrow new ValidationError(\"user is required: pass a user id, a login or the shown name\");\n\t}\n\t// a value of another type cannot name an employee; it is only reported back\n\tconst asText = typeof raw === \"string\" || typeof raw === \"number\" ? String(raw) : JSON.stringify(raw);\n\tconst user = resolveTriggerUser(typeof raw === \"number\" ? raw : asText, users);\n\tif (!user) {\n\t\tthrow new ValidationError(`no employee matches ${asText}`);\n\t}\n\treturn user;\n}\n\n/**\n * Builds the input of a monthly statement.\n *\n * @param deps - data sources\n * @param user - employee the statement belongs to\n * @param year - four digit year\n * @param month - month, 1 to 12\n * @returns the report input including the generator line\n */\nfunction statementInput(\n\tdeps: MessageDeps,\n\tuser: UserRecord,\n\tyear: number,\n\tmonth: number,\n): ReportInput & { generator: string } {\n\tconst timestamp = (deps.now ?? (() => Math.floor(Date.now() / 1000)))();\n\tconst prefix = `${year}-${String(month).padStart(2, \"0\")}`;\n\tconst first = `${prefix}-01`;\n\tconst lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();\n\tconst last = `${prefix}-${String(lastDay).padStart(2, \"0\")}`;\n\t// a statement has to show the current state of the month, so the range is recalculated first\n\tdeps.aggregation.recalculateRange(user.id, first, last, { now: timestamp });\n\tconst { labels, language } = reportLabels(user.locale);\n\n\treturn {\n\t\tuser: { displayName: user.displayName, login: user.login, timezone: user.timezone },\n\t\tlabels,\n\t\tlanguage,\n\t\tlocale: user.locale || \"en\",\n\t\tyear,\n\t\tmonth,\n\t\tdays: deps.aggregation.days(user.id, first, last),\n\t\tabsences: deps.absences.withTypesInRange(user.id, first, last).map(absence => ({\n\t\t\ttypeCode: absence.typeCode,\n\t\t\ttypeName: absence.typeName,\n\t\t\tdateFrom: absence.dateFrom,\n\t\t\tdateTo: absence.dateTo,\n\t\t\tdayPortion: absence.dayPortion,\n\t\t\thours: absence.hours,\n\t\t})),\n\t\tgeneratedAt: timestamp,\n\t\tgenerator: `time-tracker ${deps.version ?? \"\"}`.trim(),\n\t};\n}\n\n/**\n * Applies a message of a script, a Blockly block or another adapter.\n *\n * @param deps - data sources\n * @param command - name of the command\n * @param payload - payload of the message\n * @returns the answer for the caller\n */\nexport async function handleMessage(deps: MessageDeps, command: string, payload: unknown): Promise<MessageResult> {\n\tconst body = (payload ?? {}) as Record<string, unknown>;\n\tconst now = deps.now ?? (() => Math.floor(Date.now() / 1000));\n\n\tif (command === \"punch\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst result = punchEmployee(\n\t\t\t{ entries: deps.entries, users: deps.users, settings: deps.settings, aggregation: deps.aggregation },\n\t\t\t{\n\t\t\t\tuserId: user.id,\n\t\t\t\tquick: booleanField(body, \"quick\") === true,\n\t\t\t\tnote: textField(body, \"note\") ?? \"sendTo.punch\",\n\t\t\t\tnow: now(),\n\t\t\t},\n\t\t);\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: result.message,\n\t\t\tdata: { userId: user.id, direction: result.direction, message: result.message },\n\t\t};\n\t}\n\n\tif (command === \"present\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst desired = booleanField(body, \"present\");\n\t\tif (desired === null) {\n\t\t\tthrow new ValidationError(\"present is required: pass true or false\");\n\t\t}\n\t\tconst result = handlePresenceState(\n\t\t\t{ entries: deps.entries, users: deps.users, aggregation: deps.aggregation, now },\n\t\t\t`users.${user.id}.present`,\n\t\t\tdesired,\n\t\t);\n\t\treturn {\n\t\t\tok: result.ok,\n\t\t\tmessage: result.message,\n\t\t\tdata: {\n\t\t\t\tuserId: user.id,\n\t\t\t\tpresent: result.present,\n\t\t\t\tchanged: result.changed,\n\t\t\t\tdirection: result.changed ? (result.present ? \"in\" : \"out\") : null,\n\t\t\t},\n\t\t};\n\t}\n\n\tif (command === \"status\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst snapshot = readUserSnapshot({\n\t\t\taggregation: deps.aggregation,\n\t\t\tusers: deps.users,\n\t\t\tsync: deps.sync,\n\t\t\tuserId: user.id,\n\t\t\tnow: now(),\n\t\t});\n\t\tif (!snapshot) {\n\t\t\tthrow new ValidationError(`employee ${user.id} disappeared`);\n\t\t}\n\t\treturn { ok: true, message: `figures of ${user.displayName}`, data: { ...snapshot } };\n\t}\n\n\tif (command === \"report\") {\n\t\tconst user = targetUser(body, deps.users);\n\t\tconst format = (textField(body, \"format\") ?? \"pdf\").toLowerCase();\n\t\tif (format !== \"pdf\" && format !== \"xlsx\") {\n\t\t\tthrow new ValidationError(`format must be pdf or xlsx (got ${format})`);\n\t\t}\n\t\tconst period = textField(body, \"period\") ?? localDate(now(), user.timezone).slice(0, 7);\n\t\tconst match = /^(\\d{4})-(\\d{2})$/.exec(period);\n\t\tif (!match) {\n\t\t\tthrow new ValidationError(`period must be YYYY-MM (got \"${period}\")`);\n\t\t}\n\t\tconst year = Number(match[1]);\n\t\tconst month = Number(match[2]);\n\t\tif (month < 1 || month > 12) {\n\t\t\tthrow new ValidationError(`month must be between 1 and 12 (got ${month})`);\n\t\t}\n\n\t\tconst input = statementInput(deps, user, year, month);\n\t\tconst file =\n\t\t\tformat === \"pdf\"\n\t\t\t\t? await buildMonthStatement({ ...input, fontPath: deps.settings.get(\"report_font_path\") ?? \"\" })\n\t\t\t\t: await buildMonthReport(input);\n\t\tconst fileName = reportFileName(user.login, year, month, format === \"pdf\" ? \"pdf\" : \"xlsx\");\n\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `${fileName} (${file.length} bytes)`,\n\t\t\tdata: {\n\t\t\t\tuserId: user.id,\n\t\t\t\tfileName,\n\t\t\t\tmimeType:\n\t\t\t\t\tformat === \"pdf\"\n\t\t\t\t\t\t? \"application/pdf\"\n\t\t\t\t\t\t: \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n\t\t\t\tbytes: file.length,\n\t\t\t\tbase64: file.toString(\"base64\"),\n\t\t\t},\n\t\t};\n\t}\n\n\tif (command === \"backup\") {\n\t\tif (!deps.backup) {\n\t\t\tthrow new ValidationError(\"this instance has no backup service\");\n\t\t}\n\t\tconst created = deps.backup.create({ actorId: 0, reason: \"sendTo\" });\n\t\treturn {\n\t\t\tok: true,\n\t\t\tmessage: `backup ${created.backup.name} written (${created.backup.sizeBytes} bytes)`,\n\t\t\tdata: { name: created.backup.name, sizeBytes: created.backup.sizeBytes, removed: created.removed },\n\t\t};\n\t}\n\n\tthrow new ValidationError(`unknown command \"${command}\": use punch, present, status, report or backup`);\n}\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAyBA,oBAAgC;AAChC,iBAAoC;AACpC,oBAA6B;AAC7B,mBAAiD;AACjD,iBAAiC;AACjC,kBAA0B;AAC1B,sBAA8B;AAC9B,sBAAoC;AACpC,oBAAiC;AACjC,sBAAmC;AAyCnC,SAAS,UAAU,SAAkC,OAA8B;AAClF,QAAM,QAAQ,QAAQ,KAAK;AAC3B,MAAI,UAAU,UAAa,UAAU,MAAM;AAC1C,WAAO;AAAA,EACR;AACA,MAAI,OAAO,UAAU,YAAY,OAAO,UAAU,WAAW;AAC5D,WAAO,OAAO,KAAK;AAAA,EACpB;AACA,MAAI,OAAO,UAAU,UAAU;AAC9B,UAAM,IAAI,8BAAgB,GAAG,KAAK,0BAA0B,OAAO,KAAK,GAAG;AAAA,EAC5E;AACA,SAAO,MAAM,KAAK,KAAK;AACxB;AASA,SAAS,aAAa,SAAkC,OAA+B;AACtF,QAAM,QAAQ,QAAQ,KAAK;AAC3B,MAAI,UAAU,UAAa,UAAU,MAAM;AAC1C,WAAO;AAAA,EACR;AACA,MAAI,OAAO,UAAU,WAAW;AAC/B,WAAO;AAAA,EACR;AACA,MAAI,OAAO,UAAU,UAAU;AAC9B,WAA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,MACN,IAAI;AAAA,MACJ,SAAS,UAAU,QAAQ,OAAO,IAAI,aAAa,QAAQ,OAAO,SAAS;AAAA,MAC3E,MAAM,EAAE,MAAM,QAAQ,OAAO,MAAM,WAAW,QAAQ,OAAO,WAAW,SAAS,QAAQ,QAAQ;AAAA,IAClG;AAAA,EACD;AAEA,QAAM,IAAI,8BAAgB,oBAAoB,OAAO,iDAAiD;AACvG;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -593,6 +593,15 @@ const migrations = [
|
|
|
593
593
|
UPDATE holidays SET key = 'whitMonday' WHERE key IS NULL AND name = 'Whit Monday';
|
|
594
594
|
UPDATE holidays SET key = 'corpusChristi' WHERE key IS NULL AND name = 'Corpus Christi';
|
|
595
595
|
`
|
|
596
|
+
},
|
|
597
|
+
{
|
|
598
|
+
version: 20,
|
|
599
|
+
name: "work profiles: whether the presence card shows the working time of the day",
|
|
600
|
+
sql: `
|
|
601
|
+
-- The presence screen is visible before the PIN is entered, so showing the worked time of an employee
|
|
602
|
+
-- is a decision of the administration, per employee. Off by default.
|
|
603
|
+
ALTER TABLE work_profiles ADD COLUMN show_worked_time INTEGER NOT NULL DEFAULT 0;
|
|
604
|
+
`
|
|
596
605
|
}
|
|
597
606
|
];
|
|
598
607
|
// Annotate the CommonJS export names for ESM import in node:
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/lib/db/migrations.ts"],
|
|
4
|
-
"sourcesContent": ["/**\n * Versioned database migrations.\n *\n * The schema follows the internal specification (section 2). Rules:\n * - Times are stored as UTC epoch seconds (INTEGER); durations as whole minutes.\n * - Local date/time fields (`ts_local`, `local_date`) are derived caches of `ts_utc` + user time zone.\n * - Migrations are never *reinterpreted*: a released migration keeps its effect for databases that already\n * ran it, and every schema change comes as a new migration. Definitions that only freshly created\n * databases ever see may be tidied up afterwards, as long as fresh and upgraded installations end up with\n * the same schema (see migration 10, which cleans up behind migrations 1, 2 and 5).\n */\n\nimport type { Db } from \"./database\";\n\n/**\n * A single schema migration: either plain SQL or a JavaScript step for changes that SQL cannot express\n * (e.g. \u201Cdrop this column, but only when it is still there\u201D).\n */\nexport interface Migration {\n\t/** Monotonically increasing version number, applied in ascending order */\n\tversion: number;\n\t/** Short description, stored in `schema_migrations` for traceability */\n\tname: string;\n\t/** SQL statements (may contain several statements separated by semicolons) */\n\tsql?: string;\n\t/** JavaScript steps, run inside the same transaction as `sql` */\n\trun?: (db: Db) => void;\n}\n\n/**\n * Checks whether a table has a column.\n *\n * Migrations that clean up after older versions use this to stay safe for both kinds of database: one that was\n * created by an older version and one that was created by the current one (which never creates the column).\n *\n * @param db - open database handle\n * @param table - table name\n * @param column - column name\n * @returns true when the column exists\n */\nexport function hasColumn(db: Db, table: string, column: string): boolean {\n\tconst rows = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n\treturn rows.some(row => row.name === column);\n}\n\nexport const migrations: Migration[] = [\n\t{\n\t\tversion: 1,\n\t\tname: \"core: users, roles, permissions, work profiles, shift and pause rules, settings, sessions, audit, import runs\",\n\t\tsql: `\n\t\t\tCREATE TABLE users (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlogin TEXT NOT NULL UNIQUE,\n\t\t\t\tpassword_hash TEXT NOT NULL DEFAULT '',\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\temail TEXT,\n\t\t\t\trfid_card TEXT,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tmust_change_pw INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlocale TEXT NOT NULL DEFAULT 'de-DE',\n\t\t\t\ttimezone TEXT NOT NULL DEFAULT 'Europe/Berlin',\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tlast_login_at INTEGER\n\t\t\t);\n\n\t\t\tCREATE TABLE roles (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tkey TEXT NOT NULL UNIQUE,\n\t\t\t\tname TEXT NOT NULL\n\t\t\t);\n\n\t\t\tCREATE TABLE permissions (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tkey TEXT NOT NULL UNIQUE\n\t\t\t);\n\n\t\t\tCREATE TABLE role_permissions (\n\t\t\t\trole_id INTEGER NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n\t\t\t\tpermission_id INTEGER NOT NULL REFERENCES permissions(id) ON DELETE CASCADE,\n\t\t\t\tPRIMARY KEY (role_id, permission_id)\n\t\t\t);\n\n\t\t\tCREATE TABLE user_roles (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\trole_id INTEGER NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n\t\t\t\tPRIMARY KEY (user_id, role_id)\n\t\t\t);\n\n\t\t\tCREATE TABLE work_profiles (\n\t\t\t\tuser_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tpercent REAL NOT NULL DEFAULT 100,\n\t\t\t\tweekly_hours REAL NOT NULL DEFAULT 42.5,\n\t\t\t\tworkdays TEXT NOT NULL DEFAULT '0;1;1;1;1;1;0',\n\t\t\t\tstart_date INTEGER,\n\t\t\t\tend_date INTEGER,\n\t\t\t\tovertime_carryover INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvorholzeit_per_year INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvacation_carryover REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_per_year REAL NOT NULL DEFAULT 0,\n\t\t\t\tovertime_model TEXT NOT NULL DEFAULT 'monthly'\n\t\t\t\t CHECK (overtime_model IN ('cumulative','yearly','monthly')),\n\t\t\t\tholiday_flags TEXT\n\t\t\t);\n\n\t\t\tCREATE TABLE shift_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tday_of_week INTEGER CHECK (day_of_week IS NULL OR day_of_week BETWEEN 0 AND 6),\n\t\t\t\tfrom_min INTEGER,\n\t\t\t\tto_min INTEGER,\n\t\t\t\tsurcharge REAL NOT NULL DEFAULT 0,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1\n\t\t\t);\n\n\t\t\tCREATE TABLE pause_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tfrom_min INTEGER NOT NULL,\n\t\t\t\tto_min INTEGER,\n\t\t\t\tpause_min INTEGER NOT NULL,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tCHECK (to_min IS NULL OR to_min > from_min)\n\t\t\t);\n\n\t\t\tCREATE TABLE app_settings (\n\t\t\t\tkey TEXT PRIMARY KEY,\n\t\t\t\tvalue TEXT NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\n\t\t\tCREATE TABLE sessions (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\texpires_at INTEGER NOT NULL,\n\t\t\t\tuser_agent TEXT,\n\t\t\t\tip TEXT,\n\t\t\t\trevoked INTEGER NOT NULL DEFAULT 0\n\t\t\t);\n\n\t\t\tCREATE TABLE audit_log (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tat_utc INTEGER NOT NULL,\n\t\t\t\tactor_id INTEGER,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tentity TEXT,\n\t\t\t\tentity_id TEXT,\n\t\t\t\tdetail TEXT,\n\t\t\t\tip TEXT\n\t\t\t);\n\n\t\t\tCREATE TABLE import_runs (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tsource TEXT NOT NULL,\n\t\t\t\tsource_path TEXT NOT NULL,\n\t\t\t\tstarted_at INTEGER NOT NULL,\n\t\t\t\tfinished_at INTEGER,\n\t\t\t\tmode TEXT NOT NULL DEFAULT 'dry-run'\n\t\t\t\t CHECK (mode IN ('dry-run','commit')),\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'running'\n\t\t\t\t CHECK (status IN ('running','ok','warnings','mismatch','failed')),\n\t\t\t\ttimezone_assumed TEXT,\n\t\t\t\tstats TEXT,\n\t\t\t\twarnings TEXT,\n\t\t\t\tactor_id INTEGER REFERENCES users(id)\n\t\t\t);\n\t\t`,\n\t},\n\t{\n\t\tversion: 2,\n\t\tname: \"time: entries, audit, day/month/year aggregates, payouts\",\n\t\tsql: `\n\t\t\tCREATE TABLE time_entries (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tts_utc INTEGER NOT NULL,\n\t\t\t\tclient_ts_utc INTEGER,\n\t\t\t\tts_local INTEGER NOT NULL,\n\t\t\t\tlocal_date TEXT NOT NULL,\n\t\t\t\tdirection TEXT NOT NULL DEFAULT 'auto'\n\t\t\t\t CHECK (direction IN ('in','out','auto')),\n\t\t\t\tsource TEXT NOT NULL DEFAULT 'web'\n\t\t\t\t CHECK (source IN ('web','nfc','terminal','api','admin','import')),\n\t\t\t\tidempotency_key TEXT,\n\t\t\t\tsync_state TEXT NOT NULL DEFAULT 'synced'\n\t\t\t\t CHECK (sync_state IN ('synced','pending','conflict')),\n\t\t\t\trevision INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tnote TEXT,\n\t\t\t\tcreated_by INTEGER REFERENCES users(id),\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tupdated_by INTEGER REFERENCES users(id)\n\t\t\t);\n\n\t\t\tCREATE INDEX idx_entries_user_date ON time_entries(user_id, local_date);\n\t\t\tCREATE INDEX idx_entries_user_ts ON time_entries(user_id, ts_utc);\n\t\t\tCREATE UNIQUE INDEX idx_entries_idem\n\t\t\t\tON time_entries(user_id, idempotency_key) WHERE idempotency_key IS NOT NULL;\n\n\t\t\tCREATE TABLE time_entry_audit (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tentry_id INTEGER,\n\t\t\t\tuser_id INTEGER NOT NULL,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tchanges TEXT,\n\t\t\t\told_ts_utc INTEGER,\n\t\t\t\tnew_ts_utc INTEGER,\n\t\t\t\trevision INTEGER,\n\t\t\t\treason TEXT,\n\t\t\t\tactor_id INTEGER NOT NULL,\n\t\t\t\tactor_ip TEXT,\n\t\t\t\tat_utc INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX idx_entry_audit_entry ON time_entry_audit(entry_id);\n\t\t`,\n\t},\n\t{\n\t\tversion: 3,\n\t\tname: \"aggregates: day, month, year and payouts\",\n\t\tsql: `\n\t\t\tCREATE TABLE day_aggregates (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tlocal_date TEXT NOT NULL,\n\t\t\t\tworked_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tbreak_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttarget_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tbalance_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tabsence_code TEXT,\n\t\t\t\tis_holiday INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tfirst_in_utc INTEGER,\n\t\t\t\tlast_out_utc INTEGER,\n\t\t\t\thas_open_entry INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (user_id, local_date)\n\t\t\t);\n\n\t\t\tCREATE TABLE month_aggregates (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tmonth INTEGER NOT NULL CHECK (month BETWEEN 1 AND 12),\n\t\t\t\tworked_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttarget_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tbalance_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tovertime_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvacation_used REAL NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (user_id, year, month)\n\t\t\t);\n\n\t\t\tCREATE TABLE year_aggregates (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tworked_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttarget_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tovertime_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tovertime_start INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvacation_days REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_used REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_left REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_planned_days REAL NOT NULL DEFAULT 0,\n\t\t\t\tsettled INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (user_id, year)\n\t\t\t);\n\n\t\t\tCREATE TABLE payouts (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tmonth INTEGER,\n\t\t\t\tminutes INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tamount REAL,\n\t\t\t\tnote TEXT,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tcreated_by INTEGER REFERENCES users(id)\n\t\t\t);\n\t\t\tCREATE INDEX idx_payouts_user ON payouts(user_id, year, month);\n\t\t`,\n\t},\n\t{\n\t\tversion: 4,\n\t\tname: \"absence: types, absences, holidays\",\n\t\tsql: `\n\t\t\tCREATE TABLE absence_types (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tcode TEXT NOT NULL,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tpaid INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tfactor REAL NOT NULL DEFAULT 100,\n\t\t\t\treduce_vacation INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1\n\t\t\t);\n\n\t\t\tCREATE UNIQUE INDEX idx_absence_types_global\n\t\t\t\tON absence_types(code) WHERE user_id IS NULL;\n\t\t\tCREATE UNIQUE INDEX idx_absence_types_user\n\t\t\t\tON absence_types(user_id, code) WHERE user_id IS NOT NULL;\n\n\t\t\tCREATE TABLE absences (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\ttype_id INTEGER NOT NULL REFERENCES absence_types(id),\n\t\t\t\tdate_from TEXT NOT NULL,\n\t\t\t\tdate_to TEXT NOT NULL,\n\t\t\t\tday_portion REAL NOT NULL DEFAULT 1 CHECK (day_portion > 0 AND day_portion <= 1),\n\t\t\t\thours REAL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'taken'\n\t\t\t\t CHECK (status IN ('taken','planned')),\n\t\t\t\tnote TEXT,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tcreated_by INTEGER REFERENCES users(id),\n\t\t\t\tCHECK (date_from <= date_to)\n\t\t\t);\n\t\t\tCREATE INDEX idx_absences_user_dates ON absences(user_id, date_from, date_to);\n\n\t\t\tCREATE TABLE holidays (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tregion TEXT NOT NULL DEFAULT 'global',\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tdate TEXT NOT NULL,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tUNIQUE (region, date)\n\t\t\t);\n\t\t\tCREATE INDEX idx_holidays_year ON holidays(year, region);\n\t\t`,\n\t},\n\t{\n\t\tversion: 5,\n\t\tname: \"devices: rfid tags and kiosk terminals\",\n\t\tsql: `\n\t\t\tCREATE TABLE rfid_tags (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuid TEXT,\n\t\t\t\ttoken_hash TEXT NOT NULL,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE SET NULL,\n\t\t\t\tlabel TEXT,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\texpires_at INTEGER,\n\t\t\t\tlast_used_at INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE UNIQUE INDEX idx_rfid_uid ON rfid_tags(uid) WHERE uid IS NOT NULL;\n\n\t\t\tCREATE TABLE kiosk_terminals (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tlocation TEXT,\n\t\t\t\ttoken_hash TEXT NOT NULL,\n\t\t\t\tpin_required INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\texpires_at INTEGER,\n\t\t\t\tlast_seen_at INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL\n\t\t\t);\n\t\t`,\n\t},\n\t{\n\t\tversion: 6,\n\t\tname: \"users: personal PIN for the kiosk terminal\",\n\t\tsql: `ALTER TABLE users ADD COLUMN pin_hash TEXT;`,\n\t},\n\t{\n\t\tversion: 7,\n\t\tname: \"kiosk terminals: short lived sessions\",\n\t\tsql: `\n\t\t\tALTER TABLE kiosk_terminals ADD COLUMN session_hash TEXT;\n\t\t\tALTER TABLE kiosk_terminals ADD COLUMN session_expires_at INTEGER;\n\t\t`,\n\t},\n\t{\n\t\tversion: 8,\n\t\tname: \"defaults: time zone Europe/Zurich becomes Europe/Berlin\",\n\t\tsql: `\n\t\t\t-- The default time zone of the adapter is Europe/Berlin now. Migration 1 is append-only, so a new\n\t\t\t-- database already gets the new default with it; existing installations are adjusted here: every\n\t\t\t-- employee and every instance setting that still carries the old default is moved over. Values that\n\t\t\t-- were chosen deliberately keep their name \u2014 they only change when they are exactly the old default.\n\t\t\tUPDATE users SET timezone = 'Europe/Berlin' WHERE timezone = 'Europe/Zurich';\n\t\t\tUPDATE app_settings SET value = 'Europe/Berlin' WHERE key = 'timezone' AND value = 'Europe/Zurich';\n\t\t`,\n\t},\n\t{\n\t\tversion: 9,\n\t\tname: \"users: picture of the employee\",\n\t\tsql: `ALTER TABLE users ADD COLUMN avatar TEXT;`,\n\t},\n\t{\n\t\tversion: 10,\n\t\tname: \"drops the leftovers of the removed data import\",\n\t\trun: (db: Db): void => {\n\t\t\t// The adapter does not read data of another time tracking system any more, so the columns that existed\n\t\t\t// for it are dropped. Fresh databases never create them (migrations 1, 2 and 5 are clean), so every\n\t\t\t// step asks first: an upgraded database loses the columns, a fresh one has nothing to do.\n\t\t\tif (hasColumn(db, \"users\", \"legacy_sha1\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE users DROP COLUMN legacy_sha1\");\n\t\t\t}\n\t\t\tif (hasColumn(db, \"work_profiles\", \"legacy_source\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE work_profiles DROP COLUMN legacy_source\");\n\t\t\t}\n\n\t\t\t// rfid_tags carried the printed card number of that system as a second identifier. SQLite cannot drop\n\t\t\t// a column that a CHECK constraint mentions, so the table is rebuilt without it; existing rows keep\n\t\t\t// their id, their uid and their token hash, and the unique index on the uid is recreated.\n\t\t\tif (!hasColumn(db, \"rfid_tags\", \"legacy_code\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdb.exec(`\n\t\t\t\tCREATE TABLE rfid_tags_new (\n\t\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\t\tuid TEXT,\n\t\t\t\t\ttoken_hash TEXT NOT NULL,\n\t\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE SET NULL,\n\t\t\t\t\tlabel TEXT,\n\t\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\t\texpires_at INTEGER,\n\t\t\t\t\tlast_used_at INTEGER,\n\t\t\t\t\tcreated_at INTEGER NOT NULL\n\t\t\t\t);\n\t\t\t\tINSERT INTO rfid_tags_new (id, uid, token_hash, user_id, label, is_active, expires_at, last_used_at, created_at)\n\t\t\t\t\tSELECT id, uid, token_hash, user_id, label, is_active, expires_at, last_used_at, created_at\n\t\t\t\t\tFROM rfid_tags;\n\t\t\t\tDROP TABLE rfid_tags;\n\t\t\t\tALTER TABLE rfid_tags_new RENAME TO rfid_tags;\n\t\t\t\tCREATE UNIQUE INDEX idx_rfid_uid ON rfid_tags(uid) WHERE uid IS NOT NULL;\n\t\t\t`);\n\t\t},\n\t},\n\t{\n\t\tversion: 11,\n\t\tname: \"terminals: the employees of a terminal\",\n\t\tsql: `\n\t\t\t-- A terminal stands at one place \u2014 an office, a workshop \u2014 and is meant for the employees that work\n\t\t\t-- there. No row for a terminal means \"all employees\", so terminals that existed before keep working\n\t\t\t-- exactly as they did.\n\t\t\tCREATE TABLE terminal_users (\n\t\t\t\tterminal_id INTEGER NOT NULL REFERENCES kiosk_terminals(id) ON DELETE CASCADE,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (terminal_id, user_id)\n\t\t\t);\n\t\t\tCREATE INDEX idx_terminal_users_user ON terminal_users(user_id);\n\t\t`,\n\t},\n\t{\n\t\tversion: 12,\n\t\tname: \"work profiles: paid breaks\",\n\t\tsql: `ALTER TABLE work_profiles ADD COLUMN pause_paid INTEGER NOT NULL DEFAULT 0;`,\n\t},\n\t{\n\t\tversion: 13,\n\t\tname: \"work profiles: paid break minutes instead of the paid flag\",\n\t\trun: (db: Db): void => {\n\t\t\t// The flag became an amount: a company may pay a quarter of an hour and nothing more. A profile that had\n\t\t\t// the flag set keeps a fully paid break (a day has 1440 minutes), a fresh profile pays nothing at all.\n\t\t\tif (!hasColumn(db, \"work_profiles\", \"pause_paid_minutes\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE work_profiles ADD COLUMN pause_paid_minutes INTEGER NOT NULL DEFAULT 0\");\n\t\t\t}\n\t\t\tif (hasColumn(db, \"work_profiles\", \"pause_paid\")) {\n\t\t\t\tdb.exec(\"UPDATE work_profiles SET pause_paid_minutes = 1440 WHERE pause_paid = 1\");\n\t\t\t\tdb.exec(\"ALTER TABLE work_profiles DROP COLUMN pause_paid\");\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tversion: 14,\n\t\tname: \"day aggregates: paid break minutes\",\n\t\tsql: `ALTER TABLE day_aggregates ADD COLUMN paid_break_min INTEGER NOT NULL DEFAULT 0;`,\n\t},\n\t{\n\t\tversion: 15,\n\t\tname: \"trigger rules: ioBroker states that punch or set the presence\",\n\t\tsql: `\n\t\t\t-- A rule watches a state of another adapter (a fingerprint reader, a button, a door contact) and turns a\n\t\t\t-- write on it into a punch or a presence change. Mode \"condition\" fires when the value matches\n\t\t\t-- \"condition\" and punches for \"user_id\"; mode \"user\" posts the employee the value names. \"last_fired_at\"\n\t\t\t-- keeps a chatty reader in check together with \"cooldown_sec\".\n\t\t\tCREATE TABLE trigger_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlabel TEXT,\n\t\t\t\tsource_state TEXT NOT NULL,\n\t\t\t\tmode TEXT NOT NULL DEFAULT 'condition'\n\t\t\t\t\tCHECK (mode IN ('condition','user')),\n\t\t\t\tcondition TEXT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\taction TEXT NOT NULL DEFAULT 'punch'\n\t\t\t\t\tCHECK (action IN ('punch','quickPunch','present','absent')),\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tcooldown_sec INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_fired_at INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX idx_trigger_rules_source ON trigger_rules(source_state);\n\t\t`,\n\t},\n\t{\n\t\tversion: 16,\n\t\tname: \"automation rules: what the adapter does on its own (clock out, reminders)\",\n\t\tsql: `\n\t\t\t-- A rule of the adapter itself, not of a foreign state: at a certain local time (clockOut, missingPunch)\n\t\t\t-- or after a while without a break (breakReminder) the adapter acts. \"user_id\" is NULL for every\n\t\t\t-- employee, so a company rule and a rule for one person can live side by side.\n\t\t\tCREATE TABLE automation_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlabel TEXT,\n\t\t\t\tkind TEXT NOT NULL\n\t\t\t\t\tCHECK (kind IN ('clockOut','missingPunch','breakReminder')),\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tat_minute INTEGER,\n\t\t\t\tafter_minutes INTEGER,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX idx_automation_rules_kind ON automation_rules(kind);\n\n\t\t\t-- What a rule already did: one row per rule, employee and local date keeps it at \"once a day\" and doubles\n\t\t\t-- as the log the administration shows. A punch that is already written is never written twice.\n\t\t\tCREATE TABLE automation_runs (\n\t\t\t\trule_id INTEGER NOT NULL REFERENCES automation_rules(id) ON DELETE CASCADE,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tlocal_date TEXT NOT NULL,\n\t\t\t\tfired_at INTEGER NOT NULL,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (rule_id, user_id, local_date)\n\t\t\t);\n\t\t\tCREATE INDEX idx_automation_runs_user ON automation_runs(user_id, local_date);\n\t\t`,\n\t},\n\t{\n\t\tversion: 17,\n\t\tname: \"automation rules: weekdays and a weekly instead of a daily guard\",\n\t\tsql: `\n\t\t\t-- A rule can be limited to certain weekdays: bit 0 is Monday \u2026 bit 6 is Sunday, 127 is every day.\n\t\t\tALTER TABLE automation_rules ADD COLUMN weekdays INTEGER NOT NULL DEFAULT 127;\n\n\t\t\t-- 'day' keeps the guard of one run per employee and date, 'week' allows one run per ISO week.\n\t\t\tALTER TABLE automation_rules ADD COLUMN repeat TEXT NOT NULL DEFAULT 'day';\n\n\t\t\t-- the guard column no longer holds a date only: for a weekly rule it is the ISO week (2026-W38), so the\n\t\t\t-- name says what it keeps. Existing rows stay valid \u2014 a date is the period of a daily rule.\n\t\t\tALTER TABLE automation_runs RENAME COLUMN local_date TO period;\n\t\t`,\n\t},\n\t{\n\t\tversion: 18,\n\t\tname: \"automation rules: the kind clockIn (punch in somebody who is missing)\",\n\t\tsql: `\n\t\t\t-- A fourth kind joins the rules: 'clockIn' punches an employee in who is still missing at the configured\n\t\t\t-- time (the decision makes sure nobody is clocked in already). SQLite cannot change a CHECK constraint in\n\t\t\t-- place, so the table is rebuilt \u2014 and because automation_runs belongs to it with ON DELETE CASCADE, the\n\t\t\t-- run log is copied first: dropping the parent would take it with it.\n\t\t\tCREATE TABLE automation_runs_copy (\n\t\t\t\trule_id INTEGER NOT NULL,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tperiod TEXT NOT NULL,\n\t\t\t\tfired_at INTEGER NOT NULL,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (rule_id, user_id, period)\n\t\t\t);\n\t\t\tINSERT INTO automation_runs_copy (rule_id, user_id, period, fired_at, action)\n\t\t\t\tSELECT rule_id, user_id, period, fired_at, action FROM automation_runs;\n\n\t\t\tCREATE TABLE automation_rules_new (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlabel TEXT,\n\t\t\t\tkind TEXT NOT NULL\n\t\t\t\t\tCHECK (kind IN ('clockIn','clockOut','missingPunch','breakReminder')),\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tat_minute INTEGER,\n\t\t\t\tafter_minutes INTEGER,\n\t\t\t\tweekdays INTEGER NOT NULL DEFAULT 127,\n\t\t\t\trepeat TEXT NOT NULL DEFAULT 'day',\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tINSERT INTO automation_rules_new\n\t\t\t\t(id, label, kind, user_id, at_minute, after_minutes, weekdays, repeat, is_active, created_at, updated_at)\n\t\t\t\tSELECT id, label, kind, user_id, at_minute, after_minutes, weekdays, repeat, is_active, created_at, updated_at\n\t\t\t\tFROM automation_rules;\n\n\t\t\tDROP TABLE automation_runs;\n\t\t\tDROP TABLE automation_rules;\n\t\t\tALTER TABLE automation_rules_new RENAME TO automation_rules;\n\t\t\t-- the runs keep their user reference; the reference to the rule is kept by the repository, which deletes\n\t\t\t-- the runs of a rule together with it\n\t\t\tALTER TABLE automation_runs_copy RENAME TO automation_runs;\n\n\t\t\tCREATE INDEX idx_automation_rules_kind ON automation_rules(kind);\n\t\t\tCREATE INDEX idx_automation_runs_user ON automation_runs(user_id, period);\n\t\t`,\n\t},\n\t{\n\t\tversion: 19,\n\t\tname: \"holidays: a stable key next to the name, so the app can translate the seeded days\",\n\t\tsql: `\n\t\t\t-- The seeded holidays carry an English name. The key says which day it is, so the web app shows it in the\n\t\t\t-- language of the display; a day somebody added by hand has no key and keeps its own name.\n\t\t\tALTER TABLE holidays ADD COLUMN key TEXT;\n\n\t\t\t-- the days that are already stored get their key from the date\n\t\t\tUPDATE holidays SET key = 'newYear' WHERE key IS NULL AND date LIKE '%-01-01';\n\t\t\tUPDATE holidays SET key = 'epiphany' WHERE key IS NULL AND date LIKE '%-01-06';\n\t\t\tUPDATE holidays SET key = 'labourDay' WHERE key IS NULL AND date LIKE '%-05-01';\n\t\t\tUPDATE holidays SET key = 'nationalDay' WHERE key IS NULL AND (date LIKE '%-08-01' OR date LIKE '%-10-26');\n\t\t\tUPDATE holidays SET key = 'assumption' WHERE key IS NULL AND date LIKE '%-08-15';\n\t\t\tUPDATE holidays SET key = 'germanUnity' WHERE key IS NULL AND date LIKE '%-10-03';\n\t\t\tUPDATE holidays SET key = 'allSaints' WHERE key IS NULL AND date LIKE '%-11-01';\n\t\t\tUPDATE holidays SET key = 'immaculateConception' WHERE key IS NULL AND date LIKE '%-12-08';\n\t\t\tUPDATE holidays SET key = 'christmas' WHERE key IS NULL AND date LIKE '%-12-25';\n\t\t\tUPDATE holidays SET key = 'boxingDay' WHERE key IS NULL AND date LIKE '%-12-26';\n\t\t\t-- the movable feasts carry their English name, which is unique enough to find them again\n\t\t\tUPDATE holidays SET key = 'goodFriday' WHERE key IS NULL AND name = 'Good Friday';\n\t\t\tUPDATE holidays SET key = 'easterMonday' WHERE key IS NULL AND name = 'Easter Monday';\n\t\t\tUPDATE holidays SET key = 'ascension' WHERE key IS NULL AND name = 'Ascension Day';\n\t\t\tUPDATE holidays SET key = 'whitMonday' WHERE key IS NULL AND name = 'Whit Monday';\n\t\t\tUPDATE holidays SET key = 'corpusChristi' WHERE key IS NULL AND name = 'Corpus Christi';\n\t\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sourcesContent": ["/**\n * Versioned database migrations.\n *\n * The schema follows the internal specification (section 2). Rules:\n * - Times are stored as UTC epoch seconds (INTEGER); durations as whole minutes.\n * - Local date/time fields (`ts_local`, `local_date`) are derived caches of `ts_utc` + user time zone.\n * - Migrations are never *reinterpreted*: a released migration keeps its effect for databases that already\n * ran it, and every schema change comes as a new migration. Definitions that only freshly created\n * databases ever see may be tidied up afterwards, as long as fresh and upgraded installations end up with\n * the same schema (see migration 10, which cleans up behind migrations 1, 2 and 5).\n */\n\nimport type { Db } from \"./database\";\n\n/**\n * A single schema migration: either plain SQL or a JavaScript step for changes that SQL cannot express\n * (e.g. \u201Cdrop this column, but only when it is still there\u201D).\n */\nexport interface Migration {\n\t/** Monotonically increasing version number, applied in ascending order */\n\tversion: number;\n\t/** Short description, stored in `schema_migrations` for traceability */\n\tname: string;\n\t/** SQL statements (may contain several statements separated by semicolons) */\n\tsql?: string;\n\t/** JavaScript steps, run inside the same transaction as `sql` */\n\trun?: (db: Db) => void;\n}\n\n/**\n * Checks whether a table has a column.\n *\n * Migrations that clean up after older versions use this to stay safe for both kinds of database: one that was\n * created by an older version and one that was created by the current one (which never creates the column).\n *\n * @param db - open database handle\n * @param table - table name\n * @param column - column name\n * @returns true when the column exists\n */\nexport function hasColumn(db: Db, table: string, column: string): boolean {\n\tconst rows = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];\n\treturn rows.some(row => row.name === column);\n}\n\nexport const migrations: Migration[] = [\n\t{\n\t\tversion: 1,\n\t\tname: \"core: users, roles, permissions, work profiles, shift and pause rules, settings, sessions, audit, import runs\",\n\t\tsql: `\n\t\t\tCREATE TABLE users (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlogin TEXT NOT NULL UNIQUE,\n\t\t\t\tpassword_hash TEXT NOT NULL DEFAULT '',\n\t\t\t\tdisplay_name TEXT NOT NULL,\n\t\t\t\temail TEXT,\n\t\t\t\trfid_card TEXT,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tmust_change_pw INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlocale TEXT NOT NULL DEFAULT 'de-DE',\n\t\t\t\ttimezone TEXT NOT NULL DEFAULT 'Europe/Berlin',\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tlast_login_at INTEGER\n\t\t\t);\n\n\t\t\tCREATE TABLE roles (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tkey TEXT NOT NULL UNIQUE,\n\t\t\t\tname TEXT NOT NULL\n\t\t\t);\n\n\t\t\tCREATE TABLE permissions (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tkey TEXT NOT NULL UNIQUE\n\t\t\t);\n\n\t\t\tCREATE TABLE role_permissions (\n\t\t\t\trole_id INTEGER NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n\t\t\t\tpermission_id INTEGER NOT NULL REFERENCES permissions(id) ON DELETE CASCADE,\n\t\t\t\tPRIMARY KEY (role_id, permission_id)\n\t\t\t);\n\n\t\t\tCREATE TABLE user_roles (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\trole_id INTEGER NOT NULL REFERENCES roles(id) ON DELETE CASCADE,\n\t\t\t\tPRIMARY KEY (user_id, role_id)\n\t\t\t);\n\n\t\t\tCREATE TABLE work_profiles (\n\t\t\t\tuser_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tpercent REAL NOT NULL DEFAULT 100,\n\t\t\t\tweekly_hours REAL NOT NULL DEFAULT 42.5,\n\t\t\t\tworkdays TEXT NOT NULL DEFAULT '0;1;1;1;1;1;0',\n\t\t\t\tstart_date INTEGER,\n\t\t\t\tend_date INTEGER,\n\t\t\t\tovertime_carryover INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvorholzeit_per_year INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvacation_carryover REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_per_year REAL NOT NULL DEFAULT 0,\n\t\t\t\tovertime_model TEXT NOT NULL DEFAULT 'monthly'\n\t\t\t\t CHECK (overtime_model IN ('cumulative','yearly','monthly')),\n\t\t\t\tholiday_flags TEXT\n\t\t\t);\n\n\t\t\tCREATE TABLE shift_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tday_of_week INTEGER CHECK (day_of_week IS NULL OR day_of_week BETWEEN 0 AND 6),\n\t\t\t\tfrom_min INTEGER,\n\t\t\t\tto_min INTEGER,\n\t\t\t\tsurcharge REAL NOT NULL DEFAULT 0,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1\n\t\t\t);\n\n\t\t\tCREATE TABLE pause_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tfrom_min INTEGER NOT NULL,\n\t\t\t\tto_min INTEGER,\n\t\t\t\tpause_min INTEGER NOT NULL,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tCHECK (to_min IS NULL OR to_min > from_min)\n\t\t\t);\n\n\t\t\tCREATE TABLE app_settings (\n\t\t\t\tkey TEXT PRIMARY KEY,\n\t\t\t\tvalue TEXT NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\n\t\t\tCREATE TABLE sessions (\n\t\t\t\tid TEXT PRIMARY KEY,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\texpires_at INTEGER NOT NULL,\n\t\t\t\tuser_agent TEXT,\n\t\t\t\tip TEXT,\n\t\t\t\trevoked INTEGER NOT NULL DEFAULT 0\n\t\t\t);\n\n\t\t\tCREATE TABLE audit_log (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tat_utc INTEGER NOT NULL,\n\t\t\t\tactor_id INTEGER,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tentity TEXT,\n\t\t\t\tentity_id TEXT,\n\t\t\t\tdetail TEXT,\n\t\t\t\tip TEXT\n\t\t\t);\n\n\t\t\tCREATE TABLE import_runs (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tsource TEXT NOT NULL,\n\t\t\t\tsource_path TEXT NOT NULL,\n\t\t\t\tstarted_at INTEGER NOT NULL,\n\t\t\t\tfinished_at INTEGER,\n\t\t\t\tmode TEXT NOT NULL DEFAULT 'dry-run'\n\t\t\t\t CHECK (mode IN ('dry-run','commit')),\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'running'\n\t\t\t\t CHECK (status IN ('running','ok','warnings','mismatch','failed')),\n\t\t\t\ttimezone_assumed TEXT,\n\t\t\t\tstats TEXT,\n\t\t\t\twarnings TEXT,\n\t\t\t\tactor_id INTEGER REFERENCES users(id)\n\t\t\t);\n\t\t`,\n\t},\n\t{\n\t\tversion: 2,\n\t\tname: \"time: entries, audit, day/month/year aggregates, payouts\",\n\t\tsql: `\n\t\t\tCREATE TABLE time_entries (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tts_utc INTEGER NOT NULL,\n\t\t\t\tclient_ts_utc INTEGER,\n\t\t\t\tts_local INTEGER NOT NULL,\n\t\t\t\tlocal_date TEXT NOT NULL,\n\t\t\t\tdirection TEXT NOT NULL DEFAULT 'auto'\n\t\t\t\t CHECK (direction IN ('in','out','auto')),\n\t\t\t\tsource TEXT NOT NULL DEFAULT 'web'\n\t\t\t\t CHECK (source IN ('web','nfc','terminal','api','admin','import')),\n\t\t\t\tidempotency_key TEXT,\n\t\t\t\tsync_state TEXT NOT NULL DEFAULT 'synced'\n\t\t\t\t CHECK (sync_state IN ('synced','pending','conflict')),\n\t\t\t\trevision INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tnote TEXT,\n\t\t\t\tcreated_by INTEGER REFERENCES users(id),\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tupdated_by INTEGER REFERENCES users(id)\n\t\t\t);\n\n\t\t\tCREATE INDEX idx_entries_user_date ON time_entries(user_id, local_date);\n\t\t\tCREATE INDEX idx_entries_user_ts ON time_entries(user_id, ts_utc);\n\t\t\tCREATE UNIQUE INDEX idx_entries_idem\n\t\t\t\tON time_entries(user_id, idempotency_key) WHERE idempotency_key IS NOT NULL;\n\n\t\t\tCREATE TABLE time_entry_audit (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tentry_id INTEGER,\n\t\t\t\tuser_id INTEGER NOT NULL,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tchanges TEXT,\n\t\t\t\told_ts_utc INTEGER,\n\t\t\t\tnew_ts_utc INTEGER,\n\t\t\t\trevision INTEGER,\n\t\t\t\treason TEXT,\n\t\t\t\tactor_id INTEGER NOT NULL,\n\t\t\t\tactor_ip TEXT,\n\t\t\t\tat_utc INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX idx_entry_audit_entry ON time_entry_audit(entry_id);\n\t\t`,\n\t},\n\t{\n\t\tversion: 3,\n\t\tname: \"aggregates: day, month, year and payouts\",\n\t\tsql: `\n\t\t\tCREATE TABLE day_aggregates (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tlocal_date TEXT NOT NULL,\n\t\t\t\tworked_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tbreak_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttarget_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tbalance_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tabsence_code TEXT,\n\t\t\t\tis_holiday INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tfirst_in_utc INTEGER,\n\t\t\t\tlast_out_utc INTEGER,\n\t\t\t\thas_open_entry INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (user_id, local_date)\n\t\t\t);\n\n\t\t\tCREATE TABLE month_aggregates (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tmonth INTEGER NOT NULL CHECK (month BETWEEN 1 AND 12),\n\t\t\t\tworked_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttarget_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tbalance_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tovertime_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvacation_used REAL NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (user_id, year, month)\n\t\t\t);\n\n\t\t\tCREATE TABLE year_aggregates (\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tworked_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\ttarget_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tovertime_min INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tovertime_start INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tvacation_days REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_used REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_left REAL NOT NULL DEFAULT 0,\n\t\t\t\tvacation_planned_days REAL NOT NULL DEFAULT 0,\n\t\t\t\tsettled INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tupdated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (user_id, year)\n\t\t\t);\n\n\t\t\tCREATE TABLE payouts (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tmonth INTEGER,\n\t\t\t\tminutes INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tamount REAL,\n\t\t\t\tnote TEXT,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tcreated_by INTEGER REFERENCES users(id)\n\t\t\t);\n\t\t\tCREATE INDEX idx_payouts_user ON payouts(user_id, year, month);\n\t\t`,\n\t},\n\t{\n\t\tversion: 4,\n\t\tname: \"absence: types, absences, holidays\",\n\t\tsql: `\n\t\t\tCREATE TABLE absence_types (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tcode TEXT NOT NULL,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tpaid INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tfactor REAL NOT NULL DEFAULT 100,\n\t\t\t\treduce_vacation INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1\n\t\t\t);\n\n\t\t\tCREATE UNIQUE INDEX idx_absence_types_global\n\t\t\t\tON absence_types(code) WHERE user_id IS NULL;\n\t\t\tCREATE UNIQUE INDEX idx_absence_types_user\n\t\t\t\tON absence_types(user_id, code) WHERE user_id IS NOT NULL;\n\n\t\t\tCREATE TABLE absences (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\ttype_id INTEGER NOT NULL REFERENCES absence_types(id),\n\t\t\t\tdate_from TEXT NOT NULL,\n\t\t\t\tdate_to TEXT NOT NULL,\n\t\t\t\tday_portion REAL NOT NULL DEFAULT 1 CHECK (day_portion > 0 AND day_portion <= 1),\n\t\t\t\thours REAL,\n\t\t\t\tstatus TEXT NOT NULL DEFAULT 'taken'\n\t\t\t\t CHECK (status IN ('taken','planned')),\n\t\t\t\tnote TEXT,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tcreated_by INTEGER REFERENCES users(id),\n\t\t\t\tCHECK (date_from <= date_to)\n\t\t\t);\n\t\t\tCREATE INDEX idx_absences_user_dates ON absences(user_id, date_from, date_to);\n\n\t\t\tCREATE TABLE holidays (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tregion TEXT NOT NULL DEFAULT 'global',\n\t\t\t\tyear INTEGER NOT NULL,\n\t\t\t\tdate TEXT NOT NULL,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tUNIQUE (region, date)\n\t\t\t);\n\t\t\tCREATE INDEX idx_holidays_year ON holidays(year, region);\n\t\t`,\n\t},\n\t{\n\t\tversion: 5,\n\t\tname: \"devices: rfid tags and kiosk terminals\",\n\t\tsql: `\n\t\t\tCREATE TABLE rfid_tags (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tuid TEXT,\n\t\t\t\ttoken_hash TEXT NOT NULL,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE SET NULL,\n\t\t\t\tlabel TEXT,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\texpires_at INTEGER,\n\t\t\t\tlast_used_at INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE UNIQUE INDEX idx_rfid_uid ON rfid_tags(uid) WHERE uid IS NOT NULL;\n\n\t\t\tCREATE TABLE kiosk_terminals (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tname TEXT NOT NULL,\n\t\t\t\tlocation TEXT,\n\t\t\t\ttoken_hash TEXT NOT NULL,\n\t\t\t\tpin_required INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\texpires_at INTEGER,\n\t\t\t\tlast_seen_at INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL\n\t\t\t);\n\t\t`,\n\t},\n\t{\n\t\tversion: 6,\n\t\tname: \"users: personal PIN for the kiosk terminal\",\n\t\tsql: `ALTER TABLE users ADD COLUMN pin_hash TEXT;`,\n\t},\n\t{\n\t\tversion: 7,\n\t\tname: \"kiosk terminals: short lived sessions\",\n\t\tsql: `\n\t\t\tALTER TABLE kiosk_terminals ADD COLUMN session_hash TEXT;\n\t\t\tALTER TABLE kiosk_terminals ADD COLUMN session_expires_at INTEGER;\n\t\t`,\n\t},\n\t{\n\t\tversion: 8,\n\t\tname: \"defaults: time zone Europe/Zurich becomes Europe/Berlin\",\n\t\tsql: `\n\t\t\t-- The default time zone of the adapter is Europe/Berlin now. Migration 1 is append-only, so a new\n\t\t\t-- database already gets the new default with it; existing installations are adjusted here: every\n\t\t\t-- employee and every instance setting that still carries the old default is moved over. Values that\n\t\t\t-- were chosen deliberately keep their name \u2014 they only change when they are exactly the old default.\n\t\t\tUPDATE users SET timezone = 'Europe/Berlin' WHERE timezone = 'Europe/Zurich';\n\t\t\tUPDATE app_settings SET value = 'Europe/Berlin' WHERE key = 'timezone' AND value = 'Europe/Zurich';\n\t\t`,\n\t},\n\t{\n\t\tversion: 9,\n\t\tname: \"users: picture of the employee\",\n\t\tsql: `ALTER TABLE users ADD COLUMN avatar TEXT;`,\n\t},\n\t{\n\t\tversion: 10,\n\t\tname: \"drops the leftovers of the removed data import\",\n\t\trun: (db: Db): void => {\n\t\t\t// The adapter does not read data of another time tracking system any more, so the columns that existed\n\t\t\t// for it are dropped. Fresh databases never create them (migrations 1, 2 and 5 are clean), so every\n\t\t\t// step asks first: an upgraded database loses the columns, a fresh one has nothing to do.\n\t\t\tif (hasColumn(db, \"users\", \"legacy_sha1\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE users DROP COLUMN legacy_sha1\");\n\t\t\t}\n\t\t\tif (hasColumn(db, \"work_profiles\", \"legacy_source\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE work_profiles DROP COLUMN legacy_source\");\n\t\t\t}\n\n\t\t\t// rfid_tags carried the printed card number of that system as a second identifier. SQLite cannot drop\n\t\t\t// a column that a CHECK constraint mentions, so the table is rebuilt without it; existing rows keep\n\t\t\t// their id, their uid and their token hash, and the unique index on the uid is recreated.\n\t\t\tif (!hasColumn(db, \"rfid_tags\", \"legacy_code\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tdb.exec(`\n\t\t\t\tCREATE TABLE rfid_tags_new (\n\t\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\t\tuid TEXT,\n\t\t\t\t\ttoken_hash TEXT NOT NULL,\n\t\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE SET NULL,\n\t\t\t\t\tlabel TEXT,\n\t\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\t\texpires_at INTEGER,\n\t\t\t\t\tlast_used_at INTEGER,\n\t\t\t\t\tcreated_at INTEGER NOT NULL\n\t\t\t\t);\n\t\t\t\tINSERT INTO rfid_tags_new (id, uid, token_hash, user_id, label, is_active, expires_at, last_used_at, created_at)\n\t\t\t\t\tSELECT id, uid, token_hash, user_id, label, is_active, expires_at, last_used_at, created_at\n\t\t\t\t\tFROM rfid_tags;\n\t\t\t\tDROP TABLE rfid_tags;\n\t\t\t\tALTER TABLE rfid_tags_new RENAME TO rfid_tags;\n\t\t\t\tCREATE UNIQUE INDEX idx_rfid_uid ON rfid_tags(uid) WHERE uid IS NOT NULL;\n\t\t\t`);\n\t\t},\n\t},\n\t{\n\t\tversion: 11,\n\t\tname: \"terminals: the employees of a terminal\",\n\t\tsql: `\n\t\t\t-- A terminal stands at one place \u2014 an office, a workshop \u2014 and is meant for the employees that work\n\t\t\t-- there. No row for a terminal means \"all employees\", so terminals that existed before keep working\n\t\t\t-- exactly as they did.\n\t\t\tCREATE TABLE terminal_users (\n\t\t\t\tterminal_id INTEGER NOT NULL REFERENCES kiosk_terminals(id) ON DELETE CASCADE,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tPRIMARY KEY (terminal_id, user_id)\n\t\t\t);\n\t\t\tCREATE INDEX idx_terminal_users_user ON terminal_users(user_id);\n\t\t`,\n\t},\n\t{\n\t\tversion: 12,\n\t\tname: \"work profiles: paid breaks\",\n\t\tsql: `ALTER TABLE work_profiles ADD COLUMN pause_paid INTEGER NOT NULL DEFAULT 0;`,\n\t},\n\t{\n\t\tversion: 13,\n\t\tname: \"work profiles: paid break minutes instead of the paid flag\",\n\t\trun: (db: Db): void => {\n\t\t\t// The flag became an amount: a company may pay a quarter of an hour and nothing more. A profile that had\n\t\t\t// the flag set keeps a fully paid break (a day has 1440 minutes), a fresh profile pays nothing at all.\n\t\t\tif (!hasColumn(db, \"work_profiles\", \"pause_paid_minutes\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE work_profiles ADD COLUMN pause_paid_minutes INTEGER NOT NULL DEFAULT 0\");\n\t\t\t}\n\t\t\tif (hasColumn(db, \"work_profiles\", \"pause_paid\")) {\n\t\t\t\tdb.exec(\"UPDATE work_profiles SET pause_paid_minutes = 1440 WHERE pause_paid = 1\");\n\t\t\t\tdb.exec(\"ALTER TABLE work_profiles DROP COLUMN pause_paid\");\n\t\t\t}\n\t\t},\n\t},\n\t{\n\t\tversion: 14,\n\t\tname: \"day aggregates: paid break minutes\",\n\t\tsql: `ALTER TABLE day_aggregates ADD COLUMN paid_break_min INTEGER NOT NULL DEFAULT 0;`,\n\t},\n\t{\n\t\tversion: 15,\n\t\tname: \"trigger rules: ioBroker states that punch or set the presence\",\n\t\tsql: `\n\t\t\t-- A rule watches a state of another adapter (a fingerprint reader, a button, a door contact) and turns a\n\t\t\t-- write on it into a punch or a presence change. Mode \"condition\" fires when the value matches\n\t\t\t-- \"condition\" and punches for \"user_id\"; mode \"user\" posts the employee the value names. \"last_fired_at\"\n\t\t\t-- keeps a chatty reader in check together with \"cooldown_sec\".\n\t\t\tCREATE TABLE trigger_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlabel TEXT,\n\t\t\t\tsource_state TEXT NOT NULL,\n\t\t\t\tmode TEXT NOT NULL DEFAULT 'condition'\n\t\t\t\t\tCHECK (mode IN ('condition','user')),\n\t\t\t\tcondition TEXT,\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\taction TEXT NOT NULL DEFAULT 'punch'\n\t\t\t\t\tCHECK (action IN ('punch','quickPunch','present','absent')),\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tcooldown_sec INTEGER NOT NULL DEFAULT 0,\n\t\t\t\tlast_fired_at INTEGER,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX idx_trigger_rules_source ON trigger_rules(source_state);\n\t\t`,\n\t},\n\t{\n\t\tversion: 16,\n\t\tname: \"automation rules: what the adapter does on its own (clock out, reminders)\",\n\t\tsql: `\n\t\t\t-- A rule of the adapter itself, not of a foreign state: at a certain local time (clockOut, missingPunch)\n\t\t\t-- or after a while without a break (breakReminder) the adapter acts. \"user_id\" is NULL for every\n\t\t\t-- employee, so a company rule and a rule for one person can live side by side.\n\t\t\tCREATE TABLE automation_rules (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlabel TEXT,\n\t\t\t\tkind TEXT NOT NULL\n\t\t\t\t\tCHECK (kind IN ('clockOut','missingPunch','breakReminder')),\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tat_minute INTEGER,\n\t\t\t\tafter_minutes INTEGER,\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tCREATE INDEX idx_automation_rules_kind ON automation_rules(kind);\n\n\t\t\t-- What a rule already did: one row per rule, employee and local date keeps it at \"once a day\" and doubles\n\t\t\t-- as the log the administration shows. A punch that is already written is never written twice.\n\t\t\tCREATE TABLE automation_runs (\n\t\t\t\trule_id INTEGER NOT NULL REFERENCES automation_rules(id) ON DELETE CASCADE,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tlocal_date TEXT NOT NULL,\n\t\t\t\tfired_at INTEGER NOT NULL,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (rule_id, user_id, local_date)\n\t\t\t);\n\t\t\tCREATE INDEX idx_automation_runs_user ON automation_runs(user_id, local_date);\n\t\t`,\n\t},\n\t{\n\t\tversion: 17,\n\t\tname: \"automation rules: weekdays and a weekly instead of a daily guard\",\n\t\tsql: `\n\t\t\t-- A rule can be limited to certain weekdays: bit 0 is Monday \u2026 bit 6 is Sunday, 127 is every day.\n\t\t\tALTER TABLE automation_rules ADD COLUMN weekdays INTEGER NOT NULL DEFAULT 127;\n\n\t\t\t-- 'day' keeps the guard of one run per employee and date, 'week' allows one run per ISO week.\n\t\t\tALTER TABLE automation_rules ADD COLUMN repeat TEXT NOT NULL DEFAULT 'day';\n\n\t\t\t-- the guard column no longer holds a date only: for a weekly rule it is the ISO week (2026-W38), so the\n\t\t\t-- name says what it keeps. Existing rows stay valid \u2014 a date is the period of a daily rule.\n\t\t\tALTER TABLE automation_runs RENAME COLUMN local_date TO period;\n\t\t`,\n\t},\n\t{\n\t\tversion: 18,\n\t\tname: \"automation rules: the kind clockIn (punch in somebody who is missing)\",\n\t\tsql: `\n\t\t\t-- A fourth kind joins the rules: 'clockIn' punches an employee in who is still missing at the configured\n\t\t\t-- time (the decision makes sure nobody is clocked in already). SQLite cannot change a CHECK constraint in\n\t\t\t-- place, so the table is rebuilt \u2014 and because automation_runs belongs to it with ON DELETE CASCADE, the\n\t\t\t-- run log is copied first: dropping the parent would take it with it.\n\t\t\tCREATE TABLE automation_runs_copy (\n\t\t\t\trule_id INTEGER NOT NULL,\n\t\t\t\tuser_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tperiod TEXT NOT NULL,\n\t\t\t\tfired_at INTEGER NOT NULL,\n\t\t\t\taction TEXT NOT NULL,\n\t\t\t\tPRIMARY KEY (rule_id, user_id, period)\n\t\t\t);\n\t\t\tINSERT INTO automation_runs_copy (rule_id, user_id, period, fired_at, action)\n\t\t\t\tSELECT rule_id, user_id, period, fired_at, action FROM automation_runs;\n\n\t\t\tCREATE TABLE automation_rules_new (\n\t\t\t\tid INTEGER PRIMARY KEY AUTOINCREMENT,\n\t\t\t\tlabel TEXT,\n\t\t\t\tkind TEXT NOT NULL\n\t\t\t\t\tCHECK (kind IN ('clockIn','clockOut','missingPunch','breakReminder')),\n\t\t\t\tuser_id INTEGER REFERENCES users(id) ON DELETE CASCADE,\n\t\t\t\tat_minute INTEGER,\n\t\t\t\tafter_minutes INTEGER,\n\t\t\t\tweekdays INTEGER NOT NULL DEFAULT 127,\n\t\t\t\trepeat TEXT NOT NULL DEFAULT 'day',\n\t\t\t\tis_active INTEGER NOT NULL DEFAULT 1,\n\t\t\t\tcreated_at INTEGER NOT NULL,\n\t\t\t\tupdated_at INTEGER NOT NULL\n\t\t\t);\n\t\t\tINSERT INTO automation_rules_new\n\t\t\t\t(id, label, kind, user_id, at_minute, after_minutes, weekdays, repeat, is_active, created_at, updated_at)\n\t\t\t\tSELECT id, label, kind, user_id, at_minute, after_minutes, weekdays, repeat, is_active, created_at, updated_at\n\t\t\t\tFROM automation_rules;\n\n\t\t\tDROP TABLE automation_runs;\n\t\t\tDROP TABLE automation_rules;\n\t\t\tALTER TABLE automation_rules_new RENAME TO automation_rules;\n\t\t\t-- the runs keep their user reference; the reference to the rule is kept by the repository, which deletes\n\t\t\t-- the runs of a rule together with it\n\t\t\tALTER TABLE automation_runs_copy RENAME TO automation_runs;\n\n\t\t\tCREATE INDEX idx_automation_rules_kind ON automation_rules(kind);\n\t\t\tCREATE INDEX idx_automation_runs_user ON automation_runs(user_id, period);\n\t\t`,\n\t},\n\t{\n\t\tversion: 19,\n\t\tname: \"holidays: a stable key next to the name, so the app can translate the seeded days\",\n\t\tsql: `\n\t\t\t-- The seeded holidays carry an English name. The key says which day it is, so the web app shows it in the\n\t\t\t-- language of the display; a day somebody added by hand has no key and keeps its own name.\n\t\t\tALTER TABLE holidays ADD COLUMN key TEXT;\n\n\t\t\t-- the days that are already stored get their key from the date\n\t\t\tUPDATE holidays SET key = 'newYear' WHERE key IS NULL AND date LIKE '%-01-01';\n\t\t\tUPDATE holidays SET key = 'epiphany' WHERE key IS NULL AND date LIKE '%-01-06';\n\t\t\tUPDATE holidays SET key = 'labourDay' WHERE key IS NULL AND date LIKE '%-05-01';\n\t\t\tUPDATE holidays SET key = 'nationalDay' WHERE key IS NULL AND (date LIKE '%-08-01' OR date LIKE '%-10-26');\n\t\t\tUPDATE holidays SET key = 'assumption' WHERE key IS NULL AND date LIKE '%-08-15';\n\t\t\tUPDATE holidays SET key = 'germanUnity' WHERE key IS NULL AND date LIKE '%-10-03';\n\t\t\tUPDATE holidays SET key = 'allSaints' WHERE key IS NULL AND date LIKE '%-11-01';\n\t\t\tUPDATE holidays SET key = 'immaculateConception' WHERE key IS NULL AND date LIKE '%-12-08';\n\t\t\tUPDATE holidays SET key = 'christmas' WHERE key IS NULL AND date LIKE '%-12-25';\n\t\t\tUPDATE holidays SET key = 'boxingDay' WHERE key IS NULL AND date LIKE '%-12-26';\n\t\t\t-- the movable feasts carry their English name, which is unique enough to find them again\n\t\t\tUPDATE holidays SET key = 'goodFriday' WHERE key IS NULL AND name = 'Good Friday';\n\t\t\tUPDATE holidays SET key = 'easterMonday' WHERE key IS NULL AND name = 'Easter Monday';\n\t\t\tUPDATE holidays SET key = 'ascension' WHERE key IS NULL AND name = 'Ascension Day';\n\t\t\tUPDATE holidays SET key = 'whitMonday' WHERE key IS NULL AND name = 'Whit Monday';\n\t\t\tUPDATE holidays SET key = 'corpusChristi' WHERE key IS NULL AND name = 'Corpus Christi';\n\t\t`,\n\t},\n\t{\n\t\tversion: 20,\n\t\tname: \"work profiles: whether the presence card shows the working time of the day\",\n\t\tsql: `\n\t\t\t-- The presence screen is visible before the PIN is entered, so showing the worked time of an employee\n\t\t\t-- is a decision of the administration, per employee. Off by default.\n\t\t\tALTER TABLE work_profiles ADD COLUMN show_worked_time INTEGER NOT NULL DEFAULT 0;\n\t\t`,\n\t},\n];\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAwCO,SAAS,UAAU,IAAQ,OAAe,QAAyB;AACzE,QAAM,OAAO,GAAG,QAAQ,qBAAqB,KAAK,GAAG,EAAE,IAAI;AAC3D,SAAO,KAAK,KAAK,SAAO,IAAI,SAAS,MAAM;AAC5C;AAEO,MAAM,aAA0B;AAAA,EACtC;AAAA,IACC,SAAS;AAAA,IACT,MAAM;AAAA,IACN,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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MAAM;AAAA,IACN,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA6CN;AAAA,EACA;AAAA,IACC,SAAS;AAAA,IACT,MAAM;AAAA,IACN,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuBN;AAAA,EACA;AAAA,IACC,SAAS;AAAA,IACT,MAAM;AAAA,IACN,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,EAKN;AACD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -84,13 +84,15 @@ function mapWorkProfileRow(row) {
|
|
|
84
84
|
vacationPerYear: row.vacation_per_year,
|
|
85
85
|
overtimeModel: row.overtime_model,
|
|
86
86
|
holidayFlags: row.holiday_flags,
|
|
87
|
-
pausePaidMinutes: row.pause_paid_minutes
|
|
87
|
+
pausePaidMinutes: row.pause_paid_minutes,
|
|
88
|
+
showWorkedTime: row.show_worked_time !== 0
|
|
88
89
|
};
|
|
89
90
|
}
|
|
90
91
|
const USER_COLUMNS = `id, login, password_hash, display_name, email, rfid_card, is_active,
|
|
91
92
|
must_change_pw, locale, timezone, pin_hash, avatar, created_at, updated_at, last_login_at`;
|
|
92
93
|
const PROFILE_COLUMNS = `user_id, percent, weekly_hours, workdays, start_date, end_date, overtime_carryover,
|
|
93
|
-
vorholzeit_per_year, vacation_carryover, vacation_per_year, overtime_model, holiday_flags, pause_paid_minutes
|
|
94
|
+
vorholzeit_per_year, vacation_carryover, vacation_per_year, overtime_model, holiday_flags, pause_paid_minutes,
|
|
95
|
+
show_worked_time`;
|
|
94
96
|
const AUDITED_USER_FIELDS = [
|
|
95
97
|
"login",
|
|
96
98
|
"displayName",
|
|
@@ -113,7 +115,8 @@ const AUDITED_PROFILE_FIELDS = [
|
|
|
113
115
|
"vacationPerYear",
|
|
114
116
|
"overtimeModel",
|
|
115
117
|
"holidayFlags",
|
|
116
|
-
"pausePaidMinutes"
|
|
118
|
+
"pausePaidMinutes",
|
|
119
|
+
"showWorkedTime"
|
|
117
120
|
];
|
|
118
121
|
function createUsersRepository(db) {
|
|
119
122
|
const selectById = db.prepare(`SELECT ${USER_COLUMNS} FROM users WHERE id = ?`);
|
|
@@ -141,7 +144,7 @@ function createUsersRepository(db) {
|
|
|
141
144
|
const selectProfile = db.prepare(`SELECT ${PROFILE_COLUMNS} FROM work_profiles WHERE user_id = ?`);
|
|
142
145
|
const upsertProfile = db.prepare(
|
|
143
146
|
`INSERT INTO work_profiles (${PROFILE_COLUMNS})
|
|
144
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
147
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
145
148
|
ON CONFLICT(user_id) DO UPDATE SET
|
|
146
149
|
percent = excluded.percent,
|
|
147
150
|
weekly_hours = excluded.weekly_hours,
|
|
@@ -154,7 +157,8 @@ function createUsersRepository(db) {
|
|
|
154
157
|
vacation_per_year = excluded.vacation_per_year,
|
|
155
158
|
overtime_model = excluded.overtime_model,
|
|
156
159
|
holiday_flags = excluded.holiday_flags,
|
|
157
|
-
pause_paid_minutes = excluded.pause_paid_minutes
|
|
160
|
+
pause_paid_minutes = excluded.pause_paid_minutes,
|
|
161
|
+
show_worked_time = excluded.show_worked_time`
|
|
158
162
|
);
|
|
159
163
|
const selectRoles = db.prepare(
|
|
160
164
|
`SELECT r.key FROM user_roles ur JOIN roles r ON r.id = ur.role_id WHERE ur.user_id = ? ORDER BY r.key`
|
|
@@ -196,7 +200,8 @@ function createUsersRepository(db) {
|
|
|
196
200
|
vacationPerYear: 0,
|
|
197
201
|
overtimeModel: "monthly",
|
|
198
202
|
holidayFlags: null,
|
|
199
|
-
pausePaidMinutes: 0
|
|
203
|
+
pausePaidMinutes: 0,
|
|
204
|
+
showWorkedTime: false
|
|
200
205
|
});
|
|
201
206
|
const resolveRoleIds = (roleKeys) => roleKeys.map((key) => {
|
|
202
207
|
const row = selectRoleId.get(key);
|
|
@@ -456,7 +461,8 @@ function createUsersRepository(db) {
|
|
|
456
461
|
next.vacationPerYear,
|
|
457
462
|
next.overtimeModel,
|
|
458
463
|
next.holidayFlags,
|
|
459
|
-
next.pausePaidMinutes
|
|
464
|
+
next.pausePaidMinutes,
|
|
465
|
+
next.showWorkedTime ? 1 : 0
|
|
460
466
|
);
|
|
461
467
|
(0, import_audit.writeAuditLog)(db, {
|
|
462
468
|
atUtc: now,
|