get('skipHooks')) { return; } if ($entity->isNew()) { return; } try { $pdo = $this->entityManager->getPDO(); $aktenId = $entity->getId(); $stmt = $pdo->prepare( "SELECT MAX(last_sync_timestamp) AS maxAdvLastSync, MAX(ai_last_sync) AS maxAiLastSync, sync_status, ai_sync_status FROM c_dokumente WHERE c_akten_id = :aktenId AND deleted = 0" ); $stmt->execute([':aktenId' => $aktenId]); $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC); if (empty($rows)) { $entity->set('syncStatus', 'unclean'); $entity->set('aiSyncStatus', 'unclean'); return; } // Timestamps $maxAdvLastSync = null; $maxAiLastSync = null; // Status-Tracker $advHasFailed = false; $advHasUnsynced = false; $aiHasFailed = false; $aiHasUnsynced = false; foreach ($rows as $row) { // Advoware: neuester Timestamp if (!empty($row['maxAdvLastSync'])) { if ($maxAdvLastSync === null || $row['maxAdvLastSync'] > $maxAdvLastSync) { $maxAdvLastSync = $row['maxAdvLastSync']; } } // AI: neuester Timestamp if (!empty($row['maxAiLastSync'])) { if ($maxAiLastSync === null || $row['maxAiLastSync'] > $maxAiLastSync) { $maxAiLastSync = $row['maxAiLastSync']; } } // Advoware: schlechtester Status $advStatus = $row['sync_status'] ?? null; if ($advStatus === 'failed') { $advHasFailed = true; } elseif ($advStatus === 'new' || $advStatus === 'unclean' || $advStatus === null || $advStatus === '') { $advHasUnsynced = true; } // AI: schlechtester Status $aiStatus = $row['ai_sync_status'] ?? null; if ($aiStatus === 'failed') { $aiHasFailed = true; } elseif ($aiStatus === 'new' || $aiStatus === 'unclean' || $aiStatus === null || $aiStatus === '') { $aiHasUnsynced = true; } } // Advoware Timestamp setzen if ($maxAdvLastSync !== null) { $entity->set('lastSync', $maxAdvLastSync); } // AI Timestamp setzen if ($maxAiLastSync !== null) { $entity->set('aiLastSync', $maxAiLastSync); } // Advoware Status setzen (worst-case) if ($advHasFailed) { $entity->set('syncStatus', 'failed'); } elseif ($advHasUnsynced) { $entity->set('syncStatus', 'unclean'); } else { $entity->set('syncStatus', 'synced'); } // AI Status setzen (worst-case) if ($aiHasFailed) { $entity->set('aiSyncStatus', 'failed'); } elseif ($aiHasUnsynced) { $entity->set('aiSyncStatus', 'unclean'); } else { $entity->set('aiSyncStatus', 'synced'); } } catch (\Exception $e) { $GLOBALS['log']->error('CAkten UpdateLastSyncFromDocuments Hook Error: ' . $e->getMessage()); } } }