trypost/app/Jobs/SyncUserToPostHog.php
Paulo Castellano e3538df2f0 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 09:28:02 -03:00

87 lines
3.1 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\User;
use App\Services\PostHogService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
/**
* Centralised PostHog sync for a single user. Dispatched from places the
* frontend can't observe (signup, Stripe webhooks) so the person profile
* and account/workspace groups carry up-to-date properties without blocking
* the calling request. Inertia navigations refresh group counts on the
* client (see `syncPostHogContext` in resources/js/app.ts), so this job is
* not needed on every domain trigger.
*
* Hierarchy mirrors the domain model:
* - person → User
* - group `account` → Account (billing/plan, parent of workspaces)
* - group `workspace` → Workspace (collaboration unit, child of account)
*
* No-op when POSTHOG_API_KEY is unset (PostHogService short-circuits), so
* self-hosted installs are unaffected.
*/
class SyncUserToPostHog implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 30;
public function __construct(public string $userId)
{
$this->onQueue('posthog');
}
public function handle(PostHogService $postHog): void
{
$user = User::with(['account.plan', 'currentWorkspace'])->find($this->userId);
if (! $user) {
return;
}
$postHog->identify((string) $user->id, [
'email' => $user->email,
'name' => $user->name,
'$set_once' => ['signed_up_at' => $user->created_at?->toIso8601String()],
]);
if ($account = $user->account) {
$usage = $account->usage();
$postHog->groupIdentify('account', (string) $account->id, [
'name' => $account->name,
'plan' => $account->plan?->name,
'plan_slug' => $account->plan?->slug,
'has_active_subscription' => $account->hasActiveSubscription(),
'is_on_trial' => $account->isOnTrial(),
'workspaces_count' => $usage['workspaceCount'],
'members_count' => $usage['memberCount'],
'social_accounts_count' => $usage['socialAccountCount'],
'posts_count' => $usage['postCount'],
'pending_invites_count' => $usage['pendingInviteCount'],
'credits_used' => $usage['creditsUsed'],
'created_at' => $account->created_at?->toIso8601String(),
]);
}
if ($workspace = $user->currentWorkspace) {
$postHog->groupIdentify('workspace', (string) $workspace->id, [
'name' => $workspace->name,
'account_id' => (string) $workspace->account_id,
'social_accounts_count' => $workspace->socialAccounts()->count(),
'posts_count' => $workspace->posts()->count(),
'created_at' => $workspace->created_at?->toIso8601String(),
]);
}
}
}