iobroker.time-tracker 0.3.4 → 0.4.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 +8 -9
- package/build/lib/adapter/messages.js +3 -1
- package/build/lib/adapter/messages.js.map +2 -2
- package/build/lib/db/migrations.js +21 -0
- package/build/lib/db/migrations.js.map +2 -2
- package/build/lib/db/repositories/absences.js +80 -7
- package/build/lib/db/repositories/absences.js.map +2 -2
- package/build/lib/services/aggregation.js +3 -2
- package/build/lib/services/aggregation.js.map +2 -2
- package/build/lib/web/api.js +49 -3
- package/build/lib/web/api.js.map +2 -2
- package/io-package.json +14 -14
- package/package.json +1 -1
- package/src-pwa/src/i18n/de.json +26 -1
- package/src-pwa/src/i18n/en.json +26 -1
- package/src-pwa/src/i18n/es.json +26 -1
- package/src-pwa/src/i18n/fr.json +26 -1
- package/src-pwa/src/i18n/it.json +26 -1
- package/src-pwa/src/i18n/nl.json +26 -1
- package/src-pwa/src/i18n/pl.json +26 -1
- package/src-pwa/src/i18n/pt.json +26 -1
- package/src-pwa/src/i18n/ru.json +26 -1
- package/src-pwa/src/i18n/uk.json +26 -1
- package/src-pwa/src/i18n/zh-cn.json +26 -1
- package/www/assets/{index-BvnH1yBe.js → index-dp7TWY3R.js} +7 -7
- package/www/assets/index-dp7TWY3R.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-BvnH1yBe.js.map +0 -1
package/README.md
CHANGED
|
@@ -355,6 +355,14 @@ local SQLite file, access is role-based, and every correction is written to an a
|
|
|
355
355
|
|
|
356
356
|
### **WORK IN PROGRESS**
|
|
357
357
|
|
|
358
|
+
### 0.4.0 (2026-09-22)
|
|
359
|
+
|
|
360
|
+
- (Alex) new: the administration decides about absences. A request of an employee waits as `requested` and counts for
|
|
361
|
+
nothing until somebody approves or rejects it — the new tab **Abwesenheiten** shows the open requests (with a reason
|
|
362
|
+
for the decision), lets the administration enter dates for an employee (approved right away) and answers “who is
|
|
363
|
+
away”. Only approved days reach the working time and the vacation balance, the state of a request is marked in the
|
|
364
|
+
app and a rejection carries its reason back (migration 21, `POST /absences/:id/approval`)
|
|
365
|
+
|
|
358
366
|
### 0.3.4 (2026-09-22)
|
|
359
367
|
|
|
360
368
|
- (Alex) feat: the absence types can be maintained in the admin now — one row per type and the form in a dialog, with
|
|
@@ -386,15 +394,6 @@ local SQLite file, access is role-based, and every correction is written to an a
|
|
|
386
394
|
and the board refreshes every 20 s (was 60 s). The API test moves the clock ten minutes and expects the open punch
|
|
387
395
|
in the answer
|
|
388
396
|
|
|
389
|
-
### 0.3.0 (2026-09-22)
|
|
390
|
-
|
|
391
|
-
- (Alex) new: the presence board can show the working time of today on the employee tiles — `1:23` next to
|
|
392
|
-
`Present`/`Away` (`0:00` before the first punch), and the tile keeps counting while the employee is present. It is
|
|
393
|
-
switched on **per employee** in the work profile (*Arbeitszeit auf der Anwesenheitskarte*, off by default), because
|
|
394
|
-
the board is visible before the PIN is entered — the decision is made on the server, the API only sends the minutes
|
|
395
|
-
for employees who agreed (`/terminal/users` and `/terminal/punch`). The new column
|
|
396
|
-
`work_profiles.show_worked_time` arrives with migration 20
|
|
397
|
-
|
|
398
397
|
Older entries are kept in [`CHANGELOG_OLD.md`](CHANGELOG_OLD.md).
|
|
399
398
|
|
|
400
399
|
## Provenance
|
|
@@ -21,6 +21,7 @@ __export(messages_exports, {
|
|
|
21
21
|
handleMessage: () => handleMessage
|
|
22
22
|
});
|
|
23
23
|
module.exports = __toCommonJS(messages_exports);
|
|
24
|
+
var import_absences = require("../db/repositories/absences");
|
|
24
25
|
var import_errors = require("../errors");
|
|
25
26
|
var import_pdf = require("../reports/pdf");
|
|
26
27
|
var import_labels = require("../reports/labels");
|
|
@@ -96,7 +97,8 @@ function statementInput(deps, user, year, month) {
|
|
|
96
97
|
year,
|
|
97
98
|
month,
|
|
98
99
|
days: deps.aggregation.days(user.id, first, last),
|
|
99
|
-
absences:
|
|
100
|
+
// only effective absences are listed: a request still waits for its decision, a rejected one never counts
|
|
101
|
+
absences: deps.absences.withTypesInRange(user.id, first, last).filter(import_absences.isApproved).map((absence) => ({
|
|
100
102
|
typeCode: absence.typeCode,
|
|
101
103
|
typeName: absence.typeName,
|
|
102
104
|
dateFrom: absence.dateFrom,
|
|
@@ -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 {\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;
|
|
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 { isApproved } 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\t// only effective absences are listed: a request still waits for its decision, a rejected one never counts\n\t\tabsences: deps.absences\n\t\t\t.withTypesInRange(user.id, first, last)\n\t\t\t.filter(isApproved)\n\t\t\t.map(absence => ({\n\t\t\t\ttypeCode: absence.typeCode,\n\t\t\t\ttypeName: absence.typeName,\n\t\t\t\tdateFrom: absence.dateFrom,\n\t\t\t\tdateTo: absence.dateTo,\n\t\t\t\tdayPortion: absence.dayPortion,\n\t\t\t\thours: absence.hours,\n\t\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;AAmBA,sBAA2B;AAO3B,oBAAgC;AAChC,iBAAoC;AACpC,oBAA6B;AAC7B,mBAAiD;AACjD,iBAAiC;AACjC,kBAA0B;AAC1B,sBAA8B;AAC9B,sBAA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AE,GAAG,OAAO,WAAU,UAAK,SAAS,IAAI,kBAAkB,MAApC,YAAyC,GAAG,CAAC,IAC7F,UAAM,6BAAiB,KAAK;AAChC,UAAM,eAAW,6BAAe,KAAK,OAAO,MAAM,OAAO,WAAW,QAAQ,QAAQ,MAAM;AAE1F,WAAO;AAAA,MACN,IAAI;AAAA,MACJ,SAAS,GAAG,QAAQ,KAAK,KAAK,MAAM;AAAA,MACpC,MAAM;AAAA,QACL,QAAQ,KAAK;AAAA,QACb;AAAA,QACA,UACC,WAAW,QACR,oBACA;AAAA,QACJ,OAAO,KAAK;AAAA,QACZ,QAAQ,KAAK,SAAS,QAAQ;AAAA,MAC/B;AAAA,IACD;AAAA,EACD;AAEA,MAAI,YAAY,UAAU;AACzB,QAAI,CAAC,KAAK,QAAQ;AACjB,YAAM,IAAI,8BAAgB,qCAAqC;AAAA,IAChE;AACA,UAAM,UAAU,KAAK,OAAO,OAAO,EAAE,SAAS,GAAG,QAAQ,SAAS,CAAC;AACnE,WAAO;AAAA,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
|
}
|
|
@@ -602,6 +602,27 @@ const migrations = [
|
|
|
602
602
|
-- is a decision of the administration, per employee. Off by default.
|
|
603
603
|
ALTER TABLE work_profiles ADD COLUMN show_worked_time INTEGER NOT NULL DEFAULT 0;
|
|
604
604
|
`
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
version: 21,
|
|
608
|
+
name: "absences: approval by the administration (requested, approved, rejected)",
|
|
609
|
+
run: (db) => {
|
|
610
|
+
if (!hasColumn(db, "absences", "approval")) {
|
|
611
|
+
db.exec(
|
|
612
|
+
"ALTER TABLE absences ADD COLUMN approval TEXT NOT NULL DEFAULT 'approved' CHECK (approval IN ('requested','approved','rejected'))"
|
|
613
|
+
);
|
|
614
|
+
}
|
|
615
|
+
if (!hasColumn(db, "absences", "decided_at")) {
|
|
616
|
+
db.exec("ALTER TABLE absences ADD COLUMN decided_at INTEGER");
|
|
617
|
+
}
|
|
618
|
+
if (!hasColumn(db, "absences", "decided_by")) {
|
|
619
|
+
db.exec("ALTER TABLE absences ADD COLUMN decided_by INTEGER REFERENCES users(id) ON DELETE SET NULL");
|
|
620
|
+
}
|
|
621
|
+
if (!hasColumn(db, "absences", "decision_note")) {
|
|
622
|
+
db.exec("ALTER TABLE absences ADD COLUMN decision_note TEXT");
|
|
623
|
+
}
|
|
624
|
+
db.exec("CREATE INDEX IF NOT EXISTS idx_absences_approval ON absences(approval, date_from)");
|
|
625
|
+
}
|
|
605
626
|
}
|
|
606
627
|
];
|
|
607
628
|
// 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\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 AD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AAA;AAAA;AAAA,EAuBN;AAAA,EACA;AAAA,IACC,SAAS;AAAA,IACT,MAAM;AAAA,IACN,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,EAKN;AACD;",
|
|
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\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\t{\n\t\tversion: 21,\n\t\tname: \"absences: approval by the administration (requested, approved, rejected)\",\n\t\trun: (db: Db): void => {\n\t\t\t// An employee requests, the administration decides. `approval` is separate from `status`, which keeps\n\t\t\t// saying whether the days are planned or already taken: a request can be planned and still wait for\n\t\t\t// its decision. Everything that exists before this migration counts as approved, so no figure changes\n\t\t\t// for a running installation; a request of an employee starts as `requested`.\n\t\t\tif (!hasColumn(db, \"absences\", \"approval\")) {\n\t\t\t\tdb.exec(\n\t\t\t\t\t\"ALTER TABLE absences ADD COLUMN approval TEXT NOT NULL DEFAULT 'approved' \" +\n\t\t\t\t\t\t\"CHECK (approval IN ('requested','approved','rejected'))\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Who decided when and why \u2014 a rejection without a reason is not much use to the employee.\n\t\t\tif (!hasColumn(db, \"absences\", \"decided_at\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE absences ADD COLUMN decided_at INTEGER\");\n\t\t\t}\n\t\t\tif (!hasColumn(db, \"absences\", \"decided_by\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE absences ADD COLUMN decided_by INTEGER REFERENCES users(id) ON DELETE SET NULL\");\n\t\t\t}\n\t\t\tif (!hasColumn(db, \"absences\", \"decision_note\")) {\n\t\t\t\tdb.exec(\"ALTER TABLE absences ADD COLUMN decision_note TEXT\");\n\t\t\t}\n\t\t\t// The administration looks at the open requests first, so they get an index of their own.\n\t\t\tdb.exec(\"CREATE INDEX IF NOT EXISTS idx_absences_approval ON absences(approval, date_from)\");\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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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;AAAA,EACA;AAAA,IACC,SAAS;AAAA,IACT,MAAM;AAAA,IACN,KAAK,CAAC,OAAiB;AAKtB,UAAI,CAAC,UAAU,IAAI,YAAY,UAAU,GAAG;AAC3C,WAAG;AAAA,UACF;AAAA,QAED;AAAA,MACD;AAEA,UAAI,CAAC,UAAU,IAAI,YAAY,YAAY,GAAG;AAC7C,WAAG,KAAK,oDAAoD;AAAA,MAC7D;AACA,UAAI,CAAC,UAAU,IAAI,YAAY,YAAY,GAAG;AAC7C,WAAG,KAAK,4FAA4F;AAAA,MACrG;AACA,UAAI,CAAC,UAAU,IAAI,YAAY,eAAe,GAAG;AAChD,WAAG,KAAK,oDAAoD;AAAA,MAC7D;AAEA,SAAG,KAAK,mFAAmF;AAAA,IAC5F;AAAA,EACD;AACD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -20,6 +20,7 @@ var absences_exports = {};
|
|
|
20
20
|
__export(absences_exports, {
|
|
21
21
|
UnknownAbsenceTypeError: () => UnknownAbsenceTypeError,
|
|
22
22
|
createAbsencesRepository: () => createAbsencesRepository,
|
|
23
|
+
isApproved: () => isApproved,
|
|
23
24
|
mapAbsenceRow: () => mapAbsenceRow,
|
|
24
25
|
mapAbsenceTypeRow: () => mapAbsenceTypeRow
|
|
25
26
|
});
|
|
@@ -27,6 +28,9 @@ module.exports = __toCommonJS(absences_exports);
|
|
|
27
28
|
var import_time = require("../../util/time");
|
|
28
29
|
var import_errors = require("../../errors");
|
|
29
30
|
var import_audit = require("./audit");
|
|
31
|
+
function isApproved(absence) {
|
|
32
|
+
return absence.approval !== "requested" && absence.approval !== "rejected";
|
|
33
|
+
}
|
|
30
34
|
class UnknownAbsenceTypeError extends Error {
|
|
31
35
|
/**
|
|
32
36
|
* Creates the error.
|
|
@@ -40,7 +44,7 @@ class UnknownAbsenceTypeError extends Error {
|
|
|
40
44
|
}
|
|
41
45
|
}
|
|
42
46
|
const TYPE_COLUMNS = "id, user_id, code, name, paid, factor, reduce_vacation, is_active";
|
|
43
|
-
const ABSENCE_COLUMNS = `id, user_id, type_id, date_from, date_to, day_portion, hours, status, note,
|
|
47
|
+
const ABSENCE_COLUMNS = `id, user_id, type_id, date_from, date_to, day_portion, hours, status, approval, decided_at, decided_by, decision_note, note,
|
|
44
48
|
created_at, created_by`;
|
|
45
49
|
const AUDITED_FIELDS = ["typeId", "dateFrom", "dateTo", "dayPortion", "hours", "note"];
|
|
46
50
|
function mapAbsenceTypeRow(row) {
|
|
@@ -65,6 +69,10 @@ function mapAbsenceRow(row) {
|
|
|
65
69
|
dayPortion: row.day_portion,
|
|
66
70
|
hours: row.hours,
|
|
67
71
|
status: row.status,
|
|
72
|
+
approval: row.approval,
|
|
73
|
+
decidedAt: row.decided_at,
|
|
74
|
+
decidedBy: row.decided_by,
|
|
75
|
+
decisionNote: row.decision_note,
|
|
68
76
|
note: row.note,
|
|
69
77
|
createdAt: row.created_at,
|
|
70
78
|
createdBy: row.created_by
|
|
@@ -96,24 +104,37 @@ function createAbsencesRepository(db) {
|
|
|
96
104
|
ORDER BY date_from, date_to, id`
|
|
97
105
|
);
|
|
98
106
|
const selectWithTypes = db.prepare(
|
|
99
|
-
`SELECT a.id, a.user_id, a.type_id, a.date_from, a.date_to, a.day_portion, a.hours, a.status, a.
|
|
100
|
-
a.created_at, a.created_by,
|
|
107
|
+
`SELECT a.id, a.user_id, a.type_id, a.date_from, a.date_to, a.day_portion, a.hours, a.status, a.approval,
|
|
108
|
+
a.decided_at, a.decided_by, a.decision_note, a.note, a.created_at, a.created_by,
|
|
101
109
|
t.code AS type_code, t.name AS type_name, t.paid AS type_paid, t.factor AS type_factor,
|
|
102
110
|
t.reduce_vacation AS type_reduce_vacation
|
|
103
111
|
FROM absences a JOIN absence_types t ON t.id = a.type_id
|
|
104
112
|
WHERE a.user_id = ? AND a.date_to >= ? AND a.date_from <= ?
|
|
105
113
|
ORDER BY a.date_from, a.date_to, a.id`
|
|
106
114
|
);
|
|
115
|
+
const selectAllWithTypes = db.prepare(
|
|
116
|
+
`SELECT a.id, a.user_id, a.type_id, a.date_from, a.date_to, a.day_portion, a.hours, a.status, a.approval,
|
|
117
|
+
a.decided_at, a.decided_by, a.decision_note, a.note, a.created_at, a.created_by,
|
|
118
|
+
t.code AS type_code, t.name AS type_name, t.paid AS type_paid, t.factor AS type_factor,
|
|
119
|
+
t.reduce_vacation AS type_reduce_vacation
|
|
120
|
+
FROM absences a JOIN absence_types t ON t.id = a.type_id
|
|
121
|
+
WHERE a.date_to >= ? AND a.date_from <= ?
|
|
122
|
+
ORDER BY a.date_from, a.date_to, a.user_id, a.id`
|
|
123
|
+
);
|
|
107
124
|
const insertAbsence = db.prepare(
|
|
108
125
|
`INSERT INTO absences
|
|
109
|
-
(user_id, type_id, date_from, date_to, day_portion, hours, status,
|
|
110
|
-
|
|
126
|
+
(user_id, type_id, date_from, date_to, day_portion, hours, status, approval, decided_at, decided_by,
|
|
127
|
+
decision_note, note, created_at, created_by)
|
|
128
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
111
129
|
);
|
|
112
130
|
const updateAbsence = db.prepare(
|
|
113
131
|
`UPDATE absences SET type_id = ?, date_from = ?, date_to = ?, day_portion = ?, hours = ?, note = ?
|
|
114
132
|
WHERE id = ?`
|
|
115
133
|
);
|
|
116
134
|
const updateStatusStatement = db.prepare("UPDATE absences SET status = ? WHERE id = ?");
|
|
135
|
+
const updateApprovalStatement = db.prepare(
|
|
136
|
+
"UPDATE absences SET approval = ?, decided_at = ?, decided_by = ?, decision_note = ? WHERE id = ?"
|
|
137
|
+
);
|
|
117
138
|
const deleteAbsence = db.prepare("DELETE FROM absences WHERE id = ?");
|
|
118
139
|
const insertType = db.prepare(
|
|
119
140
|
`INSERT INTO absence_types (user_id, code, name, paid, factor, reduce_vacation, is_active)
|
|
@@ -229,7 +250,7 @@ function createAbsencesRepository(db) {
|
|
|
229
250
|
},
|
|
230
251
|
findById: read,
|
|
231
252
|
create(input) {
|
|
232
|
-
var _a, _b, _c, _d;
|
|
253
|
+
var _a, _b, _c, _d, _e;
|
|
233
254
|
const type = requireType(input);
|
|
234
255
|
const dateFrom = requireDate(input.dateFrom, "dateFrom");
|
|
235
256
|
const dateTo = requireDate((_a = input.dateTo) != null ? _a : dateFrom, "dateTo");
|
|
@@ -238,7 +259,10 @@ function createAbsencesRepository(db) {
|
|
|
238
259
|
}
|
|
239
260
|
const dayPortion = requireDayPortion((_b = input.dayPortion) != null ? _b : 1);
|
|
240
261
|
const status = (_c = input.status) != null ? _c : "planned";
|
|
241
|
-
const
|
|
262
|
+
const approval = (_d = input.approval) != null ? _d : "approved";
|
|
263
|
+
const now = (_e = input.now) != null ? _e : Math.floor(Date.now() / 1e3);
|
|
264
|
+
const decidedAt = approval === "requested" ? null : now;
|
|
265
|
+
const decidedBy = approval === "requested" ? null : input.actorId;
|
|
242
266
|
let absenceId = 0;
|
|
243
267
|
const run = db.transaction(() => {
|
|
244
268
|
var _a2, _b2, _c2;
|
|
@@ -250,6 +274,10 @@ function createAbsencesRepository(db) {
|
|
|
250
274
|
dayPortion,
|
|
251
275
|
(_a2 = input.hours) != null ? _a2 : null,
|
|
252
276
|
status,
|
|
277
|
+
approval,
|
|
278
|
+
decidedAt,
|
|
279
|
+
decidedBy,
|
|
280
|
+
null,
|
|
253
281
|
(_b2 = input.note) != null ? _b2 : null,
|
|
254
282
|
now,
|
|
255
283
|
input.actorId
|
|
@@ -365,6 +393,36 @@ function createAbsencesRepository(db) {
|
|
|
365
393
|
}
|
|
366
394
|
return updated;
|
|
367
395
|
},
|
|
396
|
+
setApproval(input) {
|
|
397
|
+
var _a;
|
|
398
|
+
const current = read(input.id);
|
|
399
|
+
if (!current) {
|
|
400
|
+
throw new import_errors.NotFoundError(`absence ${input.id} not found`);
|
|
401
|
+
}
|
|
402
|
+
const now = (_a = input.now) != null ? _a : Math.floor(Date.now() / 1e3);
|
|
403
|
+
const run = db.transaction(() => {
|
|
404
|
+
var _a2, _b;
|
|
405
|
+
updateApprovalStatement.run(input.approval, now, input.actorId, (_a2 = input.note) != null ? _a2 : null, input.id);
|
|
406
|
+
(0, import_audit.writeAuditLog)(db, {
|
|
407
|
+
atUtc: now,
|
|
408
|
+
actorId: input.actorId,
|
|
409
|
+
action: "absence.approval",
|
|
410
|
+
entity: "absence",
|
|
411
|
+
entityId: input.id,
|
|
412
|
+
detail: {
|
|
413
|
+
changes: { approval: { old: current.approval, new: input.approval } },
|
|
414
|
+
...input.note ? { note: input.note } : {}
|
|
415
|
+
},
|
|
416
|
+
ip: (_b = input.actorIp) != null ? _b : null
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
run();
|
|
420
|
+
const updated = read(input.id);
|
|
421
|
+
if (!updated) {
|
|
422
|
+
throw new Error(`absence ${input.id} disappeared right after the decision`);
|
|
423
|
+
}
|
|
424
|
+
return updated;
|
|
425
|
+
},
|
|
368
426
|
remove(input) {
|
|
369
427
|
var _a;
|
|
370
428
|
const current = read(input.id);
|
|
@@ -419,6 +477,20 @@ function createAbsencesRepository(db) {
|
|
|
419
477
|
factor: row.type_factor,
|
|
420
478
|
reduceVacation: row.type_reduce_vacation !== 0
|
|
421
479
|
}));
|
|
480
|
+
},
|
|
481
|
+
allInRange(from, to) {
|
|
482
|
+
const rows = selectAllWithTypes.all(
|
|
483
|
+
requireDate(from, "from"),
|
|
484
|
+
requireDate(to, "to")
|
|
485
|
+
);
|
|
486
|
+
return rows.map((row) => ({
|
|
487
|
+
...mapAbsenceRow(row),
|
|
488
|
+
typeCode: row.type_code,
|
|
489
|
+
typeName: row.type_name,
|
|
490
|
+
paid: row.type_paid !== 0,
|
|
491
|
+
factor: row.type_factor,
|
|
492
|
+
reduceVacation: row.type_reduce_vacation !== 0
|
|
493
|
+
}));
|
|
422
494
|
}
|
|
423
495
|
};
|
|
424
496
|
}
|
|
@@ -426,6 +498,7 @@ function createAbsencesRepository(db) {
|
|
|
426
498
|
0 && (module.exports = {
|
|
427
499
|
UnknownAbsenceTypeError,
|
|
428
500
|
createAbsencesRepository,
|
|
501
|
+
isApproved,
|
|
429
502
|
mapAbsenceRow,
|
|
430
503
|
mapAbsenceTypeRow
|
|
431
504
|
});
|