2026-08-06 14:34:50 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
declare(strict_types=1);
|
|
|
|
|
|
|
|
|
|
use App\Actions\Billing\StartSubscriptionCheckout;
|
|
|
|
|
use App\Enums\Plan\Slug;
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
use App\Enums\PostHog\CheckoutEvent;
|
2026-08-06 14:34:50 +00:00
|
|
|
use App\Enums\PostHog\WelcomeEvent;
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
use App\Enums\SocialAccount\Platform as SocialPlatform;
|
|
|
|
|
use App\Enums\SocialAccount\Status;
|
2026-08-06 14:34:50 +00:00
|
|
|
use App\Enums\User\Goal;
|
|
|
|
|
use App\Enums\User\Persona;
|
|
|
|
|
use App\Enums\User\ReferralSource;
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
use App\Enums\UserWorkspace\Role;
|
|
|
|
|
use App\Enums\Workspace\ContentLanguage;
|
2026-08-06 14:34:50 +00:00
|
|
|
use App\Jobs\PostHog\SendEvent;
|
|
|
|
|
use App\Models\Account;
|
|
|
|
|
use App\Models\Plan;
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
use App\Models\SocialAccount;
|
2026-08-06 14:34:50 +00:00
|
|
|
use App\Models\User;
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
use App\Models\Workspace;
|
|
|
|
|
use App\Services\PostHogService;
|
2026-08-06 14:34:50 +00:00
|
|
|
use Illuminate\Support\Facades\Bus;
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
use Illuminate\Support\Facades\Exceptions;
|
2026-08-06 14:34:50 +00:00
|
|
|
use Illuminate\Support\Facades\Route;
|
|
|
|
|
|
|
|
|
|
beforeEach(function () {
|
|
|
|
|
config(['trypost.self_hosted' => false]);
|
|
|
|
|
$this->user = User::factory()->create();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('welcome redirects to the persona step', function () {
|
|
|
|
|
$this->actingAs($this->user)
|
|
|
|
|
->get(route('app.welcome'))
|
|
|
|
|
->assertRedirect(route('app.welcome.persona'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('persona renders for an unsubscribed account', function () {
|
|
|
|
|
$this->actingAs($this->user)
|
|
|
|
|
->get(route('app.welcome.persona'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page
|
|
|
|
|
->component('welcome/Persona', false)
|
|
|
|
|
->has('personas', count(Persona::cases()))
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('persona requires a valid selection', function (array $payload) {
|
|
|
|
|
$this->actingAs($this->user)
|
|
|
|
|
->post(route('app.welcome.persona.store'), $payload)
|
|
|
|
|
->assertSessionHasErrors('persona');
|
|
|
|
|
|
|
|
|
|
expect($this->user->fresh()->persona)->toBeNull();
|
|
|
|
|
})->with([
|
|
|
|
|
'missing' => [[]],
|
|
|
|
|
'invalid' => [['persona' => 'not-a-persona']],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('persona store saves the selection mirrors it to PostHog and advances to goals', function () {
|
|
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user)
|
|
|
|
|
->post(route('app.welcome.persona.store'), ['persona' => Persona::Agency->value])
|
|
|
|
|
->assertRedirect(route('app.welcome.goals'));
|
|
|
|
|
|
|
|
|
|
expect($this->user->fresh()->persona)->toBe(Persona::Agency);
|
|
|
|
|
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => $event->method === 'capture'
|
|
|
|
|
&& data_get($event->payload, 'distinctId') === $this->user->id
|
|
|
|
|
&& data_get($event->payload, 'event') === WelcomeEvent::Persona->value
|
|
|
|
|
&& data_get($event->payload, 'properties.persona') === Persona::Agency->value);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('goals redirects to persona until a persona is selected', function () {
|
|
|
|
|
$this->actingAs($this->user)
|
|
|
|
|
->get(route('app.welcome.goals'))
|
|
|
|
|
->assertRedirect(route('app.welcome.persona'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('goals renders after a persona is selected', function () {
|
|
|
|
|
$this->user->update(['persona' => Persona::Agency->value]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.goals'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page
|
|
|
|
|
->component('welcome/Goals', false)
|
|
|
|
|
->has('goals', count(Goal::cases()))
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('goals requires at least one valid goal', function (array $goals, string $error) {
|
|
|
|
|
$this->user->update(['persona' => Persona::Agency->value]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.goals.store'), ['goals' => $goals])
|
|
|
|
|
->assertSessionHasErrors($error);
|
|
|
|
|
|
|
|
|
|
expect($this->user->fresh()->goals)->toBeNull();
|
|
|
|
|
})->with([
|
|
|
|
|
'empty' => [[], 'goals'],
|
|
|
|
|
'invalid' => [['not-a-goal'], 'goals.0'],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('goals store saves choices mirrors them to PostHog and advances to referral source', function () {
|
|
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
|
|
|
|
$this->user->update(['persona' => Persona::Creator->value]);
|
|
|
|
|
|
|
|
|
|
$goals = [Goal::AiContent->value, Goal::SaveTime->value];
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.goals.store'), ['goals' => $goals])
|
|
|
|
|
->assertRedirect(route('app.welcome.referral-source'));
|
|
|
|
|
|
|
|
|
|
expect($this->user->fresh()->goals)->toBe($goals);
|
|
|
|
|
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => $event->method === 'capture'
|
|
|
|
|
&& data_get($event->payload, 'event') === WelcomeEvent::Goals->value
|
|
|
|
|
&& data_get($event->payload, 'properties.goals') === $goals);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('completed welcome steps remain reachable when going back', function () {
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
attachCurrentWorkspace($this->user);
|
2026-08-06 14:34:50 +00:00
|
|
|
$this->user->update([
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value],
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
'referral_source' => ReferralSource::Google->value,
|
2026-08-06 14:34:50 +00:00
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.persona'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page->component('welcome/Persona', false));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.goals'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page->component('welcome/Goals', false));
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.referral-source'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page->component('welcome/ReferralSource', false));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.connect'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page->component('welcome/Connect', false));
|
2026-08-06 14:34:50 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('referral source redirects through incomplete prior steps', function (array $attributes, string $routeName) {
|
|
|
|
|
$this->user->update($attributes);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.referral-source'))
|
|
|
|
|
->assertRedirect(route($routeName));
|
|
|
|
|
})->with([
|
|
|
|
|
'missing persona' => [[], 'app.welcome.persona'],
|
|
|
|
|
'missing goals' => [['persona' => Persona::Agency->value], 'app.welcome.goals'],
|
|
|
|
|
'only removed goals' => [
|
|
|
|
|
[
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => ['team_collaboration', 'automate_api', 'track_performance'],
|
|
|
|
|
],
|
|
|
|
|
'app.welcome.goals',
|
|
|
|
|
],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('referral source allows users who still have at least one current goal', function () {
|
|
|
|
|
$this->user->update([
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value, 'team_collaboration'],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.referral-source'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page->component('welcome/ReferralSource', false));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('referral source renders after prior steps are complete', function () {
|
|
|
|
|
$this->user->update([
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.referral-source'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page
|
|
|
|
|
->component('welcome/ReferralSource', false)
|
|
|
|
|
->has('sources', count(ReferralSource::cases()))
|
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 23:34:43 +00:00
|
|
|
->where('sources', fn ($sources): bool => collect($sources)->contains(ReferralSource::GitHub->value)
|
|
|
|
|
&& collect($sources)->contains(ReferralSource::Threads->value)
|
|
|
|
|
&& collect($sources)->contains(ReferralSource::HackerNews->value)
|
|
|
|
|
&& collect($sources)->contains(ReferralSource::Directories->value)
|
|
|
|
|
&& collect($sources)->contains(ReferralSource::Founder->value))
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
->missing('plan')
|
2026-08-06 14:34:50 +00:00
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('referral source requires a valid selection', function (array $payload) {
|
|
|
|
|
$this->user->update([
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.referral-source.store'), $payload)
|
|
|
|
|
->assertSessionHasErrors('referral_source');
|
|
|
|
|
|
|
|
|
|
expect($this->user->fresh()->referral_source)->toBeNull();
|
|
|
|
|
})->with([
|
|
|
|
|
'missing' => [[]],
|
|
|
|
|
'invalid' => [['referral_source' => 'not-a-source']],
|
|
|
|
|
]);
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
test('welcome funnel captures connect between referral and checkout.started', function () {
|
2026-08-06 14:34:50 +00:00
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
|
2026-08-06 14:34:50 +00:00
|
|
|
|
|
|
|
|
Plan::where('slug', Slug::Workspace)->firstOrFail()->update([
|
|
|
|
|
'stripe_monthly_price_id' => 'price_monthly_test',
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)
|
|
|
|
|
->shouldReceive('redirect')
|
|
|
|
|
->once()
|
|
|
|
|
->andReturn(redirect('https://checkout.stripe.test/session'));
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.persona.store'), ['persona' => Persona::Agency->value])
|
|
|
|
|
->assertRedirect(route('app.welcome.goals'));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.goals.store'), ['goals' => [Goal::SaveTime->value]])
|
|
|
|
|
->assertRedirect(route('app.welcome.referral-source'));
|
|
|
|
|
|
2026-08-06 14:34:50 +00:00
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.referral-source.store'), [
|
|
|
|
|
'referral_source' => ReferralSource::ProductHunt->value,
|
|
|
|
|
])
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
->assertRedirect(route('app.welcome.connect'));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
2026-08-06 14:34:50 +00:00
|
|
|
->assertRedirect('https://checkout.stripe.test/session');
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
$funnel = WelcomeEvent::funnel();
|
|
|
|
|
|
|
|
|
|
$captured = collect(Bus::dispatched(SendEvent::class))
|
|
|
|
|
->filter(fn (SendEvent $event): bool => $event->method === 'capture')
|
|
|
|
|
->map(fn (SendEvent $event): string => (string) data_get($event->payload, 'event'))
|
|
|
|
|
->filter(fn (string $event): bool => in_array($event, $funnel, true))
|
|
|
|
|
->values()
|
|
|
|
|
->all();
|
|
|
|
|
|
|
|
|
|
expect($captured)->toBe($funnel);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('referral source store saves the source mirrors it to PostHog and advances to connect', function () {
|
|
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
|
|
|
|
$this->user->update([
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.referral-source.store'), [
|
|
|
|
|
'referral_source' => ReferralSource::ProductHunt->value,
|
|
|
|
|
])
|
|
|
|
|
->assertRedirect(route('app.welcome.connect'));
|
|
|
|
|
|
2026-08-06 14:34:50 +00:00
|
|
|
expect($this->user->fresh()->referral_source)->toBe(ReferralSource::ProductHunt);
|
|
|
|
|
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => $event->method === 'capture'
|
|
|
|
|
&& data_get($event->payload, 'event') === WelcomeEvent::Referral->value
|
|
|
|
|
&& data_get($event->payload, 'properties.referral_source') === ReferralSource::ProductHunt->value);
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
Bus::assertNotDispatched(
|
|
|
|
|
SendEvent::class,
|
|
|
|
|
fn (SendEvent $event): bool => data_get($event->payload, 'event') === CheckoutEvent::Started->value,
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('connect redirects through incomplete prior steps', function (array $attributes, string $routeName, string $method, bool $withWorkspace) {
|
|
|
|
|
$this->user->update($attributes);
|
|
|
|
|
|
|
|
|
|
if ($withWorkspace) {
|
|
|
|
|
attachCurrentWorkspace($this->user);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh());
|
|
|
|
|
|
|
|
|
|
$response = $method === 'get'
|
|
|
|
|
? $this->get(route('app.welcome.connect'))
|
|
|
|
|
: $this->post(route('app.welcome.connect.store'));
|
|
|
|
|
|
|
|
|
|
$response->assertRedirect(route($routeName));
|
|
|
|
|
})->with([
|
|
|
|
|
'get missing persona' => [[], 'app.welcome.persona', 'get'],
|
|
|
|
|
'get missing goals' => [['persona' => Persona::Agency->value], 'app.welcome.goals', 'get'],
|
|
|
|
|
'get missing referral' => [
|
|
|
|
|
[
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value],
|
|
|
|
|
],
|
|
|
|
|
'app.welcome.referral-source',
|
|
|
|
|
'get',
|
|
|
|
|
],
|
|
|
|
|
'post missing persona' => [[], 'app.welcome.persona', 'post'],
|
|
|
|
|
'post missing goals' => [['persona' => Persona::Agency->value], 'app.welcome.goals', 'post'],
|
|
|
|
|
'post missing referral' => [
|
|
|
|
|
[
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value],
|
|
|
|
|
],
|
|
|
|
|
'app.welcome.referral-source',
|
|
|
|
|
'post',
|
|
|
|
|
],
|
|
|
|
|
'get only removed goals' => [
|
|
|
|
|
[
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => ['team_collaboration', 'automate_api', 'track_performance'],
|
|
|
|
|
'referral_source' => ReferralSource::Google->value,
|
|
|
|
|
],
|
|
|
|
|
'app.welcome.goals',
|
|
|
|
|
'get',
|
|
|
|
|
],
|
|
|
|
|
'post only removed goals' => [
|
|
|
|
|
[
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => ['team_collaboration', 'automate_api', 'track_performance'],
|
|
|
|
|
'referral_source' => ReferralSource::Google->value,
|
|
|
|
|
],
|
|
|
|
|
'app.welcome.goals',
|
|
|
|
|
'post',
|
|
|
|
|
],
|
|
|
|
|
])->with([
|
|
|
|
|
'without workspace' => [false],
|
|
|
|
|
'with empty workspace' => [true],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('connect returns 404 when prior steps are complete but the user has no workspace', function () {
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.connect'))
|
|
|
|
|
->assertNotFound();
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->from(route('app.welcome.connect'))
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
|
|
|
|
->assertNotFound();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('connect renders the network grid when the workspace has no accounts', function () {
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
attachCurrentWorkspace($this->user);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.connect'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page
|
|
|
|
|
->component('welcome/Connect', false)
|
|
|
|
|
->has('platforms', count(SocialPlatform::connectableOptions()))
|
|
|
|
|
->where('accounts', [])
|
|
|
|
|
);
|
2026-08-06 14:34:50 +00:00
|
|
|
});
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
test('connect renders connected accounts for the current workspace', function () {
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
$account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.connect'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page
|
|
|
|
|
->component('welcome/Connect', false)
|
|
|
|
|
->has('platforms', count(SocialPlatform::connectableOptions()))
|
|
|
|
|
->has('accounts', 1)
|
|
|
|
|
->where('accounts.0.id', $account->id)
|
|
|
|
|
->where('accounts.0.platform', SocialPlatform::LinkedIn->value)
|
|
|
|
|
->where('accounts.0.status', Status::Connected->value)
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('connect copy exists in every locale', function (string $locale) {
|
|
|
|
|
expect(__('welcome.connect.title', [], $locale))->not->toBe('welcome.connect.title')
|
|
|
|
|
->and(__('welcome.connect.description', [], $locale))->not->toBe('welcome.connect.description')
|
|
|
|
|
->and(__('welcome.connect.required', [], $locale))->not->toBe('welcome.connect.required');
|
|
|
|
|
})->with(ContentLanguage::values());
|
|
|
|
|
|
|
|
|
|
test('connect store requires a connected social account', function () {
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
attachCurrentWorkspace($this->user);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
|
|
|
|
->assertSessionHasErrors('connect');
|
|
|
|
|
|
|
|
|
|
Bus::assertNotDispatched(
|
|
|
|
|
SendEvent::class,
|
|
|
|
|
fn (SendEvent $event): bool => data_get($event->payload, 'event') === WelcomeEvent::Connect->value,
|
|
|
|
|
);
|
|
|
|
|
Bus::assertNotDispatched(
|
|
|
|
|
SendEvent::class,
|
|
|
|
|
fn (SendEvent $event): bool => data_get($event->payload, 'event') === CheckoutEvent::Started->value,
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('connect store rejects disconnected or expired social accounts', function () {
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
SocialAccount::factory()->linkedin()->disconnected()->create(['workspace_id' => $workspace->id]);
|
|
|
|
|
SocialAccount::factory()->x()->tokenExpired()->create(['workspace_id' => $workspace->id]);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
|
|
|
|
->assertSessionHasErrors('connect');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('connect store ignores social accounts on another workspace', function () {
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
attachCurrentWorkspace($this->user);
|
|
|
|
|
|
|
|
|
|
$otherWorkspace = Workspace::factory()->create([
|
|
|
|
|
'account_id' => $this->user->account_id,
|
|
|
|
|
'user_id' => $this->user->id,
|
|
|
|
|
]);
|
|
|
|
|
SocialAccount::factory()->linkedin()->create(['workspace_id' => $otherWorkspace->id]);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
|
|
|
|
->assertSessionHasErrors('connect');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('connect store starts Stripe checkout when a social account is connected', function () {
|
|
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
|
|
|
|
|
|
|
|
|
|
Plan::where('slug', Slug::Workspace)->firstOrFail()->update([
|
|
|
|
|
'stripe_monthly_price_id' => 'price_monthly_test',
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
]);
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
$this->mock(StartSubscriptionCheckout::class)
|
|
|
|
|
->shouldReceive('redirect')
|
|
|
|
|
->once()
|
|
|
|
|
->withArgs(fn (Account $account, string $priceId, string $cancelUrl): bool => $account->is($this->user->account)
|
|
|
|
|
&& $priceId === 'price_monthly_test'
|
|
|
|
|
&& $cancelUrl === route('app.welcome.connect'))
|
|
|
|
|
->andReturn(redirect('https://checkout.stripe.test/session'));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
|
|
|
|
->assertRedirect('https://checkout.stripe.test/session');
|
|
|
|
|
|
|
|
|
|
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => $event->method === 'capture'
|
|
|
|
|
&& data_get($event->payload, 'event') === WelcomeEvent::Connect->value
|
|
|
|
|
&& data_get($event->payload, 'properties.platforms') === [SocialPlatform::LinkedIn->value]);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('connect store captures checkout.started with the plan name and interval', function () {
|
|
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
|
|
|
|
|
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
$plan = Plan::where('slug', Slug::Workspace)->firstOrFail();
|
|
|
|
|
$plan->update(['stripe_monthly_price_id' => 'price_monthly_test']);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)
|
|
|
|
|
->shouldReceive('redirect')
|
|
|
|
|
->once()
|
|
|
|
|
->andReturn(redirect('https://checkout.stripe.test/session'));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
->post(route('app.welcome.connect.store'));
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
|
|
|
|
|
Bus::assertDispatched(SendEvent::class, fn (SendEvent $event): bool => $event->method === 'capture'
|
|
|
|
|
&& data_get($event->payload, 'event') === CheckoutEvent::Started->value
|
|
|
|
|
&& data_get($event->payload, 'properties.plan_name') === $plan->name
|
|
|
|
|
&& data_get($event->payload, 'properties.interval') === 'monthly');
|
|
|
|
|
});
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
test('connect store does not capture checkout.started when Stripe checkout creation fails', function () {
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
|
|
|
|
|
Plan::where('slug', Slug::Workspace)->firstOrFail()->update([
|
|
|
|
|
'stripe_monthly_price_id' => 'price_monthly_test',
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)
|
|
|
|
|
->shouldReceive('redirect')
|
|
|
|
|
->once()
|
|
|
|
|
->andThrow(new RuntimeException('Stripe checkout could not be created.'));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
->post(route('app.welcome.connect.store'));
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
Bus::assertNotDispatched(
|
|
|
|
|
SendEvent::class,
|
|
|
|
|
fn (SendEvent $event): bool => data_get($event->payload, 'event') === WelcomeEvent::Connect->value,
|
|
|
|
|
);
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
Bus::assertNotDispatched(
|
|
|
|
|
SendEvent::class,
|
|
|
|
|
fn (SendEvent $event): bool => data_get($event->payload, 'event') === CheckoutEvent::Started->value,
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
test('connect store still redirects to stripe when posthog capture fails', function () {
|
|
|
|
|
Exceptions::fake();
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
|
|
|
|
|
|
|
|
|
|
Plan::where('slug', Slug::Workspace)->firstOrFail()->update([
|
|
|
|
|
'stripe_monthly_price_id' => 'price_monthly_test',
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)
|
|
|
|
|
->shouldReceive('redirect')
|
|
|
|
|
->once()
|
|
|
|
|
->andReturn(redirect('https://checkout.stripe.test/session'));
|
|
|
|
|
|
|
|
|
|
$this->mock(PostHogService::class)
|
|
|
|
|
->shouldReceive('capture')
|
|
|
|
|
->andThrow(new RuntimeException('PostHog is down.'));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
|
|
|
|
->assertRedirect('https://checkout.stripe.test/session');
|
|
|
|
|
|
|
|
|
|
Exceptions::assertReported(RuntimeException::class);
|
|
|
|
|
});
|
|
|
|
|
|
2026-08-06 14:34:50 +00:00
|
|
|
test('welcome steps redirect to calendar for subscribed accounts', function (string $routeName, string $method, array $payload = []) {
|
|
|
|
|
subscribeAccount($this->user->account);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh());
|
|
|
|
|
|
|
|
|
|
$response = $method === 'get'
|
|
|
|
|
? $this->get(route($routeName))
|
|
|
|
|
: $this->post(route($routeName), $payload);
|
|
|
|
|
|
|
|
|
|
$response->assertRedirect(route('app.calendar'));
|
|
|
|
|
})->with([
|
|
|
|
|
'persona' => ['app.welcome.persona', 'get'],
|
|
|
|
|
'persona store' => ['app.welcome.persona.store', 'post', ['persona' => Persona::Agency->value]],
|
|
|
|
|
'goals' => ['app.welcome.goals', 'get'],
|
|
|
|
|
'goals store' => ['app.welcome.goals.store', 'post', ['goals' => [Goal::SaveTime->value]]],
|
|
|
|
|
'referral source' => ['app.welcome.referral-source', 'get'],
|
|
|
|
|
'referral source store' => ['app.welcome.referral-source.store', 'post', ['referral_source' => ReferralSource::Google->value]],
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
'connect' => ['app.welcome.connect', 'get'],
|
|
|
|
|
'connect store' => ['app.welcome.connect.store', 'post'],
|
2026-08-06 14:34:50 +00:00
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('welcome redirects generic-trial accounts with app access to calendar', function () {
|
|
|
|
|
config(['trypost.billing.require_card_for_trial' => false]);
|
|
|
|
|
|
|
|
|
|
$this->user->account->forceFill([
|
|
|
|
|
'trial_ends_at' => now()->addDays(8),
|
|
|
|
|
])->save();
|
|
|
|
|
|
|
|
|
|
expect($this->user->account->fresh()->hasAppAccess())->toBeTrue()
|
|
|
|
|
->and($this->user->account->fresh()->subscribed(Account::SUBSCRIPTION_NAME))->toBeFalse();
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.persona'))
|
|
|
|
|
->assertRedirect(route('app.calendar'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('welcome steps redirect to calendar in self hosted mode', function (string $routeName, string $method, array $payload = []) {
|
|
|
|
|
config(['trypost.self_hosted' => true]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user);
|
|
|
|
|
|
|
|
|
|
$response = $method === 'get'
|
|
|
|
|
? $this->get(route($routeName))
|
|
|
|
|
: $this->post(route($routeName), $payload);
|
|
|
|
|
|
|
|
|
|
$response->assertRedirect(route('app.calendar'));
|
|
|
|
|
})->with([
|
|
|
|
|
'persona' => ['app.welcome.persona', 'get'],
|
|
|
|
|
'persona store' => ['app.welcome.persona.store', 'post', ['persona' => Persona::Agency->value]],
|
|
|
|
|
'goals' => ['app.welcome.goals', 'get'],
|
|
|
|
|
'goals store' => ['app.welcome.goals.store', 'post', ['goals' => [Goal::SaveTime->value]]],
|
|
|
|
|
'referral source' => ['app.welcome.referral-source', 'get'],
|
|
|
|
|
'referral source store' => ['app.welcome.referral-source.store', 'post', ['referral_source' => ReferralSource::Google->value]],
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
'connect' => ['app.welcome.connect', 'get'],
|
|
|
|
|
'connect store' => ['app.welcome.connect.store', 'post'],
|
2026-08-06 14:34:50 +00:00
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('old onboarding icp routes are not registered', function (string $routeName) {
|
|
|
|
|
expect(Route::has($routeName))->toBeFalse();
|
|
|
|
|
})->with([
|
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 23:34:43 +00:00
|
|
|
// `app.onboarding` is reused for the post-subscription activation checklist.
|
2026-08-06 14:34:50 +00:00
|
|
|
'store' => 'app.onboarding.store',
|
|
|
|
|
'goals' => 'app.onboarding.goals',
|
|
|
|
|
'goals store' => 'app.onboarding.goals.store',
|
|
|
|
|
'referral source' => 'app.onboarding.referral-source',
|
|
|
|
|
'referral source store' => 'app.onboarding.referral-source.store',
|
|
|
|
|
'connect' => 'app.onboarding.connect',
|
|
|
|
|
'checkout' => 'app.onboarding.checkout',
|
|
|
|
|
]);
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
test('members cannot start Stripe checkout from welcome', function (bool $withWorkspace) {
|
2026-08-06 14:34:50 +00:00
|
|
|
$member = User::factory()->create(['account_id' => $this->user->account_id]);
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
completeWelcomeThroughReferral($member);
|
|
|
|
|
|
|
|
|
|
if ($withWorkspace) {
|
|
|
|
|
attachCurrentWorkspace($member);
|
|
|
|
|
}
|
2026-08-06 14:34:50 +00:00
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($member->fresh())
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
->get(route('app.welcome.connect'))
|
2026-08-06 14:34:50 +00:00
|
|
|
->assertRedirect(route('app.welcome.subscription-required'));
|
|
|
|
|
|
|
|
|
|
$this->actingAs($member->fresh())
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
->post(route('app.welcome.connect.store'))
|
2026-08-06 14:34:50 +00:00
|
|
|
->assertRedirect(route('app.welcome.subscription-required'));
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
})->with([
|
|
|
|
|
'without workspace' => [false],
|
|
|
|
|
'with empty workspace' => [true],
|
|
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('subscribed owners skip connect validation and go to calendar', function () {
|
|
|
|
|
subscribeAccount($this->user->account);
|
|
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
attachCurrentWorkspace($this->user);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
2026-08-06 14:34:50 +00:00
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->post(route('app.welcome.connect.store'))
|
|
|
|
|
->assertRedirect(route('app.calendar'));
|
2026-08-06 14:34:50 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('members without app access are held on the subscription required screen', function (string $routeName, string $method, array $payload = []) {
|
|
|
|
|
$member = User::factory()->create(['account_id' => $this->user->account_id]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($member->fresh());
|
|
|
|
|
|
|
|
|
|
$response = $method === 'get'
|
|
|
|
|
? $this->get(route($routeName))
|
|
|
|
|
: $this->post(route($routeName), $payload);
|
|
|
|
|
|
|
|
|
|
$response->assertRedirect(route('app.welcome.subscription-required'));
|
|
|
|
|
})->with([
|
|
|
|
|
'persona' => ['app.welcome.persona', 'get'],
|
|
|
|
|
'persona store' => ['app.welcome.persona.store', 'post', ['persona' => Persona::Agency->value]],
|
|
|
|
|
'goals' => ['app.welcome.goals', 'get'],
|
|
|
|
|
'goals store' => ['app.welcome.goals.store', 'post', ['goals' => [Goal::SaveTime->value]]],
|
|
|
|
|
'referral source' => ['app.welcome.referral-source', 'get'],
|
|
|
|
|
'referral source store' => ['app.welcome.referral-source.store', 'post', ['referral_source' => ReferralSource::Google->value]],
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
'connect' => ['app.welcome.connect', 'get'],
|
|
|
|
|
'connect store' => ['app.welcome.connect.store', 'post'],
|
2026-08-06 14:34:50 +00:00
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
test('subscription required screen renders for members without app access', function () {
|
|
|
|
|
$member = User::factory()->create(['account_id' => $this->user->account_id]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($member->fresh())
|
|
|
|
|
->get(route('app.welcome.subscription-required'))
|
|
|
|
|
->assertOk()
|
|
|
|
|
->assertInertia(fn ($page) => $page
|
|
|
|
|
->component('welcome/SubscriptionRequired', false)
|
|
|
|
|
->where('ownerName', $this->user->name)
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('subscription required screen sends owners back to the welcome flow', function () {
|
|
|
|
|
$this->actingAs($this->user)
|
|
|
|
|
->get(route('app.welcome.subscription-required'))
|
|
|
|
|
->assertRedirect(route('app.welcome.persona'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('subscription required screen sends subscribed users to the calendar', function () {
|
|
|
|
|
subscribeAccount($this->user->account);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
|
|
|
|
->get(route('app.welcome.subscription-required'))
|
|
|
|
|
->assertRedirect(route('app.calendar'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('subscription required screen sends members with app access to the calendar', function () {
|
|
|
|
|
['owner' => $owner, 'member' => $member] = strandedMemberOnSharedAccount();
|
|
|
|
|
subscribeAccount($owner->account);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($member)
|
|
|
|
|
->get(route('app.welcome.subscription-required'))
|
|
|
|
|
->assertRedirect(route('app.calendar'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('subscription required screen redirects to calendar in self hosted mode', function () {
|
|
|
|
|
config(['trypost.self_hosted' => true]);
|
|
|
|
|
|
|
|
|
|
$member = User::factory()->create(['account_id' => $this->user->account_id]);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($member->fresh())
|
|
|
|
|
->get(route('app.welcome.subscription-required'))
|
|
|
|
|
->assertRedirect(route('app.calendar'));
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('welcome sends members with app access to the calendar', function () {
|
|
|
|
|
['owner' => $owner, 'member' => $member] = strandedMemberOnSharedAccount();
|
|
|
|
|
subscribeAccount($owner->account);
|
|
|
|
|
|
|
|
|
|
$this->actingAs($member)
|
|
|
|
|
->get(route('app.welcome.persona'))
|
|
|
|
|
->assertRedirect(route('app.calendar'));
|
|
|
|
|
});
|
|
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
test('connect store fails loudly when the monthly price is not configured', function () {
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test']);
|
|
|
|
|
Bus::fake();
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
completeWelcomeThroughReferral($this->user);
|
|
|
|
|
$workspace = attachCurrentWorkspace($this->user);
|
|
|
|
|
SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id]);
|
2026-08-06 14:34:50 +00:00
|
|
|
Plan::where('slug', Slug::Workspace)->update(['stripe_monthly_price_id' => null]);
|
|
|
|
|
|
|
|
|
|
$this->mock(StartSubscriptionCheckout::class)->shouldNotReceive('redirect');
|
|
|
|
|
|
|
|
|
|
$this->actingAs($this->user->fresh())
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
->post(route('app.welcome.connect.store'))
|
2026-08-06 14:34:50 +00:00
|
|
|
->assertServerError();
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
Bus::assertNotDispatched(
|
|
|
|
|
SendEvent::class,
|
|
|
|
|
fn (SendEvent $event): bool => data_get($event->payload, 'event') === WelcomeEvent::Connect->value,
|
|
|
|
|
);
|
feat: fire signup/checkout PostHog events from the backend (#277)
* feat: fire user.signed_up, checkout.started, checkout.completed from the backend
These 3 PostHog conversion events only fired client-side (useTracking.ts),
so ad blockers and cut-short page unloads could drop them the same way
they were dropping the GTM/ad-platform click IDs. Moves the PostHog side
to the backend, same reliability rationale, same touchpoints already
established for the click-id work:
- user.signed_up: App\Actions\User\CreateUser, right after SyncUser is
dispatched, gated on !is_invite. auth_provider derived from
google_id/github_id presence, same values the frontend session-based
flow used.
- checkout.started: WelcomeController::storeReferralSource, alongside the
existing WelcomeEvent::Referral capture, right before checkout starts.
- checkout.completed: new TrackCheckoutCompleted job, dispatched from
StripeEventListener::handleSubscriptionCreated (webhook-driven — more
reliable than the old frontend flow, which depended on the user staying
on billing/Processing.vue). Conversion value/currency/transaction_id
read from the subscription webhook payload; transaction_id is the
Stripe subscription id rather than the old Checkout Session id.
Two new enums (UserEvent, CheckoutEvent) follow the existing per-domain
PostHog event enum convention (WelcomeEvent, BillingEvent, PostEvent).
useTracking.ts keeps its GTM dataLayer pushes (untouched, separate
concern) and drops only the captureEvent(...) calls for these 3 events —
PostHog already had CreateUser/WelcomeController/StripeEventListener as
established backend touchpoints, so this reuses them instead of adding
new infrastructure.
* chore: remove now-dead GTM dataLayer pushes from useTracking.ts
All 3 conversion events (sign_up, begin_checkout, purchase) now go to
PostHog exclusively from the backend, and PostHog is the single source
feeding Meta/Google/LinkedIn/etc ad destinations (not GTM). The
dataLayer.push(...) calls in useTracking.ts had no consumer left, so the
composable is now fully dead — deleted, along with its 3 call sites.
Each call site's surrounding scaffolding that existed only to support the
tracking call was simplified alongside it: ReferralSource.vue's submit()
no longer needs the onStart/onError/onHttpException/onFinish dance (that
was only there to gate trackBeginCheckout), and Processing.vue's
completePurchase() no longer reads auth.plan just to pass it to
trackPurchase().
datalayer.ts is untouched — it only pushes context variables (user name/
email, account/workspace name) that Crisp reads, not events.
* feat: split checkout.completed into trial.started / checkout.completed / trial.converted
checkout.completed used to fire on every customer.subscription.created
regardless of the resulting status, conflating two different business
events: a card-required trial starting (status trialing, no charge yet)
and an immediate paid subscription starting (status active — first-month
coupon or no trial). These are now separate PostHog events:
- trial.started: subscription created with status trialing. No
conversion_value (nothing has been charged) — carries trial_ends_at
instead.
- checkout.completed: subscription created with status active (coupon or
immediate full-price checkout) — unchanged behavior, still carries
conversion_value/currency/transaction_id.
- trial.converted (new): the trial's first successful charge, detected on
customer.subscription.updated via Stripe's own previous_attributes.status
transitioning from trialing to active. This is the Stripe-recommended way
to detect what changed in an .updated webhook, and doesn't depend on our
own DB write ordering — Cashier's WebhookController dispatches
WebhookReceived before it syncs the local subscription row, so trusting
our own stripe_status here would be fragile.
TrackCheckoutCompleted and the new TrackTrialConverted share their
plan/interval/persona/conversion_* property computation via
App\Support\StripeSubscriptionConversion (same shape, two different
moments in the billing lifecycle) instead of duplicating it.
Deliberately out of scope per product decision: trial-expired-without-
converting tracking (signups minus conversions already gives that number),
and the async-payment-method incomplete status edge case (card/debit only,
Stripe Checkout resolves 3DS inline before redirecting back — incomplete
essentially can't happen in this flow).
* refactor: derive auth_provider from the created User model, not the input array
$user already has google_id/github_id populated (they were passed straight
into User::create() a few lines above), so re-reading them from $data was
redundant — same information, extra indirection.
* fix: OAuth signup silently drops pending invites and bypasses the self-hosted registration gate
Found while reviewing why CreateUser's `! $isInviteRegistration` PostHog
gate never actually excluded anyone via Google/GitHub — because is_invite
was always false for OAuth registrations, regardless of whether the
person arrived from an invite link. Two real, pre-existing bugs:
1. SocialLogin.vue's Google/GitHub buttons linked to the OAuth redirect
routes with no query params at all — invite, redirect and email were
silently dropped the moment someone clicked "Sign up with Google"
instead of using the email form. The person got a brand-new
independent account + workspace instead of joining the inviter's
account; the invite itself sat unaccepted with zero feedback.
2. /auth/google/redirect and /auth/github/redirect were never wrapped in
the `registration.enabled` middleware that gates /register in
self-hosted mode — so self-hosted installs could be signed up into via
OAuth with no invite at all, bypassing the intended lock.
Fix:
- New PreservesInviteRedirect trait carries `invite`/`redirect` across the
OAuth round-trip via session (PreservesAttributionParameters' pattern,
but kept separate since this isn't marketing data).
- SocialLogin.vue now forwards `redirect`/`invite` from its parent page
onto the Google/GitHub links; Register.vue and Login.vue pass their
props through.
- registerNewUser() now passes the same `is_invite` semantics
RegisterRequest already uses for the email flow, and both
registerNewUser()/loginExistingUser() honor the pending redirect (same
target AcceptInvite.vue already sends the email flow to), so accepting
via OAuth now lands back on the invite page authenticated, exactly like
email/password does — no auto-accept, same explicit-consent UX.
- The self-hosted gate can only be enforced in registerNewUser() (after
the callback resolves an identity) since /redirect is shared with
login and can't tell new vs. returning users apart beforehand.
New App\Models\Invite::fromId() (safe UUID-checked lookup) and
App\Support\SafeInternalRedirect (same-app-path-only check) replace
duplicated inline logic in RegisterRequest, RegisteredUserController and
AuthenticatedSessionController, and are now shared with the OAuth path
too.
* refactor: replace client-supplied redirect param with server-resolved invite redirect
Never trust a redirect URL from the client. Login/register/OAuth now only
accept an invite id (already validated via Invite::fromId()) and derive the
return-to-invite route server-side, eliminating the open-redirect surface
instead of validating around it.
* refactor: use Request::string() for invite id, trim comments
Str::isNotEmpty()/toString() replace manual is_string/empty checks.
Also cut oversized inline comments down to one line each.
* refactor: tighten Invite::fromId, drop redundant is_string check
* test: cover GitHub invite acceptance and self-hosted gate scenarios
Mirrors the existing Google coverage — GitHubController has the same
invite-completion and self-hosted-gate logic but only Google had tests for it.
* refactor: fold null-account check into owner_id guard via nullsafe operator
* refactor: dedupe Stripe conversion tracking jobs and properties
TrackCheckoutCompleted, TrackTrialStarted, and TrackTrialConverted shared
near-identical boilerplate (guard clause, capture call, tries/timeout).
Extracted AbstractTrackStripeSubscriptionEvent so each job only declares its
event name and properties. StripeSubscriptionConversion now exposes
baseProperties() (plan_name/interval/persona) shared by all three, with
propertiesFor() adding conversion_* on top for the two charge-backed events.
* refactor: extract named status helpers in StripeEventListener
currentStatus()/wasTrialing()/isNowActive() replace inline data_get()
comparisons in trackSubscriptionStart() and trackTrialConversion().
* refactor: drop redundant persona from Stripe PostHog event properties
Persona is already set as a person property via identify() during
onboarding, so it is joinable on every event without repeating it —
sending it again on every billing capture was dead weight.
* refactor: drop redundant plan property in TrackBilling
PostHogService::capture() already injects 'plan' from $account when an
account is passed — the manual key was silently overwritten by the
identical value.
* feat: log PostHog payloads to laravel.log in local environment
Lets capture()/identify()/groupIdentify() be verified from laravel.log
during local testing (e.g. signup, invite flows) without a real PostHog
API key configured. Logging is independent of isEnabled() — the actual
dispatch to PostHog stays gated on it as before.
* fix: cold-review pass — dead code, ordering bug, missing test coverage
- Fire checkout.started only after the price-ID guard, not before it, so a
misconfigured plan can't record a phantom checkout.started for a checkout
that never starts (WelcomeController).
- Reorder OAuth registerNewUser() so the destructive session pull of
attribution parameters happens after the self-hosted invite gate, not
before — a rejected attempt no longer discards UTM/click-id attribution
(GoogleController, GitHubController).
- Delete the SignupSuccess page/controller/route entirely: it only ever
displayed a 5s cosmetic transition before redirecting home, its tracking
call was already removed, and app.calendar's own middleware handles
onboarding redirects regardless of entry point. The 3 post-registration
redirects now go straight to app.welcome (was silently dropped to
app.home in an earlier pass of this cleanup — welcome is correct, that
was the whole point of the intermediate page).
- Remove dead code left behind by the useTracking.ts removal: unused
persona/conversion props (and the Stripe API call in BillingController
that only existed to populate them), unused auth_provider session flash
across 3 controllers, unused captureEvent() export in posthog.ts, and
unused RegisterRequest::isInviteRegistration().
- Add missing test coverage: login with a valid/unknown invite param
(AuthenticatedSessionController's invite-redirect branch had zero
coverage), and a regression test locking in the checkout.started
ordering fix.
* fix: second cold-review pass — invite email mismatch, stale session leak, null interval bug
- Reject OAuth registration (Google/GitHub) when the invite's email doesn't
match the authenticated provider account's email, mirroring the check
RegisterRequest already enforces for the web form. Previously an invite
for one email could be completed by signing in with a different Google/
GitHub account, leaving a permanently workspace-less orphaned account
(AcceptInvite's WrongEmail path never runs the shell-account cleanup,
since that only fires on Result::Accepted).
- Fix PreservesInvite::storeInvite() to always overwrite the session value
(matching PreservesAttributionParameters, which it claimed to mirror but
didn't). It previously only wrote when the invite param was present,
so a stale invite id from an aborted OAuth attempt could leak into a
later, unrelated login/registration in the same session.
- Fix StripeSubscriptionConversion::baseProperties() mislabeling a
conversion as 'yearly' when both the webhook price id and the plan's
stripe_yearly_price_id are null (null === null) — now requires the plan
price id to be non-null before comparing, matching the equivalent guard
in App\Support\BillingCycle::intervalMonths().
- Remove the fully dead fromCheckout/Cache::add mechanism in
BillingController::processing() — its only consumer (the frontend
trackPurchase call) was already deleted earlier in this PR.
- Drop the unused owner eager-load in AbstractTrackStripeSubscriptionEvent
and TrackBilling — neither reads $account->owner, only owner_id.
* fix: normalize invite email casing at creation; resolve PostHogService via container
- CreateInvite::execute() now lowercases the invite email before storing it.
Invite acceptance/decline/registration all compare it verbatim against
User.email (itself always lowercase), so a mismatched-case invite created
before this fix could otherwise never be accepted by its own recipient.
- CreateUser::execute() resolves PostHogService from the container instead
of `new PostHogService`, matching the DI pattern used by every other
PostHog call site added in this PR.
* fix: validate self-hosted invites against the DB; enforce OAuth provider toggles server-side; count past_due recovery as a trial conversion
- EnsureRegistrationEnabled, GoogleController, and GitHubController now
require the invite param to resolve to a real Invite (Invite::fromId())
instead of just checking presence. Previously any random string/UUID
satisfied the self-hosted "invite required" gate and produced a fully
functional account with its own workspace, defeating the restriction
entirely.
- google_auth_enabled/github_auth_enabled were only ever read on the
frontend to show/hide the login button — the actual OAuth routes
(GoogleController/GitHubController::redirect(), and the settings
connect-provider endpoint) had no backend check, so a disabled provider
could still be used end-to-end by hitting the URL directly. Both are now
gated with abort_unless(..., 404). The settings Authentication page also
stops rendering a "Connect" button for a disabled, not-yet-connected
provider.
- StripeEventListener::trackTrialConversion now also fires trial.converted
on a past_due -> active recovery (a trial's first charge attempt failing
and then succeeding on retry), not just the immediate trialing -> active
transition. Guarded by trial_end being set so a long-time paying
customer's unrelated payment-method recovery is never miscounted as a
trial conversion.
* refactor: merge the two connectProvider abort_unless checks into one
* refactor: centralize social auth providers in a SocialAuthProvider enum
google/github were each hand-checked against config("trypost.{provider}_auth_enabled")
independently in GoogleController, GitHubController, AuthenticationController
(3 different shapes: hardcoded config key, in_array against a private const
array, and a duplicated string list for labels), plus a fourth copy of the
enabled flags in HandleInertiaRequests. Adding a provider meant touching all
of them by hand.
App\Enums\Auth\SocialAuthProvider is now the single source of truth: cases()
replaces the PROVIDERS const array everywhere it was iterated, label()
replaces the hand-written label map, and isEnabled() replaces every direct
config() call. AuthenticationController::connectProvider() collapses its two
abort_unless checks into one via tryFrom()?->isEnabled().
* refactor: add User::isConnectedTo() and drop the manual foreach in canDisconnect()
The same "{$provider}_id" dynamic-property pattern was hand-written in three
places in AuthenticationController (disconnectProvider's column lookup,
getConnectedAccounts' connected flag, canDisconnect's loop). User::isConnectedTo()
centralizes it, and canDisconnect() now reads as a single collection pipeline
("is there some other connected provider or a password") instead of a
counter-then-compare loop. disconnectProvider() also switches to the
already-resolved SocialAuthProvider throughout instead of re-deriving from
the raw string, and its flash message now uses ->label() instead of
ucfirst($provider) (which mis-cased "github" as "Github" instead of "GitHub").
* refactor: remove the fixed 5s post-checkout redirect delay
REDIRECT_DELAY_MS existed to give a client-side PostHog/ad-pixel capture
call time to flush before navigating away. That call was removed earlier in
this PR (checkout.completed now fires from the Stripe webhook, server-side,
independent of this page), so the delay had nothing left to wait for —
navigate immediately once the poll confirms subscriptionActive.
* refactor: extract SocialProvider type instead of repeating the 'google' | 'github' union
* fix: Login.vue never displayed session-flashed email errors
GoogleController/GitHubController flash OAuth failures (wrong invite email,
GitHub email unavailable) via redirect()->route('login')->withErrors([...]).
That lands as page.props.errors (Inertia's page-level error bag), not as
the <Form> component's own local submission errors — so the InputError
bound to errors.email never showed it, silently swallowing the redirect's
whole point. Falls back to usePageErrors() (already used elsewhere in the
app for this exact scenario) when the form's own errors are empty.
* test: add a browser test for the Login.vue flashed-error display fix
Pest feature tests can only assert session state, not what actually renders
— this drives a real browser through the OAuth invite-email-mismatch
redirect and asserts the error text is visible on /login. Confirmed it
fails without the Login.vue fix (assertSee fails at the expected point)
and passes with it restored.
* fix: PostHog debug logging silently skipped by redundant isEnabled() pre-checks
signup, trial, and billing events never reached PostHogService::capture()
locally because CreateUser and StripeEventListener short-circuited on
isEnabled() before the local-logging path in capture() could run. Added
shouldTrack() (isEnabled() || local environment) and applied it at every
dispatch/handle guard in the chain, while the real API call in SendEvent
stays gated on isEnabled() alone so production behavior is unchanged.
* fix: correctly guard past_due trial-conversion recovery against a later unrelated payment retry
convertedFromTrial() used trial_end being non-null to detect a past_due ->
active recovery as a trial conversion, but Stripe never clears trial_end
once set, so the guard could never actually exclude a long-time paying
customer's unrelated card-decline recovery months later — it would fire
trial.converted again, double-counting conversion_value. Now compares the
subscription item's current_period_start against trial_end, which only
match for the trial's own first billing period.
Also reverts the CreateInvite.php Str::lower() normalization added earlier
in this branch — invite emails are stored and compared as submitted, with
no manual casing normalization anywhere.
Adds a diagnostic log in trackTrialConversion() (unconditional, not gated
on shouldTrack()) to verify this against a real Stripe webhook payload via
a test-clock walkthrough.
* fix: don't fire checkout.started before the Stripe checkout session actually exists; drop diagnostic logging
WelcomeController::storeReferralSource captured checkout.started before
calling StartSubscriptionCheckout::redirect(), so a failure creating the
Stripe session (e.g. the coupon/promo-code conflict ConfigureSubscription
Checkout throws on, or any Stripe API error) still left a false-positive
conversion event in PostHog. redirect() now runs first; the capture only
fires once the checkout session was actually created.
Also removes the unconditional Log::info() added to trackTrialConversion()
for the manual Stripe test-clock verification — the current_period_start
fix it was added to confirm has now been validated against a real webhook
payload, so it's no longer needed and shouldn't keep logging on every
production subscription.updated event.
* refactor: centralize OAuth invite-registration validation in PreservesInvite
GoogleController and GitHubController each duplicated the same self-hosted
registration gate and invite-email-mismatch check verbatim. Moved both into
resolveInviteForRegistration() and inviteEmailMismatchRedirect() on the
shared PreservesInvite trait so a future OAuth provider (or an edit to one
controller) can't silently drift from the other on these security-relevant
checks.
2026-08-12 14:47:47 +00:00
|
|
|
Bus::assertNotDispatched(
|
|
|
|
|
SendEvent::class,
|
|
|
|
|
fn (SendEvent $event): bool => data_get($event->payload, 'event') === CheckoutEvent::Started->value,
|
|
|
|
|
);
|
2026-08-06 14:34:50 +00:00
|
|
|
});
|
Add social connect step to welcome before Stripe (#293)
* feat: add social connect step to welcome before Stripe checkout
Ask new owners to connect a network after referral source so we can track welcome.connect in PostHog and still let them continue to checkout without a connection.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Nest welcome connect copy under a connect array.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Require a connected social account before welcome checkout.
Skip is no longer allowed, and the welcome layout takes a Tailwind size so the connect grid can sit two rows of six.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden the welcome connect step after review.
Track connect only after Stripe creates a session, restore a missing workspace before showing networks, and cover the remaining checkout and analytics cases.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor social account status handling across components
Updated the SocialAccountsGrid, NetworkConnectGrid, onboarding, and welcome connect components to utilize the new SocialAccountStatus enum for improved clarity and maintainability. This change replaces string literals for account statuses with the enum values, enhancing type safety and consistency throughout the application.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Refactor workspace resolution in WelcomeController and StoreWelcomeConnectRequest
Updated the WelcomeController and StoreWelcomeConnectRequest to directly access the user's current workspace, simplifying the code by removing the resolveCurrentWorkspace method. This change enhances readability and maintains functionality by ensuring the current workspace is correctly utilized in the connection process. Additionally, removed outdated test cases related to workspace restoration.
* Inline welcome connect PostHog platforms from the current workspace.
Drop the extra helper — the grid already loads accounts the same way as onboarding and accounts.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Inline Stripe checkout into the welcome connect store.
startCheckout was a one-caller wrapper; storeConnect now matches the other welcome steps.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move welcome connect validation into the controller.
The FormRequest had no input to validate and duplicated step-gating. Require a connected account in storeConnect, and drop the dead owner abort plus the always-true PostHog connected flag.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Show welcome toasts and cover remaining connect cases.
Mount the app Toast host on WelcomeLayout so OAuth, Telegram, and disconnect feedback is visible. Add tests for stale goals, an empty workspace grid, accounts on another workspace, and skipped identify when Stripe fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Assume a welcome workspace, validate connect in the FormRequest, and add browser tests.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Rename WelcomeEvent::dashboardFunnel() to funnel().
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms from the social account observer.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Queue connected-platform identify on the posthog queue.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Harden welcome connect: 404 without a workspace, and keep step redirects ahead of connect validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Identify connected platforms on workspace and account groups, and keep the account union on the owner.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Share hasCurrentGoals on User and keep Stripe checkout when PostHog capture fails.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Skip welcome connect validation when the controller would redirect the user away.
Co-authored-by: Cursor <cursoragent@cursor.com>
* Move current-goal membership onto the Goal enum.
Co-authored-by: Cursor <cursoragent@cursor.com>
---------
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-17 22:37:43 +00:00
|
|
|
|
|
|
|
|
function completeWelcomeThroughReferral(User $user): void
|
|
|
|
|
{
|
|
|
|
|
$user->update([
|
|
|
|
|
'persona' => Persona::Agency->value,
|
|
|
|
|
'goals' => [Goal::SaveTime->value],
|
|
|
|
|
'referral_source' => ReferralSource::ProductHunt->value,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function attachCurrentWorkspace(User $user): Workspace
|
|
|
|
|
{
|
|
|
|
|
$workspace = Workspace::factory()->create([
|
|
|
|
|
'account_id' => $user->account_id,
|
|
|
|
|
'user_id' => $user->id,
|
|
|
|
|
]);
|
|
|
|
|
$workspace->members()->attach($user->id, ['role' => Role::Admin->value]);
|
|
|
|
|
$user->update(['current_workspace_id' => $workspace->id]);
|
|
|
|
|
|
|
|
|
|
return $workspace;
|
|
|
|
|
}
|