trypost/tests/Feature/Social/YouTubeControllerTest.php
Paulo Castellano 173a1e4c61
Fix Facebook Page connect pagination (#212) (#253)
* Fix Facebook and Instagram-via-Facebook Page connect pagination.

Follow Graph API paging.next on /me/accounts so authorized non-first Pages are found and multi-Page accounts get the picker instead of silently connecting the first result.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Paginate Meta accounts until paging.next is exhausted.

Drop the artificial 50-page cap and stop only when there is no next URL, or the same request URL repeats (broken pagination loop).

Co-authored-by: Cursor <cursoragent@cursor.com>

* Redact tokens in Graph pagination logs and harden test coverage.

Cover happy-path and failure cases for Meta /me/accounts pagination, including mid-loop failures, invalid paging.next, and Instagram pages without a linked IG account.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Fail closed on incomplete Meta accounts pagination.

If a later /me/accounts page fails after earlier pages succeeded, throw instead of returning a truncated list that could auto-connect the wrong Page. Also revert the IG detail timeout that could wipe the whole connect list.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify Graph pagination helpers and page fetchers.

Bake the first request query into the URL, drop requestKey, and let IncompleteGraphPaginationException bubble from the controllers without catch/rethrow noise.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move incomplete pagination exception under Social\Meta.

Colocate it with GraphPaginator so the Meta scope is clear from the namespace instead of a generic Social exception name.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Rename pagination exception to IncompleteMetaGraphPaginationException.

Keep it under Exceptions/Social with Meta in the class name instead of moving it into Services.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Make GraphPaginator results explicit before mapping pages.

Assign the paginated accounts to a variable first so the Facebook and Instagram-via-Facebook fetchers read more clearly.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Build Meta Graph pagination URLs with Laravel Uri.

Replace manual http_build_query concatenation with Uri::of()->withQuery().

Co-authored-by: Cursor <cursoragent@cursor.com>

* Use Laravel HTTP and Uri helpers in Meta Graph pagination.

Prefer response collect/json key access, filled(), and Uri path parsing over manual array and parse_url handling.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify graphVersion using Uri path and str().

Drop basename and native string casts; Uri::path() already yields the Graph API version segment.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Drop unnecessary str() around graph API config.

Uri: :of() already accepts the string returned by config().
Co-authored-by: Cursor <cursoragent@cursor.com>

* Simplify GraphPaginator with Laravel helpers.

Consolidate failure handling via abort(), and use collect, when, throw_if, and Uri::value() for a shorter pagination loop.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Refactor social OAuth page/channel selection handling. Update selectPage and selectChannel methods in Facebook, Instagram, and YouTube controllers to return popup callbacks instead of redirecting on session expiration or workspace not found. Enhance HandleInertiaRequests middleware to prevent deferring onboarding progress on social OAuth popup routes. Add tests to verify behavior for expired sessions and onboarding progress.

* Unify Instagram connect behind one card with a method picker.

Hide the Instagram-via-Facebook grid card and offer Instagram Login vs Facebook Pages from a single network entry, matching LinkedIn.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Move social popup onboarding assertions into connection tests.

Cover the deferred-prop popup regression on Facebook, Instagram, and YouTube select routes instead of a synthetic onboarding share check.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Stop suppressing onboarding defer on all social routes.

Override onboardingProgress only in popupCallback so picker pages stay deferred and the close page does not re-hit select after session clear.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Always open the Instagram method dialog on connect.

Drop connectMethods and the single-method OAuth shortcut; the picker always offers both Login and Facebook Pages.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Filter Instagram dialog options by enabled platforms.

Keep always opening the method picker, but only list OAuth entry points that are turned on.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Extract Instagram connect methods into a dedicated helper.

Keep connectableOptions focused on shaping grid options while the enabled OAuth list lives in instagramConnectMethods().

Co-authored-by: Cursor <cursoragent@cursor.com>

* Harden Meta Graph pagination and localize Instagram connect copy.

Fail closed on Graph request errors and pathological paging, keep Instagram connect going when profile detail lookups time out, and translate the Instagram method dialog strings.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-08 12:01:46 -03:00

384 lines
14 KiB
PHP

<?php
declare(strict_types=1);
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status;
use App\Enums\UserWorkspace\Role;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Facades\Http;
use Inertia\Testing\AssertableInertia;
use Laravel\Socialite\Facades\Socialite;
use Laravel\Socialite\Two\User as SocialiteUser;
beforeEach(function () {
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create(['user_id' => $this->user->id]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->workspace->members()->attach($this->user->id, ['role' => Role::Member->value]);
});
test('youtube connect redirects to oauth provider', function () {
$driverMock = Mockery::mock();
$driverMock->shouldReceive('scopes')->andReturnSelf();
$driverMock->shouldReceive('with')->andReturnSelf();
$driverMock->shouldReceive('redirect')->andReturn(Mockery::mock([
'getTargetUrl' => 'https://accounts.google.com/o/oauth2/v2/auth?test=1',
]));
Socialite::shouldReceive('driver')
->with('google')
->andReturn($driverMock);
$response = $this->actingAs($this->user)
->withHeader('X-Inertia', 'true')
->get(route('app.social.youtube.connect'));
$response->assertStatus(409); // Inertia::location returns 409 with X-Inertia header
expect(session('social_connect_workspace'))->toBe($this->workspace->id);
});
test('youtube oauth callback creates account with single channel', function () {
session([
'social_connect_workspace' => $this->workspace->id,
]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('google_user_123');
$socialiteUser->token = 'test-access-token';
$socialiteUser->refreshToken = 'test-refresh-token';
$socialiteUser->expiresIn = 3600;
Socialite::shouldReceive('driver')
->with('google')
->andReturn(Mockery::mock([
'user' => $socialiteUser,
]));
Http::fake([
'https://www.googleapis.com/youtube/v3/channels*' => Http::response([
'items' => [
[
'id' => 'UC_channel_123',
'snippet' => [
'title' => 'My YouTube Channel',
'description' => 'Channel description',
'customUrl' => '@mychannel',
'thumbnails' => [
'default' => ['url' => null],
],
],
'statistics' => [
'subscriberCount' => 1000,
],
],
],
], 200),
]);
$response = $this->actingAs($this->user)->get(route('app.social.youtube.callback'));
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page->component('accounts/PopupCallback'));
$response->assertInertia(fn (AssertableInertia $page) => $page->where('success', true));
$this->assertDatabaseHas('social_accounts', [
'workspace_id' => $this->workspace->id,
'platform' => Platform::YouTube->value,
'platform_user_id' => 'UC_channel_123',
'username' => 'mychannel',
'display_name' => 'My YouTube Channel',
'status' => Status::Connected->value,
]);
});
test('youtube callback redirects to channel selection when multiple channels', function () {
session([
'social_connect_workspace' => $this->workspace->id,
]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('google_user_123');
$socialiteUser->token = 'test-access-token';
$socialiteUser->refreshToken = 'test-refresh-token';
$socialiteUser->expiresIn = 3600;
Socialite::shouldReceive('driver')
->with('google')
->andReturn(Mockery::mock([
'user' => $socialiteUser,
]));
Http::fake([
'https://www.googleapis.com/youtube/v3/channels*' => Http::response([
'items' => [
[
'id' => 'UC_channel_1',
'snippet' => [
'title' => 'Channel 1',
'customUrl' => '@channel1',
'thumbnails' => ['default' => ['url' => null]],
],
'statistics' => ['subscriberCount' => 500],
],
[
'id' => 'UC_channel_2',
'snippet' => [
'title' => 'Channel 2',
'customUrl' => '@channel2',
'thumbnails' => ['default' => ['url' => null]],
],
'statistics' => ['subscriberCount' => 1000],
],
],
], 200),
]);
$response = $this->actingAs($this->user)->get(route('app.social.youtube.callback'));
$response->assertRedirect(route('app.social.youtube.select-channel'));
expect(session('youtube_oauth'))->not->toBeNull();
});
test('youtube callback fails when no channels found', function () {
session([
'social_connect_workspace' => $this->workspace->id,
]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('google_user_123');
$socialiteUser->token = 'test-access-token';
$socialiteUser->refreshToken = 'test-refresh-token';
$socialiteUser->expiresIn = 3600;
Socialite::shouldReceive('driver')
->with('google')
->andReturn(Mockery::mock([
'user' => $socialiteUser,
]));
Http::fake([
'https://www.googleapis.com/youtube/v3/channels*' => Http::response([
'items' => [],
], 200),
]);
$response = $this->actingAs($this->user)->get(route('app.social.youtube.callback'));
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page->where('success', false));
$response->assertInertia(fn (AssertableInertia $page) => $page->where('message', 'No YouTube channels found. Please create a channel first.'));
});
test('youtube callback fails with expired session', function () {
// No session data - simulating expired session
$response = $this->actingAs($this->user)->get(route('app.social.youtube.callback'));
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page->where('success', false));
$response->assertInertia(fn (AssertableInertia $page) => $page->where('message', 'Session expired. Please try again.'));
});
test('user can connect multiple youtube accounts in self-hosted mode', function () {
config()->set('trypost.self_hosted', true);
SocialAccount::factory()->youtube()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => 'UC_channel_123',
]);
session([
'social_connect_workspace' => $this->workspace->id,
]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('google_user_456');
$socialiteUser->token = 'new-access-token';
$socialiteUser->refreshToken = 'new-refresh-token';
$socialiteUser->expiresIn = 3600;
Socialite::shouldReceive('driver')
->with('google')
->andReturn(Mockery::mock([
'user' => $socialiteUser,
]));
Http::fake([
'https://www.googleapis.com/youtube/v3/channels*' => Http::response([
'items' => [
[
'id' => 'UC_another_channel',
'snippet' => [
'title' => 'Another Channel',
'customUrl' => '@anotherchannel',
'thumbnails' => ['default' => ['url' => null]],
],
'statistics' => ['subscriberCount' => 500],
],
],
], 200),
]);
$response = $this->actingAs($this->user)->get(route('app.social.youtube.callback'));
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page->where('success', true));
expect($this->workspace->socialAccounts()->where('platform', Platform::YouTube)->count())->toBe(2);
});
test('youtube callback handles oauth errors gracefully', function () {
session([
'social_connect_workspace' => $this->workspace->id,
]);
$mock = Mockery::mock();
$mock->shouldReceive('user')->andThrow(new Exception('OAuth error'));
Socialite::shouldReceive('driver')
->with('google')
->andReturn($mock);
$response = $this->actingAs($this->user)->get(route('app.social.youtube.callback'));
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page->where('success', false));
$response->assertInertia(fn (AssertableInertia $page) => $page->where('message', 'Error connecting account. Please try again.'));
});
test('youtube channel selection creates account', function () {
session([
'social_connect_workspace' => $this->workspace->id,
'youtube_oauth' => [
'access_token' => 'test-access-token',
'refresh_token' => 'test-refresh-token',
'expires_in' => 3600,
'user_id' => 'google_user_123',
],
]);
Http::fake([
'https://www.googleapis.com/youtube/v3/channels*' => Http::response([
'items' => [
[
'id' => 'UC_channel_123',
'snippet' => [
'title' => 'My YouTube Channel',
'description' => 'Channel description',
'customUrl' => '@mychannel',
'thumbnails' => ['default' => ['url' => null]],
],
'statistics' => ['subscriberCount' => 1000],
],
],
], 200),
]);
$response = $this->actingAs($this->user)->post(route('app.social.youtube.select'), [
'channel_id' => 'UC_channel_123',
]);
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page
->component('accounts/PopupCallback')
->where('success', true)
->where('onboardingProgress', false)
);
$this->assertDatabaseHas('social_accounts', [
'workspace_id' => $this->workspace->id,
'platform' => Platform::YouTube->value,
'platform_user_id' => 'UC_channel_123',
'username' => 'mychannel',
]);
// After connect the session is cleared; PopupCallback sets onboardingProgress
// inline so Inertia does not deferred-reload this select URL into /accounts.
$this->actingAs($this->user)
->get(route('app.social.youtube.select-channel'))
->assertOk()
->assertInertia(fn (AssertableInertia $page) => $page
->component('accounts/PopupCallback')
->where('success', false)
->where('message', __('accounts.popup_callback.session_expired'))
->where('onboardingProgress', false)
);
});
test('youtube select channel returns popup callback when the session expired', function () {
$this->actingAs($this->user)
->get(route('app.social.youtube.select-channel'))
->assertOk()
->assertInertia(fn (AssertableInertia $page) => $page
->component('accounts/PopupCallback')
->where('success', false)
->where('message', __('accounts.popup_callback.session_expired'))
->where('onboardingProgress', false)
);
});
test('youtube channel selection fails with expired session', function () {
// No session data
$response = $this->actingAs($this->user)->post(route('app.social.youtube.select'), [
'channel_id' => 'UC_channel_123',
]);
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page->where('success', false));
$response->assertInertia(fn (AssertableInertia $page) => $page->where('message', 'Session expired. Please try again.'));
});
test('youtube callback shows network_taken when the network is already connected', function () {
config()->set('trypost.self_hosted', false);
SocialAccount::factory()->youtube()->create([
'workspace_id' => $this->workspace->id,
'platform_user_id' => 'UC_existing',
]);
session([
'social_connect_workspace' => $this->workspace->id,
]);
$socialiteUser = Mockery::mock(SocialiteUser::class);
$socialiteUser->shouldReceive('getId')->andReturn('google_user_123');
$socialiteUser->token = 'test-access-token';
$socialiteUser->refreshToken = 'test-refresh-token';
$socialiteUser->expiresIn = 3600;
Socialite::shouldReceive('driver')
->with('google')
->andReturn(Mockery::mock([
'user' => $socialiteUser,
]));
Http::fake([
'https://www.googleapis.com/youtube/v3/channels*' => Http::response([
'items' => [
[
'id' => 'UC_channel_123',
'snippet' => [
'title' => 'My YouTube Channel',
'customUrl' => '@mychannel',
'thumbnails' => ['default' => ['url' => null]],
],
'statistics' => ['subscriberCount' => 1000],
],
],
], 200),
]);
$response = $this->actingAs($this->user)->get(route('app.social.youtube.callback'));
$response->assertOk();
$response->assertInertia(fn (AssertableInertia $page) => $page->component('accounts/PopupCallback'));
$response->assertInertia(fn (AssertableInertia $page) => $page->where('success', false));
$response->assertInertia(fn (AssertableInertia $page) => $page->where('message', __('accounts.popup_callback.network_taken')));
expect($this->workspace->socialAccounts()->where('platform', Platform::YouTube)->count())->toBe(1);
});