93 lines
2.8 KiB
PHP
93 lines
2.8 KiB
PHP
<?php
|
|
namespace Espo\Custom\Hooks\CAkten;
|
|
|
|
use Espo\ORM\Entity;
|
|
use Espo\ORM\Repository\Option\SaveOptions;
|
|
use Espo\Core\Hook\Hook\BeforeSave;
|
|
|
|
/**
|
|
* Hook: Aktualisiert lastSync basierend auf dem neuesten lastSyncTimestamp
|
|
* der verknüpften Dokumente
|
|
*/
|
|
class UpdateLastSyncFromDocuments implements BeforeSave
|
|
{
|
|
public function __construct(
|
|
private \Espo\ORM\EntityManager $entityManager
|
|
) {}
|
|
|
|
public function beforeSave(Entity $entity, SaveOptions $options): void
|
|
{
|
|
// Überspringe, wenn skipHooks gesetzt ist (verhindert Loops)
|
|
if ($options->get('skipHooks')) {
|
|
return;
|
|
}
|
|
|
|
// Nur wenn Entity bereits existiert (nicht bei Create)
|
|
if ($entity->isNew()) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
$pdo = $this->entityManager->getPDO();
|
|
$aktenId = $entity->getId();
|
|
|
|
// Hole das neueste lastSyncTimestamp aller verknüpften Dokumente
|
|
$stmt = $pdo->prepare(
|
|
"SELECT MAX(last_sync_timestamp) AS maxLastSync
|
|
FROM c_dokumente
|
|
WHERE c_akten_id = :aktenId AND deleted = 0 AND last_sync_timestamp IS NOT NULL"
|
|
);
|
|
$stmt->execute([':aktenId' => $aktenId]);
|
|
$result = $stmt->fetch(\PDO::FETCH_ASSOC);
|
|
|
|
if ($result && $result['maxLastSync']) {
|
|
$entity->set('lastSync', $result['maxLastSync']);
|
|
}
|
|
|
|
// Berechne syncStatus basierend auf verknüpften Dokumenten
|
|
$this->updateSyncStatus($entity, $pdo, $aktenId);
|
|
|
|
} catch (\Exception $e) {
|
|
$GLOBALS['log']->error('CAkten UpdateLastSyncFromDocuments Hook Error: ' . $e->getMessage());
|
|
}
|
|
}
|
|
|
|
private function updateSyncStatus(Entity $entity, \PDO $pdo, string $aktenId): void
|
|
{
|
|
$stmt = $pdo->prepare(
|
|
"SELECT 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');
|
|
return;
|
|
}
|
|
|
|
$hasUnsynced = false;
|
|
$hasFailed = false;
|
|
|
|
foreach ($rows as $row) {
|
|
$status = $row['sync_status'] ?? null;
|
|
|
|
if ($status === 'failed') {
|
|
$hasFailed = true;
|
|
}
|
|
|
|
if ($status === 'new' || $status === 'unclean' || $status === null || $status === '') {
|
|
$hasUnsynced = true;
|
|
}
|
|
}
|
|
|
|
if ($hasFailed) {
|
|
$entity->set('syncStatus', 'failed');
|
|
} elseif ($hasUnsynced) {
|
|
$entity->set('syncStatus', 'unclean');
|
|
} else {
|
|
$entity->set('syncStatus', 'synced');
|
|
}
|
|
}
|
|
}
|