diff --git a/modules/custom/activity_creator/activity_creator.install b/modules/custom/activity_creator/activity_creator.install index dce929ac071..f3670b4d411 100644 --- a/modules/custom/activity_creator/activity_creator.install +++ b/modules/custom/activity_creator/activity_creator.install @@ -5,6 +5,7 @@ * Installation code for the activity_creator module. */ +use Drupal\activity_creator\ActivityInterface; use Drupal\Core\Database\Database; /** @@ -137,3 +138,59 @@ function activity_creator_update_8801() { // Output logged messages to related channel of update execution. return $updateHelper->logger()->output(); } + +/** + * Remove activities notification status if related entity not exist. + */ +function activity_creator_update_8802(&$sandbox) { + $database = Drupal::database(); + if (!isset($sandbox['total'])) { + $query = $database->select('activity_notification_status', 'ans'); + $query->addExpression('COUNT(*)'); + $count = $query->execute()->fetchField(); + $sandbox['total'] = $count; + $sandbox['current'] = 0; + } + + // Activities per one batch operation. + $activities_per_batch = 10; + + // Get activity IDs. + $aids = $database + ->select('activity_notification_status', 'ans') + ->fields('ans', ['aid']) + ->range($sandbox['current'], $sandbox['current'] + $activities_per_batch) + ->execute() + ->fetchCol(); + + // Get activity storage. + $activity_storage = $activity = Drupal::entityTypeManager() + ->getStorage('activity'); + + foreach ($aids as $aid) { + /** @var \Drupal\activity_creator\ActivityInterface $activity */ + $activity = $activity_storage->load($aid); + + if (!$activity instanceof ActivityInterface) { + $aids_for_delete[] = $aid; + } + elseif (is_null($activity->getRelatedEntity())) { + $activity_storage->delete([$activity]); + $aids_for_delete[] = $aid; + } + + $sandbox['current']++; + } + + if (!empty($aids_for_delete)) { + Drupal::service('activity_creator.activity_notifications') + ->deleteNotificationsbyIds($aids_for_delete); + } + + if ($sandbox['total'] == 0) { + $sandbox['#finished'] = 1; + } + else { + $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']); + } +} diff --git a/modules/custom/activity_creator/src/ActivityNotifications.php b/modules/custom/activity_creator/src/ActivityNotifications.php index 25b682d5287..953d0f3d238 100644 --- a/modules/custom/activity_creator/src/ActivityNotifications.php +++ b/modules/custom/activity_creator/src/ActivityNotifications.php @@ -257,7 +257,7 @@ public function deleteNotificationsbyIds(array $activity_ids): bool { $txn = $this->database->startTransaction(); try { $this->database->delete('activity_notification_status') - ->condition('aid', $activity_ids) + ->condition('aid', $activity_ids, 'IN') ->execute(); } catch (\Exception $exception) {