Remove redundant debug logs in TimeEntryService for cleaner output; streamline code by eliminating unnecessary console statements while maintaining essential functionality.

This commit is contained in:
Torsten Schulz (local)
2025-10-20 08:04:11 +02:00
parent a335a06edb
commit 44fb9a0bdd

View File

@@ -686,14 +686,11 @@ class TimeEntryService {
// Hole den aktuellen Status // Hole den aktuellen Status
const currentState = await this.getCurrentState(uid); const currentState = await this.getCurrentState(uid);
console.log(`DEBUG Bereinigtes Arbeitsende: runningEntry=${!!runningEntry}, currentState=${currentState}, open=${open}`);
// Arbeitsende berechnen, wenn derzeit gearbeitet wird // Arbeitsende berechnen, wenn derzeit gearbeitet wird
// Das ist der Fall bei: 'start work' (direkt nach Arbeitsbeginn) oder 'stop pause' (nach Pausenende) // Das ist der Fall bei: 'start work' (direkt nach Arbeitsbeginn) oder 'stop pause' (nach Pausenende)
const isCurrentlyWorking = runningEntry && (currentState === 'start work' || currentState === 'stop pause'); const isCurrentlyWorking = runningEntry && (currentState === 'start work' || currentState === 'stop pause');
if (isCurrentlyWorking && open && open !== '—' && open !== 'Arbeitsende erreicht') { if (isCurrentlyWorking && open && open !== '—' && open !== 'Arbeitsende erreicht') {
console.log(`DEBUG: Berechne bereinigtes Arbeitsende...`);
// Parse "Offen" Zeit (Format: HH:MM:SS) // Parse "Offen" Zeit (Format: HH:MM:SS)
const openParts = open.split(':'); const openParts = open.split(':');
const openH = parseInt(openParts[0]); const openH = parseInt(openParts[0]);
@@ -733,9 +730,6 @@ class TimeEntryService {
const endM = endTime.getMinutes(); const endM = endTime.getMinutes();
adjustedEndTodayWeek = `${endH.toString().padStart(2, '0')}:${endM.toString().padStart(2, '0')}`; adjustedEndTodayWeek = `${endH.toString().padStart(2, '0')}:${endM.toString().padStart(2, '0')}`;
} }
console.log(`DEBUG: Offen heute=${openMinutes}min, Gesamt-Überstunden=${generalOvertimeMinutes}min → Bereinigt (Generell)=${adjustedEndTodayGeneral}`);
console.log(`DEBUG: Offen heute=${openMinutes}min, Wochen-Überstunden=${weekOvertimeMinutes}min → Bereinigt (Woche)=${adjustedEndTodayWeek}`);
} }
// Berechne Arbeitsfreie Stunden (Urlaub + Krankheit + Feiertage) bis heute // Berechne Arbeitsfreie Stunden (Urlaub + Krankheit + Feiertage) bis heute
@@ -936,11 +930,6 @@ class TimeEntryService {
}); });
} }
console.log(`DEBUG _calculateTotalOvertimeOldStyle ERGEBNIS:`);
console.log(` Soll-Minuten: ${totalSollMinutes} (${(totalSollMinutes/60).toFixed(2)}h)`);
console.log(` Ist-Minuten: ${totalIstMinutes} (${(totalIstMinutes/60).toFixed(2)}h)`);
console.log(` Differenz: ${totalIstMinutes - totalSollMinutes} min (${((totalIstMinutes - totalSollMinutes)/60).toFixed(2)}h)`);
const overtimeMinutes = totalIstMinutes - totalSollMinutes; const overtimeMinutes = totalIstMinutes - totalSollMinutes;
const overtimeHours = Math.floor(Math.abs(overtimeMinutes) / 60); const overtimeHours = Math.floor(Math.abs(overtimeMinutes) / 60);
const overtimeMins = Math.abs(overtimeMinutes) % 60; const overtimeMins = Math.abs(overtimeMinutes) % 60;
@@ -954,20 +943,11 @@ class TimeEntryService {
const { Timewish, Holiday, Vacation, Sick, Worklog, User } = database.getModels(); const { Timewish, Holiday, Vacation, Sick, Worklog, User } = database.getModels();
const sequelize = database.sequelize; const sequelize = database.sequelize;
console.log('DEBUG _calculateTotalOvertime: Starte optimierte DB-basierte Berechnung...');
// Hole den Überstunden-Offset und daily_hours für diesen User // Hole den Überstunden-Offset und daily_hours für diesen User
const user = await User.findByPk(userId, { attributes: ['overtime_offset_minutes', 'daily_hours'], raw: true }); const user = await User.findByPk(userId, { attributes: ['overtime_offset_minutes', 'daily_hours'], raw: true });
const overtimeOffsetMinutes = user?.overtime_offset_minutes || 0; const overtimeOffsetMinutes = user?.overtime_offset_minutes || 0;
const userDailyHours = user?.daily_hours || 8; const userDailyHours = user?.daily_hours || 8;
if (overtimeOffsetMinutes !== 0) {
const offsetHours = Math.floor(Math.abs(overtimeOffsetMinutes) / 60);
const offsetMins = Math.abs(overtimeOffsetMinutes) % 60;
const offsetSign = overtimeOffsetMinutes >= 0 ? '+' : '-';
console.log(`DEBUG: Überstunden-Offset aus User-Tabelle: ${offsetSign}${offsetHours}:${offsetMins.toString().padStart(2, '0')} (${overtimeOffsetMinutes} Minuten)`);
}
// Hole alle Timewishes für Mo-Fr // Hole alle Timewishes für Mo-Fr
const allTimewishes = await Timewish.findAll({ const allTimewishes = await Timewish.findAll({
where: { where: {
@@ -980,8 +960,6 @@ class TimeEntryService {
order: [['day', 'ASC'], ['start_date', 'ASC']] order: [['day', 'ASC'], ['start_date', 'ASC']]
}); });
console.log(`DEBUG: ${allTimewishes.length} Timewishes gefunden:`, allTimewishes.map(tw => `Tag ${tw.day}: ${tw.hours}h (${tw.start_date} - ${tw.end_date || 'heute'})`).join(', '));
// Erstelle Map: Tag -> Array von Timewishes // Erstelle Map: Tag -> Array von Timewishes
const timewishMap = new Map(); const timewishMap = new Map();
allTimewishes.forEach(tw => { allTimewishes.forEach(tw => {
@@ -1020,8 +998,6 @@ class TimeEntryService {
yesterdayDate.setDate(yesterdayDate.getDate() - 1); yesterdayDate.setDate(yesterdayDate.getDate() - 1);
const endDateStr = yesterdayDate.toISOString().split('T')[0]; const endDateStr = yesterdayDate.toISOString().split('T')[0];
console.log(`DEBUG: Berechne Überstunden bis ${endDateStr}`);
// Hole alle Arbeitstage mit Netto-Arbeitszeit aus der DB // Hole alle Arbeitstage mit Netto-Arbeitszeit aus der DB
// WICHTIG: Berücksichtigt timefix-Korrekturen! // WICHTIG: Berücksichtigt timefix-Korrekturen!
// Dies ist VIEL schneller als 253x getWeekOverview aufzurufen! // Dies ist VIEL schneller als 253x getWeekOverview aufzurufen!
@@ -1068,8 +1044,6 @@ class TimeEntryService {
type: sequelize.QueryTypes.SELECT type: sequelize.QueryTypes.SELECT
}); });
console.log(`DEBUG: ${workDays.length} Arbeitstage gefunden (mit timefix-Korrekturen)`);
// Hole User-Bundesland // Hole User-Bundesland
const { State: StateModel } = database.getModels(); const { State: StateModel } = database.getModels();
const userForState = await User.findByPk(userId, { const userForState = await User.findByPk(userId, {
@@ -1166,8 +1140,6 @@ class TimeEntryService {
totalIstHoursFromDB += netHours; totalIstHoursFromDB += netHours;
}); });
console.log(`DEBUG: Gesamt Ist-Stunden aus DB-Query: ${totalIstHoursFromDB.toFixed(2)}h`);
// Berechne Soll-Stunden für alle Arbeitstage // Berechne Soll-Stunden für alle Arbeitstage
let totalSollMinutes = 0; let totalSollMinutes = 0;
let processedDays = 0; let processedDays = 0;
@@ -1211,11 +1183,6 @@ class TimeEntryService {
const sollHours = getDailySollHours(dateStr, dow); const sollHours = getDailySollHours(dateStr, dow);
totalSollMinutes += sollHours * 60; totalSollMinutes += sollHours * 60;
workedDays++; workedDays++;
// Debug: Zeige erste 5 Tage
if (processedDays < 5) {
console.log(` DEBUG Tag ${processedDays + 1}: ${dateStr}, Soll=${sollHours.toFixed(2)}h, Ist=${istHours.toFixed(2)}h`);
}
processedDays++; processedDays++;
} }
}); });
@@ -1223,16 +1190,6 @@ class TimeEntryService {
// Verwende die Ist-Stunden direkt aus der DB-Query (korrekt!) // Verwende die Ist-Stunden direkt aus der DB-Query (korrekt!)
const totalIstMinutes = totalIstHoursFromDB * 60; const totalIstMinutes = totalIstHoursFromDB * 60;
console.log(`DEBUG _calculateTotalOvertime ANALYSE:`);
console.log(` - Krankheitstage: ${sickDaysCount}`);
console.log(` - Feiertage: ${holidayDaysCount}`);
console.log(` - Urlaubstage (ganz): ${vacationFullDays}`);
console.log(` - Urlaubstage (halb): ${vacationHalfDays}`);
console.log(` - Fehlzeit (nicht gearbeitet): ${notWorkedDays}`);
console.log(` = Gearbeitet: ${workedDays}`);
console.log(` = Verarbeitete Tage (Soll gezählt): ${processedDays}`);
console.log(` Berechnung: Soll=${totalSollMinutes}min (${(totalSollMinutes/60).toFixed(2)}h), Ist=${totalIstMinutes}min (${(totalIstMinutes/60).toFixed(2)}h)`);
// Berechne Überstunden ohne Offset // Berechne Überstunden ohne Offset
const overtimeMinutesRaw = Math.round(totalIstMinutes - totalSollMinutes); const overtimeMinutesRaw = Math.round(totalIstMinutes - totalSollMinutes);
@@ -1244,16 +1201,6 @@ class TimeEntryService {
const overtimeSign = overtimeMinutes >= 0 ? '+' : '-'; const overtimeSign = overtimeMinutes >= 0 ? '+' : '-';
const formatted = `${overtimeSign}${overtimeHours}:${overtimeMins.toString().padStart(2, '0')}`; const formatted = `${overtimeSign}${overtimeHours}:${overtimeMins.toString().padStart(2, '0')}`;
if (overtimeOffsetMinutes !== 0) {
const rawHours = Math.floor(Math.abs(overtimeMinutesRaw) / 60);
const rawMins = Math.abs(overtimeMinutesRaw) % 60;
const rawSign = overtimeMinutesRaw >= 0 ? '+' : '-';
console.log(`DEBUG: Überstunden (berechnet): ${rawSign}${rawHours}:${rawMins.toString().padStart(2, '0')}`);
console.log(`DEBUG: Überstunden (mit Offset): ${formatted}`);
} else {
console.log(`DEBUG: Überstunden (Gesamt - Timewish): ${formatted} (${overtimeMinutes} Minuten)`);
}
return { minutes: overtimeMinutes, formatted }; return { minutes: overtimeMinutes, formatted };
} }
@@ -1274,8 +1221,6 @@ class TimeEntryService {
const day = now.getDate(); const day = now.getDate();
const currentDay = now.getDay(); // 0 = Sonntag, 1 = Montag, ..., 6 = Samstag const currentDay = now.getDay(); // 0 = Sonntag, 1 = Montag, ..., 6 = Samstag
console.log(`DEBUG: Heute ist ${year}-${(month+1).toString().padStart(2,'0')}-${day.toString().padStart(2,'0')}, Tag ${currentDay} (0=So, 1=Mo, ..., 6=Sa)`);
// Offset zu Montag berechnen // Offset zu Montag berechnen
// Montag ist Tag 1, wir wollen zum Montag der aktuellen Woche // Montag ist Tag 1, wir wollen zum Montag der aktuellen Woche
// Wenn Sonntag (0), dann ist das Ende der Woche, also -6 Tage zum Montag // Wenn Sonntag (0), dann ist das Ende der Woche, also -6 Tage zum Montag
@@ -1283,8 +1228,6 @@ class TimeEntryService {
// Wenn Dienstag (2), dann -1 Tag, etc. // Wenn Dienstag (2), dann -1 Tag, etc.
const daysToMonday = currentDay === 0 ? -6 : 1 - currentDay; const daysToMonday = currentDay === 0 ? -6 : 1 - currentDay;
console.log(`DEBUG: Tage bis Montag: ${daysToMonday}`);
// Berechne Montag der Woche // Berechne Montag der Woche
const weekStart = new Date(year, month, day + daysToMonday + (weekOffset * 7)); const weekStart = new Date(year, month, day + daysToMonday + (weekOffset * 7));
weekStart.setHours(0, 0, 0, 0); weekStart.setHours(0, 0, 0, 0);
@@ -1293,8 +1236,6 @@ class TimeEntryService {
const weekEnd = new Date(year, month, day + daysToMonday + (weekOffset * 7) + 6); const weekEnd = new Date(year, month, day + daysToMonday + (weekOffset * 7) + 6);
weekEnd.setHours(23, 59, 59, 999); weekEnd.setHours(23, 59, 59, 999);
console.log(`Wochenübersicht für User ${uid}, Woche ${weekOffset}: ${weekStart.getFullYear()}-${(weekStart.getMonth()+1).toString().padStart(2,'0')}-${weekStart.getDate().toString().padStart(2,'0')} bis ${weekEnd.getFullYear()}-${(weekEnd.getMonth()+1).toString().padStart(2,'0')}-${weekEnd.getDate().toString().padStart(2,'0')}`);
// Hole alle Worklog-Einträge für diese Woche // Hole alle Worklog-Einträge für diese Woche
const pairs = await worklogRepository.findPairsByUserInDateRange(uid, weekStart, weekEnd); const pairs = await worklogRepository.findPairsByUserInDateRange(uid, weekStart, weekEnd);
@@ -1398,20 +1339,12 @@ class TimeEntryService {
}); });
const endFix = endFixEntry ? timefixMap.get(endFixEntry.id)?.find(f => f.fix_type === 'stop work') : null; const endFix = endFixEntry ? timefixMap.get(endFixEntry.id)?.find(f => f.fix_type === 'stop work') : null;
if (startFix || endFix) {
console.log(`DEBUG Timefix für Block ${pair.id}: startFix=${!!startFix}, endFix=${!!endFix}`);
if (startFix) {
console.log(`DEBUG startFix.fix_date_time:`, startFix.fix_date_time, typeof startFix.fix_date_time);
}
}
// Verwende korrigierte Zeiten falls vorhanden // Verwende korrigierte Zeiten falls vorhanden
const originalStartTime = workStartUTC; const originalStartTime = workStartUTC;
const originalEndTime = workEndUTC; const originalEndTime = workEndUTC;
if (startFix) { if (startFix) {
workStartUTC = new Date(startFix.fix_date_time); workStartUTC = new Date(startFix.fix_date_time);
console.log(`DEBUG workStartUTC nach Korrektur:`, workStartUTC, workStartUTC.getHours());
} }
if (endFix) { if (endFix) {
workEndUTC = new Date(endFix.fix_date_time); workEndUTC = new Date(endFix.fix_date_time);
@@ -1499,8 +1432,6 @@ class TimeEntryService {
return false; return false;
}); });
console.log(`DEBUG: Block ${pair.id} hat ${blockEntries.length} Pausen-Einträge`);
// Finde Pausen-Paare NUR für diesen Block // Finde Pausen-Paare NUR für diesen Block
const pausePairs = []; const pausePairs = [];
const pauseStarts = {}; const pauseStarts = {};
@@ -1669,8 +1600,6 @@ class TimeEntryService {
return false; return false;
}); });
console.log(`DEBUG: Laufender Block ${pair.id} hat ${blockEntries.length} Pausen-Einträge`);
// Finde laufende Pause // Finde laufende Pause
const pauseStarts = {}; const pauseStarts = {};
const pausePairs = []; const pausePairs = [];
@@ -2085,10 +2014,6 @@ class TimeEntryService {
const seconds = String(now.getUTCSeconds()).padStart(2, '0'); const seconds = String(now.getUTCSeconds()).padStart(2, '0');
const utcTimeString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; const utcTimeString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
console.log(`DEBUG clock: Lokale Zeit = ${now.toLocaleString('de-DE', { timeZone: 'Europe/Berlin' })}`);
console.log(`DEBUG clock: UTC-String für DB = ${utcTimeString}`);
console.log(`DEBUG clock: ISO-String = ${now.toISOString()}`);
const entry = await worklogRepository.create({ const entry = await worklogRepository.create({
user_id: uid, user_id: uid,
state: action, // Speichere nur den Action-String, nicht als JSON state: action, // Speichere nur den Action-String, nicht als JSON
@@ -2096,8 +2021,6 @@ class TimeEntryService {
relatedTo_id: relatedToId relatedTo_id: relatedToId
}); });
console.log(`DEBUG clock: Entry gespeichert mit tstamp = ${entry.tstamp}`);
return entry; return entry;
} }
@@ -2153,8 +2076,6 @@ class TimeEntryService {
async _findLastUnpairedStart(userId, startAction) { async _findLastUnpairedStart(userId, startAction) {
const allEntries = await worklogRepository.findByUser(userId); const allEntries = await worklogRepository.findByUser(userId);
console.log(`DEBUG _findLastUnpairedStart: Suche nach '${startAction}', ${allEntries.length} Einträge gefunden`);
// Finde den letzten Start ohne Stop // Finde den letzten Start ohne Stop
for (let i = allEntries.length - 1; i >= 0; i--) { for (let i = allEntries.length - 1; i >= 0; i--) {
const entry = allEntries[i]; const entry = allEntries[i];
@@ -2191,16 +2112,12 @@ class TimeEntryService {
return eAction === stopAction && e.relatedTo_id === entry.id; return eAction === stopAction && e.relatedTo_id === entry.id;
}); });
console.log(`DEBUG: Eintrag ${entry.id} (${action}), hasStop: ${hasStop}`);
if (!hasStop) { if (!hasStop) {
console.log(`DEBUG: Verwende Eintrag ${entry.id} als relatedTo_id`);
return entry.id; return entry.id;
} }
} }
} }
console.log(`DEBUG: Kein ungepaarter '${startAction}' gefunden`);
return null; return null;
} }
@@ -2226,7 +2143,6 @@ class TimeEntryService {
const lastEntry = await worklogRepository.findLatestByUser(uid); const lastEntry = await worklogRepository.findLatestByUser(uid);
if (!lastEntry) { if (!lastEntry) {
console.log('DEBUG getRunningEntry: Kein letzter Eintrag gefunden');
return null; return null;
} }
@@ -2242,21 +2158,15 @@ class TimeEntryService {
const action = state?.action || state; const action = state?.action || state;
console.log(`DEBUG getRunningEntry: Letzter Eintrag ID ${lastEntry.id}, action: ${action}`);
// Wenn letzter Eintrag "stop work" oder null ist, läuft nichts // Wenn letzter Eintrag "stop work" oder null ist, läuft nichts
if (!action || action === 'stop work') { if (!action || action === 'stop work') {
console.log(`DEBUG getRunningEntry: Keine laufende Arbeit (action: ${action})`);
return null; return null;
} }
// Finde den zugehörigen "start work" // Finde den zugehörigen "start work"
const startWorkId = await this._findLastUnpairedStart(uid, 'start work'); const startWorkId = await this._findLastUnpairedStart(uid, 'start work');
console.log(`DEBUG getRunningEntry: startWorkId = ${startWorkId}`);
if (!startWorkId) { if (!startWorkId) {
console.log('DEBUG getRunningEntry: Kein startWorkId gefunden');
return null; return null;
} }
@@ -2264,10 +2174,7 @@ class TimeEntryService {
const allEntries = await worklogRepository.findByUser(uid); const allEntries = await worklogRepository.findByUser(uid);
const startWorkEntry = allEntries.find(e => e.id === startWorkId); const startWorkEntry = allEntries.find(e => e.id === startWorkId);
console.log(`DEBUG getRunningEntry: startWorkEntry gefunden: ${!!startWorkEntry}`);
if (!startWorkEntry) { if (!startWorkEntry) {
console.log('DEBUG getRunningEntry: Kein startWorkEntry gefunden');
return null; return null;
} }
@@ -2328,8 +2235,6 @@ class TimeEntryService {
currentPauseStart: currentPauseStart currentPauseStart: currentPauseStart
}; };
console.log(`DEBUG getRunningEntry: Returning result with ${pauseDurations.length} pauses, currentPauseStart: ${currentPauseStart}`);
return result; return result;
} }