fix: PostHog property keys, deletion idempotency and full enabled gate

Three fixes from a fresh code review:

1. SyncUser identify used 'email' / 'name' instead of the PostHog
   special person properties '\$email' / '\$name'. The frontend already
   used the correct keys; the backend identify (sole source for users
   who sign up but never log in) would have populated only custom
   properties, leaving the built-in person profile email/name blank
   in the PostHog UI.

2. handleSubscriptionDeleted now short-circuits when plan_id is already
   null. Stripe re-delivers webhooks on transient failures, and the
   prior version would dispatch a duplicate 'subscription.cancelled'
   event and re-flush the (already empty) Pennant cache on each retry.

3. useTracking composable called posthog.capture directly, bypassing
   the new enabled gate. While posthog-js queues calls before init
   (so no events leaked over the network in self-hosted mode), the
   buffer grew unbounded and would fire all queued events in bulk if
   init was ever called. Replaced with a gated captureEvent helper
   exported from posthog.ts.

Plus: drop the now-trivial 'updating non-plan fields does not flush
the pennant cache' test (no observer to test against), refresh stale
doc comments referencing the removed SyncUserToPostHog filename, and
add a Bus::assertNotDispatched check to the deletion-idempotency test.
This commit is contained in:
Paulo Castellano 2026-05-07 13:15:36 -03:00
parent cd28ac4025
commit b709c19862
8 changed files with 41 additions and 32 deletions

View file

@ -57,8 +57,8 @@ public function handle(PostHogService $postHog): void
}
$postHog->identify((string) $user->id, [
'email' => $user->email,
'name' => $user->name,
'$email' => $user->email,
'$name' => $user->name,
'$set_once' => ['signed_up_at' => $user->created_at?->toIso8601String()],
]);

View file

@ -91,6 +91,14 @@ protected function handleSubscriptionUpdated(Account $account, array $payload):
*/
protected function handleSubscriptionDeleted(Account $account, array $payload): void
{
// Stripe re-delivers webhooks on transient failures; if the plan is
// already cleared we skip the rest so the cancellation event isn't
// captured twice and the (idempotent but pointless) cache flush
// doesn't run again.
if ($account->plan_id === null) {
return;
}
$previousPlan = $account->plan?->name;
$account->update(['plan_id' => null]);

View file

@ -1,4 +1,4 @@
import posthog from '@/posthog';
import { captureEvent } from '@/posthog';
const push = (data: Record<string, unknown>) => {
window.dataLayer = window.dataLayer || [];
@ -7,7 +7,7 @@ const push = (data: Record<string, unknown>) => {
export const useTracking = () => ({
trackSignUp: (authProvider: string) => {
posthog.capture('user.signed_up', {
captureEvent('user.signed_up', {
auth_provider: authProvider,
});
@ -18,7 +18,7 @@ export const useTracking = () => ({
},
trackBeginCheckout: (plan: { name: string; interval: string }) => {
posthog.capture('checkout.started', {
captureEvent('checkout.started', {
plan_name: plan.name,
interval: plan.interval,
});
@ -31,7 +31,7 @@ export const useTracking = () => ({
},
trackPurchase: (plan: { name: string; interval: string }) => {
posthog.capture('checkout.completed', {
captureEvent('checkout.completed', {
plan_name: plan.name,
interval: plan.interval,
});

View file

@ -38,7 +38,7 @@ export const initializePostHog = (): void => {
* - Workspace switches re-attach the right `workspace` group (the
* navigation event carries the fresh `auth.currentWorkspace`).
*
* Hierarchy mirrors the backend `app/Jobs/SyncUserToPostHog.php`:
* Hierarchy mirrors the backend `app/Jobs/PostHog/SyncUser.php`:
* person → User, group `account` → billing/plan parent,
* group `workspace` → collaboration child (carries `account_id`).
*/
@ -90,4 +90,17 @@ export const capturePageview = (): void => {
posthog.capture('$pageview', { $current_url: window.location.href });
};
/**
* Gated wrapper around `posthog.capture` for arbitrary domain events. Use
* this from composables/components instead of calling `posthog.capture`
* directly so self-hosted (or otherwise disabled) installs never queue
* events into the SDK buffer.
*/
export const captureEvent = (event: string, properties?: Record<string, unknown>): void => {
if (!enabled) {
return;
}
posthog.capture(event, properties);
};
export default posthog;

View file

@ -49,8 +49,8 @@
Queue::assertPushed(SendEvent::class, function ($job) {
return $job->method === 'identify'
&& $job->payload['distinctId'] === (string) $this->user->id
&& $job->payload['properties']['email'] === $this->user->email
&& $job->payload['properties']['name'] === $this->user->name
&& $job->payload['properties']['$email'] === $this->user->email
&& $job->payload['properties']['$name'] === $this->user->name
&& isset($job->payload['properties']['$set_once']['signed_up_at']);
});
});

View file

@ -103,7 +103,7 @@
(new TrackBilling((string) $this->account->id, BillingEvent::Created, $this->payload))
->handle(app(PostHogService::class));
// SyncUser can still be queued but it would itself no-op when handled.
// The contract of this job is: no PostHog network call without a key.
// The contract of this job is: when PostHog is disabled, handle short-
// circuits before any DB query and no SendEvent reaches the queue.
Queue::assertNotPushed(SendEvent::class);
});

View file

@ -183,6 +183,9 @@
});
test('subscription deleted dispatches TrackBilling with subscription.cancelled event', function () {
$starter = Plan::query()->where('slug', 'starter')->firstOrFail();
$this->account->update(['plan_id' => $starter->id]);
Bus::fake([TrackBilling::class]);
$this->listener->handle(new WebhookReceived([
@ -330,12 +333,18 @@
test('subscription deleted is idempotent when plan_id is already null', function () {
$this->account->update(['plan_id' => null]);
Bus::fake([TrackBilling::class]);
$this->listener->handle(new WebhookReceived([
'type' => 'customer.subscription.deleted',
'data' => ['object' => ['customer' => 'cus_test123']],
]));
expect($this->account->fresh()->plan_id)->toBeNull();
// Re-delivery of a cancellation must not produce a duplicate
// 'subscription.cancelled' event downstream.
Bus::assertNotDispatched(TrackBilling::class);
});
// ========================================

View file

@ -39,24 +39,3 @@
expect(Feature::for($account)->value(MemberLimit::class))->toBe($plus->member_limit);
expect(Feature::for($account)->value(MonthlyCreditsLimit::class))->toBe($plus->monthly_credits_limit);
});
test('updating non-plan fields does not flush the pennant cache', function () {
$plan = Plan::where('slug', 'plus')->first();
$account = Account::factory()->create(['plan_id' => $plan->id]);
Feature::for($account)->value(WorkspaceLimit::class);
$cachedRow = DB::table('features')
->where('scope', 'account|'.$account->id)
->first();
expect($cachedRow)->not->toBeNull();
$account->update(['name' => 'Updated Name']);
$stillCachedRow = DB::table('features')
->where('scope', 'account|'.$account->id)
->first();
expect($stillCachedRow->id)->toBe($cachedRow->id);
});