feat(time): add span-based attendance tracking under 2.0
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { TimeService } from "./time-v2/service";
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import bcrypt from 'bcrypt';
|
||||
import crypto from 'crypto';
|
||||
@@ -200,6 +201,14 @@ export const publicLinkService = {
|
||||
},
|
||||
|
||||
async submitFormData(server: FastifyInstance, token: string, payload: any, providedPin?: string) {
|
||||
return server.db.transaction(async tx => {
|
||||
const scoped = Object.create(server);
|
||||
scoped.db = tx;
|
||||
return publicLinkService.submitFormDataTransaction(scoped, token, payload, providedPin);
|
||||
});
|
||||
},
|
||||
|
||||
async submitFormDataTransaction(server: FastifyInstance, token: string, payload: any, providedPin?: string) {
|
||||
// 1. Validierung (Token & PIN)
|
||||
const linkConfig = await server.db.query.publicLinks.findFirst({
|
||||
where: eq(schema.publicLinks.token, token)
|
||||
@@ -223,7 +232,7 @@ export const publicLinkService = {
|
||||
|
||||
// Profil laden, um die user_id zu bekommen
|
||||
const authProfile = await server.db.query.authProfiles.findFirst({
|
||||
where: eq(schema.authProfiles.id, rawProfileId)
|
||||
where: and(eq(schema.authProfiles.id, rawProfileId), eq(schema.authProfiles.tenant_id, tenantId))
|
||||
});
|
||||
|
||||
if (!authProfile) throw new Error("Profile_Not_Found");
|
||||
@@ -245,7 +254,7 @@ export const publicLinkService = {
|
||||
// SCHRITT A: Stammdaten laden
|
||||
// =================================================================
|
||||
const project = await server.db.query.projects.findFirst({
|
||||
where: eq(schema.projects.id, payload.project)
|
||||
where: and(eq(schema.projects.id, payload.project), eq(schema.projects.tenant, tenantId))
|
||||
});
|
||||
if (!project) throw new Error("Project not found");
|
||||
|
||||
@@ -351,29 +360,42 @@ export const publicLinkService = {
|
||||
generatedDocumentId: createdDoc.id
|
||||
};
|
||||
|
||||
// 1. START EVENT
|
||||
await server.db.insert(schema.stafftimeevents).values({
|
||||
tenant_id: tenantId,
|
||||
user_id: userId, // WICHTIG: User ID
|
||||
actortype: "user",
|
||||
actoruser_id: userId, // WICHTIG: User ID
|
||||
eventtime: startDate,
|
||||
eventtype: "START",
|
||||
source: "PUBLIC_LINK",
|
||||
metadata: eventMetadata // WICHTIG: Schema heißt 'metadata', nicht 'payload'
|
||||
});
|
||||
const timeService = new TimeService(server.db);
|
||||
const actor = { tenant: tenantId, user: userId, trusted: true };
|
||||
await timeService.lock(server.db, actor, userId);
|
||||
if (await timeService.active(actor, userId)) {
|
||||
await timeService.mutate(actor, userId, `public-link:${createdDoc.id}`, {
|
||||
action: 'create', data: {
|
||||
type: 'work', started_at: startDate.toISOString(), ended_at: endDate.toISOString(),
|
||||
description: eventMetadata.description, breaks: [],
|
||||
projects: [{ project_id: project.id, started_at: startDate.toISOString(), ended_at: endDate.toISOString(), notes: eventMetadata.description }],
|
||||
},
|
||||
}, 'public_link');
|
||||
} else {
|
||||
// 1. START EVENT
|
||||
await server.db.insert(schema.stafftimeevents).values({
|
||||
tenant_id: tenantId,
|
||||
user_id: userId, // WICHTIG: User ID
|
||||
actortype: "user",
|
||||
actoruser_id: userId, // WICHTIG: User ID
|
||||
eventtime: startDate,
|
||||
eventtype: "START",
|
||||
source: "PUBLIC_LINK",
|
||||
metadata: eventMetadata // WICHTIG: Schema heißt 'metadata', nicht 'payload'
|
||||
});
|
||||
|
||||
// 2. STOP EVENT
|
||||
await server.db.insert(schema.stafftimeevents).values({
|
||||
tenant_id: tenantId,
|
||||
user_id: userId,
|
||||
actortype: "user",
|
||||
actoruser_id: userId,
|
||||
eventtime: endDate,
|
||||
eventtype: "STOP",
|
||||
source: "PUBLIC_LINK",
|
||||
metadata: eventMetadata
|
||||
});
|
||||
// 2. STOP EVENT
|
||||
await server.db.insert(schema.stafftimeevents).values({
|
||||
tenant_id: tenantId,
|
||||
user_id: userId,
|
||||
actortype: "user",
|
||||
actoruser_id: userId,
|
||||
eventtime: endDate,
|
||||
eventtype: "STOP",
|
||||
source: "PUBLIC_LINK",
|
||||
metadata: eventMetadata
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// =================================================================
|
||||
|
||||
108
backend/src/modules/time-v2/compatibility.ts
Normal file
108
backend/src/modules/time-v2/compatibility.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { FastifyInstance } from 'fastify';
|
||||
import { Actor, authorize, digest, rows, TimeService } from './service';
|
||||
import { fail, Span } from './domain';
|
||||
import { timeActor, uuid } from '../../routes/staff/time-v2';
|
||||
/** Existing consumers still receive work segments with pauses excluded, backed by a stable span ID. */
|
||||
export function legacySpans(spans: Span[]) {
|
||||
return spans.flatMap(s => {
|
||||
const base = { id: s.id, version: s.version, sourceEventIds: [s.id], status: s.status, user_id: s.user_id, description: s.description, payload: { description: s.description }, model: 'spans-v2', attendance: s };
|
||||
if (s.type !== 'work')
|
||||
return [{ ...base, type: s.type, startedAt: s.started_at, endedAt: s.ended_at }];
|
||||
const result: any[] = [];
|
||||
let start = s.started_at;
|
||||
for (const p of s.breaks) {
|
||||
if (Date.parse(start) < Date.parse(p.started_at))
|
||||
result.push({ ...base, type: 'work', startedAt: start, endedAt: p.started_at });
|
||||
result.push({ ...base, type: 'pause', startedAt: p.started_at, endedAt: p.ended_at });
|
||||
if (!p.ended_at)
|
||||
return result;
|
||||
start = p.ended_at;
|
||||
}
|
||||
if (!s.ended_at || Date.parse(start) < Date.parse(s.ended_at))
|
||||
result.push({ ...base, type: 'work', startedAt: start, endedAt: s.ended_at });
|
||||
return result;
|
||||
});
|
||||
}
|
||||
export async function legacyEvent(service: TimeService, a: Actor, user: string, body: any, requestId?: string, source = 'legacy') {
|
||||
authorize(a, user, 'write');
|
||||
const key = `legacy:${digest({ body, requestId, actor: a.user, source })}`;
|
||||
const [cached] = await rows(service.db, sql `SELECT response FROM staff_time_v2_requests WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid AND request_id=${key}`);
|
||||
if (cached)
|
||||
return cached.response;
|
||||
const at = body.eventtime, type = body.eventtype;
|
||||
const command: any = { at };
|
||||
const active = await service.current({ ...a, trusted: true }, user);
|
||||
if (type === 'work_start')
|
||||
Object.assign(command, { action: 'start', description: body.payload?.description });
|
||||
else if (['work_end', 'auto_stop', 'pause_start', 'pause_end'].includes(type)) {
|
||||
if (!active)
|
||||
fail('Keine laufende Anwesenheit.', 409);
|
||||
Object.assign(command, { action: type === 'pause_start' ? 'pause' : type === 'pause_end' ? 'resume' : 'stop', id: active.id, version: active.version });
|
||||
}
|
||||
else if (/^(vacation|sick|overtime_compensation|holiday|other)_start$/.test(type)) {
|
||||
Object.assign(command, { action: 'create', data: { type: type.slice(0, -6), started_at: at, ended_at: null, description: body.payload?.description || '' } });
|
||||
}
|
||||
else if (/^(vacation|sick|overtime_compensation|holiday|other)_end$/.test(type)) {
|
||||
if (!active || active.type !== type.slice(0, -4))
|
||||
fail('Kein passender laufender Eintrag.', 409);
|
||||
Object.assign(command, { action: 'update', id: active.id, version: active.version, reason: 'Abschluss über bestehende Erfassung', data: { ...active, ended_at: at } });
|
||||
}
|
||||
else
|
||||
fail('Unbekannter Ereignistyp.');
|
||||
// For clients without IDs, the exact event payload is the stable key. Resolve retries before constructing a changed version.
|
||||
return service.mutate(a, user, key, command, source);
|
||||
}
|
||||
export function installTimeCompatibility(server: FastifyInstance, internal = false) {
|
||||
const service = new TimeService(server.db);
|
||||
server.addHook('preHandler', async (req, reply) => {
|
||||
try {
|
||||
const path = req.url.split('?')[0], b = (req.body || {}) as any, q = req.query as any;
|
||||
const operation = path.split('/').pop()!;
|
||||
const a: Actor = internal ? { ...timeActor(req), trusted: true } : timeActor(req);
|
||||
// Internal keys remain bound to their authenticated tenant and user context.
|
||||
if (internal && ((b.tenant_id && Number(b.tenant_id) !== a.tenant) || (q.tenantId && Number(q.tenantId) !== a.tenant)))
|
||||
fail('Falscher Mandant.', 403);
|
||||
let user = uuid(b.user_id || b.employeeUserId || q.targetUserId || a.user);
|
||||
const ids = b.eventIds || b.originalEventIds;
|
||||
if (Array.isArray(ids) && ids.length) {
|
||||
const [owner] = await rows(server.db, sql `SELECT user_id FROM staff_time_spans WHERE tenant_id=${a.tenant} AND id=${uuid(ids[0])}::uuid`);
|
||||
if (owner)
|
||||
user = owner.user_id;
|
||||
}
|
||||
authorize(a, user, ['approve', 'reject'].includes(operation) ? 'approve' : req.method === 'GET' ? 'read' : 'write');
|
||||
if (!await service.active(a, user))
|
||||
return;
|
||||
if (operation === 'spans') {
|
||||
const spans = await service.list(a, user, q.from, q.to);
|
||||
const current = await service.current(a, user);
|
||||
if (current && !spans.some(s => s.id === current.id)) spans.push(current);
|
||||
return reply.send(legacySpans(spans));
|
||||
}
|
||||
if (operation === 'evaluation') {
|
||||
const result = await service.evaluation(a, user, q.from, q.to);
|
||||
return reply.send({ ...result, spans: legacySpans(result.spans) });
|
||||
}
|
||||
if (operation === 'event')
|
||||
return reply.send(await legacyEvent(service, a, user, b, req.headers['idempotency-key'] as string, internal ? 'terminal' : 'legacy'));
|
||||
if (operation === 'edit')
|
||||
fail('Dieser Eintrag wird unter 2.0 → Zeiterfassung einschließlich seiner Pausen bearbeitet.', 409);
|
||||
if (['submit', 'approve', 'reject'].includes(operation)) {
|
||||
if (!Array.isArray(ids) || ids.length !== 1)
|
||||
fail('Bitte vollständige Anwesenheiten einzeln unter 2.0 bearbeiten.', 409);
|
||||
const before = await service.get(a, uuid(ids[0]));
|
||||
if (before.status === ({ submit: 'submitted', approve: 'approved', reject: 'rejected' } as any)[operation])
|
||||
return reply.send(before);
|
||||
const result = await service.mutate(a, user, req.headers['idempotency-key'] as string || randomUUID(), {
|
||||
action: operation, id: before.id, version: before.version, reason: b.reason,
|
||||
}, 'legacy');
|
||||
return reply.send(result);
|
||||
}
|
||||
}
|
||||
catch (error: any) {
|
||||
req.log.error(error);
|
||||
return reply.code(error.statusCode || 400).send({ error: error.statusCode ? error.message : 'Zeitaktion konnte nicht verarbeitet werden.' });
|
||||
}
|
||||
});
|
||||
}
|
||||
167
backend/src/modules/time-v2/domain.ts
Normal file
167
backend/src/modules/time-v2/domain.ts
Normal file
@@ -0,0 +1,167 @@
|
||||
import dayjs from 'dayjs';
|
||||
import utc from 'dayjs/plugin/utc';
|
||||
import timezone from 'dayjs/plugin/timezone';
|
||||
dayjs.extend(utc);
|
||||
dayjs.extend(timezone);
|
||||
export const TYPES = ['work', 'vacation', 'sick', 'overtime_compensation', 'holiday', 'other'] as const;
|
||||
export type TimeType = typeof TYPES[number];
|
||||
export type Period = {
|
||||
started_at: string;
|
||||
ended_at: string | null;
|
||||
};
|
||||
export type Span = Period & {
|
||||
id?: string;
|
||||
user_id?: string;
|
||||
type: TimeType;
|
||||
description: string;
|
||||
status: string;
|
||||
version?: number;
|
||||
date_from?: string | null;
|
||||
date_to?: string | null;
|
||||
timezone: string;
|
||||
breaks: Period[];
|
||||
projects: (Period & {
|
||||
project_id: number;
|
||||
notes: string;
|
||||
})[];
|
||||
};
|
||||
export class TimeError extends Error {
|
||||
constructor(public statusCode: number, message: string) { super(message); }
|
||||
}
|
||||
export const fail = (message: string, status = 400): never => { throw new TimeError(status, message); };
|
||||
export function instant(value: unknown): string {
|
||||
if (typeof value !== 'string' || !/T.*(?:Z|[+-]\d\d:\d\d)$/.test(value) || !Number.isFinite(Date.parse(value)))
|
||||
fail('Zeitpunkt mit Zeitzone erforderlich.');
|
||||
dateOnly((value as string).slice(0, 10));
|
||||
return new Date(value as string).toISOString();
|
||||
}
|
||||
export function dateOnly(value: unknown): string {
|
||||
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(Date.parse(value)) || new Date(value).toISOString().slice(0, 10) !== value)
|
||||
fail('Ungültiges Datum.');
|
||||
return value as string;
|
||||
}
|
||||
export function midnight(date: string, zone = 'Europe/Berlin') { return dayjs.tz(dateOnly(date), zone).toISOString(); }
|
||||
export function nextDay(date: string) { return dayjs.utc(dateOnly(date)).add(1, 'day').format('YYYY-MM-DD'); }
|
||||
export function range(from: string, to: string, zone = 'Europe/Berlin') {
|
||||
dateOnly(from);
|
||||
dateOnly(to);
|
||||
if (from > to || dayjs.utc(to).diff(dayjs.utc(from), 'day') > 3660)
|
||||
fail('Zeitraum muss zwischen 1 und 3661 Tagen liegen.');
|
||||
return { started_at: midnight(from, zone), ended_at: midnight(nextDay(to), zone) };
|
||||
}
|
||||
const end = (p: Period) => p.ended_at ? Date.parse(p.ended_at) : Infinity;
|
||||
export const overlaps = (a: Period, b: Period) => Date.parse(a.started_at) < end(b) && Date.parse(b.started_at) < end(a);
|
||||
export const minutes = (p: Period, window: Period) => Math.max(0, Math.min(end(p), end(window)) - Math.max(Date.parse(p.started_at), Date.parse(window.started_at))) / 60000;
|
||||
export function normalizeSpan(input: any): Span {
|
||||
if (!input || !TYPES.includes(input.type))
|
||||
fail('Ungültige Zeitart.');
|
||||
const zone = input.timezone || 'Europe/Berlin';
|
||||
try {
|
||||
new Intl.DateTimeFormat('de', { timeZone: zone });
|
||||
}
|
||||
catch {
|
||||
fail('Ungültige Zeitzone.');
|
||||
}
|
||||
const allDay = input.date_from != null || input.date_to != null;
|
||||
const span: Span = {
|
||||
type: input.type, description: String(input.description || '').slice(0, 10000), timezone: zone,
|
||||
started_at: allDay ? midnight(input.date_from, zone) : instant(input.started_at),
|
||||
ended_at: allDay ? midnight(input.date_to, zone) : input.ended_at == null ? null : instant(input.ended_at),
|
||||
date_from: allDay ? dateOnly(input.date_from) : null, date_to: allDay ? dateOnly(input.date_to) : null,
|
||||
status: 'factual', breaks: [], projects: [],
|
||||
};
|
||||
if (allDay && (span.type === 'work' || span.date_to! <= span.date_from!))
|
||||
fail('Ungültiger ganztägiger Zeitraum; Ende ist exklusiv.');
|
||||
if (span.ended_at && end(span) <= Date.parse(span.started_at))
|
||||
fail('Ende muss nach Beginn liegen.');
|
||||
if (!Array.isArray(input.breaks || []) || !Array.isArray(input.projects || []))
|
||||
fail('Ungültige Teilzeiträume.');
|
||||
span.breaks = (input.breaks || []).map((p: any) => ({ started_at: instant(p.started_at), ended_at: p.ended_at == null ? null : instant(p.ended_at) }));
|
||||
span.projects = (input.projects || []).map((p: any) => {
|
||||
if (!Number.isSafeInteger(Number(p.project_id)) || Number(p.project_id) <= 0)
|
||||
fail('Projekt erforderlich.');
|
||||
return { started_at: instant(p.started_at), ended_at: instant(p.ended_at), project_id: Number(p.project_id), notes: String(p.notes || '').slice(0, 10000) };
|
||||
});
|
||||
if (span.type !== 'work' && (span.breaks.length || span.projects.length))
|
||||
fail('Pausen und Projekte benötigen eine Anwesenheit.');
|
||||
for (const parts of [span.breaks, span.projects]) {
|
||||
if (parts.length > 200)
|
||||
fail('Zu viele Teilzeiträume.');
|
||||
parts.sort((a, b) => Date.parse(a.started_at) - Date.parse(b.started_at));
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const p = parts[i];
|
||||
if (end(p) <= Date.parse(p.started_at) || Date.parse(p.started_at) < Date.parse(span.started_at) || end(p) > end(span))
|
||||
fail('Teilzeitraum muss innerhalb der Anwesenheit liegen.');
|
||||
if (i && overlaps(parts[i - 1], p))
|
||||
fail('Teilzeiträume dürfen sich nicht überschneiden.');
|
||||
}
|
||||
}
|
||||
for (const project of span.projects)
|
||||
if (span.breaks.some(p => overlaps(p, project)))
|
||||
fail('Projektzeit darf keine Pause enthalten.');
|
||||
return span;
|
||||
}
|
||||
export function transition(span: Span, action: string, reason = '') {
|
||||
if (!span.ended_at)
|
||||
fail('Laufende Einträge zuerst beenden.', 409);
|
||||
if (action === 'submit' && ['factual', 'rejected'].includes(span.status))
|
||||
return 'submitted';
|
||||
if (action === 'approve' && span.status === 'submitted')
|
||||
return 'approved';
|
||||
if (action === 'reject' && span.status === 'submitted' && reason.trim())
|
||||
return 'rejected';
|
||||
fail('Ungültiger Statuswechsel oder fehlender Ablehnungsgrund.', 409);
|
||||
}
|
||||
export function evaluate(spans: Span[], profile: any, holidayDates: string[], from: string, to: string, zone = 'Europe/Berlin') {
|
||||
const window = range(from, to, zone);
|
||||
const sum = { timeSpanWorkingMinutes: 0, sumWorkingMinutesSubmitted: 0, sumWorkingMinutesApproved: 0,
|
||||
sumWorkingMinutesRecreationDays: 0, sumRecreationDays: 0, sumWorkingMinutesVacationDays: 0, sumVacationDays: 0,
|
||||
sumWorkingMinutesSickDays: 0, sumSickDays: 0, sumOvertimeCompensationMinutes: 0, sumOtherMinutes: 0,
|
||||
presenceMinutes: 0, breakMinutes: 0, saldoApproved: 0, saldoSubmitted: 0 };
|
||||
for (const s of spans.filter(s => s.type === 'work' && s.ended_at)) {
|
||||
const gross = minutes(s, window), breaks = s.breaks.reduce((n, p) => n + minutes(p, window), 0), net = gross - breaks;
|
||||
sum.presenceMinutes += gross;
|
||||
sum.breakMinutes += breaks;
|
||||
if (['submitted', 'approved'].includes(s.status))
|
||||
sum.sumWorkingMinutesSubmitted += net;
|
||||
if (s.status === 'approved')
|
||||
sum.sumWorkingMinutesApproved += net;
|
||||
}
|
||||
const holidays = new Set(holidayDates);
|
||||
for (let date = from; date <= to; date = nextDay(date)) {
|
||||
const day = range(date, date, zone), weekday = dayjs.utc(date).day();
|
||||
const target = Math.max(0, Number(profile.weekly_regular_working_hours?.[weekday] || 0)) * 60;
|
||||
sum.timeSpanWorkingMinutes += target;
|
||||
// Credits are capped per day; holidays take precedence over overlapping absence credits.
|
||||
let remaining = target;
|
||||
const approved = spans.filter(s => s.type !== 'work' && s.status === 'approved' && s.ended_at && overlaps(s, day));
|
||||
if ((profile.recreation_days_compensation && holidays.has(date)) || approved.some(s => s.type === 'holiday')) {
|
||||
sum.sumWorkingMinutesRecreationDays += target;
|
||||
sum.sumRecreationDays += target > 0 ? 1 : 0;
|
||||
remaining = 0;
|
||||
}
|
||||
for (const type of ['vacation', 'sick', 'overtime_compensation', 'other']) {
|
||||
for (const s of approved.filter(s => s.type === type)) {
|
||||
const credit = Math.min(remaining, s.date_from ? target : minutes(s, day));
|
||||
if (type === 'vacation') {
|
||||
sum.sumWorkingMinutesVacationDays += credit;
|
||||
sum.sumVacationDays += target ? credit / target : 0;
|
||||
}
|
||||
if (type === 'sick') {
|
||||
sum.sumWorkingMinutesSickDays += credit;
|
||||
sum.sumSickDays += target ? credit / target : 0;
|
||||
}
|
||||
// Freizeitausgleich consumes the balance through the regular daily target, without a credit.
|
||||
if (type === 'overtime_compensation')
|
||||
sum.sumOvertimeCompensationMinutes += credit;
|
||||
if (type === 'other')
|
||||
sum.sumOtherMinutes += credit;
|
||||
remaining -= credit;
|
||||
}
|
||||
}
|
||||
}
|
||||
const credit = sum.sumWorkingMinutesRecreationDays + sum.sumWorkingMinutesVacationDays + sum.sumWorkingMinutesSickDays;
|
||||
sum.saldoApproved = sum.sumWorkingMinutesApproved + credit - sum.timeSpanWorkingMinutes;
|
||||
sum.saldoSubmitted = sum.sumWorkingMinutesSubmitted + credit - sum.timeSpanWorkingMinutes;
|
||||
return sum;
|
||||
}
|
||||
146
backend/src/modules/time-v2/migration.ts
Normal file
146
backend/src/modules/time-v2/migration.ts
Normal file
@@ -0,0 +1,146 @@
|
||||
import { sql } from 'drizzle-orm';
|
||||
import { Actor, authorize, digest, rows, TimeService } from './service';
|
||||
import { fail, normalizeSpan, overlaps, Span } from './domain';
|
||||
type Candidate = {
|
||||
span: Span;
|
||||
origins: {
|
||||
kind: string;
|
||||
id: string;
|
||||
}[];
|
||||
};
|
||||
/** Conservative replay: never invent missing ends or silently discard ambiguous points. */
|
||||
export function previewLegacy(events: any[], entries: any[], connects: any[]) {
|
||||
const issues: string[] = [], candidates: Candidate[] = [];
|
||||
const invalidated = new Set(events.map(e => e.invalidates_event_id).filter(Boolean));
|
||||
const valid = events.filter(e => !invalidated.has(e.id) && e.eventtype !== 'invalidated');
|
||||
const states = new Map<string, string>();
|
||||
for (const e of [...valid].sort((a, b) => String(a.created_at).localeCompare(String(b.created_at)) || a.id.localeCompare(b.id))) {
|
||||
if (['submitted', 'approved', 'rejected'].includes(e.eventtype) && e.related_event_id)
|
||||
states.set(e.related_event_id, e.eventtype);
|
||||
}
|
||||
const points = valid.filter(e => !['submitted', 'approved', 'rejected'].includes(e.eventtype))
|
||||
.sort((a, b) => Date.parse(a.eventtime) - Date.parse(b.eventtime) || String(a.created_at).localeCompare(String(b.created_at)) || a.id.localeCompare(b.id));
|
||||
let current: any = null, origins: Candidate['origins'] = [];
|
||||
const close = () => {
|
||||
if (!current)
|
||||
return;
|
||||
const statusSet = new Set(origins.map(o => states.get(o.id) || 'factual'));
|
||||
if (statusSet.size > 1)
|
||||
issues.push(`Uneinheitliche Freigaben ab ${current.started_at}; vor Übernahme vereinheitlichen.`);
|
||||
current.status = statusSet.size === 1 ? [...statusSet][0] : 'factual';
|
||||
if (!current.ended_at)
|
||||
issues.push(`Offener Alt-Eintrag ab ${current.started_at}; zuerst abschließen.`);
|
||||
try {
|
||||
const normalized = normalizeSpan(current);
|
||||
normalized.status = current.status;
|
||||
candidates.push({ span: normalized, origins: [...origins] });
|
||||
}
|
||||
catch (e: any) {
|
||||
issues.push(`${current.started_at}: ${e.message}`);
|
||||
}
|
||||
current = null;
|
||||
origins = [];
|
||||
};
|
||||
for (const e of points) {
|
||||
const type = e.eventtype === 'START' ? 'work_start' : e.eventtype === 'STOP' || e.eventtype === 'auto_stop' ? 'work_end' : e.eventtype;
|
||||
const time = new Date(e.eventtime).toISOString();
|
||||
if (type === 'pause_start' || type === 'pause_end') {
|
||||
if (!current || current.type !== 'work') {
|
||||
issues.push(`Pause ohne Anwesenheit: ${e.id}`);
|
||||
continue;
|
||||
}
|
||||
const open = current.breaks.find((p: any) => !p.ended_at);
|
||||
if (type === 'pause_start' && !open)
|
||||
current.breaks.push({ started_at: time, ended_at: null });
|
||||
else if (type === 'pause_end' && open)
|
||||
open.ended_at = time;
|
||||
else
|
||||
issues.push(`Widersprüchliche Pause: ${e.id}`);
|
||||
origins.push({ kind: 'event', id: e.id });
|
||||
continue;
|
||||
}
|
||||
if (type.endsWith('_start')) {
|
||||
if (current) {
|
||||
issues.push(`Neuer Beginn vor vorherigem Ende: ${e.id}`);
|
||||
close();
|
||||
}
|
||||
current = { type: type.slice(0, -6), started_at: time, ended_at: null, description: e.metadata?.description || e.payload?.description || '', breaks: [], projects: [], timezone: 'Europe/Berlin' };
|
||||
origins = [{ kind: 'event', id: e.id }];
|
||||
if (e.metadata?.project)
|
||||
current.projects.push({ project_id: Number(e.metadata.project), started_at: time, ended_at: null, notes: current.description });
|
||||
}
|
||||
else if (type.endsWith('_end')) {
|
||||
if (!current || current.type !== type.slice(0, -4)) {
|
||||
issues.push(`Ende ohne passenden Beginn: ${e.id}`);
|
||||
continue;
|
||||
}
|
||||
current.ended_at = time;
|
||||
for (const p of current.breaks)
|
||||
if (!p.ended_at)
|
||||
p.ended_at = time;
|
||||
for (const p of current.projects)
|
||||
p.ended_at = time;
|
||||
origins.push({ kind: 'event', id: e.id });
|
||||
close();
|
||||
}
|
||||
else
|
||||
issues.push(`Unbekanntes Ereignis ${e.eventtype}: ${e.id}`);
|
||||
}
|
||||
close();
|
||||
for (const e of entries.filter(e => !e.archived)) {
|
||||
try {
|
||||
const span = normalizeSpan({ ...e, ended_at: e.stopped_at, timezone: 'Europe/Berlin', breaks: [], projects: connects.filter(c => c.time_entry_id === e.id).map(c => ({ ...c, ended_at: c.stopped_at })) });
|
||||
span.status = e.state === 'draft' ? 'factual' : e.state;
|
||||
if (!span.ended_at)
|
||||
issues.push(`Offener Alt-Eintrag ${e.id}; zuerst abschließen.`);
|
||||
candidates.push({ span, origins: [{ kind: 'entry', id: e.id }] });
|
||||
}
|
||||
catch (err: any) {
|
||||
issues.push(`Alt-Eintrag ${e.id}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
candidates.sort((a, b) => Date.parse(a.span.started_at) - Date.parse(b.span.started_at));
|
||||
for (let i = 1; i < candidates.length; i++)
|
||||
if (overlaps(candidates[i - 1].span, candidates[i].span))
|
||||
issues.push(`Überlappende Alt-Einträge ab ${candidates[i].span.started_at}.`);
|
||||
const totalMinutes = candidates.reduce((n, { span: s }) => n + (s.type === 'work' && s.ended_at ? (Date.parse(s.ended_at) - Date.parse(s.started_at) - s.breaks.reduce((v, p) => v + (p.ended_at ? Date.parse(p.ended_at) - Date.parse(p.started_at) : 0), 0)) / 60000 : 0), 0);
|
||||
return { candidates, issues, totalMinutes, count: candidates.length, fingerprint: digest({ events, entries, connects }) };
|
||||
}
|
||||
export class TimeMigration {
|
||||
constructor(public service: TimeService) { }
|
||||
async preview(a: Actor, user: string, db = this.service.db) {
|
||||
authorize(a, user, 'activate');
|
||||
const events = await rows(db, sql `SELECT * FROM staff_time_events WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid ORDER BY event_time,id`);
|
||||
// Raw SQL column names differ from the historical Drizzle property names.
|
||||
const mapped = events.map(e => ({ ...e, eventtype: e.event_type, eventtime: e.event_time }));
|
||||
const entries = await rows(db, sql `SELECT * FROM staff_time_entries WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid ORDER BY started_at,id`);
|
||||
const connects = await rows(db, sql `SELECT c.* FROM staff_time_entry_connects c JOIN staff_time_entries e ON e.id=c.time_entry_id WHERE e.tenant_id=${a.tenant} AND e.user_id=${user}::uuid ORDER BY c.started_at,c.id`);
|
||||
const result = previewLegacy(mapped, entries, connects);
|
||||
for (const { span } of result.candidates)
|
||||
for (const project of span.projects) {
|
||||
if (!(await rows(db, sql `SELECT id FROM projects WHERE id=${project.project_id} AND tenant=${a.tenant}`)).length)
|
||||
result.issues.push(`Projekt ${project.project_id} fehlt im Mandanten.`);
|
||||
}
|
||||
return { ...result, active: await this.service.active(a, user, db) };
|
||||
}
|
||||
async activate(a: Actor, user: string, fingerprint: string) {
|
||||
authorize(a, user, 'activate');
|
||||
return this.service.db.transaction(async (tx: any) => {
|
||||
await this.service.lock(tx, a, user);
|
||||
if (await this.service.active(a, user, tx))
|
||||
return { active: true, alreadyActivated: true };
|
||||
const preview = await this.preview(a, user, tx);
|
||||
if (preview.fingerprint !== fingerprint)
|
||||
fail('Altdaten wurden geändert. Vorschau erneut laden.', 409);
|
||||
if (preview.issues.length)
|
||||
fail('Altdaten enthalten Konflikte. Vor Aktivierung korrigieren.', 409);
|
||||
for (const c of preview.candidates) {
|
||||
const created = await this.service.save(tx, a, user, c.span, null, 'migration', 'Übernahme aus bisheriger Zeiterfassung', 'migration');
|
||||
for (const origin of c.origins)
|
||||
await tx.execute(sql `INSERT INTO staff_time_span_origins(tenant_id,source_kind,source_id,span_id) VALUES(${a.tenant},${origin.kind},${origin.id}::uuid,${created.id}::uuid)`);
|
||||
}
|
||||
await tx.execute(sql `INSERT INTO staff_time_v2_accounts(tenant_id,user_id,activated_by) VALUES(${a.tenant},${user}::uuid,${a.user}::uuid)`);
|
||||
return { active: true, count: preview.count, totalMinutes: preview.totalMinutes };
|
||||
});
|
||||
}
|
||||
}
|
||||
189
backend/src/modules/time-v2/service.ts
Normal file
189
backend/src/modules/time-v2/service.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { sql, SQL } from 'drizzle-orm';
|
||||
import { fail, normalizeSpan, transition, range, evaluate, Span, instant, overlaps } from './domain';
|
||||
export type Actor = {
|
||||
tenant: number;
|
||||
user: string;
|
||||
admin?: boolean;
|
||||
permissions?: string[];
|
||||
trusted?: boolean;
|
||||
};
|
||||
export const can = (a: Actor, permission: string) => Boolean(a.admin || a.trusted || a.permissions?.includes(permission));
|
||||
export function authorize(a: Actor, user: string, operation = 'read') {
|
||||
if (!a.tenant || !a.user || !user)
|
||||
fail('Anmeldung und Mandant erforderlich.', 403);
|
||||
if (operation === 'approve' || operation === 'activate') {
|
||||
if (!can(a, `staff.time.${operation}`))
|
||||
fail('Keine Berechtigung für diese Aktion.', 403);
|
||||
}
|
||||
else if (user !== a.user && !can(a, `staff.time.${operation}_all`) && !(operation === 'read' && ['write_all', 'approve', 'activate'].some(p => can(a, `staff.time.${p}`))))
|
||||
fail('Keine Berechtigung für fremde Zeiten.', 403);
|
||||
}
|
||||
export async function rows(db: any, query: SQL): Promise<any[]> {
|
||||
const result = await db.execute(query);
|
||||
const normalize = (value: any, key = ''): any => {
|
||||
if (value instanceof Date)
|
||||
return value.toISOString();
|
||||
if (Array.isArray(value))
|
||||
return value.map(v => normalize(v));
|
||||
if (value && typeof value === 'object')
|
||||
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalize(v, k)]));
|
||||
if (typeof value === 'string' && (key.endsWith('_at') || key === 'event_time') && /^\d{4}-\d{2}-\d{2}[ T]/.test(value))
|
||||
return new Date(value).toISOString();
|
||||
return value;
|
||||
};
|
||||
return normalize(result.rows);
|
||||
}
|
||||
export const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
export class TimeService {
|
||||
constructor(public db: any) { }
|
||||
async lock(tx: any, a: Actor, user: string) {
|
||||
await tx.execute(sql `SELECT pg_advisory_xact_lock(hashtextextended(${`staff-time:${a.tenant}:${user}`},0))`);
|
||||
const member = await rows(tx, sql `SELECT user_id FROM auth_profiles WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid LIMIT 1`);
|
||||
if (!member.length)
|
||||
fail('Mitarbeiter im Mandanten nicht gefunden.', 404);
|
||||
}
|
||||
async active(a: Actor, user: string, db = this.db) {
|
||||
return (await rows(db, sql `SELECT * FROM staff_time_v2_accounts WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid`))[0] || null;
|
||||
}
|
||||
async list(a: Actor, user: string, from?: string, to?: string, db = this.db): Promise<Span[]> {
|
||||
authorize(a, user);
|
||||
const w = from && to ? range(from, to) : null;
|
||||
const filter = w ? sql `AND s.started_at < ${w.ended_at}::timestamptz AND (s.ended_at IS NULL OR s.ended_at > ${w.started_at}::timestamptz)` : sql ``;
|
||||
return rows(db, sql `SELECT s.*,
|
||||
COALESCE((SELECT jsonb_agg(b ORDER BY b.started_at) FROM staff_time_span_breaks b WHERE b.span_id=s.id),'[]'::jsonb) AS breaks,
|
||||
COALESCE((SELECT jsonb_agg(p ORDER BY p.started_at) FROM staff_time_span_projects p WHERE p.span_id=s.id),'[]'::jsonb) AS projects
|
||||
FROM staff_time_spans s WHERE s.tenant_id=${a.tenant} AND s.user_id=${user}::uuid ${filter} ORDER BY s.started_at DESC,s.id`);
|
||||
}
|
||||
async current(a: Actor, user: string, db = this.db): Promise<Span | null> {
|
||||
authorize(a, user);
|
||||
const [open] = await rows(db, sql `SELECT id FROM staff_time_spans WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid AND ended_at IS NULL LIMIT 1`);
|
||||
return open ? this.get(a, open.id, db) : null;
|
||||
}
|
||||
async get(a: Actor, id: string, db = this.db): Promise<Span> {
|
||||
const [s] = await rows(db, sql `SELECT * FROM staff_time_spans WHERE id=${id}::uuid AND tenant_id=${a.tenant}`);
|
||||
if (!s)
|
||||
fail('Zeiteintrag nicht gefunden.', 404);
|
||||
authorize(a, s.user_id);
|
||||
s.breaks = await rows(db, sql `SELECT * FROM staff_time_span_breaks WHERE span_id=${id}::uuid ORDER BY started_at`);
|
||||
s.projects = await rows(db, sql `SELECT * FROM staff_time_span_projects WHERE span_id=${id}::uuid ORDER BY started_at`);
|
||||
return s;
|
||||
}
|
||||
async history(a: Actor, id: string) {
|
||||
await this.get(a, id);
|
||||
return rows(this.db, sql `SELECT * FROM staff_time_span_history WHERE span_id=${id}::uuid ORDER BY created_at,id`);
|
||||
}
|
||||
async save(tx: any, a: Actor, user: string, data: any, before: Span | null, action: string, reason: string, source: string): Promise<Span> {
|
||||
const s = normalizeSpan(data);
|
||||
s.status = data.status || 'factual';
|
||||
const conflict = await rows(tx, sql `SELECT id FROM staff_time_spans WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid
|
||||
AND (${before?.id || null}::uuid IS NULL OR id <> ${before?.id || null}::uuid)
|
||||
AND started_at < COALESCE(${s.ended_at}::timestamptz,'infinity'::timestamptz)
|
||||
AND COALESCE(ended_at,'infinity'::timestamptz) > ${s.started_at}::timestamptz LIMIT 1`);
|
||||
if (conflict.length)
|
||||
fail('Der Zeitraum überschneidet sich mit einem bestehenden Eintrag.', 409);
|
||||
for (const p of s.projects) {
|
||||
if (!(await rows(tx, sql `SELECT id FROM projects WHERE id=${p.project_id} AND tenant=${a.tenant}`)).length)
|
||||
fail('Projekt gehört nicht zum Mandanten.', 400);
|
||||
}
|
||||
let id = before?.id;
|
||||
if (id) {
|
||||
await tx.execute(sql `UPDATE staff_time_spans SET type=${s.type},started_at=${s.started_at}::timestamptz,ended_at=${s.ended_at}::timestamptz,
|
||||
date_from=${s.date_from}::date,date_to=${s.date_to}::date,timezone=${s.timezone},description=${s.description},status=${s.status},version=version+1,updated_at=now() WHERE id=${id}::uuid`);
|
||||
await tx.execute(sql `DELETE FROM staff_time_span_breaks WHERE span_id=${id}::uuid`);
|
||||
await tx.execute(sql `DELETE FROM staff_time_span_projects WHERE span_id=${id}::uuid`);
|
||||
}
|
||||
else {
|
||||
const [created] = await rows(tx, sql `INSERT INTO staff_time_spans(tenant_id,user_id,type,started_at,ended_at,date_from,date_to,timezone,description,source,status)
|
||||
VALUES(${a.tenant},${user}::uuid,${s.type},${s.started_at}::timestamptz,${s.ended_at}::timestamptz,${s.date_from}::date,${s.date_to}::date,${s.timezone},${s.description},${source},${s.status}) RETURNING id`);
|
||||
id = created.id;
|
||||
}
|
||||
for (const p of s.breaks)
|
||||
await tx.execute(sql `INSERT INTO staff_time_span_breaks(span_id,started_at,ended_at) VALUES(${id}::uuid,${p.started_at}::timestamptz,${p.ended_at}::timestamptz)`);
|
||||
for (const p of s.projects)
|
||||
await tx.execute(sql `INSERT INTO staff_time_span_projects(span_id,project_id,started_at,ended_at,notes) VALUES(${id}::uuid,${p.project_id},${p.started_at}::timestamptz,${p.ended_at}::timestamptz,${p.notes})`);
|
||||
const after = await this.get({ ...a, trusted: true }, id!, tx);
|
||||
await tx.execute(sql `INSERT INTO staff_time_span_history(span_id,actor_id,action,reason,before_data,after_data)
|
||||
VALUES(${id}::uuid,${a.user}::uuid,${action},${reason},${before ? JSON.stringify(before) : null}::jsonb,${JSON.stringify(after)}::jsonb)`);
|
||||
return after;
|
||||
}
|
||||
async mutate(a: Actor, user: string, requestId: string, command: any, source = 'web') {
|
||||
const approval = ['approve', 'reject'].includes(command.action);
|
||||
authorize(a, user, approval ? 'approve' : 'write');
|
||||
if (typeof requestId !== 'string' || requestId.length < 8 || requestId.length > 200)
|
||||
fail('Eindeutige Anfrage-ID erforderlich.');
|
||||
const fingerprint = digest({ command, actor: a.user, source });
|
||||
return this.db.transaction(async (tx: any) => {
|
||||
await this.lock(tx, a, user);
|
||||
if (!await this.active(a, user, tx))
|
||||
fail('Zeiterfassung 2.0 zuerst mit Datenvorschau aktivieren.', 409);
|
||||
const [previous] = await rows(tx, sql `SELECT * FROM staff_time_v2_requests WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid AND request_id=${requestId}`);
|
||||
if (previous) {
|
||||
if (previous.fingerprint !== fingerprint)
|
||||
fail('Anfrage-ID wurde bereits für andere Daten verwendet.', 409);
|
||||
return previous.response;
|
||||
}
|
||||
const action = command.action;
|
||||
if (['create', 'start'].includes(action) && command.id)
|
||||
fail('Neue Einträge dürfen keine bestehende ID ersetzen.');
|
||||
let before: Span | null = null, data: any;
|
||||
if (command.id) {
|
||||
before = await this.get({ ...a, trusted: true }, command.id, tx);
|
||||
if (before.user_id !== user)
|
||||
fail('Eintrag gehört zu anderem Mitarbeiter.', 403);
|
||||
if (command.version !== before.version)
|
||||
fail('Eintrag wurde zwischenzeitlich geändert. Bitte neu laden.', 409);
|
||||
}
|
||||
if (action === 'create')
|
||||
data = { ...command.data, status: 'factual' };
|
||||
else if (action === 'start') {
|
||||
data = { type: 'work', started_at: instant(command.at), ended_at: null, description: command.description || '' };
|
||||
}
|
||||
else if (['stop', 'pause', 'resume'].includes(action)) {
|
||||
if (!before || before.type !== 'work' || before.ended_at)
|
||||
fail('Keine passende laufende Anwesenheit.', 409);
|
||||
data = { ...before, breaks: before.breaks.map(p => ({ ...p })) };
|
||||
const at = instant(command.at), open = data.breaks.find((p: any) => !p.ended_at);
|
||||
if (action === 'pause') {
|
||||
if (open)
|
||||
fail('Pause läuft bereits.', 409);
|
||||
data.breaks.push({ started_at: at, ended_at: null });
|
||||
}
|
||||
else {
|
||||
if (action === 'resume' && !open)
|
||||
fail('Keine laufende Pause.', 409);
|
||||
if (open)
|
||||
open.ended_at = at;
|
||||
if (action === 'stop')
|
||||
data.ended_at = at;
|
||||
}
|
||||
}
|
||||
else if (action === 'update') {
|
||||
if (!before)
|
||||
fail('Eintrag erforderlich.');
|
||||
if (!String(command.reason || '').trim())
|
||||
fail('Korrekturgrund erforderlich.');
|
||||
data = { ...command.data, status: 'factual' };
|
||||
}
|
||||
else if (['submit', 'approve', 'reject'].includes(action)) {
|
||||
if (!before)
|
||||
fail('Eintrag erforderlich.');
|
||||
data = { ...before, status: transition(before, action, command.reason) };
|
||||
}
|
||||
else
|
||||
fail('Unbekannte Aktion.');
|
||||
const response = await this.save(tx, a, user, data, before, action, String(command.reason || ''), source);
|
||||
await tx.execute(sql `INSERT INTO staff_time_v2_requests(tenant_id,user_id,request_id,fingerprint,response)
|
||||
VALUES(${a.tenant},${user}::uuid,${requestId},${fingerprint},${JSON.stringify(response)}::jsonb)`);
|
||||
return response;
|
||||
});
|
||||
}
|
||||
async evaluation(a: Actor, user: string, from: string, to: string) {
|
||||
const spans = await this.list(a, user, from, to);
|
||||
const [profile] = await rows(this.db, sql `SELECT * FROM auth_profiles WHERE tenant_id=${a.tenant} AND user_id=${user}::uuid LIMIT 1`);
|
||||
if (!profile)
|
||||
fail('Mitarbeiterprofil fehlt.', 404);
|
||||
const holidays = await rows(this.db, sql `SELECT DISTINCT date FROM holidays WHERE state_code IN ('DE',${profile.state_code || 'DE'}) AND date BETWEEN ${from}::date AND ${to}::date`);
|
||||
return { userId: user, spans, summary: { ...evaluate(spans, profile, holidays.map(h => h.date), from, to), from, to, user_id: user, tenant_id: a.tenant } };
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { TimeService } from "../time-v2/service";
|
||||
import { legacySpans } from "../time-v2/compatibility";
|
||||
import { FastifyInstance } from "fastify";
|
||||
import {and, eq, gte, lte, asc, inArray} from "drizzle-orm";
|
||||
import {
|
||||
@@ -13,6 +15,14 @@ export async function generateTimesEvaluation(
|
||||
startDateInput: string,
|
||||
endDateInput: string
|
||||
) {
|
||||
const service = new TimeService(server.db);
|
||||
const actor = { tenant: tenant_id, user: user_id };
|
||||
if (await service.active(actor, user_id)) {
|
||||
const result = await service.evaluation(actor, user_id, startDateInput, endDateInput);
|
||||
return { ...result.summary, sumWorkingMinutesEingereicht: result.summary.sumWorkingMinutesSubmitted,
|
||||
saldo: result.summary.saldoApproved, saldoInOfficial: result.summary.saldoSubmitted,
|
||||
times: legacySpans(result.spans).map(s => ({ ...s, started_at: s.startedAt, stopped_at: s.endedAt, state: s.status })) };
|
||||
}
|
||||
const startDate = server.dayjs(startDateInput);
|
||||
const endDate = server.dayjs(endDateInput);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user