From d670c07ca45ed05402245ea7706acc2293aa4674 Mon Sep 17 00:00:00 2001 From: Steven Nguyen Date: Thu, 4 Jan 2024 21:44:33 +0000 Subject: [PATCH] Delete subscribers and update topic totals when deleting target --- app/init.php | 1 + src/Appwrite/Platform/Workers/Deletes.php | 45 +++++++++++++++++++++-- 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/app/init.php b/app/init.php index c45dad5fd1..ccf3209dc0 100644 --- a/app/init.php +++ b/app/init.php @@ -171,6 +171,7 @@ const DELETE_TYPE_CACHE_BY_TIMESTAMP = 'cacheByTimeStamp'; const DELETE_TYPE_CACHE_BY_RESOURCE = 'cacheByResource'; const DELETE_TYPE_SCHEDULES = 'schedules'; const DELETE_TYPE_TOPIC = 'topic'; +const DELETE_TYPE_TARGET = 'target'; // Mail Types const MAIL_TYPE_VERIFICATION = 'verification'; const MAIL_TYPE_MAGIC_SESSION = 'magicSession'; diff --git a/src/Appwrite/Platform/Workers/Deletes.php b/src/Appwrite/Platform/Workers/Deletes.php index c718a5a3bf..5815a7916c 100644 --- a/src/Appwrite/Platform/Workers/Deletes.php +++ b/src/Appwrite/Platform/Workers/Deletes.php @@ -158,6 +158,9 @@ class Deletes extends Action case DELETE_TYPE_TOPIC: $this->deleteTopic($project, $getProjectDB, $document); break; + case DELETE_TYPE_TARGET: + $this->deleteTarget($project, $getProjectDB, $document); + break; default: throw new \Exception('No delete operation for type: ' . \strval($type)); break; @@ -221,6 +224,35 @@ class Deletes extends Action ], $dbForProject); } + /** + * @param Document $project + * @param callable $getProjectDB + * @param Document $target + * @throws Exception + */ + protected function deleteTarget(Document $project, callable $getProjectDB, Document $target) + { + /** @var Database */ + $dbForProject = $getProjectDB($project); + + // Delete subscribers and decrement topic counts + $this->deleteByGroup( + 'subscribers', + [ + Query::equal('targetInternalId', [$target->getInternalId()]) + ], + $dbForProject, + function (Document $subscriber) use ($dbForProject) { + $topicId = $subscriber->getAttribute('topicId'); + $topicInternalId = $subscriber->getAttribute('topicInternalId'); + $topic = $dbForProject->getDocument('topics', $topicId); + if (!$topic->isEmpty() && $topic->getInternalId() === $topicInternalId) { + $dbForProject->decreaseDocumentAttribute('topics', $topicId, 'total', min: 0); + } + } + ); + } + /** * @param Document $project * @param callable $getProjectDB @@ -563,9 +595,16 @@ class Deletes extends Action ], $dbForProject); // Delete targets - $this->deleteByGroup('targets', [ - Query::equal('userInternalId', [$userInternalId]) - ], $dbForProject); + $this->listByGroup( + 'targets', + [ + Query::equal('userInternalId', [$userInternalId]) + ], + $dbForProject, + function (Document $target) use ($getProjectDB, $project) { + $this->deleteTarget($project, $getProjectDB, $target); + } + ); } /**