diff --git a/src/Models/Message.php b/src/Models/Message.php index 580b74a7..3df11659 100644 --- a/src/Models/Message.php +++ b/src/Models/Message.php @@ -95,6 +95,10 @@ protected static function boot(): void static::creating(function ($model) { $model->hash = $model->hash ?: Uuid::uuid4()->toString(); }); + + static::deleting(function (self $message) { + $message->failures()->delete(); + }); } public function failures(): HasMany diff --git a/src/Models/Subscriber.php b/src/Models/Subscriber.php index 60d77af1..1063bff1 100644 --- a/src/Models/Subscriber.php +++ b/src/Models/Subscriber.php @@ -87,10 +87,12 @@ function ($model) { $model->hash = Uuid::uuid4()->toString(); } ); - static::deleting( function (self $subscriber) { $subscriber->tags()->detach(); + $subscriber->messages()->each(static function (Message $message) { + $message->failures()->delete(); + }); $subscriber->messages()->delete(); } ); diff --git a/tests/Unit/Models/MessageTest.php b/tests/Unit/Models/MessageTest.php new file mode 100644 index 00000000..0099d6e0 --- /dev/null +++ b/tests/Unit/Models/MessageTest.php @@ -0,0 +1,30 @@ +create(); + $message->failures()->create(); + + // when + $message->delete(); + + // then + static::assertCount(0, Message::all()); + static::assertCount(0, MessageFailure::all()); + } +} diff --git a/tests/Unit/Models/SubscriberTest.php b/tests/Unit/Models/SubscriberTest.php index 97e6a69a..2370076c 100644 --- a/tests/Unit/Models/SubscriberTest.php +++ b/tests/Unit/Models/SubscriberTest.php @@ -8,6 +8,7 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Sendportal\Base\Models\Campaign; use Sendportal\Base\Models\Message; +use Sendportal\Base\Models\MessageFailure; use Sendportal\Base\Models\Subscriber; use Tests\TestCase; @@ -39,6 +40,25 @@ public function it_has_many_messages() static::assertEquals($campaignTwo->id, $messageTwo->source_id); } + /** @test */ + public function deleting_a_subscriber_also_deletes_its_messages_and_any_failures_associated_to_them() + { + // given + $subscriber = Subscriber::factory()->create(); + $message = Message::factory()->create([ + 'subscriber_id' => $subscriber->id, + ]); + $message->failures()->create(); + + // when + $subscriber->delete(); + + // then + static::assertCount(0, Subscriber::all()); + static::assertCount(0, Message::all()); + static::assertCount(0, MessageFailure::all()); + } + /** * @param Subscriber $subscriber *