trypost/app/Services/PostHogService.php

87 lines
2.2 KiB
PHP
Raw Normal View History

2026-03-31 00:18:07 +00:00
<?php
declare(strict_types=1);
namespace App\Services;
refactor: namespace PostHog jobs + extract billing tracking, add tests Reorganises PostHog plumbing under `App\Jobs\PostHog` and extracts the Stripe billing capture out of `StripeEventListener` into its own job. Adds the missing test coverage that was promised but not delivered in the previous commit. Code changes: - Move `app/Jobs/SendPostHogEvent.php` → `app/Jobs/PostHog/SendEvent.php` (low-level dispatcher). - Move `app/Jobs/SyncUserToPostHog.php` → `app/Jobs/PostHog/SyncUser.php` (high-level user/account/workspace sync). - New `app/Jobs/PostHog/TrackBilling.php` that owns the capture('subscription.*') + SyncUser re-dispatch flow. Receives account id + event name + payload, runs on the `posthog` queue. - `StripeEventListener` slims down to a switch table mapping Stripe event types to PostHog event names and dispatches `TrackBilling`. No more inline tracking logic in the listener. - `resources/js/posthog.ts` now owns `syncPostHogContext(page)` and `capturePageview()`. `resources/js/app.ts` imports them — no behaviour inlined in the bootstrap. - `app/Services/PostHogService.php` and `app/Actions/User/CreateUser.php` updated to the new namespaces. Tests added/updated: - `tests/Feature/Jobs/PostHog/SyncUserTest.php` — identify/group payload shape, account metrics, workspace skip when none, queue assignment, no-op without api key. - `tests/Feature/Jobs/PostHog/TrackBillingTest.php` — capture payload, SyncUser re-dispatch, missing-account/owner handling, api key gate. - `tests/Feature/Jobs/PostHog/SendEventTest.php` — moved from `tests/Feature/SendPostHogEventTest.php` and updated to new namespace. - `tests/Unit/PostHogServiceTest.php` — adds coverage for the account-aware capture (auto-attached `\$groups.account`, `account_id`, `plan`) and the no-account branch. - `tests/Feature/Listeners/StripeEventListenerTest.php` — replaces the old inline-PostHog assertions with `Bus::fake([TrackBilling::class])` and verifies the listener dispatches TrackBilling with the right account id + event name for each subscription type, and skips non-subscription event types. - `tests/Feature/Actions/User/CreateUserTest.php` — verifies signup dispatches `SyncUser` with the new user id. Suite: 1427 passed (+20 net new, including the previous round of metrics-related tests).
2026-05-07 12:41:36 +00:00
use App\Jobs\PostHog\SendEvent;
feat: end-to-end PostHog tracking with reactive group metrics Wire PostHog identify + dual-group context across the stack so events land on the right person and account/workspace groups, with counts kept fresh by Inertia navigations rather than per-domain triggers. - New `app/Jobs/SyncUserToPostHog.php` (queue `posthog`): centralised high-level sync — identifies the user and group-identifies their account + current workspace using `$account->usage()` so the metrics reuse the same source of truth Inertia ships in shared props. - `app/Actions/User/CreateUser.php`: dispatches `SyncUserToPostHog` on signup instead of calling `PostHogService` inline. Keeps the action fast and routes everything through the queue. - `app/Listeners/StripeEventListener.php`: webhook now captures `subscription.created`/`updated`/`cancelled` against the account owner profile (with `account` group auto-attached) and re-dispatches `SyncUserToPostHog` so plan/has_active_subscription/is_on_trial refresh after Stripe state changes. - `app/Services/PostHogService.php`: `capture()` accepts an optional `Account` that auto-attaches `$groups.account`, `account_id`, and `plan` properties. Each public method short-circuits when `POSTHOG_API_KEY` is unset so self-hosted installs are unaffected. - `app/Models/Traits/HasUsage.php`: adds `postCount` to the usage shape (combined `withCount(['socialAccounts','posts'])` query) so posts count is part of the same payload Inertia already ships. - `config/horizon.php`: adds `posthog` to `supervisor-1` queues so the queued PostHog jobs actually drain in production. - `resources/js/app.ts`: extracts `syncPostHogContext(page)` and calls it on boot AND on every Inertia navigation, reading the fresh `usage` props. This: - Refreshes account group counts (workspaces, social accounts, posts, members, credits) without per-domain triggers. - Resolves the workspace-switch case where `setup()` does not re-run but `navigate` fires with the new `auth.currentWorkspace`. - Captures the initial `$pageview` so the first page of a session is no longer dropped. - `resources/js/components/UserMenuContent.vue`: `posthog.reset()` on logout so a follow-up login on the same browser doesn't keep events attributed to the previous user. - `resources/js/composables/useFeatureAccess.ts`: TS `Usage` interface gains `postCount`. - `tests/Feature/Models/HasUsageTraitTest.php`: updated for the new usage shape. Full suite: 1407 passed. Hierarchy aligned with the domain model: person = User, group `account` = billing/plan parent, group `workspace` = collaboration child (carries `account_id` for drill-down).
2026-05-07 12:28:02 +00:00
use App\Models\Account;
2026-03-31 00:18:07 +00:00
use Illuminate\Support\Facades\Log;
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
use Throwable;
2026-03-31 00:18:07 +00:00
class PostHogService
{
public static function isEnabled(): bool
{
return (bool) config('services.posthog.enabled')
&& (bool) config('services.posthog.api_key');
}
2026-03-31 00:18:07 +00:00
/**
* @param array<string, mixed> $properties
*/
feat: end-to-end PostHog tracking with reactive group metrics Wire PostHog identify + dual-group context across the stack so events land on the right person and account/workspace groups, with counts kept fresh by Inertia navigations rather than per-domain triggers. - New `app/Jobs/SyncUserToPostHog.php` (queue `posthog`): centralised high-level sync — identifies the user and group-identifies their account + current workspace using `$account->usage()` so the metrics reuse the same source of truth Inertia ships in shared props. - `app/Actions/User/CreateUser.php`: dispatches `SyncUserToPostHog` on signup instead of calling `PostHogService` inline. Keeps the action fast and routes everything through the queue. - `app/Listeners/StripeEventListener.php`: webhook now captures `subscription.created`/`updated`/`cancelled` against the account owner profile (with `account` group auto-attached) and re-dispatches `SyncUserToPostHog` so plan/has_active_subscription/is_on_trial refresh after Stripe state changes. - `app/Services/PostHogService.php`: `capture()` accepts an optional `Account` that auto-attaches `$groups.account`, `account_id`, and `plan` properties. Each public method short-circuits when `POSTHOG_API_KEY` is unset so self-hosted installs are unaffected. - `app/Models/Traits/HasUsage.php`: adds `postCount` to the usage shape (combined `withCount(['socialAccounts','posts'])` query) so posts count is part of the same payload Inertia already ships. - `config/horizon.php`: adds `posthog` to `supervisor-1` queues so the queued PostHog jobs actually drain in production. - `resources/js/app.ts`: extracts `syncPostHogContext(page)` and calls it on boot AND on every Inertia navigation, reading the fresh `usage` props. This: - Refreshes account group counts (workspaces, social accounts, posts, members, credits) without per-domain triggers. - Resolves the workspace-switch case where `setup()` does not re-run but `navigate` fires with the new `auth.currentWorkspace`. - Captures the initial `$pageview` so the first page of a session is no longer dropped. - `resources/js/components/UserMenuContent.vue`: `posthog.reset()` on logout so a follow-up login on the same browser doesn't keep events attributed to the previous user. - `resources/js/composables/useFeatureAccess.ts`: TS `Usage` interface gains `postCount`. - `tests/Feature/Models/HasUsageTraitTest.php`: updated for the new usage shape. Full suite: 1407 passed. Hierarchy aligned with the domain model: person = User, group `account` = billing/plan parent, group `workspace` = collaboration child (carries `account_id` for drill-down).
2026-05-07 12:28:02 +00:00
public function capture(string $distinctId, string $event, array $properties = [], ?Account $account = null): void
2026-03-31 00:18:07 +00:00
{
if (! self::isEnabled()) {
feat: end-to-end PostHog tracking with reactive group metrics Wire PostHog identify + dual-group context across the stack so events land on the right person and account/workspace groups, with counts kept fresh by Inertia navigations rather than per-domain triggers. - New `app/Jobs/SyncUserToPostHog.php` (queue `posthog`): centralised high-level sync — identifies the user and group-identifies their account + current workspace using `$account->usage()` so the metrics reuse the same source of truth Inertia ships in shared props. - `app/Actions/User/CreateUser.php`: dispatches `SyncUserToPostHog` on signup instead of calling `PostHogService` inline. Keeps the action fast and routes everything through the queue. - `app/Listeners/StripeEventListener.php`: webhook now captures `subscription.created`/`updated`/`cancelled` against the account owner profile (with `account` group auto-attached) and re-dispatches `SyncUserToPostHog` so plan/has_active_subscription/is_on_trial refresh after Stripe state changes. - `app/Services/PostHogService.php`: `capture()` accepts an optional `Account` that auto-attaches `$groups.account`, `account_id`, and `plan` properties. Each public method short-circuits when `POSTHOG_API_KEY` is unset so self-hosted installs are unaffected. - `app/Models/Traits/HasUsage.php`: adds `postCount` to the usage shape (combined `withCount(['socialAccounts','posts'])` query) so posts count is part of the same payload Inertia already ships. - `config/horizon.php`: adds `posthog` to `supervisor-1` queues so the queued PostHog jobs actually drain in production. - `resources/js/app.ts`: extracts `syncPostHogContext(page)` and calls it on boot AND on every Inertia navigation, reading the fresh `usage` props. This: - Refreshes account group counts (workspaces, social accounts, posts, members, credits) without per-domain triggers. - Resolves the workspace-switch case where `setup()` does not re-run but `navigate` fires with the new `auth.currentWorkspace`. - Captures the initial `$pageview` so the first page of a session is no longer dropped. - `resources/js/components/UserMenuContent.vue`: `posthog.reset()` on logout so a follow-up login on the same browser doesn't keep events attributed to the previous user. - `resources/js/composables/useFeatureAccess.ts`: TS `Usage` interface gains `postCount`. - `tests/Feature/Models/HasUsageTraitTest.php`: updated for the new usage shape. Full suite: 1407 passed. Hierarchy aligned with the domain model: person = User, group `account` = billing/plan parent, group `workspace` = collaboration child (carries `account_id` for drill-down).
2026-05-07 12:28:02 +00:00
return;
}
$payload = [
2026-03-31 00:18:07 +00:00
'distinctId' => $distinctId,
'event' => $event,
'properties' => $properties,
feat: end-to-end PostHog tracking with reactive group metrics Wire PostHog identify + dual-group context across the stack so events land on the right person and account/workspace groups, with counts kept fresh by Inertia navigations rather than per-domain triggers. - New `app/Jobs/SyncUserToPostHog.php` (queue `posthog`): centralised high-level sync — identifies the user and group-identifies their account + current workspace using `$account->usage()` so the metrics reuse the same source of truth Inertia ships in shared props. - `app/Actions/User/CreateUser.php`: dispatches `SyncUserToPostHog` on signup instead of calling `PostHogService` inline. Keeps the action fast and routes everything through the queue. - `app/Listeners/StripeEventListener.php`: webhook now captures `subscription.created`/`updated`/`cancelled` against the account owner profile (with `account` group auto-attached) and re-dispatches `SyncUserToPostHog` so plan/has_active_subscription/is_on_trial refresh after Stripe state changes. - `app/Services/PostHogService.php`: `capture()` accepts an optional `Account` that auto-attaches `$groups.account`, `account_id`, and `plan` properties. Each public method short-circuits when `POSTHOG_API_KEY` is unset so self-hosted installs are unaffected. - `app/Models/Traits/HasUsage.php`: adds `postCount` to the usage shape (combined `withCount(['socialAccounts','posts'])` query) so posts count is part of the same payload Inertia already ships. - `config/horizon.php`: adds `posthog` to `supervisor-1` queues so the queued PostHog jobs actually drain in production. - `resources/js/app.ts`: extracts `syncPostHogContext(page)` and calls it on boot AND on every Inertia navigation, reading the fresh `usage` props. This: - Refreshes account group counts (workspaces, social accounts, posts, members, credits) without per-domain triggers. - Resolves the workspace-switch case where `setup()` does not re-run but `navigate` fires with the new `auth.currentWorkspace`. - Captures the initial `$pageview` so the first page of a session is no longer dropped. - `resources/js/components/UserMenuContent.vue`: `posthog.reset()` on logout so a follow-up login on the same browser doesn't keep events attributed to the previous user. - `resources/js/composables/useFeatureAccess.ts`: TS `Usage` interface gains `postCount`. - `tests/Feature/Models/HasUsageTraitTest.php`: updated for the new usage shape. Full suite: 1407 passed. Hierarchy aligned with the domain model: person = User, group `account` = billing/plan parent, group `workspace` = collaboration child (carries `account_id` for drill-down).
2026-05-07 12:28:02 +00:00
];
if ($account) {
$payload['properties']['$groups'] = ['account' => (string) $account->id];
$payload['properties']['account_id'] = (string) $account->id;
$payload['properties']['plan'] = $account->plan?->name;
}
$this->dispatch('capture', $payload);
2026-03-31 00:18:07 +00:00
}
/**
* @param array<string, mixed> $properties
*/
public function identify(string $distinctId, array $properties = []): void
{
if (! self::isEnabled()) {
feat: end-to-end PostHog tracking with reactive group metrics Wire PostHog identify + dual-group context across the stack so events land on the right person and account/workspace groups, with counts kept fresh by Inertia navigations rather than per-domain triggers. - New `app/Jobs/SyncUserToPostHog.php` (queue `posthog`): centralised high-level sync — identifies the user and group-identifies their account + current workspace using `$account->usage()` so the metrics reuse the same source of truth Inertia ships in shared props. - `app/Actions/User/CreateUser.php`: dispatches `SyncUserToPostHog` on signup instead of calling `PostHogService` inline. Keeps the action fast and routes everything through the queue. - `app/Listeners/StripeEventListener.php`: webhook now captures `subscription.created`/`updated`/`cancelled` against the account owner profile (with `account` group auto-attached) and re-dispatches `SyncUserToPostHog` so plan/has_active_subscription/is_on_trial refresh after Stripe state changes. - `app/Services/PostHogService.php`: `capture()` accepts an optional `Account` that auto-attaches `$groups.account`, `account_id`, and `plan` properties. Each public method short-circuits when `POSTHOG_API_KEY` is unset so self-hosted installs are unaffected. - `app/Models/Traits/HasUsage.php`: adds `postCount` to the usage shape (combined `withCount(['socialAccounts','posts'])` query) so posts count is part of the same payload Inertia already ships. - `config/horizon.php`: adds `posthog` to `supervisor-1` queues so the queued PostHog jobs actually drain in production. - `resources/js/app.ts`: extracts `syncPostHogContext(page)` and calls it on boot AND on every Inertia navigation, reading the fresh `usage` props. This: - Refreshes account group counts (workspaces, social accounts, posts, members, credits) without per-domain triggers. - Resolves the workspace-switch case where `setup()` does not re-run but `navigate` fires with the new `auth.currentWorkspace`. - Captures the initial `$pageview` so the first page of a session is no longer dropped. - `resources/js/components/UserMenuContent.vue`: `posthog.reset()` on logout so a follow-up login on the same browser doesn't keep events attributed to the previous user. - `resources/js/composables/useFeatureAccess.ts`: TS `Usage` interface gains `postCount`. - `tests/Feature/Models/HasUsageTraitTest.php`: updated for the new usage shape. Full suite: 1407 passed. Hierarchy aligned with the domain model: person = User, group `account` = billing/plan parent, group `workspace` = collaboration child (carries `account_id` for drill-down).
2026-05-07 12:28:02 +00:00
return;
}
2026-03-31 00:18:07 +00:00
$this->dispatch('identify', [
'distinctId' => $distinctId,
'properties' => $properties,
]);
}
/**
* @param array<string, mixed> $properties
*/
public function groupIdentify(string $groupType, string $groupKey, array $properties = []): void
{
if (! self::isEnabled()) {
feat: end-to-end PostHog tracking with reactive group metrics Wire PostHog identify + dual-group context across the stack so events land on the right person and account/workspace groups, with counts kept fresh by Inertia navigations rather than per-domain triggers. - New `app/Jobs/SyncUserToPostHog.php` (queue `posthog`): centralised high-level sync — identifies the user and group-identifies their account + current workspace using `$account->usage()` so the metrics reuse the same source of truth Inertia ships in shared props. - `app/Actions/User/CreateUser.php`: dispatches `SyncUserToPostHog` on signup instead of calling `PostHogService` inline. Keeps the action fast and routes everything through the queue. - `app/Listeners/StripeEventListener.php`: webhook now captures `subscription.created`/`updated`/`cancelled` against the account owner profile (with `account` group auto-attached) and re-dispatches `SyncUserToPostHog` so plan/has_active_subscription/is_on_trial refresh after Stripe state changes. - `app/Services/PostHogService.php`: `capture()` accepts an optional `Account` that auto-attaches `$groups.account`, `account_id`, and `plan` properties. Each public method short-circuits when `POSTHOG_API_KEY` is unset so self-hosted installs are unaffected. - `app/Models/Traits/HasUsage.php`: adds `postCount` to the usage shape (combined `withCount(['socialAccounts','posts'])` query) so posts count is part of the same payload Inertia already ships. - `config/horizon.php`: adds `posthog` to `supervisor-1` queues so the queued PostHog jobs actually drain in production. - `resources/js/app.ts`: extracts `syncPostHogContext(page)` and calls it on boot AND on every Inertia navigation, reading the fresh `usage` props. This: - Refreshes account group counts (workspaces, social accounts, posts, members, credits) without per-domain triggers. - Resolves the workspace-switch case where `setup()` does not re-run but `navigate` fires with the new `auth.currentWorkspace`. - Captures the initial `$pageview` so the first page of a session is no longer dropped. - `resources/js/components/UserMenuContent.vue`: `posthog.reset()` on logout so a follow-up login on the same browser doesn't keep events attributed to the previous user. - `resources/js/composables/useFeatureAccess.ts`: TS `Usage` interface gains `postCount`. - `tests/Feature/Models/HasUsageTraitTest.php`: updated for the new usage shape. Full suite: 1407 passed. Hierarchy aligned with the domain model: person = User, group `account` = billing/plan parent, group `workspace` = collaboration child (carries `account_id` for drill-down).
2026-05-07 12:28:02 +00:00
return;
}
2026-03-31 00:18:07 +00:00
$this->dispatch('groupIdentify', [
'groupType' => $groupType,
'groupKey' => $groupKey,
'properties' => $properties,
]);
}
/**
* @param array<string, mixed> $payload
*/
private function dispatch(string $method, array $payload): void
{
try {
SendEvent::dispatch($method, $payload);
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
} catch (Throwable $e) {
2026-03-31 00:18:07 +00:00
Log::warning('PostHogService: failed to dispatch event', ['method' => $method, 'error' => $e->getMessage()]);
}
}
}