trypost/tests/Feature/Onboarding/OnboardingControllerTest.php
Paulo Castellano a1fa897106
Activation checklist + MCP OAuth authorize UX (#239) (#250)
* Wire onboarding activation into Account, observers, and shared Inertia data

Add onboarding casts/hasFinishedOnboarding, AccessToken ObservedBy,
Platform::connectableOptions, Post/SocialAccount onboarding broadcast hooks,
and lazy onboardingResidual share + SharedData types.

* Register onboarding routes and post-checkout activation redirects.

Wire billing processing and the sidebar checklist so owners land on
activation after subscribe, with locale sidebar/uk onboarding strings.

* Align MCP grant usability with onboarding activation checks

Unbound MCP tokens fall back to the user's current workspace and require
createPost so viewer/unscoped grants neither unlock the checklist nor
broadcast onboarding status.

* Require bound MCP workspace for onboarding activation.

Drop current-workspace fallback from usable MCP grants so checklist
detection and broadcasts match Passport token scoping; viewers still
cannot unlock the MCP step.

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

* Harden onboarding review findings and tighten locale strings.

Fix Welcome/Persona/TrackPost suites broken by the activation route reuse
and PostObserver analytics side effects, restore Echo poll fallbacks,
reject unbound MCP grants in tests, and drop unused onboarding.mcp keys.

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

* Remove unused sidebar and MCP authorization locale keys.

Drop dead sidebar menu/theme strings (including the overwritten
workspace label and api_keys nav entry) and unused MCP authorize
app_title/approving copy across all locales.

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

* Fix SetLocale crashing on Passport Symfony OAuth responses.

OAuth errors return a raw Symfony Response without withCookie(); attach
the default locale cookie via headers so authorize no longer 500s.

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

* Prompt OAuth guests to log in before rejecting unknown clients.

MCP Inspector often reuses a stale client_id; validateAuthorizationRequest
was returning invalid_client JSON before the login redirect. Guests now
hit /login first, then client validation runs after authentication.

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

* Render Inertia OAuth authorize errors for browser logins.

After login, Inertia follows the intended authorize URL; raw invalid_client
JSON broke that visit. HTML/Inertia requests now get mcp/AuthorizeError
while API JSON clients still receive the OAuth error payload.

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

* Detect Inertia OAuth error pages via Request::inertia().

Use the framework helper so post-login authorize failures keep returning
an Inertia page instead of raw OAuth JSON.

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

* Simplify OAuth authorize error page detection to expectsJson.

Drop the X-Inertia header sniff; browser and Inertia visits already do
not expectsJson, while API clients still receive the OAuth JSON payload.

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

* Share MCP authorize layout and drop the error close button.

Keep authorize and authorize-error on the same centered card shell instead of the auth split layout.

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

* Simplify onboarding activation for reviewability and safety.

Use an exists-based MCP check, keep GETs read-only, move sync into
syncAndNotify, clear MCP skips on connect, restrict complete to owners,
and share Echo/poll via one composable.

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

* Move MCP OAuth authorize UX out of the onboarding PR.

Keep the activation checklist focused; OAuth guest/error-page work now
lives on fix/mcp-oauth-authorize-ux.

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

* Fix corrupted French MCP locale after OAuth key cleanup.

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

* Restore MCP OAuth authorize UX onto the onboarding branch.

Keep authorize error page, guest login-before-client validation, and
SetLocale Symfony cookie fix in #250.

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

* Fix OAuth prompt=none redirects and harden onboarding tests.

Keep login_required/consent_required as redirects instead of Inertia,
add regression coverage for owner-only activation, require invite email
confirmation, and align MCP connected apps with the sessions list UI.

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

* Simplify onboarding guards and dedupe viewed analytics.

Introduce isOnboardingOpen / belongsToAccount helpers, collapse
duplicated sync/dispatch paths, and capture onboarding.viewed once
per account.

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

* Simplify onboarding event, observers, and status helpers.

Tighten Account onboarding predicates, drop nullable broadcast/dispatch
APIs, and collapse repeated observer/controller guards.

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

* Treat in-app users as always having an account.

Add resolveAccount(), tighten belongsToAccount to string ids, and fold
guest residual handling into ResolveOnboardingStatus.

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

* Rename onboarding residual share test to progress.

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

* Simplify onboarding status and rename residual to progress.

Use accountOrFail, extract MCP onboarding scope, auto-leave the ready
screen, and send non-onboarding checkout back to accounts.

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

* Extract HasAccount and prefer data_get in onboarding flows.

Move account helpers off User, drop nullable sidebarProgress, and
read OAuth/onboarding payloads with data_get.

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

* Simplify onboarding checks and extract HasOnboarding.

Use Eloquent + policies for MCP/backfill paths, and move account
onboarding helpers into a dedicated trait.

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

* Add trait tests and tidy onboarding imports.

Cover HasAccount and HasOnboarding under Models/Traits, prefer filled() for checkout session ids, and import Throwable instead of FQCN.

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

* Simplify checkout session_id and OAuth error props.

Read session_id via request->string(), and take OAuth error details from the League exception instead of decoding the response body.

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

* Simplify PostObserver onboarding notify path.

Share one otherPosts check for first-create and last-delete instead of separate callbacks.

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

* Use post author as onboarding sync actor.

Drop Auth::user() preference in PostObserver; checklist sync attributes to $post->user.

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

* Simplify SocialAccountObserver and OAuth authorize flow.

Share create/delete onboarding notify, drop Auth actor fallback to owner, and inline Passport Inertia error handling.

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

* Use lazy Inertia props for onboarding partial reloads.

Drop partial-header branching; wrap page props in closures and always redirect completed/dismissed accounts to the calendar.

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

* Defer sidebar onboarding progress and stamp completion as owner-only.

Skip the MCP checklist work on full Inertia visits via deferred shared props,
early-exit token scans, and keep account completion stamps owner-gated.

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

* Simplify deferred onboarding progress share via canShowProgress.

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

* Add User firstName for shared auth and simplify onboarding page.

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

* Move User firstName coverage into UserTest.

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

* Use first_name directly without empty-name fallbacks.

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

* Resolve onboarding sample prompt on the frontend via i18n.

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

* Stamp onboarding completion via the account owner after teammate unlocks.

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

* Count only the account owner MCP grant toward onboarding activation.

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

* Fix OAuth consent auth-token mismatch for mid-activation owners.

Skip deferred onboardingProgress on Passport authorize so Inertia does not
rotate the session authToken, cover happy and stale-token paths in tests,
and polish MCP setup copy plus sidebar/onboarding layout.

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

* Keep users on onboarding after activation completes.

Stamp completion and re-render the finished checklist instead of
redirecting to the calendar so owners can review the done state.

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

* Clarify Passport consent-view opt-out and guard app-route deferral.

Rename the authorize-only route check and assert onboardingProgress still
defers on calendar, onboarding, and MCP settings.

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

* Harden onboarding completion and MCP consent workspace binding.

Reject OAuth approve without a workspace, retry auto-complete until
stamped, send dismissed complete straight to calendar, and cover the
device consent defer opt-out.

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

* Enable activation checklist for self-hosted installs.

Remove the self-hosted onboarding redirects, keep the SaaS-only dismiss backfill, and cover subscription-less owners plus skip/complete destinations.

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

* Add GitHub, Hacker News, and directories referral sources.

Expand the welcome referral step with open-source and directory discovery channels.

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

* Refine welcome referral sources and labels.

Split Instagram/Threads, add Founder, and shorten Google, GitHub, AI, and blog option labels.

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

* Sort accounts platforms alphabetically and drop connect hover plus.

Reuse connectableOptions for the accounts index and remove the unused plus badge on disconnected cards.

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

* Centralize PostHog once-capture so disabled installs don't burn dedupe keys.

Move isEnabled + Cache::add into PostHogService::captureOnce and route onboarding viewed/step events through it.

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

* Simplify onboarding backfill to complete every existing open account.

Drop self-hosted and subscription filters; down clears completed_at again.

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

* Drop PostHog captureOnce and use plain capture for onboarding.

Remove cache-based event dedupe; callers rely on PostHogService::capture gating.

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

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-07 20:34:43 -03:00

644 lines
23 KiB
PHP

<?php
declare(strict_types=1);
use App\Enums\PostHog\OnboardingEvent;
use App\Enums\SocialAccount\Platform;
use App\Enums\UserWorkspace\Role;
use App\Events\OnboardingStatusUpdated;
use App\Jobs\PostHog\SendEvent;
use App\Models\AccessToken;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Bus;
use Illuminate\Support\Facades\Event;
beforeEach(function () {
config([
'trypost.self_hosted' => false,
'services.posthog.enabled' => true,
'services.posthog.api_key' => 'phc_test',
]);
Bus::fake();
$this->user = User::factory()->create();
$this->workspace = Workspace::factory()->create([
'account_id' => $this->user->account_id,
'user_id' => $this->user->id,
]);
$this->user->update(['current_workspace_id' => $this->workspace->id]);
$this->user->refresh();
subscribeAccount($this->user->account);
});
test('onboarding renders activation status and connection props', function () {
$socialAccount = SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]);
$this->actingAs($this->user)
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->component('onboarding/Index', false)
->where('status.mcp_connected', false)
->where('status.social_connected', true)
->where('status.first_post_created', false)
->where('status.all_complete', false)
->where('status.show_progress', true)
->where('status.completed_at', null)
->where('status.dismissed_at', null)
->where('mcpUrl', route('mcp.trypost'))
->where('canSkipSteps', true)
->where('canManageAccounts', true)
->where('canCreatePost', true)
->missing('mcpClients')
->missing('samplePrompt')
->has('platforms', collect(Platform::cases())->filter->isConnectable()->count())
->where('accounts.0.id', $socialAccount->id)
->where('auth.user.first_name', $this->user->firstName())
);
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => $event->method === 'capture'
&& data_get($event->payload, 'distinctId') === $this->user->id
&& data_get($event->payload, 'event') === OnboardingEvent::Viewed->value);
});
test('onboarding flags the social step when only a sibling workspace is connected', function () {
$otherWorkspace = Workspace::factory()->create([
'account_id' => $this->user->account_id,
'user_id' => $this->user->id,
]);
SocialAccount::factory()->create(['workspace_id' => $otherWorkspace->id]);
$this->actingAs($this->user)
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->where('status.social_connected', true)
->where('accounts', [])
->missing('socialConnectedElsewhere')
);
});
test('onboarding does not flag social elsewhere when the current workspace is connected', function () {
SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);
$this->actingAs($this->user)
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->where('status.social_connected', true)
->missing('socialConnectedElsewhere')
);
});
test('onboarding partial reload refreshes status and accounts', function () {
$response = $this->actingAs($this->user)
->get(route('app.onboarding'))
->assertOk();
$response->assertInertia(fn ($page) => $page
->reloadOnly(['status', 'accounts', 'onboardingProgress'], fn ($reload) => $reload
->has('status')
->has('accounts')
)
);
});
test('a member visit does not capture onboarding viewed', function () {
Bus::fake();
$member = User::factory()->create([
'account_id' => $this->user->account_id,
'current_workspace_id' => $this->workspace->id,
]);
$this->workspace->members()->attach($member->id, ['role' => Role::Member->value]);
$this->actingAs($member->fresh())
->get(route('app.onboarding'))
->assertOk();
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Viewed->value,
);
$this->actingAs($this->user->fresh())
->get(route('app.onboarding'))
->assertOk();
Bus::assertDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Viewed->value,
);
});
test('onboarding does not capture viewed when the checklist is already complete', function () {
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
Bus::fake();
$this->actingAs($this->user->fresh())
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->where('status.all_complete', true)
->where('status.completed_at', null));
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Viewed->value,
);
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Completed->value,
);
});
test('owner can skip the mcp step', function () {
Carbon::setTestNow('2026-07-24 12:00:00');
Event::fake([OnboardingStatusUpdated::class]);
$this->actingAs($this->user)
->post(route('app.onboarding.mcp.skip'))
->assertRedirect();
expect($this->user->account->fresh()->onboarding_skipped_steps)->toBe(['mcp']);
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::StepSkipped->value
&& data_get($event->payload, 'properties.step') === 'mcp');
Event::assertDispatched(
OnboardingStatusUpdated::class,
fn (OnboardingStatusUpdated $event): bool => $event->workspaceId === $this->workspace->id,
);
});
test('skipping the last open step completes the onboarding', function () {
Carbon::setTestNow('2026-07-24 12:00:00');
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
$this->actingAs($this->user)
->post(route('app.onboarding.mcp.skip'))
->assertRedirect();
expect($this->user->account->fresh()->onboarding_completed_at?->equalTo(now()))->toBeTrue();
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Completed->value);
});
test('skipping an already connected step is a no-op', function () {
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.mcp.skip'))
->assertRedirect();
expect($this->user->account->fresh()->onboarding_skipped_steps)->toBeNull();
});
test('skipping the same step twice is a no-op', function () {
$this->actingAs($this->user)
->post(route('app.onboarding.mcp.skip'));
Bus::fake();
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.mcp.skip'))
->assertRedirect();
expect($this->user->account->fresh()->onboarding_skipped_steps)->toBe(['mcp']);
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::StepSkipped->value,
);
});
test('dismissed accounts are redirected away from onboarding index', function () {
Carbon::setTestNow('2026-07-29 12:00:00');
$this->user->account->forceFill(['onboarding_dismissed_at' => now()])->save();
Bus::fake();
$this->actingAs($this->user->fresh())
->get(route('app.onboarding'))
->assertRedirect(route('app.calendar'));
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Viewed->value,
);
});
test('completed accounts can still view the finished onboarding checklist', function () {
Carbon::setTestNow('2026-07-29 12:00:00');
$this->user->account->forceFill(['onboarding_completed_at' => now()])->save();
Bus::fake();
$this->actingAs($this->user->fresh())
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->component('onboarding/Index', false)
->where('status.all_complete', true)
->where('status.completed_at', now()->toIso8601String())
);
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Viewed->value,
);
});
test('partial reload refreshes status and accounts while onboarding is open', function () {
$response = $this->actingAs($this->user)
->get(route('app.onboarding'))
->assertOk();
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
$response->assertInertia(fn ($page) => $page
->reloadOnly(['status', 'accounts', 'onboardingProgress'], fn ($reload) => $reload
->where('status.social_connected', true)
->has('accounts', 1)
->missing('platforms')
)
);
});
test('ready state renders without stamping completion on GET', function () {
Carbon::setTestNow('2026-07-29 12:00:00');
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
Bus::fake();
// Steps are done but completed_at stays null until POST complete / observers.
$this->actingAs($this->user->fresh())
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->component('onboarding/Index', false)
->where('status.all_complete', true)
->where('status.completed_at', null)
);
expect($this->user->account->fresh()->onboarding_completed_at)->toBeNull();
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Viewed->value,
);
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Completed->value,
);
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::StepCompleted->value,
);
});
test('skip step after completion is a no-op', function () {
Carbon::setTestNow('2026-07-29 12:00:00');
Event::fake([OnboardingStatusUpdated::class]);
$this->user->account->forceFill(['onboarding_completed_at' => now()])->save();
Bus::fake();
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.mcp.skip'))
->assertRedirect();
expect($this->user->account->fresh()->onboarding_skipped_steps)->toBeNull();
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::StepSkipped->value,
);
Event::assertNotDispatched(OnboardingStatusUpdated::class);
});
test('onboarding cannot be completed before every activation step', function () {
$this->actingAs($this->user)
->post(route('app.onboarding.complete'))
->assertRedirect(route('app.onboarding'));
expect($this->user->account->fresh()->onboarding_completed_at)->toBeNull();
Bus::assertNotDispatched(SendEvent::class, fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Completed->value);
});
test('onboarding completes after every activation step', function () {
Carbon::setTestNow('2026-07-24 12:00:00');
Event::fake([OnboardingStatusUpdated::class]);
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.complete'))
->assertRedirect(route('app.onboarding'));
expect($this->user->account->fresh()->onboarding_completed_at?->equalTo(now()))->toBeTrue();
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Completed->value);
Event::assertDispatched(
OnboardingStatusUpdated::class,
fn (OnboardingStatusUpdated $event): bool => $event->workspaceId === $this->workspace->id,
);
});
test('onboarding complete does not re-fire completed when already stamped', function () {
Carbon::setTestNow('2026-07-24 12:00:00');
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
$this->user->account->forceFill(['onboarding_completed_at' => now()])->save();
Bus::fake();
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.complete'))
->assertRedirect(route('app.onboarding'));
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Completed->value,
);
});
test('members do not see the skip control', function () {
$member = User::factory()->create(['account_id' => $this->user->account_id]);
$this->workspace->members()->attach($member->id, [
'role' => Role::Member->value,
]);
$member->update(['current_workspace_id' => $this->workspace->id]);
$this->actingAs($member->fresh())
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->where('canSkipSteps', false)
->where('canManageAccounts', false)
->where('canCreatePost', true));
});
test('viewers cannot manage social accounts or create posts from onboarding', function () {
$viewer = User::factory()->create(['account_id' => $this->user->account_id]);
$this->workspace->members()->attach($viewer->id, [
'role' => Role::Viewer->value,
]);
$viewer->update(['current_workspace_id' => $this->workspace->id]);
$this->actingAs($viewer->fresh())
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->where('canSkipSteps', false)
->where('canManageAccounts', false)
->where('canCreatePost', false)
// MCP setup stays visible even without createPost — only write CTAs are gated.
->where('mcpUrl', route('mcp.trypost')));
});
test('only the account owner can skip onboarding steps', function (Role $role) {
$teammate = User::factory()->create(['account_id' => $this->user->account_id]);
$this->workspace->members()->attach($teammate->id, [
'role' => $role->value,
]);
$teammate->update(['current_workspace_id' => $this->workspace->id]);
$this->actingAs($teammate->fresh())
->post(route('app.onboarding.mcp.skip'))
->assertForbidden();
expect($this->user->account->fresh()->onboarding_skipped_steps)->toBeNull();
})->with([
'member' => Role::Member,
'viewer' => Role::Viewer,
]);
test('teammates cannot stamp completion via the complete endpoint', function (Role $role) {
Carbon::setTestNow('2026-07-29 12:00:00');
Event::fake([OnboardingStatusUpdated::class]);
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
$teammate = User::factory()->create(['account_id' => $this->user->account_id]);
$this->workspace->members()->attach($teammate->id, [
'role' => $role->value,
]);
$teammate->update(['current_workspace_id' => $this->workspace->id]);
$this->actingAs($teammate->fresh())
->post(route('app.onboarding.complete'))
->assertForbidden();
expect($this->user->account->fresh()->onboarding_completed_at)->toBeNull();
Event::assertNotDispatched(OnboardingStatusUpdated::class);
})->with([
'member' => Role::Member,
'viewer' => Role::Viewer,
]);
test('owner stamps completion via the complete endpoint for every workspace', function () {
Carbon::setTestNow('2026-07-29 12:00:00');
Event::fake([OnboardingStatusUpdated::class]);
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
$otherWorkspace = Workspace::factory()->create([
'account_id' => $this->user->account_id,
'user_id' => $this->user->id,
]);
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.complete'))
->assertRedirect(route('app.onboarding'));
expect($this->user->account->fresh()->onboarding_completed_at?->equalTo(now()))->toBeTrue();
Event::assertDispatched(
OnboardingStatusUpdated::class,
fn (OnboardingStatusUpdated $event): bool => $event->workspaceId === $this->workspace->id,
);
Event::assertDispatched(
OnboardingStatusUpdated::class,
fn (OnboardingStatusUpdated $event): bool => $event->workspaceId === $otherWorkspace->id,
);
});
test('complete stamps when activation finished on another workspace', function () {
Carbon::setTestNow('2026-07-29 12:00:00');
Event::fake([OnboardingStatusUpdated::class]);
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
$emptyWorkspace = Workspace::factory()->create([
'account_id' => $this->user->account_id,
'user_id' => $this->user->id,
]);
$this->user->update(['current_workspace_id' => $emptyWorkspace->id]);
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.complete'))
->assertRedirect(route('app.onboarding'));
expect($this->user->account->fresh()->onboarding_completed_at?->equalTo(now()))->toBeTrue();
});
test('complete after dismiss redirects to calendar without stamping completion', function () {
Carbon::setTestNow('2026-07-24 12:00:00');
AccessToken::withoutEvents(fn () => mcpAccessToken($this->user, mcpOauthClient(), $this->workspace));
SocialAccount::withoutEvents(fn () => SocialAccount::factory()->create([
'workspace_id' => $this->workspace->id,
]));
Post::withoutEvents(fn () => Post::factory()->create([
'workspace_id' => $this->workspace->id,
'user_id' => $this->user->id,
]));
$this->user->account->forceFill(['onboarding_dismissed_at' => now()])->save();
Bus::fake();
$this->actingAs($this->user->fresh())
->post(route('app.onboarding.complete'))
->assertRedirect(route('app.calendar'));
expect($this->user->account->fresh()->onboarding_completed_at)->toBeNull();
Bus::assertNotDispatched(
SendEvent::class,
fn (SendEvent $event): bool => data_get($event->payload, 'event') === OnboardingEvent::Completed->value,
);
});
test('unsubscribed accounts are redirected to welcome by middleware', function (string $routeName, string $method, array|string $params = []) {
$this->user->account->subscriptions()->delete();
$this->actingAs($this->user->fresh());
$response = $method === 'get'
? $this->get(route($routeName, $params))
: $this->post(route($routeName, $params));
$response->assertRedirect(route('app.welcome.persona'));
})->with([
'index' => ['app.onboarding', 'get'],
'skip step' => ['app.onboarding.mcp.skip', 'post'],
'complete' => ['app.onboarding.complete', 'post'],
]);
test('self hosted activation endpoints remain available', function (string $routeName, string $method, array|string $params = []) {
config(['trypost.self_hosted' => true]);
$this->actingAs($this->user);
$response = $method === 'get'
? $this->get(route($routeName, $params))
: $this->post(route($routeName, $params));
if ($method === 'get') {
$response->assertOk()
->assertInertia(fn ($page) => $page->component('onboarding/Index', false));
return;
}
// Must not bounce to calendar (the old self-hosted gate).
expect($response->headers->get('Location'))->not->toBe(route('app.calendar'));
if ($routeName === 'app.onboarding.mcp.skip') {
$response->assertRedirect();
expect($this->user->account->fresh()->onboarding_skipped_steps)->toBe(['mcp']);
return;
}
// Incomplete checklist: stay on onboarding (same as SaaS).
$response->assertRedirect(route('app.onboarding'));
})->with([
'index' => ['app.onboarding', 'get'],
'skip step' => ['app.onboarding.mcp.skip', 'post'],
'complete' => ['app.onboarding.complete', 'post'],
]);
test('self hosted owners can open onboarding without a subscription', function () {
config(['trypost.self_hosted' => true]);
$this->user->account->subscriptions()->delete();
expect($this->user->account->fresh()->hasAppAccess())->toBeTrue();
$this->actingAs($this->user->fresh())
->get(route('app.onboarding'))
->assertOk()
->assertInertia(fn ($page) => $page
->component('onboarding/Index', false)
->where('status.show_progress', true)
);
});