@@ -382,4 +382,45 @@ public function test_delete_user_deletes_owned_organizations_that_have_only_one_
382382 1
383383 );
384384 }
385+
386+ public function test_delete_user_with_current_organization_set_to_owned_org_that_will_be_deleted_does_not_cause_foreign_key_violation (): void
387+ {
388+ // Arrange
389+ // User A creates an organization and invites User B
390+ $ userA = User::factory ()->create ();
391+ $ userB = User::factory ()->create ();
392+ $ organizationOfA = Organization::factory ()->withOwner ($ userA )->create ();
393+ $ organizationOfB = Organization::factory ()->withOwner ($ userB )->create ();
394+ Member::factory ()->forUser ($ userA )->forOrganization ($ organizationOfA )->role (Role::Owner)->create ();
395+ Member::factory ()->forUser ($ userB )->forOrganization ($ organizationOfB )->role (Role::Owner)->create ();
396+ $ memberBInOrgA = Member::factory ()->forUser ($ userB )->forOrganization ($ organizationOfA )->role (Role::Employee)->create ();
397+ TimeEntry::factory ()->forOrganization ($ organizationOfA )->forMember ($ memberBInOrgA )->createMany (2 );
398+
399+ // User B's current_organization_id points to their own org (the one that will be deleted)
400+ $ userB ->update (['current_team_id ' => $ organizationOfB ->getKey ()]);
401+
402+ // Act
403+ $ this ->deletionService ->deleteUser ($ userB );
404+
405+ // Assert
406+ $ this ->assertDatabaseMissing (User::class, [
407+ 'id ' => $ userB ->getKey (),
408+ ]);
409+ $ this ->assertDatabaseMissing (Organization::class, [
410+ 'id ' => $ organizationOfB ->getKey (),
411+ ]);
412+ $ this ->assertDatabaseHas (Organization::class, [
413+ 'id ' => $ organizationOfA ->getKey (),
414+ ]);
415+ // The placeholder user should exist with current_team_id set to the org where they are a placeholder
416+ $ placeholderUser = User::query ()->where ('is_placeholder ' , true )->first ();
417+ $ this ->assertNotNull ($ placeholderUser );
418+ $ this ->assertSame ($ organizationOfA ->getKey (), $ placeholderUser ->current_team_id );
419+ $ this ->assertDatabaseHas (Member::class, [
420+ 'id ' => $ memberBInOrgA ->getKey (),
421+ 'user_id ' => $ placeholderUser ->getKey (),
422+ 'organization_id ' => $ organizationOfA ->getKey (),
423+ 'role ' => Role::Placeholder->value ,
424+ ]);
425+ }
385426}
0 commit comments