Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Send lifecycle, billing and usage events to PostHog (#437)
Paulo Castellano69c8de811cdf
diff --git a/.ai/rules/index.md b/.ai/rules/index.mdindex 6da72a938..b4efb589b 100644--- a/.ai/rules/index.md+++ b/.ai/rules/index.md@@ -10,9 +10,10 @@ Before planning or editing, find the row whose globs match the file's path and r| app/Services/Analytics/Collectors/** | .ai/rules/collectors.md || resources/js/components/posts/editor/** | .ai/rules/editor.md || app/Enums/GoogleBusiness/**, app/Jobs/PublishToSocialPlatform.php, app/Jobs/ReconcileGoogleBusinessPost.php, app/Console/Commands/ReconcileGoogleBusinessPosts.php, app/Services/Social/GoogleBusinessPublisher.php, app/Support/PostPlatformMetaRules.php | .ai/rules/google-business.md |-| app/Listeners/StripeEventListener.php, app/Jobs/PostHog/TrackBilling.php, app/Jobs/PostHog/SyncAccountUsage.php | .ai/rules/jobs-post-hog.md |+| app/Listeners/Stripe*.php, app/Jobs/PostHog/** | .ai/rules/jobs-post-hog.md || app/Jobs/SendNotification.php, app/Jobs/ReconcileGoogleBusinessPost.php, app/Console/Commands/RecoverStuckPosts.php | .ai/rules/jobs.md || resources/js/** | .ai/rules/js.md |+| app/Http/Middleware/Mcp/**, app/Support/Mcp/**, app/Mcp/Servers/**, app/Enums/Mcp/** | .ai/rules/mcp.md || app/Actions/Media/**, app/Models/Media.php | .ai/rules/media.md || app/Http/Middleware/App/HandleInertiaRequests.php | .ai/rules/middleware-app.md || app/Jobs/PostHog/**, app/Models/Post.php, database/migrations/**, app/Models/SocialAccount.php | .ai/rules/migrations.md |diff --git a/.ai/rules/jobs-post-hog.md b/.ai/rules/jobs-post-hog.mdindex 09016fad4..e608e1b08 100644--- a/.ai/rules/jobs-post-hog.md+++ b/.ai/rules/jobs-post-hog.md@@ -1,11 +1,36 @@---paths:- - 'app/Listeners/StripeEventListener.php'- - 'app/Jobs/PostHog/TrackBilling.php'- - 'app/Jobs/PostHog/SyncAccountUsage.php'+ - 'app/Listeners/Stripe*.php'+ - 'app/Jobs/PostHog/**'---# Jobs Post Hog## Sync PostHog billing state after CashierListen to Cashier's WebhookHandled event so local subscription state is persisted before PostHog jobs are dispatched. Account group properties are the current snapshot: subscription_status is canceled as soon as an ends_at exists (including grace period), while has_active_subscription remains true until access ends. Keep first_month_offer_ends_at event-derived and set it only on subscription creation so renewals cannot extend it.++## Stripe webhooks without a Cashier handler go through StripeBillingSignalListener+Cashier fires `WebhookHandled` only for types with a `handle*` method. `checkout.session.expired`, `invoice.payment_failed` and `invoice.upcoming` have none, so `StripeBillingSignalListener` listens to `WebhookReceived` for them.+It must filter on its `JOBS` map (type => job, also the source of the extra `cashier.webhook.events`) BEFORE its own `stripe_billing_signal:{id}` dedupe: `WebhookReceived` fires for every webhook, and deduping first would consume `StripeEventListener`'s `stripe_webhook_event:` key and silently drop subscription events.+New Cashier-handled types (`customer.subscription.*`, ...) stay in `StripeEventListener` (`WebhookHandled`).++## Lifecycle stage first sync is silent; post.published is claimed atomically+`accounts.lifecycle_stage` null means a pre-deploy account: the first sync writes properties only, no `lifecycle_stage.changed` / `activation.reached`, so workflows do not all fire at once. `CreateUser` seeds `signed_up`, so new accounts emit real transitions.+Stage definitions and thresholds live in `LifecycleStage` and the `ResolveLifecycleStage` constants (`ACTIVE_WITHIN_DAYS`, `AT_RISK_WITHIN_DAYS`).+`churned` means the account was charged at least once: `accounts.first_paid_at`, written by `StripeEventListener` the first time a subscription webhook says `active` (backfilled from local subscriptions by its migration). Never decide it from the subscription dates: Cashier's `customer.subscription.deleted` handler runs `skipTrial()` and clears `trial_ends_at`, so a trial cancelled before its first charge looks paid afterwards.+`post.published` fires once per post group: `TrackPostPublished` claims it with an atomic `Cache::add("posthog:post_group_published:{group}")`. Never a read-then-decide guard, which races between the group's jobs.++## Tracking from domain code must never break the user's action+Domain code (actions, observers, controllers, middleware, listeners) only dispatches a PostHog job, inline where the action happens: `X::dispatchIf(PostHogService::isEnabled(), ...)` (`shouldTrack()` in the Stripe listeners), putting any other condition in the same `dispatchIf`. It passes ids and plain values; the job loads the models and builds the properties, so no tracking query runs in the request (`TrackRepurposeActivated`, `TrackWorkspaceLimitHit`). Outside the Stripe listeners (which catch everything themselves), wrap it in `rescue(function () use (...): void { X::dispatchIf(...); })` (`CreateApiKey`). Never `rescue(fn () => X::dispatchIf(...))`: a returned `PendingDispatch` is pushed when it is destroyed, after `rescue()` has returned. When the tracking needs more than that one dispatch (an early return, a claim, values read from the request), it goes in one private `track<EnumCase>` method of the same class, which the caller calls in one line (`LoadMcpWorkspace::trackToolCalled`).+Dispatch after the action's transaction, never inside it (`ActivateRepurpose`, `SocialController@disconnect`). A model observer may run inside a caller's transaction (`SocialAccountObserver::updated`): wrap it in `DB::afterCommit(function () use (...): void { rescue(function () use (...): void { ... }); })`. A rolled-back transaction then emits nothing, and the push runs after commit, inside `rescue()`. Never `->afterCommit()` on the dispatch: that push happens at commit, outside `rescue()`, and a failure there breaks the caller's commit.+A system command that saves state and then announces it (`SyncPostHogLifecycleStages`) does both per item in `rescue(function () { DB::transaction(function () { save; dispatch; }); })`, the dispatch without `afterCommit()`: a failed push rolls the save back so the next run retries it, and the loop goes on.++## Who an event is attributed to+The `distinct_id` is the user who acted, passed by the caller (`auth()->id()` in an action, `$request->user()`); a job falls back to the model's creator, then to the account owner, when it has none (`TrackRepurposeActivated`, `TrackSocialAccountConnected` for Telegram). System events with nobody acting go to the owner (Stripe jobs, `TrackSocialAccountConnectionLost`, lifecycle). Posts are the exception: always their author, never a fallback.+`subscription.cancelled` is sent once per Stripe subscription (`posthog:subscription_cancelled:{id}`): a dunning that ends in `unpaid` clears `plan_id` before the delete arrives, so the delete is tracked when the account still has a plan or has paid (`first_paid_at`), never for an abandoned checkout.++## Imported network posts never feed PostHog+Only posts written in TryPost by a user count. Every post query behind a PostHog event or property filters `createdInTryPost()` (`SyncAccountPublishingActivity`, `Account::scopeWithLifecycleActivity`, `TrackPostPublished` `is_first`, `HasUsage::cachedPostCount`), and the post jobs (`TrackPost`, `TrackPostPublished`, `TrackPostFailed`) load the post with `->createdInTryPost()->whereNotNull('user_id')`, so a post imported from the network or without an author is never found, with no fallback to the owner.++## Naming tracking code+A dedicated job exists only when it has its own logic (it loads models or decides something); otherwise dispatch `CaptureAccountEvent` with the enum case. Dedicated jobs are named `Track<Subject><EnumCase>` (`TrackPostPublished`, `TrackWorkspaceLimitHit`). When one event has two causes, each cause gets its job, named after it: `social_account.disconnected` is `TrackSocialAccountRemoved` (a member removed it) and `TrackSocialAccountConnectionLost` (the system lost the connection). A job that picks between two events is named after the decision (`TrackPlanChanged`, `TrackLifecycleChange`).diff --git a/.ai/rules/mcp.md b/.ai/rules/mcp.mdnew file mode 100644index 000000000..023295725--- /dev/null+++ b/.ai/rules/mcp.md@@ -0,0 +1,12 @@+---+paths:+ - 'app/Http/Middleware/Mcp/**'+ - 'app/Support/Mcp/**'+ - 'app/Mcp/Servers/**'+ - 'app/Enums/Mcp/**'+---++# Mcp++## Compare MCP JSON-RPC methods with App\Enums\Mcp\Method+Never compare an MCP method as a string literal ('tools/call', 'tools/list', 'initialize', ...). Use `App\Enums\Mcp\Method`, comparing the raw value strictly: `$request->json('method') !== Method::ToolsCall->value` (`LoadMcpWorkspace`). Never `$request->enum('method', Method::class)`: the body is client input, and a non-scalar `method` makes `tryFrom()` throw a TypeError, which turns laravel/mcp's JSON-RPC -32600 into a 500. laravel/mcp keeps its method names in the protected `Server::$methods` array, so there is no package constant. A method the app starts reading gets a case in the enum. `ChallengeChatGptToolCalls`, `ChatGptMcpClient` and `TryPostServer` still use strings; moving them is issue #438.diff --git a/AGENTS.md b/AGENTS.mdindex 4d13bab54..54eeab672 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -323,10 +323,21 @@ used** — `syncWorkspaceQuantity()` was removed with the per-workspace model.`Account::canCreateWorkspace()` — never compare `plan->slug` to decide whatan account may do. A **missing** `plan_id` is not unlimited: it may createonly the signup workspace (`count === 0`).-- `WorkspacePolicy::create()` is owner-only. The cap is not a permission: GET- `/workspaces/create` still renders at the cap (the upgrade dialog opens on- submit). POST is redirected back to create with `workspaces.limit_reached`,- not 403'd.+- `WorkspacePolicy::create()` is owner-only. The cap is not a permission and the+ server decides it, never the browser's shared props (owner decision October+ 2026), through `User::atWorkspaceLimit()` (`workspaceLimitApplies()`: never+ self-hosted, never the first workspace).+ - Every "new workspace" entry point (sidebar workspace menu, workspaces list)+ asks first with a non-navigating `useHttp` POST to+ `app.workspaces.creation-check.store` (`useWorkspaceLimit().createOrUpgrade`).+ `{ allowed: false }` opens the `WorkspaceUpgradeDialog` in place, on the page+ the user is on; `allowed: true` (or a failed check) visits+ `app.workspaces.create`. A refused check tracks `workspace.limit_hit`.+ - GET `/workspaces/create` is never shown at the cap: it tracks+ `workspace.limit_hit` and redirects to `app.workspaces.index` with+ `workspaces.limit_reached`. Without a subscription it still goes to billing.+ - POST at the cap is refused the same way (to the list, not 403'd, never to create),+ tracked once by `store` itself after its transaction.- First-month coupon qualification is card required + first-time subscriber +that plan's monthly price. Workspace count is not part of it.(`incomplete` / `incomplete_expired` still qualify; coupon +@@ -641,8 +652,9 @@ rolls the switch back and toasts.## PostHog person properties-`App\Jobs\PostHog\SyncUser` is the only place that writes person properties, and-the distinction between its two buckets is load-bearing:+`App\Jobs\PostHog\SyncUser` writes the user's person properties (two narrower+jobs below add one each), and the distinction between its two buckets is+load-bearing:- **`$set_once`** — first-touch facts that must never be rewritten: `signed_up_at`and the attribution keys (`utm_*`, `gclid`, `fbclid`, …). A later sync must not@@ -650,6 +662,10 @@ the distinction between its two buckets is load-bearing:- **Top level** — current state, overwritten on every sync: `$email`, `$name`, and`locale`.+The only other jobs that write person properties are `IdentifyConnectedPlatforms`+(`connected_platforms`) and `TrackLifecycleChange` (`lifecycle_stage`), both+current state at the top level.+`locale` mirrors `users.locale` and is what the PostHog email automations (theonboarding cadence and friends) read to decide which translation to send, so ithas to reflect the language the user picked *now* — never `$set_once`. Anythingdiff --git a/app/Actions/Account/ResolveLifecycleStage.php b/app/Actions/Account/ResolveLifecycleStage.phpnew file mode 100644index 000000000..974ae7c0b--- /dev/null+++ b/app/Actions/Account/ResolveLifecycleStage.php@@ -0,0 +1,41 @@+<?php++declare(strict_types=1);++namespace App\Actions\Account;++use App\Enums\Account\LifecycleStage;+use App\Models\Account;+use Carbon\CarbonInterface;++class ResolveLifecycleStage+{+ public const ACTIVE_WITHIN_DAYS = 7;++ public const AT_RISK_WITHIN_DAYS = 21;++ public static function execute(Account $account, ?CarbonInterface $lastPublishedAt, bool $hasSocialAccount): LifecycleStage+ {+ if (! $account->hasAppAccess()) {+ return $account->hasPaidSubscription() ? LifecycleStage::Churned : LifecycleStage::SignedUp;+ }++ if (! $hasSocialAccount) {+ return LifecycleStage::Onboarding;+ }++ if (blank($lastPublishedAt)) {+ return LifecycleStage::Connected;+ }++ if ($lastPublishedAt->greaterThanOrEqualTo(now()->subDays(self::ACTIVE_WITHIN_DAYS))) {+ return LifecycleStage::Active;+ }++ if ($lastPublishedAt->greaterThanOrEqualTo(now()->subDays(self::AT_RISK_WITHIN_DAYS))) {+ return LifecycleStage::AtRisk;+ }++ return LifecycleStage::Dormant;+ }+}diff --git a/app/Actions/ApiKey/CreateApiKey.php b/app/Actions/ApiKey/CreateApiKey.phpindex 98ea6c9d0..a3df80a53 100644--- a/app/Actions/ApiKey/CreateApiKey.php+++ b/app/Actions/ApiKey/CreateApiKey.php@@ -4,9 +4,12 @@ declare(strict_types=1);namespace App\Actions\ApiKey;+use App\Enums\PostHog\ApiKeyEvent;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Models\AccessToken;use App\Models\User;use App\Models\Workspace;+use App\Services\PostHogService;class CreateApiKey{@@ -16,21 +19,18 @@ class CreateApiKey*/public static function execute(User $user, Workspace $workspace, array $data): array{- $result = $user->createToken(data_get($data, 'name'));- $token = AccessToken::query()->findOrFail($result->token->id);- $expiresAt = data_get($data, 'expires_at');+ $created = IssueApiKey::execute($user, $workspace, $data);- $token->forceFill([- 'workspace_id' => $workspace->id,- // Empty = never expire (overrides Passport's JWT default lifetime in the DB).- 'expires_at' => filled($expiresAt)- ? now()->parse($expiresAt)->endOfDay()- : null,- ])->saveQuietly();+ rescue(function () use ($user, $workspace): void {+ CaptureAccountEvent::dispatchIf(+ PostHogService::isEnabled(),+ (string) $user->id,+ (string) $workspace->account_id,+ ApiKeyEvent::Created,+ ['workspace_id' => (string) $workspace->id],+ );+ });- return [- 'token' => $token->refresh(),- 'plain_token' => $result->accessToken,- ];+ return $created;}}diff --git a/app/Actions/ApiKey/IssueApiKey.php b/app/Actions/ApiKey/IssueApiKey.phpnew file mode 100644index 000000000..c24ff0719--- /dev/null+++ b/app/Actions/ApiKey/IssueApiKey.php@@ -0,0 +1,36 @@+<?php++declare(strict_types=1);++namespace App\Actions\ApiKey;++use App\Models\AccessToken;+use App\Models\User;+use App\Models\Workspace;++class IssueApiKey+{+ /**+ * @param array{name: string, expires_at?: string|null} $data+ * @return array{token: AccessToken, plain_token: string}+ */+ public static function execute(User $user, Workspace $workspace, array $data): array+ {+ $result = $user->createToken(data_get($data, 'name'));+ $token = AccessToken::query()->findOrFail($result->token->id);+ $expiresAt = data_get($data, 'expires_at');++ $token->forceFill([+ 'workspace_id' => $workspace->id,+ // Empty = never expire (overrides Passport's JWT default lifetime in the DB).+ 'expires_at' => filled($expiresAt)+ ? now()->parse($expiresAt)->endOfDay()+ : null,+ ])->saveQuietly();++ return [+ 'token' => $token->refresh(),+ 'plain_token' => $result->accessToken,+ ];+ }+}diff --git a/app/Actions/ApiKey/RegenerateApiKey.php b/app/Actions/ApiKey/RegenerateApiKey.phpindex a8906fac6..a802d079f 100644--- a/app/Actions/ApiKey/RegenerateApiKey.php+++ b/app/Actions/ApiKey/RegenerateApiKey.php@@ -22,7 +22,7 @@ class RegenerateApiKeyreturn DB::transaction(function () use ($user, $workspace, $token): array {$token->forceFill(['revoked' => true])->saveQuietly();- return CreateApiKey::execute($user, $workspace, [+ return IssueApiKey::execute($user, $workspace, ['name' => $token->name,'expires_at' => $token->expires_at?->isFuture()? $token->expires_at->toDateString()diff --git a/app/Actions/Billing/StartSubscriptionCheckout.php b/app/Actions/Billing/StartSubscriptionCheckout.phpindex 68dbdf45d..95c484288 100644--- a/app/Actions/Billing/StartSubscriptionCheckout.php+++ b/app/Actions/Billing/StartSubscriptionCheckout.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Actions\Billing;+use App\Enums\Billing\Interval;use App\Models\Account;use App\Models\Plan;use App\Support\Billing\ConfigureSubscriptionCheckout;@@ -33,6 +34,11 @@ class StartSubscriptionCheckout$session = $subscription->checkout(['success_url' => route('app.billing.processing').'?session_id={CHECKOUT_SESSION_ID}','cancel_url' => $cancelUrl,+ 'metadata' => array_filter([+ ConfigureSubscriptionCheckout::PLAN_METADATA_KEY => $plan?->slug->value,+ ConfigureSubscriptionCheckout::INTERVAL_METADATA_KEY => (filled($plan) ? Interval::forPrice($plan, $priceId) : Interval::Monthly)->value,+ ConfigureSubscriptionCheckout::FIRST_MONTH_OFFER_METADATA_KEY => filled($subscription->couponId) ? 'true' : 'false',+ ], filled(...)),]);return Inertia::location($session->url);diff --git a/app/Actions/Invite/CreateInvite.php b/app/Actions/Invite/CreateInvite.phpindex bf13ca2f9..42b670a7d 100644--- a/app/Actions/Invite/CreateInvite.php+++ b/app/Actions/Invite/CreateInvite.php@@ -4,9 +4,12 @@ declare(strict_types=1);namespace App\Actions\Invite;+use App\Enums\PostHog\WorkspaceEvent;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Mail\WorkspaceInvite as WorkspaceInviteMail;use App\Models\Invite;use App\Models\Workspace;+use App\Services\PostHogService;use Illuminate\Support\Facades\Mail;class CreateInvite@@ -28,6 +31,19 @@ class CreateInvite->locale($inviter->preferredLocale())->send(new WorkspaceInviteMail($invite));+ rescue(function () use ($workspace, $invite, $inviter): void {+ CaptureAccountEvent::dispatchIf(+ PostHogService::isEnabled(),+ (string) $inviter->id,+ (string) $workspace->account_id,+ WorkspaceEvent::MemberInvited,+ [+ 'is_admin' => $invite->is_admin,+ 'requires_approval' => $invite->requires_approval,+ ],+ );+ });+return $invite;}}diff --git a/app/Actions/Post/FinalizePostPublication.php b/app/Actions/Post/FinalizePostPublication.phpindex 97c2f346b..c63a6267d 100644--- a/app/Actions/Post/FinalizePostPublication.php+++ b/app/Actions/Post/FinalizePostPublication.php@@ -7,11 +7,14 @@ namespace App\Actions\Post;use App\Enums\Notification\Type;use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;+use App\Jobs\PostHog\TrackPostFailed;+use App\Jobs\PostHog\TrackPostPublished;use App\Jobs\SendNotification;use App\Mail\PostPublished;use App\Mail\PostPublishFailed;use App\Models\Post;use App\Models\User;+use App\Services\PostHogService;use Illuminate\Support\Facades\DB;/**@@ -67,7 +70,17 @@ class FinalizePostPublicationreturn;}- $this->notify($outcome['post'], $outcome['successful']);+ $settled = data_get($outcome, 'post');+ $successful = data_get($outcome, 'successful');++ $this->notify($settled, $successful);++ rescue(function () use ($settled, $successful): void {+ ($successful ? TrackPostPublished::class : TrackPostFailed::class)::dispatchIf(+ PostHogService::isEnabled(),+ (string) $settled->id,+ );+ });}/**diff --git a/app/Actions/Repurpose/ActivateRepurpose.php b/app/Actions/Repurpose/ActivateRepurpose.phpindex d2f0d7e71..4aeae2a29 100644--- a/app/Actions/Repurpose/ActivateRepurpose.php+++ b/app/Actions/Repurpose/ActivateRepurpose.php@@ -6,8 +6,10 @@ namespace App\Actions\Repurpose;use App\Enums\Repurpose\Status;use App\Enums\SocialAccount\Status as AccountStatus;+use App\Jobs\PostHog\TrackRepurposeActivated;use App\Models\Repurpose;use App\Models\SocialAccount;+use App\Services\PostHogService;use App\Support\PostPlatformMetaRules;use App\Support\Repurpose\RepurposeTransition;use Illuminate\Database\Eloquent\Collection;@@ -17,7 +19,7 @@ class ActivateRepurpose{public static function execute(Repurpose $repurpose): Repurpose{- return RepurposeTransition::apply(+ $activated = RepurposeTransition::apply($repurpose,[Status::Draft, Status::Disabled],__('repurposes.errors.only_idle_activates'),@@ -35,6 +37,12 @@ class ActivateRepurpose]);},);++ rescue(function () use ($activated): void {+ TrackRepurposeActivated::dispatchIf(PostHogService::isEnabled(), (string) $activated->id, auth()->id());+ });++ return $activated;}public static function assertSourceUsable(Repurpose $repurpose): voiddiff --git a/app/Actions/SocialAccount/ConnectTelegramChannel.php b/app/Actions/SocialAccount/ConnectTelegramChannel.phpindex 32949f39c..db2b2c525 100644--- a/app/Actions/SocialAccount/ConnectTelegramChannel.php+++ b/app/Actions/SocialAccount/ConnectTelegramChannel.php@@ -9,8 +9,10 @@ use App\Enums\SocialAccount\Status;use App\Events\TelegramChannelConnected;use App\Events\TelegramConnectFailed;use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;+use App\Jobs\PostHog\TrackSocialAccountConnected;use App\Models\SocialAccount;use App\Models\Workspace;+use App\Services\PostHogService;use App\Services\Social\Telegram\TelegramApi;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Http;@@ -82,7 +84,18 @@ class ConnectTelegramChannelreturn null;}- TelegramChannelConnected::dispatch($workspace->id, $nonce, $account->id, $account->wasRecentlyCreated && $reconnect === null);+ $created = $account->wasRecentlyCreated && blank($reconnect);++ TelegramChannelConnected::dispatch($workspace->id, $nonce, $account->id, $created);++ rescue(function () use ($created, $account): void {+ TrackSocialAccountConnected::dispatchIf(+ $created && PostHogService::isEnabled(),+ socialAccountId: (string) $account->id,+ userId: null,+ source: TrackSocialAccountConnected::SOURCE_TELEGRAM,+ );+ });return $account;}diff --git a/app/Actions/User/CreateUser.php b/app/Actions/User/CreateUser.phpindex d6bfaedb7..fd00cbb12 100644--- a/app/Actions/User/CreateUser.php+++ b/app/Actions/User/CreateUser.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Actions\User;use App\Actions\Workspace\CreateWorkspace;+use App\Enums\Account\LifecycleStage;use App\Enums\Plan\Slug;use App\Enums\PostHog\UserEvent;use App\Enums\User\Locale;@@ -39,7 +40,12 @@ class CreateUser$accountAttributes['trial_ends_at'] = now()->addDays(config('cashier.trial_days'));}- $account = Account::create($accountAttributes);+ if (PostHogService::isEnabled()) {+ $accountAttributes['lifecycle_stage'] = LifecycleStage::SignedUp;+ $accountAttributes['lifecycle_stage_changed_at'] = now();+ }++ $account = Account::query()->forceCreate($accountAttributes);$locale = Locale::from(data_get($data, 'locale', Locale::DEFAULT->value));diff --git a/app/Console/Commands/SyncPostHogLifecycleStages.php b/app/Console/Commands/SyncPostHogLifecycleStages.phpnew file mode 100644index 000000000..d0bdf0924--- /dev/null+++ b/app/Console/Commands/SyncPostHogLifecycleStages.php@@ -0,0 +1,62 @@+<?php++declare(strict_types=1);++namespace App\Console\Commands;++use App\Actions\Account\ResolveLifecycleStage;+use App\Jobs\PostHog\TrackLifecycleChange;+use App\Models\Account;+use App\Services\PostHogService;+use Illuminate\Console\Command;+use Illuminate\Support\Facades\DB;++class SyncPostHogLifecycleStages extends Command+{+ protected $signature = 'posthog:sync-lifecycle-stages';++ protected $description = 'Resolve every account lifecycle stage and activation, and send the changes to PostHog';++ public function handle(): int+ {+ if (! PostHogService::isEnabled()) {+ return self::SUCCESS;+ }++ Account::query()+ ->with('subscriptions')+ ->withLifecycleActivity()+ ->lazyById(200)+ ->each(fn (Account $account) => $this->sync($account));++ return self::SUCCESS;+ }++ private function sync(Account $account): void+ {+ $previousStage = $account->lifecycle_stage;+ $stage = ResolveLifecycleStage::execute($account, $account->last_published_at, $account->has_social_account);+ $activatedNow = blank($account->activated_at) && filled($account->first_published_at);++ if ($stage === $previousStage && ! $activatedNow) {+ return;+ }++ if ($stage !== $previousStage) {+ $account->lifecycle_stage = $stage;+ $account->lifecycle_stage_changed_at = now();+ }++ if ($activatedNow) {+ $account->activated_at = $account->first_published_at;+ }++ rescue(function () use ($account, $previousStage, $stage, $activatedNow): void {+ DB::transaction(function () use ($account, $previousStage, $stage, $activatedNow): void {+ Account::withoutTimestamps(fn (): bool => $account->saveQuietly());++ TrackLifecycleChange::dispatch((string) $account->id, $previousStage, $stage, $account->lifecycle_stage_changed_at, $account->activated_at, $activatedNow);+ });+ });+ }+}diff --git a/app/Enums/Account/LifecycleStage.php b/app/Enums/Account/LifecycleStage.phpnew file mode 100644index 000000000..b835daaf6--- /dev/null+++ b/app/Enums/Account/LifecycleStage.php@@ -0,0 +1,16 @@+<?php++declare(strict_types=1);++namespace App\Enums\Account;++enum LifecycleStage: string+{+ case Churned = 'churned';+ case SignedUp = 'signed_up';+ case Onboarding = 'onboarding';+ case Connected = 'connected';+ case Active = 'active';+ case AtRisk = 'at_risk';+ case Dormant = 'dormant';+}diff --git a/app/Enums/Billing/Interval.php b/app/Enums/Billing/Interval.phpindex 62b140bd4..e4c1f513b 100644--- a/app/Enums/Billing/Interval.php+++ b/app/Enums/Billing/Interval.php@@ -11,6 +11,13 @@ enum Interval: stringcase Monthly = 'monthly';case Yearly = 'yearly';+ public static function forPrice(Plan $plan, ?string $priceId): self+ {+ return filled($plan->stripe_yearly_price_id) && $priceId === $plan->stripe_yearly_price_id+ ? self::Yearly+ : self::Monthly;+ }+public function priceIdFor(Plan $plan): ?string{return match ($this) {diff --git a/app/Enums/Mcp/Method.php b/app/Enums/Mcp/Method.phpnew file mode 100644index 000000000..08b67e986--- /dev/null+++ b/app/Enums/Mcp/Method.php@@ -0,0 +1,18 @@+<?php++declare(strict_types=1);++namespace App\Enums\Mcp;++/**+ * The JSON-RPC methods of the MCP protocol the app looks at. laravel/mcp keeps+ * its own list in a protected array, so there is no constant to compare with.+ */+enum Method: string+{+ case Initialize = 'initialize';+ case NotificationsInitialized = 'notifications/initialized';+ case Ping = 'ping';+ case ToolsList = 'tools/list';+ case ToolsCall = 'tools/call';+}diff --git a/app/Enums/PostHog/ActivationEvent.php b/app/Enums/PostHog/ActivationEvent.phpnew file mode 100644index 000000000..e01ea45c1--- /dev/null+++ b/app/Enums/PostHog/ActivationEvent.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum ActivationEvent: string+{+ case Reached = 'activation.reached';+}diff --git a/app/Enums/PostHog/AiEvent.php b/app/Enums/PostHog/AiEvent.phpnew file mode 100644index 000000000..524dcb1d5--- /dev/null+++ b/app/Enums/PostHog/AiEvent.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum AiEvent: string+{+ case AssistUsed = 'ai.assist_used';+}diff --git a/app/Enums/PostHog/ApiKeyEvent.php b/app/Enums/PostHog/ApiKeyEvent.phpnew file mode 100644index 000000000..c14145743--- /dev/null+++ b/app/Enums/PostHog/ApiKeyEvent.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum ApiKeyEvent: string+{+ case Created = 'api_key.created';+}diff --git a/app/Enums/PostHog/CheckoutEvent.php b/app/Enums/PostHog/CheckoutEvent.phpindex 8e5f65f9a..551820356 100644--- a/app/Enums/PostHog/CheckoutEvent.php+++ b/app/Enums/PostHog/CheckoutEvent.php@@ -8,4 +8,5 @@ enum CheckoutEvent: string{case Started = 'checkout.started';case Completed = 'checkout.completed';+ case Expired = 'checkout.expired';}diff --git a/app/Enums/PostHog/InvoiceEvent.php b/app/Enums/PostHog/InvoiceEvent.phpnew file mode 100644index 000000000..bdc6a3944--- /dev/null+++ b/app/Enums/PostHog/InvoiceEvent.php@@ -0,0 +1,11 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum InvoiceEvent: string+{+ case PaymentFailed = 'invoice.payment_failed';+ case Upcoming = 'invoice.upcoming';+}diff --git a/app/Enums/PostHog/LifecycleEvent.php b/app/Enums/PostHog/LifecycleEvent.phpnew file mode 100644index 000000000..183f21b23--- /dev/null+++ b/app/Enums/PostHog/LifecycleEvent.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum LifecycleEvent: string+{+ case StageChanged = 'lifecycle_stage.changed';+}diff --git a/app/Enums/PostHog/McpEvent.php b/app/Enums/PostHog/McpEvent.phpindex ffc56f86e..e0abbced9 100644--- a/app/Enums/PostHog/McpEvent.php+++ b/app/Enums/PostHog/McpEvent.php@@ -7,4 +7,5 @@ namespace App\Enums\PostHog;enum McpEvent: string{case Connected = 'mcp.connected';+ case ToolCalled = 'mcp.tool_called';}diff --git a/app/Enums/PostHog/PlanEvent.php b/app/Enums/PostHog/PlanEvent.phpnew file mode 100644index 000000000..96e9895e9--- /dev/null+++ b/app/Enums/PostHog/PlanEvent.php@@ -0,0 +1,11 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum PlanEvent: string+{+ case Upgraded = 'plan.upgraded';+ case Downgraded = 'plan.downgraded';+}diff --git a/app/Enums/PostHog/PostEvent.php b/app/Enums/PostHog/PostEvent.phpindex e67b1e30d..48cc034b5 100644--- a/app/Enums/PostHog/PostEvent.php+++ b/app/Enums/PostHog/PostEvent.php@@ -7,4 +7,6 @@ namespace App\Enums\PostHog;enum PostEvent: string{case Created = 'post.created';+ case Published = 'post.published';+ case Failed = 'post.failed';}diff --git a/app/Enums/PostHog/RepurposeEvent.php b/app/Enums/PostHog/RepurposeEvent.phpnew file mode 100644index 000000000..babc44aaa--- /dev/null+++ b/app/Enums/PostHog/RepurposeEvent.php@@ -0,0 +1,10 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum RepurposeEvent: string+{+ case Activated = 'repurpose.activated';+}diff --git a/app/Enums/PostHog/SocialAccountEvent.php b/app/Enums/PostHog/SocialAccountEvent.phpnew file mode 100644index 000000000..973684f08--- /dev/null+++ b/app/Enums/PostHog/SocialAccountEvent.php@@ -0,0 +1,11 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum SocialAccountEvent: string+{+ case Connected = 'social_account.connected';+ case Disconnected = 'social_account.disconnected';+}diff --git a/app/Enums/PostHog/WorkspaceEvent.php b/app/Enums/PostHog/WorkspaceEvent.phpnew file mode 100644index 000000000..3210729d7--- /dev/null+++ b/app/Enums/PostHog/WorkspaceEvent.php@@ -0,0 +1,11 @@+<?php++declare(strict_types=1);++namespace App\Enums\PostHog;++enum WorkspaceEvent: string+{+ case MemberInvited = 'workspace.member_invited';+ case LimitHit = 'workspace.limit_hit';+}diff --git a/app/Http/Controllers/App/PostAiAssistantController.php b/app/Http/Controllers/App/PostAiAssistantController.phpindex c0a131374..dc116082a 100644--- a/app/Http/Controllers/App/PostAiAssistantController.php+++ b/app/Http/Controllers/App/PostAiAssistantController.php@@ -6,8 +6,11 @@ namespace App\Http\Controllers\App;use App\Actions\Ai\AssistPostContent;use App\Enums\Ai\PostAssistantMode;+use App\Enums\PostHog\AiEvent;use App\Enums\SocialAccount\Platform;use App\Http\Requests\App\Ai\AssistPostContentRequest;+use App\Jobs\PostHog\CaptureAccountEvent;+use App\Services\PostHogService;use Illuminate\Http\Client\ConnectionException;use Illuminate\Http\Client\RequestException;use Illuminate\Http\JsonResponse;@@ -28,11 +31,13 @@ class PostAiAssistantController extends Controllerreturn response()->json(['message' => $gate->message()], Response::HTTP_PAYMENT_REQUIRED);}+ $mode = PostAssistantMode::from($request->string('mode')->toString());+try {$content = AssistPostContent::execute(workspace: $workspace,user: $request->user(),- mode: PostAssistantMode::from($request->string('mode')->toString()),+ mode: $mode,currentContent: $request->string('current_content')->toString(),prompt: $request->input('prompt'),previousContent: $request->input('previous_content'),@@ -45,6 +50,19 @@ class PostAiAssistantController extends Controllerreturn response()->json(['message' => __('posts.composer.assistant_error')], Response::HTTP_BAD_GATEWAY);}+ rescue(function () use ($request, $workspace, $mode): void {+ CaptureAccountEvent::dispatchIf(+ PostHogService::isEnabled(),+ (string) $request->user()->id,+ (string) $workspace->account_id,+ AiEvent::AssistUsed,+ [+ 'mode' => $mode->value,+ 'workspace_id' => (string) $workspace->id,+ ],+ );+ });+return response()->json(['content' => $content]);}}diff --git a/app/Http/Controllers/App/WorkspaceController.php b/app/Http/Controllers/App/WorkspaceController.phpindex b77c18c9d..52ed9fdac 100644--- a/app/Http/Controllers/App/WorkspaceController.php+++ b/app/Http/Controllers/App/WorkspaceController.php@@ -8,10 +8,12 @@ use App\Actions\Workspace\CreateWorkspace;use App\Actions\Workspace\DeleteWorkspace;use App\Http\Requests\App\Workspace\StoreWorkspaceRequest;use App\Http\Requests\App\Workspace\UpdateWorkspaceRequest;+use App\Jobs\PostHog\TrackWorkspaceLimitHit;use App\Models\Account;use App\Models\Invite;use App\Models\User;use App\Models\Workspace;+use App\Services\PostHogService;use Illuminate\Http\RedirectResponse;use Illuminate\Http\Request;use Illuminate\Support\Facades\DB;@@ -42,21 +44,30 @@ class WorkspaceController extends Controller$user = $request->user();- if ($redirect = $this->denyAdditionalWorkspace($user, redirectWhenAtLimit: false)) {+ if ($redirect = $this->denyAdditionalWorkspace($user)) {return $redirect;}+ if ($user->atWorkspaceLimit() && $user->currentWorkspace) {+ rescue(function () use ($user): void {+ TrackWorkspaceLimitHit::dispatchIf(PostHogService::isEnabled(), (string) $user->id, $user->account?->plan?->slug->value, $user->account?->workspaceLimit(), now());+ });++ return redirect()->route('app.workspaces.index')+ ->with('flash.error', __('workspaces.limit_reached'));+ }+return Inertia::render('workspaces/Create');}- private function denyAdditionalWorkspace(User $user, bool $redirectWhenAtLimit = true): ?RedirectResponse+ private function denyAdditionalWorkspace(User $user): ?RedirectResponse{// Invitee signup shells must stay empty until accept — otherwise they become billable.if (Invite::query()->forEmail($user->email)->whereNull('accepted_at')->exists()) {abort(403);}- if (config('trypost.self_hosted') || $user->ownedWorkspacesCount() === 0) {+ if (! $user->workspaceLimitApplies()) {return null;}@@ -65,11 +76,6 @@ class WorkspaceController extends Controller->with('flash.error', __('workspaces.subscription_required'));}- if ($redirectWhenAtLimit && ! $user->account->canCreateWorkspace()) {- return redirect()->route('app.workspaces.create')- ->with('flash.error', __('workspaces.limit_reached'));- }-return null;}@@ -77,19 +83,32 @@ class WorkspaceController extends Controller{$user = $request->user();- $redirect = DB::transaction(function () use ($user, $request): ?RedirectResponse {+ $limitReached = false;++ $redirect = DB::transaction(function () use ($user, $request, &$limitReached): ?RedirectResponse {Account::query()->whereKey($user->account_id)->lockForUpdate()->first();if ($redirect = $this->denyAdditionalWorkspace($user)) {return $redirect;}+ if ($user->atWorkspaceLimit()) {+ $limitReached = true;++ return redirect()->route('app.workspaces.index')+ ->with('flash.error', __('workspaces.limit_reached'));+ }+CreateWorkspace::execute($user, $request->validated());return null;});if ($redirect) {+ rescue(function () use ($user, $limitReached): void {+ TrackWorkspaceLimitHit::dispatchIf(PostHogService::isEnabled() && $limitReached, (string) $user->id, $user->account?->plan?->slug->value, $user->account?->workspaceLimit(), now());+ });+return $redirect;}diff --git a/app/Http/Controllers/App/WorkspaceCreationCheckController.php b/app/Http/Controllers/App/WorkspaceCreationCheckController.phpnew file mode 100644index 000000000..024eb81f7--- /dev/null+++ b/app/Http/Controllers/App/WorkspaceCreationCheckController.php@@ -0,0 +1,29 @@+<?php++declare(strict_types=1);++namespace App\Http\Controllers\App;++use App\Http\Controllers\Controller;+use App\Http\Resources\App\WorkspaceCreationCheckResource;+use App\Jobs\PostHog\TrackWorkspaceLimitHit;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Http\Request;++class WorkspaceCreationCheckController extends Controller+{+ public function store(Request $request): WorkspaceCreationCheckResource+ {+ $this->authorize('create', Workspace::class);++ $user = $request->user();+ $allowed = $user->account?->canCreateWorkspace() !== false;++ rescue(function () use ($user, $allowed): void {+ TrackWorkspaceLimitHit::dispatchIf(PostHogService::isEnabled() && ! $allowed, (string) $user->id, $user->account?->plan?->slug->value, $user->account?->workspaceLimit(), now());+ });++ return new WorkspaceCreationCheckResource($allowed);+ }+}diff --git a/app/Http/Controllers/Auth/SocialController.php b/app/Http/Controllers/Auth/SocialController.phpindex de989d318..f4a0b47b4 100644--- a/app/Http/Controllers/Auth/SocialController.php+++ b/app/Http/Controllers/Auth/SocialController.php@@ -14,9 +14,12 @@ use App\Exceptions\SocialAccount\ConnectFlowException;use App\Exceptions\SocialAccount\NetworkAlreadyConnectedException;use App\Http\Controllers\Controller;use App\Http\Requests\Auth\FinishSocialConnectionRequest;+use App\Jobs\PostHog\TrackSocialAccountConnected;+use App\Jobs\PostHog\TrackSocialAccountRemoved;use App\Models\Repurpose;use App\Models\SocialAccount;use App\Models\Workspace;+use App\Services\PostHogService;use App\Support\Social\PendingConnection;use Exception;use Illuminate\Http\RedirectResponse;@@ -72,6 +75,16 @@ class SocialController extends Controllerreturn back()->with('flash.error', $exception->getMessage());}+ rescue(function () use ($request, $account): void {+ TrackSocialAccountRemoved::dispatchIf(+ PostHogService::isEnabled(),+ (string) $request->user()->id,+ (string) $account->id,+ (string) $account->workspace_id,+ $account->platform,+ );+ });+$this->flashAccountChange($before);return back();@@ -138,6 +151,17 @@ class SocialController extends Controllerreturn $this->failConnection('error_connecting');}+ foreach ($accounts as $account) {+ rescue(function () use ($account, $reconnect, $request, $pending): void {+ TrackSocialAccountConnected::dispatchIf(+ PostHogService::isEnabled() && blank($reconnect) && $account->wasRecentlyCreated,+ (string) $account->id,+ (string) $request->user()->id,+ $pending->returnRouteName(),+ );+ });+ }+PendingConnection::forget();$created = $accounts->first(fn (SocialAccount $account): bool => $account->wasRecentlyCreated && $reconnect === null);diff --git a/app/Http/Middleware/Mcp/LoadMcpWorkspace.php b/app/Http/Middleware/Mcp/LoadMcpWorkspace.phpindex f486fc7f8..835c2dc8d 100644--- a/app/Http/Middleware/Mcp/LoadMcpWorkspace.php+++ b/app/Http/Middleware/Mcp/LoadMcpWorkspace.php@@ -4,10 +4,14 @@ declare(strict_types=1);namespace App\Http\Middleware\Mcp;+use App\Enums\Mcp\Method;use App\Http\Middleware\Api\LoadWorkspaceFromToken;+use App\Jobs\PostHog\TrackMcpToolCalled;+use App\Services\PostHogService;use App\Support\Mcp\ChatGptMcpClient;use Closure;use Illuminate\Http\Request;+use Illuminate\Support\Facades\Cache;use Symfony\Component\HttpFoundation\Response;class LoadMcpWorkspace@@ -25,6 +29,34 @@ class LoadMcpWorkspacereturn $next($request);}- return $this->loadWorkspace->handle($request, $next, 'mcp');+ return $this->loadWorkspace->handle($request, function (Request $request) use ($next): Response {+ $this->trackToolCalled($request);++ return $next($request);+ }, 'mcp');+ }++ /**+ * Once per user per UTC day, so a busy agent sends one event, not one per call.+ */+ private function trackToolCalled(Request $request): void+ {+ if ($request->json('method') !== Method::ToolsCall->value) {+ return;+ }++ rescue(function () use ($request): void {+ $user = $request->user();+ $today = now()->utc();+ $tool = $request->json('params.name');++ TrackMcpToolCalled::dispatchIf(+ PostHogService::isEnabled() && Cache::add("posthog:mcp_tool_called:{$user->id}:{$today->toDateString()}", true, $today->endOfDay()),+ (string) $user->id,+ (string) $user->current_workspace_id,+ $user->token()?->oauth_access_token_id,+ is_string($tool) ? $tool : null,+ );+ });}}diff --git a/app/Http/Resources/App/WorkspaceCreationCheckResource.php b/app/Http/Resources/App/WorkspaceCreationCheckResource.phpnew file mode 100644index 000000000..3fffdeccb--- /dev/null+++ b/app/Http/Resources/App/WorkspaceCreationCheckResource.php@@ -0,0 +1,25 @@+<?php++declare(strict_types=1);++namespace App\Http\Resources\App;++use Illuminate\Http\Request;+use Illuminate\Http\Resources\Json\JsonResource;++/**+ * Whether the user may go on to create another workspace, or must see the+ * upgrade dialog first.+ */+class WorkspaceCreationCheckResource extends JsonResource+{+ /**+ * @return array{allowed: bool}+ */+ public function toArray(Request $request): array+ {+ return [+ 'allowed' => (bool) $this->resource,+ ];+ }+}diff --git a/app/Jobs/PostHog/AbstractTrackStripeSubscriptionEvent.php b/app/Jobs/PostHog/AbstractTrackStripeEvent.phpsimilarity index 77%rename from app/Jobs/PostHog/AbstractTrackStripeSubscriptionEvent.phprename to app/Jobs/PostHog/AbstractTrackStripeEvent.phpindex 884479ef6..5d9da8232 100644--- a/app/Jobs/PostHog/AbstractTrackStripeSubscriptionEvent.php+++ b/app/Jobs/PostHog/AbstractTrackStripeEvent.php@@ -13,10 +13,10 @@ use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;/**- * Shared PostHog capture pipeline for jobs backed by a Stripe subscription- * webhook payload. Subclasses provide the event name and its properties.+ * Shared PostHog capture pipeline for jobs backed by a Stripe webhook+ * payload. Subclasses provide the event name and its properties.*/-abstract class AbstractTrackStripeSubscriptionEvent implements ShouldQueue+abstract class AbstractTrackStripeEvent implements ShouldQueue{use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;@@ -42,7 +42,7 @@ abstract class AbstractTrackStripeSubscriptionEvent implements ShouldQueue$account = Account::with('plan')->find($this->accountId);- if (! $account?->owner_id || ! $account->plan) {+ if (blank($account?->owner_id) || ! $this->shouldCapture($account)) {return;}@@ -54,6 +54,11 @@ abstract class AbstractTrackStripeSubscriptionEvent implements ShouldQueue);}+ protected function shouldCapture(Account $account): bool+ {+ return true;+ }+abstract protected function event(): string;/**diff --git a/app/Jobs/PostHog/CaptureAccountEvent.php b/app/Jobs/PostHog/CaptureAccountEvent.phpnew file mode 100644index 000000000..05b859de3--- /dev/null+++ b/app/Jobs/PostHog/CaptureAccountEvent.php@@ -0,0 +1,50 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Models\Account;+use App\Services\PostHogService;+use BackedEnum;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;++class CaptureAccountEvent implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ /**+ * @param array<string, mixed> $properties+ */+ public function __construct(+ public string $distinctId,+ public string $accountId,+ public BackedEnum $event,+ public array $properties = [],+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $account = Account::with('plan')->find($this->accountId);++ if (blank($account)) {+ return;+ }++ $postHog->capture($this->distinctId, (string) $this->event->value, $this->properties, $account);+ }+}diff --git a/app/Jobs/PostHog/SyncAccountPublishingActivity.php b/app/Jobs/PostHog/SyncAccountPublishingActivity.phpindex ad0369a57..70cf4ad78 100644--- a/app/Jobs/PostHog/SyncAccountPublishingActivity.php+++ b/app/Jobs/PostHog/SyncAccountPublishingActivity.php@@ -5,8 +5,6 @@ declare(strict_types=1);namespace App\Jobs\PostHog;use App\Models\Account;-use App\Models\Post;-use App\Models\Workspace;use App\Services\PostHogService;use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;use Illuminate\Contracts\Queue\ShouldQueue;@@ -67,13 +65,13 @@ class SyncAccountPublishingActivity implements ShouldBeUniqueUntilProcessing, Shreturn;}- $latestPublication = Post::query()- ->whereIn('workspace_id', Workspace::query()->select('id')->where('account_id', $account->id))+ $latestPublication = $account->posts()+ ->createdInTryPost()->publicationPublished()- ->whereNotNull('published_at')- ->latest('published_at')- ->latest('publication_updated_at')- ->latest('id')+ ->whereNotNull('posts.published_at')+ ->latest('posts.published_at')+ ->latest('posts.publication_updated_at')+ ->latest('posts.id')->first();$postHog->groupIdentifyNow('account', (string) $account->id, [diff --git a/app/Jobs/PostHog/TrackBilling.php b/app/Jobs/PostHog/TrackBilling.phpindex 85e144aff..9e9d63834 100644--- a/app/Jobs/PostHog/TrackBilling.php+++ b/app/Jobs/PostHog/TrackBilling.php@@ -7,6 +7,7 @@ namespace App\Jobs\PostHog;use App\Enums\PostHog\BillingEvent;use App\Models\Account;use App\Services\PostHogService;+use App\Support\Billing\StripeValue;use App\Support\StripeSubscriptionConversion;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;@@ -53,6 +54,8 @@ class TrackBilling implements ShouldQueue'stripe_status' => data_get($this->payload, 'data.object.status'),'plan_slug' => $account->plan?->slug->value,'previous_plan' => $this->previousPlan,+ ...$this->cancellationProperties(),+ ...$this->cancelReasonProperties(),],$account,);@@ -60,12 +63,53 @@ class TrackBilling implements ShouldQueue$postHog->groupIdentify('account', (string) $account->id, ['subscription_status' => $account->subscriptionStatus(),'has_active_subscription' => $account->hasActiveSubscription(),+ ...$this->currentCancellationProperties($account),...$this->firstMonthOfferProperties(),]);SyncUser::dispatch((string) $account->owner_id);}+ /**+ * @return array{cancel_at_period_end: bool, cancel_at: string|null}+ */+ private function cancellationProperties(): array+ {+ return [+ 'cancel_at_period_end' => (bool) data_get($this->payload, 'data.object.cancel_at_period_end', false),+ 'cancel_at' => StripeValue::timestamp(data_get($this->payload, 'data.object.cancel_at'))?->toIso8601String(),+ ];+ }++ /**+ * @return array{cancel_at_period_end: bool, cancel_at: string|null}+ */+ private function currentCancellationProperties(Account $account): array+ {+ $subscription = $account->subscription(Account::SUBSCRIPTION_NAME);+ $onGracePeriod = (bool) $subscription?->onGracePeriod();++ return [+ 'cancel_at_period_end' => $onGracePeriod,+ 'cancel_at' => $onGracePeriod ? $subscription->ends_at->toIso8601String() : null,+ ];+ }++ /**+ * @return array{}|array{cancel_reason: string|null, cancel_feedback: string|null}+ */+ private function cancelReasonProperties(): array+ {+ if ($this->event !== BillingEvent::Cancelled) {+ return [];+ }++ return [+ 'cancel_reason' => data_get($this->payload, 'data.object.cancellation_details.reason'),+ 'cancel_feedback' => data_get($this->payload, 'data.object.cancellation_details.feedback'),+ ];+ }+/*** @return array<string, mixed>*/diff --git a/app/Jobs/PostHog/TrackCheckoutCompleted.php b/app/Jobs/PostHog/TrackCheckoutCompleted.phpindex f3c30ae1f..7f0a02ca3 100644--- a/app/Jobs/PostHog/TrackCheckoutCompleted.php+++ b/app/Jobs/PostHog/TrackCheckoutCompleted.php@@ -8,8 +8,13 @@ use App\Enums\PostHog\CheckoutEvent;use App\Models\Account;use App\Support\StripeSubscriptionConversion;-class TrackCheckoutCompleted extends AbstractTrackStripeSubscriptionEvent+class TrackCheckoutCompleted extends AbstractTrackStripeEvent{+ protected function shouldCapture(Account $account): bool+ {+ return filled($account->plan);+ }+protected function event(): string{return CheckoutEvent::Completed->value;diff --git a/app/Jobs/PostHog/TrackCheckoutExpired.php b/app/Jobs/PostHog/TrackCheckoutExpired.phpnew file mode 100644index 000000000..16c093922--- /dev/null+++ b/app/Jobs/PostHog/TrackCheckoutExpired.php@@ -0,0 +1,39 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\CheckoutEvent;+use App\Models\Account;+use App\Models\Plan;+use App\Support\Billing\ConfigureSubscriptionCheckout;++class TrackCheckoutExpired extends AbstractTrackStripeEvent+{+ protected function shouldCapture(Account $account): bool+ {+ return ! $account->subscribed(Account::SUBSCRIPTION_NAME);+ }++ protected function event(): string+ {+ return CheckoutEvent::Expired->value;+ }++ /**+ * @return array{plan_name: string|null, interval: string|null, is_first_month_offer: bool, checkout_session_id: string|null}+ */+ protected function properties(Account $account): array+ {+ $metadata = data_get($this->payload, 'data.object.metadata', []);+ $planSlug = data_get($metadata, ConfigureSubscriptionCheckout::PLAN_METADATA_KEY);++ return [+ 'plan_name' => filled($planSlug) ? Plan::where('slug', $planSlug)->value('name') : null,+ 'interval' => data_get($metadata, ConfigureSubscriptionCheckout::INTERVAL_METADATA_KEY),+ 'is_first_month_offer' => data_get($metadata, ConfigureSubscriptionCheckout::FIRST_MONTH_OFFER_METADATA_KEY) === 'true',+ 'checkout_session_id' => data_get($this->payload, 'data.object.id'),+ ];+ }+}diff --git a/app/Jobs/PostHog/TrackInvoicePaymentFailed.php b/app/Jobs/PostHog/TrackInvoicePaymentFailed.phpnew file mode 100644index 000000000..f0cda076f--- /dev/null+++ b/app/Jobs/PostHog/TrackInvoicePaymentFailed.php@@ -0,0 +1,35 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\InvoiceEvent;+use App\Models\Account;+use App\Support\Billing\StripeValue;++class TrackInvoicePaymentFailed extends AbstractTrackStripeEvent+{+ protected function event(): string+ {+ return InvoiceEvent::PaymentFailed->value;+ }++ /**+ * @return array{attempt_count: int, amount: float|null, currency: string|null, next_attempt_at: string|null, is_final_attempt: bool, billing_reason: string|null, invoice_id: string|null}+ */+ protected function properties(Account $account): array+ {+ $nextAttempt = data_get($this->payload, 'data.object.next_payment_attempt');++ return [+ 'attempt_count' => (int) data_get($this->payload, 'data.object.attempt_count', 0),+ 'amount' => StripeValue::amount(data_get($this->payload, 'data.object.amount_due')),+ 'currency' => StripeValue::currency(data_get($this->payload, 'data.object.currency')),+ 'next_attempt_at' => StripeValue::timestamp($nextAttempt)?->toIso8601String(),+ 'is_final_attempt' => blank($nextAttempt),+ 'billing_reason' => data_get($this->payload, 'data.object.billing_reason'),+ 'invoice_id' => data_get($this->payload, 'data.object.id'),+ ];+ }+}diff --git a/app/Jobs/PostHog/TrackInvoiceUpcoming.php b/app/Jobs/PostHog/TrackInvoiceUpcoming.phpnew file mode 100644index 000000000..f2d5dd4ba--- /dev/null+++ b/app/Jobs/PostHog/TrackInvoiceUpcoming.php@@ -0,0 +1,69 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\Billing\Interval;+use App\Enums\PostHog\InvoiceEvent;+use App\Models\Account;+use App\Models\Plan;+use App\Support\Billing\FirstFullCharge;+use App\Support\Billing\StripeValue;++class TrackInvoiceUpcoming extends AbstractTrackStripeEvent+{+ protected function event(): string+ {+ return InvoiceEvent::Upcoming->value;+ }++ /**+ * @return array{amount: float|null, currency: string|null, charge_at: string|null, period_end: string|null, interval: string|null, is_first_full_charge: bool|null}+ */+ protected function properties(Account $account): array+ {+ $invoice = data_get($this->payload, 'data.object');+ $subscription = $account->subscription(Account::SUBSCRIPTION_NAME);+ $line = $this->subscriptionLine($invoice);++ $chargeAt = StripeValue::timestamp(data_get($invoice, 'next_payment_attempt') ?? data_get($line, 'period.start'));+ $interval = $this->interval(data_get($line, 'pricing.price_details.price') ?? $subscription?->stripe_price);++ return [+ 'amount' => StripeValue::amount(data_get($invoice, 'amount_due')),+ 'currency' => StripeValue::currency(data_get($invoice, 'currency')),+ 'charge_at' => $chargeAt?->toIso8601String(),+ 'period_end' => StripeValue::timestamp(data_get($line, 'period.end'))?->toIso8601String(),+ 'interval' => $interval?->value,+ 'is_first_full_charge' => filled($subscription?->created_at) && filled($chargeAt) && filled($interval)+ ? FirstFullCharge::isFirst($subscription->created_at, $chargeAt, $interval)+ : null,+ ];+ }++ /**+ * The invoice's line for the subscription itself; proration lines also+ * belong to the subscription item, and a line without a parent is an+ * invoice item, so the flag must be exactly false.+ *+ * @return array<string, mixed>|null+ */+ private function subscriptionLine(mixed $invoice): ?array+ {+ return collect(data_get($invoice, 'lines.data', []))+ ->first(fn (array $line): bool => data_get($line, 'parent.subscription_item_details.proration') === false);+ }++ private function interval(?string $priceId): ?Interval+ {+ if (blank($priceId)) {+ return null;+ }++ return transform(+ Plan::forStripePrices([$priceId])->first(),+ fn (Plan $plan): Interval => Interval::forPrice($plan, $priceId),+ );+ }+}diff --git a/app/Jobs/PostHog/TrackLifecycleChange.php b/app/Jobs/PostHog/TrackLifecycleChange.phpnew file mode 100644index 000000000..a76b2781a--- /dev/null+++ b/app/Jobs/PostHog/TrackLifecycleChange.php@@ -0,0 +1,84 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\Account\LifecycleStage;+use App\Enums\PostHog\ActivationEvent;+use App\Enums\PostHog\LifecycleEvent;+use App\Models\Account;+use App\Services\PostHogService;+use Carbon\CarbonInterface;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;++class TrackLifecycleChange implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ public function __construct(+ public string $accountId,+ public ?LifecycleStage $previousStage,+ public LifecycleStage $stage,+ public ?CarbonInterface $stageChangedAt,+ public ?CarbonInterface $activatedAt,+ public bool $activatedNow,+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $account = Account::with('plan')->find($this->accountId);++ if (blank($account)) {+ return;+ }++ $postHog->groupIdentify('account', (string) $account->id, [+ 'lifecycle_stage' => $this->stage->value,+ 'lifecycle_stage_changed_at' => $this->stageChangedAt?->toIso8601String(),+ 'activated_at' => $this->activatedAt?->toIso8601String(),+ ]);++ if (blank($account->owner_id)) {+ return;+ }++ $ownerId = (string) $account->owner_id;++ $postHog->identify($ownerId, ['lifecycle_stage' => $this->stage->value]);++ if (blank($this->previousStage)) {+ return;+ }++ if ($this->previousStage !== $this->stage) {+ $postHog->capture($ownerId, LifecycleEvent::StageChanged->value, [+ 'stage' => $this->stage->value,+ 'previous_stage' => $this->previousStage->value,+ 'reached_at' => $this->stageChangedAt?->toIso8601String(),+ ], $account);+ }++ if ($this->activatedNow && filled($this->activatedAt)) {+ $postHog->capture($ownerId, ActivationEvent::Reached->value, [+ 'reached_at' => $this->activatedAt->toIso8601String(),+ 'days_since_signup' => (int) $account->created_at->diffInDays($this->activatedAt),+ 'channels_count' => $account->socialAccounts()->connected()->count(),+ ], $account);+ }+ }+}diff --git a/app/Jobs/PostHog/TrackMcpToolCalled.php b/app/Jobs/PostHog/TrackMcpToolCalled.phpnew file mode 100644index 000000000..6b2bbb870--- /dev/null+++ b/app/Jobs/PostHog/TrackMcpToolCalled.php@@ -0,0 +1,63 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\AccessToken\McpClient;+use App\Enums\PostHog\McpEvent;+use App\Models\AccessToken;+use App\Models\Workspace;+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;++class TrackMcpToolCalled implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ public function __construct(+ public string $userId,+ public string $workspaceId,+ public ?string $accessTokenId,+ public ?string $tool,+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $account = Workspace::query()->with('account.plan')->find($this->workspaceId)?->account;++ if (blank($account)) {+ return;+ }++ $clientName = transform(+ $this->accessTokenId,+ fn (string $id): ?string => AccessToken::query()->with('client')->find($id)?->client?->name,+ );++ $postHog->capture(+ $this->userId,+ McpEvent::ToolCalled->value,+ [+ 'tool' => $this->tool,+ 'client' => McpClient::fromClientName((string) $clientName)->value,+ 'workspace_id' => $this->workspaceId,+ ],+ $account,+ );+ }+}diff --git a/app/Jobs/PostHog/TrackPlanChanged.php b/app/Jobs/PostHog/TrackPlanChanged.phpnew file mode 100644index 000000000..0cb5fc655--- /dev/null+++ b/app/Jobs/PostHog/TrackPlanChanged.php@@ -0,0 +1,89 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\Billing\Interval;+use App\Enums\PostHog\PlanEvent;+use App\Models\Account;+use App\Models\Plan;+use App\Support\Billing\StripeValue;++class TrackPlanChanged extends AbstractTrackStripeEvent+{+ private const FROM_ITEM = 'data.previous_attributes.items.data.0';++ private const TO_ITEM = 'data.object.items.data.0';++ protected function shouldCapture(Account $account): bool+ {+ $fromPlan = $this->plan(self::FROM_ITEM);+ $toPlan = $this->plan(self::TO_ITEM);++ return filled($fromPlan) && filled($toPlan) && $fromPlan->isNot($toPlan);+ }++ protected function event(): string+ {+ return $this->monthlyMinorUnits(self::TO_ITEM) > $this->monthlyMinorUnits(self::FROM_ITEM)+ ? PlanEvent::Upgraded->value+ : PlanEvent::Downgraded->value;+ }++ /**+ * @return array{plan_from: string, plan_to: string, interval_from: string, interval_to: string, monthly_amount_from: float|null, monthly_amount_to: float|null}+ */+ protected function properties(Account $account): array+ {+ return [+ 'plan_from' => $this->plan(self::FROM_ITEM)->slug->value,+ 'plan_to' => $this->plan(self::TO_ITEM)->slug->value,+ 'interval_from' => $this->interval(self::FROM_ITEM)->value,+ 'interval_to' => $this->interval(self::TO_ITEM)->value,+ 'monthly_amount_from' => $this->monthlyAmount(self::FROM_ITEM),+ 'monthly_amount_to' => $this->monthlyAmount(self::TO_ITEM),+ ];+ }++ private function plan(string $itemPath): ?Plan+ {+ return once(fn (): ?Plan => transform(+ data_get($this->payload, "{$itemPath}.price.id"),+ fn (string $priceId): ?Plan => Plan::forStripePrices([$priceId])->first(),+ ));+ }++ private function interval(string $itemPath): Interval+ {+ return Interval::forPrice($this->plan($itemPath), data_get($this->payload, "{$itemPath}.price.id"));+ }++ /**+ * The item's price times its quantity, in the currency's minor units.+ */+ private function itemAmount(string $itemPath): ?int+ {+ $unitAmount = data_get($this->payload, "{$itemPath}.price.unit_amount");++ return is_int($unitAmount) ? $unitAmount * (int) data_get($this->payload, "{$itemPath}.quantity", 1) : null;+ }++ private function monthlyMinorUnits(string $itemPath): float+ {+ return $this->perMonth($itemPath, (float) ($this->itemAmount($itemPath) ?? 0));+ }++ private function perMonth(string $itemPath, float $amount): float+ {+ return $this->interval($itemPath) === Interval::Yearly ? $amount / 12 : $amount;+ }++ private function monthlyAmount(string $itemPath): ?float+ {+ return transform(+ StripeValue::amount($this->itemAmount($itemPath)),+ fn (float $amount): float => $this->perMonth($itemPath, $amount),+ );+ }+}diff --git a/app/Jobs/PostHog/TrackPost.php b/app/Jobs/PostHog/TrackPost.phpindex bd31ff04d..c46a54b77 100644--- a/app/Jobs/PostHog/TrackPost.php+++ b/app/Jobs/PostHog/TrackPost.php@@ -33,6 +33,8 @@ class TrackPost implements ShouldQueue}$post = Post::query()+ ->createdInTryPost()+ ->whereNotNull('user_id')->with(['workspace.account.plan'])->find($this->postId);@@ -46,14 +48,8 @@ class TrackPost implements ShouldQueuereturn;}- $distinctId = (string) ($post->user_id ?? $account->owner_id);-- if ($distinctId === '') {- return;- }-$postHog->capture(- $distinctId,+ (string) $post->user_id,PostEvent::Created->value,['post_id' => (string) $post->id,diff --git a/app/Jobs/PostHog/TrackPostFailed.php b/app/Jobs/PostHog/TrackPostFailed.phpnew file mode 100644index 000000000..0fb2a993b--- /dev/null+++ b/app/Jobs/PostHog/TrackPostFailed.php@@ -0,0 +1,62 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\PostEvent;+use App\Exceptions\Social\ErrorCategory;+use App\Models\Post;+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;++class TrackPostFailed implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ public function __construct(public string $postId)+ {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $post = Post::query()+ ->createdInTryPost()+ ->whereNotNull('user_id')+ ->with(['workspace.account.plan'])+ ->find($this->postId);++ $account = $post?->workspace?->account;++ if (blank($account)) {+ return;+ }++ $postHog->capture(+ (string) $post->user_id,+ PostEvent::Failed->value,+ [+ 'post_id' => (string) $post->id,+ 'post_group_id' => $post->post_group_id,+ 'platform' => $post->platform?->value,+ 'network' => $post->platform?->network(),+ 'created_via' => $post->created_via?->value,+ 'error_type' => data_get($post->error_context, 'category', ErrorCategory::Unknown->value),+ ],+ $account,+ );+ }+}diff --git a/app/Jobs/PostHog/TrackPostPublished.php b/app/Jobs/PostHog/TrackPostPublished.phpnew file mode 100644index 000000000..889948739--- /dev/null+++ b/app/Jobs/PostHog/TrackPostPublished.php@@ -0,0 +1,111 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\PostEvent;+use App\Models\Account;+use App\Models\Post;+use App\Services\PostHogService;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Database\Eloquent\Builder;+use Illuminate\Database\Eloquent\Collection;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;+use Illuminate\Support\Facades\Cache;++class TrackPostPublished implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ public function __construct(public string $postId)+ {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $post = Post::query()+ ->createdInTryPost()+ ->whereNotNull('user_id')+ ->with(['workspace.account.plan'])+ ->find($this->postId);++ $account = $post?->workspace?->account;++ if (blank($account)) {+ return;+ }++ $groupPosts = filled($post->post_group_id)+ ? $post->groupPosts()->get(['id', 'platform', 'published_at'])+ : new Collection([$post]);++ $publishedBefore = $this->publishedBefore($account, $groupPosts);++ $groupKey = $post->post_group_id ?: $post->id;++ if (! Cache::add("posthog:post_group_published:{$groupKey}", true, now()->addDays(90))) {+ return;+ }++ $postHog->capture(+ (string) $post->user_id,+ PostEvent::Published->value,+ [+ 'post_group_id' => $post->post_group_id,+ 'created_via' => $post->created_via?->value,+ 'platforms' => $groupPosts+ ->map(fn (Post $groupPost): ?string => $groupPost->platform?->network())+ ->filter()+ ->unique()+ ->sort()+ ->values()+ ->all(),+ 'channels_count' => $groupPosts->count(),+ 'is_first' => ! $publishedBefore,+ ],+ $account,+ );+ }++ /**+ * Whether the account published in TryPost before this group, decided by+ * time (then id) rather than by status: two groups settling together+ * would each see the other already published.+ *+ * @param Collection<int, Post> $groupPosts+ */+ private function publishedBefore(Account $account, Collection $groupPosts): bool+ {+ $first = $groupPosts+ ->filter(fn (Post $groupPost): bool => filled($groupPost->published_at))+ ->sortBy([['published_at', 'asc'], ['id', 'asc']])+ ->first();++ if (blank($first)) {+ return true;+ }++ return $account->posts()+ ->createdInTryPost()+ ->published()+ ->where(fn (Builder $query) => $query+ ->where('posts.published_at', '<', $first->published_at)+ ->orWhere(fn (Builder $tied) => $tied+ ->where('posts.published_at', $first->published_at)+ ->where('posts.id', '<', $first->id)))+ ->exists();+ }+}diff --git a/app/Jobs/PostHog/TrackRepurposeActivated.php b/app/Jobs/PostHog/TrackRepurposeActivated.phpnew file mode 100644index 000000000..2adb6a5be--- /dev/null+++ b/app/Jobs/PostHog/TrackRepurposeActivated.php@@ -0,0 +1,60 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\RepurposeEvent;+use App\Models\Repurpose;+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;++class TrackRepurposeActivated implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ /**+ * @param string|null $userId Who activated it; without one the event goes to its creator, then to the account owner.+ */+ public function __construct(+ public string $repurposeId,+ public ?string $userId = null,+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $repurpose = Repurpose::query()->with(['sourceAccount', 'workspace.account.plan'])->find($this->repurposeId);+ $account = $repurpose?->workspace?->account;++ $distinctId = $this->userId ?? $repurpose?->user_id ?? $account?->owner_id;++ if (blank($account) || blank($distinctId)) {+ return;+ }++ $postHog->capture(+ (string) $distinctId,+ RepurposeEvent::Activated->value,+ [+ 'repurpose_id' => (string) $repurpose->id,+ 'source' => $repurpose->sourceAccount?->platform->value,+ 'destinations_count' => count($repurpose->destinations),+ ],+ $account,+ );+ }+}diff --git a/app/Jobs/PostHog/TrackSocialAccountConnected.php b/app/Jobs/PostHog/TrackSocialAccountConnected.phpnew file mode 100644index 000000000..65e1ccc54--- /dev/null+++ b/app/Jobs/PostHog/TrackSocialAccountConnected.php@@ -0,0 +1,78 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\SocialAccountEvent;+use App\Models\SocialAccount;+use App\Services\PostHogService;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Database\Eloquent\Builder;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;++class TrackSocialAccountConnected implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public const SOURCE_TELEGRAM = 'telegram';++ public int $tries = 3;++ public int $timeout = 30;++ /**+ * @param string|null $userId Who connected it; null for the account owner (a Telegram connect arrives by webhook, with nobody signed in).+ */+ public function __construct(+ public string $socialAccountId,+ public ?string $userId,+ public string $source,+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $socialAccount = SocialAccount::query()+ ->with('workspace.account.plan')+ ->find($this->socialAccountId);++ $account = $socialAccount?->workspace?->account;++ $distinctId = $this->userId ?? $account?->owner_id;++ if (blank($account) || blank($distinctId)) {+ return;+ }++ $nthChannel = $account->socialAccounts()+ ->where(fn (Builder $query) => $query+ ->where('social_accounts.created_at', '<', $socialAccount->created_at)+ ->orWhere(fn (Builder $tied) => $tied+ ->where('social_accounts.created_at', $socialAccount->created_at)+ ->where('social_accounts.id', '<=', $socialAccount->id)))+ ->count();++ $postHog->capture(+ (string) $distinctId,+ SocialAccountEvent::Connected->value,+ [+ 'social_account_id' => (string) $socialAccount->id,+ 'platform' => $socialAccount->platform->value,+ 'network' => $socialAccount->platform->network(),+ 'workspace_id' => (string) $socialAccount->workspace_id,+ 'source' => $this->source,+ 'nth_channel' => $nthChannel,+ ],+ $account,+ );+ }+}diff --git a/app/Jobs/PostHog/TrackSocialAccountConnectionLost.php b/app/Jobs/PostHog/TrackSocialAccountConnectionLost.phpnew file mode 100644index 000000000..8f9098c52--- /dev/null+++ b/app/Jobs/PostHog/TrackSocialAccountConnectionLost.php@@ -0,0 +1,63 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\SocialAccountEvent;+use App\Enums\SocialAccount\Status;+use App\Models\SocialAccount;+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;++/**+ * The channel stayed in the workspace but lost its connection (expired token,+ * failed verification). Nobody acted, so the event goes to the account owner.+ */+class TrackSocialAccountConnectionLost implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ public function __construct(+ public string $socialAccountId,+ public Status $status,+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $socialAccount = SocialAccount::query()->with('workspace.account.plan')->find($this->socialAccountId);+ $account = $socialAccount?->workspace?->account;++ if (blank($account?->owner_id)) {+ return;+ }++ $postHog->capture(+ (string) $account->owner_id,+ SocialAccountEvent::Disconnected->value,+ [+ 'social_account_id' => (string) $socialAccount->id,+ 'platform' => $socialAccount->platform->value,+ 'network' => $socialAccount->platform->network(),+ 'workspace_id' => (string) $socialAccount->workspace_id,+ 'reason' => $this->status->value,+ 'error_type' => $this->status->value,+ ],+ $account,+ );+ }+}diff --git a/app/Jobs/PostHog/TrackSocialAccountRemoved.php b/app/Jobs/PostHog/TrackSocialAccountRemoved.phpnew file mode 100644index 000000000..77110e499--- /dev/null+++ b/app/Jobs/PostHog/TrackSocialAccountRemoved.php@@ -0,0 +1,65 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\SocialAccountEvent;+use App\Enums\SocialAccount\Platform;+use App\Models\Workspace;+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;++/**+ * A member removed the channel. The row is gone by the time this runs, so the+ * channel is described by the values read before it was deleted.+ */+class TrackSocialAccountRemoved implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public const REASON = 'removed';++ public int $tries = 3;++ public int $timeout = 30;++ public function __construct(+ public string $userId,+ public string $socialAccountId,+ public string $workspaceId,+ public Platform $platform,+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $account = Workspace::query()->with('account.plan')->find($this->workspaceId)?->account;++ if (blank($account)) {+ return;+ }++ $postHog->capture(+ $this->userId,+ SocialAccountEvent::Disconnected->value,+ [+ 'social_account_id' => $this->socialAccountId,+ 'platform' => $this->platform->value,+ 'network' => $this->platform->network(),+ 'workspace_id' => $this->workspaceId,+ 'reason' => self::REASON,+ ],+ $account,+ );+ }+}diff --git a/app/Jobs/PostHog/TrackTrialConverted.php b/app/Jobs/PostHog/TrackTrialConverted.phpindex ebf7a283c..e6fbd4435 100644--- a/app/Jobs/PostHog/TrackTrialConverted.php+++ b/app/Jobs/PostHog/TrackTrialConverted.php@@ -8,8 +8,13 @@ use App\Enums\PostHog\TrialEvent;use App\Models\Account;use App\Support\StripeSubscriptionConversion;-class TrackTrialConverted extends AbstractTrackStripeSubscriptionEvent+class TrackTrialConverted extends AbstractTrackStripeEvent{+ protected function shouldCapture(Account $account): bool+ {+ return filled($account->plan);+ }+protected function event(): string{return TrialEvent::Converted->value;diff --git a/app/Jobs/PostHog/TrackTrialStarted.php b/app/Jobs/PostHog/TrackTrialStarted.phpindex 0c0db0970..5b1bdb602 100644--- a/app/Jobs/PostHog/TrackTrialStarted.php+++ b/app/Jobs/PostHog/TrackTrialStarted.php@@ -9,8 +9,13 @@ use App\Models\Account;use App\Support\StripeSubscriptionConversion;use Illuminate\Support\Carbon;-class TrackTrialStarted extends AbstractTrackStripeSubscriptionEvent+class TrackTrialStarted extends AbstractTrackStripeEvent{+ protected function shouldCapture(Account $account): bool+ {+ return filled($account->plan);+ }+protected function event(): string{return TrialEvent::Started->value;diff --git a/app/Jobs/PostHog/TrackWorkspaceLimitHit.php b/app/Jobs/PostHog/TrackWorkspaceLimitHit.phpnew file mode 100644index 000000000..3c92d8efb--- /dev/null+++ b/app/Jobs/PostHog/TrackWorkspaceLimitHit.php@@ -0,0 +1,61 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Enums\PostHog\WorkspaceEvent;+use App\Models\User;+use App\Services\PostHogService;+use Carbon\CarbonInterface;+use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Bus\Dispatchable;+use Illuminate\Queue\InteractsWithQueue;+use Illuminate\Queue\SerializesModels;++class TrackWorkspaceLimitHit implements ShouldQueue+{+ use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;++ public int $tries = 3;++ public int $timeout = 30;++ /**+ * The plan and the limit are the ones the refusal saw: an upgrade right+ * after it must not make the event read as a hit on the new plan.+ */+ public function __construct(+ public string $userId,+ public ?string $planSlug,+ public ?int $workspaceLimit,+ public CarbonInterface $hitAt,+ ) {+ $this->onQueue('posthog');+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $account = User::query()->with('account.plan')->find($this->userId)?->account;++ if (blank($account)) {+ return;+ }++ $postHog->capture(+ $this->userId,+ WorkspaceEvent::LimitHit->value,+ [+ 'plan_slug' => $this->planSlug,+ 'workspaces_count' => $account->workspaces()->where('workspaces.created_at', '<=', $this->hitAt)->count(),+ 'workspace_limit' => $this->workspaceLimit,+ ],+ $account,+ );+ }+}diff --git a/app/Listeners/StripeBillingSignalListener.php b/app/Listeners/StripeBillingSignalListener.phpnew file mode 100644index 000000000..4b2c48d99--- /dev/null+++ b/app/Listeners/StripeBillingSignalListener.php@@ -0,0 +1,82 @@+<?php++declare(strict_types=1);++namespace App\Listeners;++use App\Jobs\PostHog\AbstractTrackStripeEvent;+use App\Jobs\PostHog\TrackCheckoutExpired;+use App\Jobs\PostHog\TrackInvoicePaymentFailed;+use App\Jobs\PostHog\TrackInvoiceUpcoming;+use App\Models\Account;+use App\Services\PostHogService;+use Illuminate\Support\Arr;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Log;+use Laravel\Cashier\Cashier;+use Laravel\Cashier\Events\WebhookReceived;+use Stripe\Checkout\Session as StripeCheckoutSession;+use Stripe\Event as StripeEvent;+use Throwable;++class StripeBillingSignalListener+{+ /**+ * @var array<string, class-string<AbstractTrackStripeEvent>>+ */+ public const JOBS = [+ StripeEvent::TYPE_CHECKOUT_SESSION_EXPIRED => TrackCheckoutExpired::class,+ StripeEvent::TYPE_INVOICE_PAYMENT_FAILED => TrackInvoicePaymentFailed::class,+ StripeEvent::TYPE_INVOICE_UPCOMING => TrackInvoiceUpcoming::class,+ ];++ public function handle(WebhookReceived $event): void+ {+ try {+ $type = data_get($event->payload, 'type');++ $job = Arr::get(self::JOBS, $type);++ if (blank($job)) {+ return;+ }++ if ($this->alreadyProcessed(data_get($event->payload, 'id'))) {+ return;+ }++ $stripeCustomerId = data_get($event->payload, 'data.object.customer');++ if (blank($stripeCustomerId) || ! PostHogService::shouldTrack()) {+ return;+ }++ if ($type === StripeEvent::TYPE_CHECKOUT_SESSION_EXPIRED && data_get($event->payload, 'data.object.mode') !== StripeCheckoutSession::MODE_SUBSCRIPTION) {+ return;+ }++ /** @var Account|null $account */+ $account = Cashier::findBillable($stripeCustomerId);++ if (! $account) {+ return;+ }++ $job::dispatch((string) $account->id, $event->payload);+ } catch (Throwable $e) {+ Log::error("Stripe billing signal error: {$e->getMessage()}", [+ 'exception' => $e,+ 'payload' => $event->payload,+ ]);+ }+ }++ private function alreadyProcessed(?string $eventId): bool+ {+ if (blank($eventId)) {+ return false;+ }++ return ! Cache::add("stripe_billing_signal:{$eventId}", true, now()->addDay());+ }+}diff --git a/app/Listeners/StripeEventListener.php b/app/Listeners/StripeEventListener.phpindex efcb5187c..fa3f754e9 100644--- a/app/Listeners/StripeEventListener.php+++ b/app/Listeners/StripeEventListener.php@@ -7,6 +7,7 @@ namespace App\Listeners;use App\Enums\PostHog\BillingEvent;use App\Jobs\PostHog\TrackBilling;use App\Jobs\PostHog\TrackCheckoutCompleted;+use App\Jobs\PostHog\TrackPlanChanged;use App\Jobs\PostHog\TrackTrialConverted;use App\Jobs\PostHog\TrackTrialStarted;use App\Models\Account;@@ -15,7 +16,11 @@ use App\Services\PostHogService;use App\Support\Billing\SubscriptionPlanSync;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Log;+use Laravel\Cashier\Cashier;use Laravel\Cashier\Events\WebhookHandled;+use Stripe\Event as StripeEvent;+use Stripe\Subscription as StripeSubscription;+use Throwable;class StripeEventListener{@@ -33,20 +38,21 @@ class StripeEventListenerreturn;}- $account = Account::where('stripe_id', $stripeCustomerId)->first();+ /** @var Account|null $account */+ $account = Cashier::findBillable($stripeCustomerId);if (! $account) {return;}match ($type) {- 'customer.subscription.created' => $this->handleSubscriptionCreated($account, $event->payload),- 'customer.subscription.updated' => $this->handleSubscriptionUpdated($account, $event->payload),- 'customer.subscription.deleted' => $this->handleSubscriptionDeleted($account, $event->payload),+ StripeEvent::TYPE_CUSTOMER_SUBSCRIPTION_CREATED => $this->handleSubscriptionCreated($account, $event->payload),+ StripeEvent::TYPE_CUSTOMER_SUBSCRIPTION_UPDATED => $this->handleSubscriptionUpdated($account, $event->payload),+ StripeEvent::TYPE_CUSTOMER_SUBSCRIPTION_DELETED => $this->handleSubscriptionDeleted($account, $event->payload),default => null,};- } catch (\Exception $e) {- Log::error('Stripe webhook error: '.$e->getMessage(), [+ } catch (Throwable $e) {+ Log::error("Stripe webhook error: {$e->getMessage()}", ['exception' => $e,'payload' => $event->payload,]);@@ -54,6 +60,10 @@ class StripeEventListener}/**+ * A subscription is born either `trialing` (card-required trial, no charge+ * yet) or `active` (first-month coupon or no trial, charged at once): two+ * business events, see App\Support\StripeSubscriptionConversion.+ ** @param array<string, mixed> $payload*/protected function handleSubscriptionCreated(Account $account, array $payload): void@@ -61,9 +71,11 @@ class StripeEventListener$previousPlan = $account->plan?->name;$this->syncPlanFromSubscription($account, $payload, clearGenericTrial: true);+ $this->recordFirstPayment($account, $payload);- $this->trackPlanChange($account, BillingEvent::Created, $previousPlan, $payload);- $this->trackSubscriptionStart($account, $payload);+ TrackBilling::dispatchIf(PostHogService::shouldTrack(), (string) $account->id, BillingEvent::Created, $payload, $previousPlan);+ TrackTrialStarted::dispatchIf(PostHogService::shouldTrack() && $this->currentStatus($payload) === StripeSubscription::STATUS_TRIALING, (string) $account->id, $payload);+ TrackCheckoutCompleted::dispatchIf(PostHogService::shouldTrack() && $this->currentStatus($payload) === StripeSubscription::STATUS_ACTIVE, (string) $account->id, $payload);}/**@@ -74,9 +86,11 @@ class StripeEventListener$previousPlan = $account->plan?->name;$this->syncPlanFromSubscription($account, $payload);+ $this->recordFirstPayment($account, $payload);- $this->trackPlanChange($account, BillingEvent::Updated, $previousPlan, $payload);- $this->trackTrialConversion($account, $payload);+ TrackBilling::dispatchIf(PostHogService::shouldTrack(), (string) $account->id, BillingEvent::Updated, $payload, $previousPlan);+ TrackTrialConverted::dispatchIf(PostHogService::shouldTrack() && $this->convertedFromTrial($payload) && $this->isNowActive($payload), (string) $account->id, $payload);+ TrackPlanChanged::dispatchIf(PostHogService::shouldTrack() && $this->priceChanged($payload), (string) $account->id, $payload);}/**@@ -84,15 +98,37 @@ class StripeEventListener*/protected function handleSubscriptionDeleted(Account $account, array $payload): void{- if ($account->plan_id === null) {+ if ($account->plan_id === null && ! $account->hasPaidSubscription()) {return;}$previousPlan = $account->plan?->name;- $account->update(['plan_id' => null]);+ if ($account->plan_id !== null) {+ $account->update(['plan_id' => null]);+ }- $this->trackPlanChange($account, BillingEvent::Cancelled, $previousPlan, $payload);+ TrackBilling::dispatchIf(+ PostHogService::shouldTrack() && $this->claimCancellation($payload),+ (string) $account->id,+ BillingEvent::Cancelled,+ $payload,+ $previousPlan,+ );+ }++ /**+ * One subscription.cancelled per subscription. A dunning that ends in+ * `unpaid` clears plan_id before the delete arrives, so plan_id can no+ * longer tell a first delivery from one Stripe redelivers days later.+ *+ * @param array<string, mixed> $payload+ */+ private function claimCancellation(array $payload): bool+ {+ $subscriptionId = data_get($payload, 'data.object.id');++ return blank($subscriptionId) || Cache::add("posthog:subscription_cancelled:{$subscriptionId}", true, now()->addDays(30));}/**@@ -111,6 +147,21 @@ class StripeEventListenerreturn ! Cache::add("stripe_webhook_event:{$eventId}", true, now()->addDay());}+ /**+ * The first time a subscription is active the account has been charged:+ * kept on the account because Cashier clears `trial_ends_at` on delete.+ *+ * @param array<string, mixed> $payload+ */+ private function recordFirstPayment(Account $account, array $payload): void+ {+ if (! $this->isNowActive($payload) || filled($account->first_paid_at)) {+ return;+ }++ Account::withoutTimestamps(fn (): bool => $account->forceFill(['first_paid_at' => now()])->saveQuietly());+ }+/*** @param array<string, mixed> $payload*/@@ -155,12 +206,7 @@ class StripeEventListenerreturn null;}- $plan = Plan::query()- ->where(function ($query) use ($priceIds): void {- $query->whereIn('stripe_monthly_price_id', $priceIds)- ->orWhereIn('stripe_yearly_price_id', $priceIds);- })- ->first();+ $plan = Plan::forStripePrices($priceIds)->first();if (! $plan) {Log::warning('Stripe webhook: no matching plan found in subscription items', [@@ -172,58 +218,6 @@ class StripeEventListenerreturn $plan;}- /**- * @param array<string, mixed> $payload- */- private function trackPlanChange(Account $account, BillingEvent $event, ?string $previousPlan, array $payload): void- {- if (! PostHogService::shouldTrack()) {- return;- }-- TrackBilling::dispatch((string) $account->id, $event, $payload, $previousPlan);- }-- /**- * A subscription is born either `trialing` (card-required trial, no- * charge yet) or `active` (first-month coupon or no trial — charged- * immediately). These are different business events, not the same- * "checkout completed" moment — see App\Support\StripeSubscriptionConversion.- *- * @param array<string, mixed> $payload- */- private function trackSubscriptionStart(Account $account, array $payload): void- {- if (! PostHogService::shouldTrack()) {- return;- }-- match ($this->currentStatus($payload)) {- 'trialing' => TrackTrialStarted::dispatch((string) $account->id, $payload),- 'active' => TrackCheckoutCompleted::dispatch((string) $account->id, $payload),- default => null,- };- }-- /**- * Fires on the trial's first successful charge, using Stripe's own- * `previous_attributes` rather than trusting local DB state. This also- * covers a `past_due` recovery without mistaking a later billing-cycle- * recovery for the trial conversion.- *- * @param array<string, mixed> $payload- */- private function trackTrialConversion(Account $account, array $payload): void- {- if (! PostHogService::shouldTrack()) {- return;- }-- if ($this->convertedFromTrial($payload) && $this->isNowActive($payload)) {- TrackTrialConverted::dispatch((string) $account->id, $payload);- }- }-/*** @param array<string, mixed> $payload*/@@ -249,11 +243,11 @@ class StripeEventListener{$previousStatus = data_get($payload, 'data.previous_attributes.status');- if ($previousStatus === 'trialing') {+ if ($previousStatus === StripeSubscription::STATUS_TRIALING) {return true;}- if ($previousStatus !== 'past_due') {+ if ($previousStatus !== StripeSubscription::STATUS_PAST_DUE) {return false;}@@ -263,11 +257,21 @@ class StripeEventListenerreturn $trialEnd !== null && $currentPeriodStart === $trialEnd;}+ /**+ * @param array<string, mixed> $payload+ */+ private function priceChanged(array $payload): bool+ {+ $previousPriceId = data_get($payload, 'data.previous_attributes.items.data.0.price.id');++ return filled($previousPriceId) && $previousPriceId !== data_get($payload, 'data.object.items.data.0.price.id');+ }+/*** @param array<string, mixed> $payload*/private function isNowActive(array $payload): bool{- return $this->currentStatus($payload) === 'active';+ return $this->currentStatus($payload) === StripeSubscription::STATUS_ACTIVE;}}diff --git a/app/Models/Account.php b/app/Models/Account.phpindex 650ec5bf7..0a683e7f3 100644--- a/app/Models/Account.php+++ b/app/Models/Account.php@@ -4,15 +4,18 @@ declare(strict_types=1);namespace App\Models;+use App\Enums\Account\LifecycleStage;use App\Models\Traits\BillsOwnerAsStripeCustomer;use App\Models\Traits\HasUsage;use Carbon\CarbonInterface;use Database\Factories\AccountFactory;+use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Concerns\HasUuids;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\HasMany;+use Illuminate\Database\Eloquent\Relations\HasManyThrough;class Account extends Model{@@ -38,6 +41,10 @@ class Account extends Model'onboarding_completed_at' => 'datetime','onboarding_dismissed_at' => 'datetime','onboarding_skipped_steps' => 'array',+ 'lifecycle_stage' => LifecycleStage::class,+ 'lifecycle_stage_changed_at' => 'datetime',+ 'activated_at' => 'datetime',+ 'first_paid_at' => 'datetime',];public function owner(): BelongsTo@@ -65,6 +72,50 @@ class Account extends Modelreturn $this->hasMany(Invite::class);}+ public function posts(): HasManyThrough+ {+ return $this->hasManyThrough(Post::class, Workspace::class);+ }++ public function socialAccounts(): HasManyThrough+ {+ return $this->hasManyThrough(SocialAccount::class, Workspace::class);+ }++ /**+ * The aggregates the lifecycle stage is resolved from: whether any channel+ * exists, whatever its status, and the first and last posts TryPost published.+ */+ public function scopeWithLifecycleActivity(Builder $query): Builder+ {+ $publishedByTryPost = fn (Builder $posts): Builder => $posts->createdInTryPost()->publicationPublished();++ return $query+ ->withExists('socialAccounts as has_social_account')+ ->withMin(['posts as first_published_at' => $publishedByTryPost], 'published_at')+ ->withMax(['posts as last_published_at' => $publishedByTryPost], 'published_at')+ ->withCasts([+ 'has_social_account' => 'boolean',+ 'first_published_at' => 'datetime',+ 'last_published_at' => 'datetime',+ ]);+ }++ public function hasHadBillableSubscription(): bool+ {+ return $this->subscriptions->contains(fn (Subscription $subscription): bool => $subscription->becameBillable());+ }++ /**+ * Charged at least once. Cashier clears `trial_ends_at` when a subscription+ * is deleted, so a trial cancelled before its first charge cannot be told+ * apart from a paid one afterwards; `first_paid_at` keeps that fact.+ */+ public function hasPaidSubscription(): bool+ {+ return filled($this->first_paid_at);+ }+public function hasActiveSubscription(): bool{if (config('trypost.self_hosted')) {diff --git a/app/Models/Plan.php b/app/Models/Plan.phpindex 21904005b..d33b5b3b6 100644--- a/app/Models/Plan.php+++ b/app/Models/Plan.php@@ -46,4 +46,15 @@ class Plan extends Model{return $query->where('is_archived', false);}++ /**+ * @param array<int, string> $priceIds+ */+ public function scopeForStripePrices(Builder $query, array $priceIds): Builder+ {+ return $query->where(function (Builder $query) use ($priceIds): void {+ $query->whereIn('stripe_monthly_price_id', $priceIds)+ ->orWhereIn('stripe_yearly_price_id', $priceIds);+ });+ }}diff --git a/app/Models/Subscription.php b/app/Models/Subscription.phpindex 8a5ac056b..296c3292a 100644--- a/app/Models/Subscription.php+++ b/app/Models/Subscription.php@@ -6,8 +6,15 @@ namespace App\Models;use Illuminate\Database\Eloquent\Concerns\HasUuids;use Laravel\Cashier\Subscription as CashierSubscription;+use Stripe\Subscription as StripeSubscription;class Subscription extends CashierSubscription{use HasUuids;++ /** Incomplete / incomplete_expired never became billable. */+ public function becameBillable(): bool+ {+ return ! $this->incomplete() && $this->stripe_status !== StripeSubscription::STATUS_INCOMPLETE_EXPIRED;+ }}diff --git a/app/Models/Traits/HasWorkspace.php b/app/Models/Traits/HasWorkspace.phpindex 9ed100e0f..77c9dcba4 100644--- a/app/Models/Traits/HasWorkspace.php+++ b/app/Models/Traits/HasWorkspace.php@@ -67,6 +67,22 @@ trait HasWorkspacereturn Workspace::where('user_id', $this->id)->count();}+ /**+ * The workspace limit never applies self-hosted, nor to the first workspace.+ */+ public function workspaceLimitApplies(): bool+ {+ return ! config('trypost.self_hosted') && $this->ownedWorkspacesCount() > 0;+ }++ /**+ * The account already holds as many workspaces as its plan allows.+ */+ public function atWorkspaceLimit(): bool+ {+ return $this->workspaceLimitApplies() && $this->account?->canCreateWorkspace() === false;+ }+/*** The account owner always manages every workspace of the account.*/diff --git a/app/Observers/SocialAccountObserver.php b/app/Observers/SocialAccountObserver.phpindex 82389d309..d8d53824c 100644--- a/app/Observers/SocialAccountObserver.php+++ b/app/Observers/SocialAccountObserver.php@@ -10,9 +10,11 @@ use App\Enums\SocialAccount\Platform;use App\Enums\SocialAccount\Status;use App\Jobs\PostHog\IdentifyConnectedPlatforms;use App\Jobs\PostHog\SyncAccountUsage;+use App\Jobs\PostHog\TrackSocialAccountConnectionLost;use App\Models\SocialAccount;use App\Services\PostHogService;use App\Services\Repurpose\RepurposeAccountSync;+use Illuminate\Support\Facades\DB;class SocialAccountObserver{@@ -65,6 +67,16 @@ class SocialAccountObserverif ($connectionChanged && $isConnected) {app(DispatchAccountAnalytics::class)->handle($socialAccount);}++ if ($connectionChanged && $wasConnected) {+ $status = $socialAccount->status;++ DB::afterCommit(function () use ($socialAccount, $status): void {+ rescue(function () use ($socialAccount, $status): void {+ TrackSocialAccountConnectionLost::dispatchIf(PostHogService::isEnabled(), (string) $socialAccount->id, $status);+ });+ });+ }}private function forgetPinterestBoards(SocialAccount $socialAccount): voiddiff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.phpindex d69f640ee..64d6b0d56 100644--- a/app/Providers/AppServiceProvider.php+++ b/app/Providers/AppServiceProvider.php@@ -5,7 +5,6 @@ declare(strict_types=1);namespace App\Providers;use App\Actions\Mcp\ListChatGptEgressRanges;-use App\Listeners\StripeEventListener;use App\Models\AccessToken;use App\Models\Account;use App\Models\AnalyticsAccountDailySnapshot;@@ -59,7 +58,6 @@ use Illuminate\Support\Facades\RateLimiter;use Illuminate\Support\ServiceProvider;use Illuminate\Validation\Rules\Password;use Laravel\Cashier\Cashier;-use Laravel\Cashier\Events\WebhookHandled;use Laravel\Nightwatch\Facades\Nightwatch;use Laravel\Nightwatch\Records\CacheEvent;use Laravel\Socialite\Facades\Socialite;@@ -95,7 +93,6 @@ class AppServiceProvider extends ServiceProvider$this->configurePostHog();$this->configureRateLimiting();$this->configureSocialite();- $this->configureStripeWebhooks();Cashier::useCustomerModel(Account::class);Cashier::useSubscriptionModel(Subscription::class);@@ -229,11 +226,6 @@ class AppServiceProvider extends ServiceProvider});}- protected function configureStripeWebhooks(): void- {- Event::listen(WebhookHandled::class, StripeEventListener::class);- }-protected function configureSocialite(): void{// Google Auth (login/signup) - separate from YouTube OAuthdiff --git a/app/Support/Billing/ConfigureSubscriptionCheckout.php b/app/Support/Billing/ConfigureSubscriptionCheckout.phpindex 36a80de84..4bf0b7336 100644--- a/app/Support/Billing/ConfigureSubscriptionCheckout.php+++ b/app/Support/Billing/ConfigureSubscriptionCheckout.php@@ -8,12 +8,17 @@ use App\Models\Account;use App\Models\Plan;use Laravel\Cashier\SubscriptionBuilder;use RuntimeException;-use Stripe\Subscription as StripeSubscription;final class ConfigureSubscriptionCheckout{public const FIRST_MONTH_COUPON_METADATA_KEY = 'trypost_first_month_coupon_id';+ public const PLAN_METADATA_KEY = 'trypost_plan_slug';++ public const INTERVAL_METADATA_KEY = 'trypost_interval';++ public const FIRST_MONTH_OFFER_METADATA_KEY = 'trypost_first_month_offer';+/*** Stripe Checkout rejects subscription trials shorter than 48 hours.*/@@ -82,11 +87,6 @@ final class ConfigureSubscriptionCheckout/** Incomplete / incomplete_expired never became billable, so retries still count as first-time. */private static function isFirstTimeSubscriber(Account $account): bool{- return ! $account->subscriptions()- ->whereNotIn('stripe_status', [- StripeSubscription::STATUS_INCOMPLETE,- StripeSubscription::STATUS_INCOMPLETE_EXPIRED,- ])- ->exists();+ return ! $account->hasHadBillableSubscription();}}diff --git a/app/Support/Billing/FirstFullCharge.php b/app/Support/Billing/FirstFullCharge.phpnew file mode 100644index 000000000..277ae31a0--- /dev/null+++ b/app/Support/Billing/FirstFullCharge.php@@ -0,0 +1,22 @@+<?php++declare(strict_types=1);++namespace App\Support\Billing;++use App\Enums\Billing\Interval;+use Carbon\CarbonInterface;++final class FirstFullCharge+{+ private const GRACE_DAYS = 2;++ public static function isFirst(CarbonInterface $subscriptionStartedAt, CarbonInterface $chargeAt, Interval $interval): bool+ {+ $previousCharge = $interval === Interval::Yearly+ ? $chargeAt->copy()->subYearsNoOverflow(1)+ : $chargeAt->copy()->subMonthsNoOverflow(1);++ return $subscriptionStartedAt->greaterThan($previousCharge->subDays(self::GRACE_DAYS));+ }+}diff --git a/app/Support/Billing/StripeValue.php b/app/Support/Billing/StripeValue.phpnew file mode 100644index 000000000..d29f6ee3e--- /dev/null+++ b/app/Support/Billing/StripeValue.php@@ -0,0 +1,34 @@+<?php++declare(strict_types=1);++namespace App\Support\Billing;++use Carbon\CarbonImmutable;+use Illuminate\Support\Str;++/**+ * Reads the raw values of a Stripe payload, null when a value is missing or+ * not of the type Stripe sends.+ */+final class StripeValue+{+ /**+ * Stripe sends amounts in cents; TryPost charges in BRL, USD and EUR only,+ * all with two decimals.+ */+ public static function amount(mixed $cents): ?float+ {+ return is_int($cents) ? $cents / 100 : null;+ }++ public static function currency(mixed $currency): ?string+ {+ return is_string($currency) && filled($currency) ? Str::upper($currency) : null;+ }++ public static function timestamp(mixed $seconds): ?CarbonImmutable+ {+ return is_numeric($seconds) ? CarbonImmutable::createFromTimestampUTC((int) $seconds) : null;+ }+}diff --git a/app/Support/Social/PendingConnection.php b/app/Support/Social/PendingConnection.phpindex 0bf2cb764..20d103fd4 100644--- a/app/Support/Social/PendingConnection.php+++ b/app/Support/Social/PendingConnection.php@@ -172,6 +172,15 @@ final class PendingConnection));}+ /**+ * The route name of the page the flow started from, which is also where+ * close, Back and the error states return.+ */+ public function returnRouteName(): string+ {+ return (string) data_get($this->data, 'return.name', self::DEFAULT_RETURN_ROUTE);+ }+public function returnUrl(): string{return self::urlFor(data_get($this->data, 'return'));diff --git a/app/Support/StripeSubscriptionConversion.php b/app/Support/StripeSubscriptionConversion.phpindex a824dee9e..76c4f9c97 100644--- a/app/Support/StripeSubscriptionConversion.php+++ b/app/Support/StripeSubscriptionConversion.php@@ -4,8 +4,10 @@ declare(strict_types=1);namespace App\Support;+use App\Enums\Billing\Interval;use App\Models\Account;use App\Support\Billing\ConfigureSubscriptionCheckout;+use App\Support\Billing\StripeValue;use Illuminate\Support\Carbon;final class StripeSubscriptionConversion@@ -22,13 +24,9 @@ final class StripeSubscriptionConversion*/public static function baseProperties(Account $account, array $payload): array{- $priceId = data_get($payload, 'data.object.items.data.0.price.id');- $yearlyPriceId = $account->plan->stripe_yearly_price_id;- $isYearly = $yearlyPriceId !== null && $priceId === $yearlyPriceId;-return ['plan_name' => $account->plan->name,- 'interval' => $isYearly ? 'yearly' : 'monthly',+ 'interval' => Interval::forPrice($account->plan, data_get($payload, 'data.object.items.data.0.price.id'))->value,];}@@ -43,12 +41,12 @@ final class StripeSubscriptionConversion{$properties = self::baseProperties($account, $payload);- $unitAmount = data_get($payload, 'data.object.items.data.0.price.unit_amount');- $currency = data_get($payload, 'data.object.items.data.0.price.currency');+ $currency = StripeValue::currency(data_get($payload, 'data.object.items.data.0.price.currency'));+ $conversionValue = StripeValue::amount(data_get($payload, 'data.object.items.data.0.price.unit_amount'));- if (is_int($unitAmount) && is_string($currency)) {- $properties['conversion_value'] = (float) ($unitAmount / 100);- $properties['conversion_currency'] = strtoupper($currency);+ if (filled($conversionValue) && filled($currency)) {+ $properties['conversion_value'] = $conversionValue;+ $properties['conversion_currency'] = $currency;$properties['conversion_transaction_id'] = data_get($payload, 'data.object.id');}diff --git a/config/cashier.php b/config/cashier.phpindex e08fc3b2b..48020b121 100644--- a/config/cashier.php+++ b/config/cashier.php@@ -2,6 +2,7 @@declare(strict_types=1);+use App\Listeners\StripeBillingSignalListener;use Laravel\Cashier\Console\WebhookCommand;use Laravel\Cashier\Invoices\DompdfInvoiceRenderer;@@ -49,7 +50,10 @@ return ['webhook' => ['secret' => env('STRIPE_WEBHOOK_SECRET'),'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300),- 'events' => WebhookCommand::DEFAULT_EVENTS,+ 'events' => [+ ...WebhookCommand::DEFAULT_EVENTS,+ ...array_keys(StripeBillingSignalListener::JOBS),+ ],],/*diff --git a/database/migrations/2026_10_19_143226_add_lifecycle_to_accounts_table.php b/database/migrations/2026_10_19_143226_add_lifecycle_to_accounts_table.phpnew file mode 100644index 000000000..67ab13b6e--- /dev/null+++ b/database/migrations/2026_10_19_143226_add_lifecycle_to_accounts_table.php@@ -0,0 +1,66 @@+<?php++declare(strict_types=1);++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Query\Builder;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::table('accounts', function (Blueprint $table) {+ $table->string('lifecycle_stage')->nullable();+ $table->timestamp('lifecycle_stage_changed_at')->nullable();+ $table->timestamp('activated_at')->nullable();+ $table->timestamp('first_paid_at')->nullable();+ });++ $this->backfillFirstPaidAt();+ }++ /**+ * Mark the accounts already charged before `first_paid_at` existed: any+ * subscription past its checkout and its trial. A past due one whose trial+ * ended within a month failed its first charge and is not paid. A trial+ * cancelled before this deploy has lost its `trial_ends_at` to Cashier and+ * counts as paid.+ */+ public function backfillFirstPaidAt(): void+ {+ DB::table('subscriptions')+ ->select('account_id', DB::raw('min(created_at) as first_paid_at'))+ ->whereNotIn('stripe_status', ['incomplete', 'incomplete_expired', 'trialing'])+ ->where(fn (Builder $query) => $query+ ->whereNotIn('stripe_status', ['past_due', 'unpaid'])+ ->orWhereNull('trial_ends_at')+ ->orWhere('trial_ends_at', '<', now()->subMonth()))+ ->whereNot(fn (Builder $query) => $query+ ->whereNotNull('ends_at')+ ->whereNotNull('trial_ends_at')+ ->whereColumn('ends_at', '<=', 'trial_ends_at'))+ ->groupBy('account_id')+ ->orderBy('account_id')+ ->chunk(500, function ($rows): void {+ foreach ($rows as $row) {+ DB::table('accounts')->where('id', $row->account_id)->whereNull('first_paid_at')->update(['first_paid_at' => $row->first_paid_at]);+ }+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('accounts', function (Blueprint $table) {+ $table->dropColumn(['lifecycle_stage', 'lifecycle_stage_changed_at', 'activated_at', 'first_paid_at']);+ });+ }+};diff --git a/resources/js/components/SidebarUserMenu.vue b/resources/js/components/SidebarUserMenu.vueindex 2f3d6b8ab..f57de1a8b 100644--- a/resources/js/components/SidebarUserMenu.vue+++ b/resources/js/components/SidebarUserMenu.vue@@ -14,6 +14,7 @@ import {import WorkspaceMenuContent from '@/components/WorkspaceMenuContent.vue';import WorkspaceUpgradeDialog from '@/components/workspaces/WorkspaceUpgradeDialog.vue';import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';+import { useWorkspaceLimit } from '@/composables/useWorkspaceLimit';import { portal } from '@/routes/app/billing';import type { User } from '@/types';@@ -36,12 +37,19 @@ const subscriptionPastDue = computed<boolean>(() =>);const { canCreateWorkspace } = useWorkspaceAbilities();+const { createOrUpgrade } = useWorkspaceLimit(+ () => workspaces.value.length,+);const workspaceUpgradeDialogOpen = ref(false);const openWorkspaceUpgradeDialog = (): void => {workspaceUpgradeDialogOpen.value = true;};++const handleCreateWorkspace = (): void => {+ createOrUpgrade(openWorkspaceUpgradeDialog);+};</script><template>@@ -116,7 +124,7 @@ const openWorkspaceUpgradeDialog = (): void => {:current-workspace="currentWorkspace":workspaces="workspaces":can-create-workspace="canCreateWorkspace"- @upgrade-required="openWorkspaceUpgradeDialog"+ @create-workspace="handleCreateWorkspace"/></DropdownMenuContent></DropdownMenu>diff --git a/resources/js/components/WorkspaceMenuContent.vue b/resources/js/components/WorkspaceMenuContent.vueindex 46c72652e..4730e0438 100644--- a/resources/js/components/WorkspaceMenuContent.vue+++ b/resources/js/components/WorkspaceMenuContent.vue@@ -39,7 +39,6 @@ import {import { useChangelogDialog } from '@/composables/useChangelogDialog';import { clearAllComposerAutosaves } from '@/composables/useComposerAutosave';import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';-import { useWorkspaceLimit } from '@/composables/useWorkspaceLimit';import { openSupportChat } from '@/lib/supportChat';import { cn } from '@/lib/utils';import posthog from '@/posthog';@@ -67,13 +66,12 @@ const props = defineProps<{}>();const emit = defineEmits<{- upgradeRequired: [];+ createWorkspace: [];}>();const page = usePage();const { canManageBilling, canManageTeam, canManageWorkspace } =useWorkspaceAbilities();-const { createOrUpgrade } = useWorkspaceLimit(() => props.workspaces.length);const selfHosted = computed(() => Boolean(page.props.selfHosted));const showBilling = computed(() => canManageBilling.value && !selfHosted.value,@@ -137,7 +135,7 @@ const switchWorkspace = (workspaceId: string): void => {};const handleCreateWorkspace = (): void => {- createOrUpgrade(() => emit('upgradeRequired'));+ emit('createWorkspace');};const handleLogout = (): void => {diff --git a/resources/js/composables/useWorkspaceLimit.ts b/resources/js/composables/useWorkspaceLimit.tsindex 0add0e1fc..4de1fbe70 100644--- a/resources/js/composables/useWorkspaceLimit.ts+++ b/resources/js/composables/useWorkspaceLimit.ts@@ -1,13 +1,24 @@-import { router, usePage } from '@inertiajs/vue3';+import { router, useHttp, usePage } from '@inertiajs/vue3';import { computed, toValue, type MaybeRefOrGetter } from 'vue';import { create as createWorkspaceRoute } from '@/routes/app/workspaces';+import { store as checkWorkspaceCreation } from '@/routes/app/workspaces/creation-check';import type { SharedData } from '@/types';+interface WorkspaceCreationCheck {+ allowed: boolean;+}++/**+ * The shared props answer whether the account is at its workspace cap on the+ * create page; creating from a menu asks the server, which opens the upgrade+ * dialog where the user is at the cap and the create page otherwise.+ */export const useWorkspaceLimit = (workspaceCount: MaybeRefOrGetter<number>,) => {const page = usePage<SharedData>();+ const http = useHttp<Record<string, never>, WorkspaceCreationCheck>({});const workspaceLimit = computed((): number | null => page.props.features?.workspaceLimit ?? null,@@ -24,14 +35,28 @@ export const useWorkspaceLimit = (return limit !== null && resolvedCount.value >= limit;});- const createOrUpgrade = (onUpgradeRequired: () => void): void => {- if (atWorkspaceLimit.value) {+ const visitCreatePage = (): void => {+ router.visit(createWorkspaceRoute.url());+ };++ const createOrUpgrade = async (+ onUpgradeRequired: () => void,+ ): Promise<void> => {+ if (http.processing) {+ return;+ }++ const check = await http+ .post(checkWorkspaceCreation.url())+ .catch(() => null);++ if (check?.allowed === false) {onUpgradeRequired();return;}- router.visit(createWorkspaceRoute.url());+ visitCreatePage();};return {diff --git a/resources/js/pages/workspaces/Create.vue b/resources/js/pages/workspaces/Create.vueindex 72a6ed5f5..cfd12b9fa 100644--- a/resources/js/pages/workspaces/Create.vue+++ b/resources/js/pages/workspaces/Create.vue@@ -6,7 +6,6 @@ import InputError from '@/components/InputError.vue';import { Button } from '@/components/ui/button';import { Input } from '@/components/ui/input';import { Label } from '@/components/ui/label';-import { Spinner } from '@/components/ui/spinner';import WorkspaceUpgradeDialog from '@/components/workspaces/WorkspaceUpgradeDialog.vue';import { useWorkspaceLimit } from '@/composables/useWorkspaceLimit';import AuthLayout from '@/layouts/AuthLayout.vue';@@ -60,9 +59,8 @@ const submit = (): void => {type="submit"class="w-full"data-testid="workspaces-create-submit"- :disabled="form.processing"+ :loading="form.processing">- <Spinner v-if="form.processing" />{{ $t('workspaces.create.submit') }}</Button></form>diff --git a/resources/js/pages/workspaces/Index.vue b/resources/js/pages/workspaces/Index.vueindex 944076597..c3fbb709c 100644--- a/resources/js/pages/workspaces/Index.vue+++ b/resources/js/pages/workspaces/Index.vue@@ -1,15 +1,15 @@<script setup lang="ts">-import { Head, router } from '@inertiajs/vue3';-import { IconCheck, IconPlus } from '@tabler/icons-vue';+import { Head, Link, router } from '@inertiajs/vue3';+import { IconCheck } from '@tabler/icons-vue';import { ref } from 'vue';import { Avatar } from '@/components/ui/avatar';-import { Badge } from '@/components/ui/badge';import { Button } from '@/components/ui/button';import WorkspaceUpgradeDialog from '@/components/workspaces/WorkspaceUpgradeDialog.vue';import { useWorkspaceAbilities } from '@/composables/useWorkspaceAbilities';import { useWorkspaceLimit } from '@/composables/useWorkspaceLimit';import AuthLayout from '@/layouts/AuthLayout.vue';+import { home } from '@/routes/app';import { switchMethod } from '@/routes/app/workspaces';interface Workspace {@@ -42,10 +42,12 @@ const switchToWorkspace = (workspace: Workspace): void => {);};+const openUpgradeDialog = (): void => {+ upgradeDialogOpen.value = true;+};+const handleCreateWorkspace = (): void => {- createOrUpgrade(() => {- upgradeDialogOpen.value = true;- });+ createOrUpgrade(openUpgradeDialog);};</script>@@ -55,71 +57,84 @@ const handleCreateWorkspace = (): void => {<AuthLayout:title="$t('workspaces.select_title')":description="$t('workspaces.select_description')"- width="md">- <ul class="flex flex-col gap-2" data-testid="workspaces-list">- <li v-for="workspace in workspaces" :key="workspace.id">- <button- type="button"- class="flex w-full cursor-pointer items-center gap-3 rounded-xl border border-border bg-card p-4 text-left transition-control hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"- :aria-current="- workspace.id === currentWorkspaceId ? 'true' : undefined- "- :data-testid="`workspaces-item-${workspace.id}`"- @click="switchToWorkspace(workspace)"- >- <Avatar- :src="workspace.logo_url"- :name="workspace.name"- class="size-10 shrink-0 rounded-lg"- fallback-class="rounded-lg bg-muted text-muted-foreground"- />- <span class="min-w-0 flex-1">- <span- class="block truncate text-sm leading-tight font-emphasis text-foreground"- >{{ workspace.name }}</span- >- <span- class="mt-1 block truncate text-sm text-muted-foreground"- >- {{- $t('workspaces.connections', {- count: String(- workspace.social_accounts_count,- ),- })- }}- ·- {{- $t('workspaces.posts', {- count: String(workspace.posts_count),- })- }}- </span>- </span>- <Badge- v-if="workspace.id === currentWorkspaceId"- variant="success"- class="h-6 shrink-0 gap-1 px-2 [&>svg]:size-4"+ <div class="flex flex-col gap-4">+ <ul+ class="flex flex-col divide-y divide-border overflow-hidden rounded-xl border border-border bg-card"+ data-testid="workspaces-list"+ >+ <li v-for="workspace in workspaces" :key="workspace.id">+ <button+ type="button"+ class="flex w-full cursor-pointer items-center gap-3 px-4 py-3 text-left transition-control hover:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring"+ :aria-current="+ workspace.id === currentWorkspaceId+ ? 'true'+ : undefined+ "+ :data-testid="`workspaces-item-${workspace.id}`"+ @click="switchToWorkspace(workspace)">- <IconCheck aria-hidden="true" />- {{ $t('workspaces.current') }}- </Badge>- </button>- </li>- </ul>+ <Avatar+ :src="workspace.logo_url"+ :name="workspace.name"+ class="size-9 shrink-0 rounded-lg"+ fallback-class="text-sm bg-primary-subtle text-primary-text font-bold"+ />+ <span class="grid min-w-0 flex-1 gap-0.5">+ <span+ class="truncate text-sm leading-5 font-semibold text-foreground"+ >{{ workspace.name }}</span+ >+ <span class="truncate text-xs text-muted-foreground">+ {{+ $t('workspaces.connections', {+ count: String(+ workspace.social_accounts_count,+ ),+ })+ }}+ ·+ {{+ $t('workspaces.posts', {+ count: String(workspace.posts_count),+ })+ }}+ </span>+ </span>+ <IconCheck+ v-if="workspace.id === currentWorkspaceId"+ class="size-4 shrink-0 text-foreground"+ stroke-width="2.5"+ :aria-label="$t('workspaces.current')"+ :data-testid="`workspaces-current-${workspace.id}`"+ />+ </button>+ </li>+ </ul>++ <div class="flex flex-col gap-2">+ <Button+ v-if="canCreateWorkspace"+ class="w-full"+ data-testid="workspaces-create"+ @click="handleCreateWorkspace"+ >+ {{ $t('workspaces.create.submit') }}+ </Button>- <Button- v-if="canCreateWorkspace"- variant="outline"- size="lg"- class="w-full bg-card text-base"- data-testid="workspaces-create"- @click="handleCreateWorkspace"- >- <IconPlus aria-hidden="true" />- {{ $t('workspaces.create.submit') }}- </Button>+ <Button+ v-if="currentWorkspaceId"+ as-child+ variant="outline"+ class="w-full bg-card"+ >+ <Link :href="home.url()" data-testid="workspaces-back">+ {{ $t('common.back') }}+ </Link>+ </Button>+ </div>+ </div><WorkspaceUpgradeDialog v-model:open="upgradeDialogOpen" /></AuthLayout>diff --git a/routes/app.php b/routes/app.phpindex 9a356257c..ad852b5ef 100644--- a/routes/app.php+++ b/routes/app.php@@ -55,6 +55,7 @@ use App\Http\Controllers\App\UnsplashController;use App\Http\Controllers\App\WebhookController;use App\Http\Controllers\App\WelcomeController;use App\Http\Controllers\App\WorkspaceController;+use App\Http\Controllers\App\WorkspaceCreationCheckController;use App\Http\Controllers\App\WorkspaceInviteController;use App\Http\Controllers\App\WorkspaceLabelController;use App\Http\Controllers\App\WorkspaceSignatureController;@@ -117,6 +118,9 @@ Route::middleware(['auth'])->group(function () {Route::get('workspaces/create', [WorkspaceController::class, 'create'])->name('app.workspaces.create');Route::post('workspaces', [WorkspaceController::class, 'store'])->name('app.workspaces.store');+ Route::post('workspaces/creation-check', [WorkspaceCreationCheckController::class, 'store'])+ ->middleware('throttle:30,1')+ ->name('app.workspaces.creation-check.store');});Route::middleware(['auth'])->group(function () {diff --git a/routes/console.php b/routes/console.phpindex d594bb09a..f2f530a4e 100644--- a/routes/console.php+++ b/routes/console.php@@ -17,8 +17,10 @@ use App\Console\Commands\RefreshExpiringTokens;use App\Console\Commands\Repurpose\PollRepurposes;use App\Console\Commands\ResolveTikTokVideoIds;use App\Console\Commands\RssFeed\PollRssFeeds;+use App\Console\Commands\SyncPostHogLifecycleStages;use App\Enums\SocialAccount\Platform;use App\Jobs\Analytics\FinalizeAccountDailySnapshots;+use App\Services\PostHogService;use App\Support\Analytics\DiscoverySchedule;use Illuminate\Support\Facades\Schedule;@@ -34,6 +36,7 @@ Schedule::command(PruneExpiredPostHistoryCommand::class)->daily()->withoutOverlaSchedule::command(PruneTemporaryUploadsCommand::class)->hourly()->withoutOverlapping()->onOneServer();Schedule::command(PollRepurposes::class)->everyFiveMinutes()->withoutOverlapping()->onOneServer();Schedule::command(PollRssFeeds::class)->everyFiveMinutes()->withoutOverlapping()->onOneServer();+Schedule::command(SyncPostHogLifecycleStages::class)->hourly()->when(PostHogService::isEnabled(...))->withoutOverlapping()->onOneServer();Schedule::command(DispatchAccountDailyAnalytics::class)->dailyAt('02:00')->timezone('UTC')diff --git a/tests/Browser/WorkspaceLimitTest.php b/tests/Browser/WorkspaceLimitTest.phpnew file mode 100644index 000000000..beb6112bb--- /dev/null+++ b/tests/Browser/WorkspaceLimitTest.php@@ -0,0 +1,96 @@+<?php++declare(strict_types=1);++use App\Enums\Plan\Slug;+use App\Jobs\PostHog\TrackWorkspaceLimitHit;+use App\Models\Plan;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ config([+ 'trypost.self_hosted' => false,+ 'services.posthog.enabled' => true,+ 'services.posthog.api_key' => 'phc_test_key',+ ]);+ Queue::fake([TrackWorkspaceLimitHit::class]);+});++$ownerOn = function (Slug $slug): User {+ $user = User::factory()->create();+ $user->account->update(['plan_id' => Plan::where('slug', $slug)->value('id')]);+ $workspace = Workspace::factory()->create(['account_id' => $user->account_id, 'user_id' => $user->id]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ subscribeAccount($user->account);++ return $user->fresh();+};++$clickNewWorkspaceInSidebar = function (mixed $page): void {+ waitFor($page, '@sidebar-workspace-menu');+ $page->click('@sidebar-workspace-menu');+ waitFor($page, '@sidebar-workspaces-trigger');+ $page->click('@sidebar-workspaces-trigger');+ waitFor($page, '@sidebar-create-workspace');+ $page->click('@sidebar-create-workspace');+};++test('at the cap, new workspace in the sidebar opens the upgrade dialog in place and tracks limit_hit', function () use ($ownerOn, $clickNewWorkspaceInSidebar) {+ $user = $ownerOn(Slug::Socials);+ $this->actingAs($user);++ $page = visit(route('app.posts.index'));+ $clickNewWorkspaceInSidebar($page);++ waitFor($page, '@workspace-upgrade-dialog');+ $page->assertVisible('@workspace-upgrade-dialog')+ ->assertPathIs(parse_url(route('app.posts.index'), PHP_URL_PATH))+ ->assertNoJavaScriptErrors();++ Queue::assertPushedTimes(TrackWorkspaceLimitHit::class, 1);+ Queue::assertPushed(TrackWorkspaceLimitHit::class, fn (TrackWorkspaceLimitHit $job) => $job->userId === (string) $user->id);+ expect($user->account->workspaces()->count())->toBe(1);+});++test('below the cap, new workspace in the sidebar opens the create page and creates the workspace', function () use ($ownerOn, $clickNewWorkspaceInSidebar) {+ $user = $ownerOn(Slug::Workspaces);+ $this->actingAs($user);++ $page = visit(route('app.posts.index'));+ $clickNewWorkspaceInSidebar($page);++ waitForPath($page, parse_url(route('app.workspaces.create'), PHP_URL_PATH));+ waitFor($page, '@workspaces-create-name');+ $page->assertMissing('@workspace-upgrade-dialog');++ $page->fill('@workspaces-create-name', 'Second')+ ->click('@workspaces-create-submit');++ waitForPath($page, parse_url(route('app.posts.index'), PHP_URL_PATH));+ $page->assertNoJavaScriptErrors();++ Queue::assertNotPushed(TrackWorkspaceLimitHit::class);+ expect(Workspace::where('name', 'Second')->where('account_id', $user->account_id)->exists())->toBeTrue();+});++test('at the cap without a current workspace, submitting the create page opens the upgrade dialog in place', function () use ($ownerOn) {+ $user = $ownerOn(Slug::Socials);+ $user->update(['current_workspace_id' => null]);+ $this->actingAs($user->fresh());++ $page = visit(route('app.workspaces.create'));+ waitFor($page, '@workspaces-create-name');++ $page->fill('@workspaces-create-name', 'Second')+ ->click('@workspaces-create-submit');++ waitFor($page, '@workspace-upgrade-dialog');+ $page->assertVisible('@workspace-upgrade-dialog')+ ->assertPathIs(parse_url(route('app.workspaces.create'), PHP_URL_PATH))+ ->assertNoJavaScriptErrors();++ expect($user->account->workspaces()->count())->toBe(1);+});diff --git a/tests/Browser/WorkspacesIndexTest.php b/tests/Browser/WorkspacesIndexTest.phpnew file mode 100644index 000000000..946cbd1f5--- /dev/null+++ b/tests/Browser/WorkspacesIndexTest.php@@ -0,0 +1,25 @@+<?php++declare(strict_types=1);++use App\Models\User;+use App\Models\Workspace;++test('back on the workspaces list returns to the app', function () {+ config(['trypost.self_hosted' => true]);++ $user = User::factory()->create();+ $workspace = Workspace::factory()->create(['account_id' => $user->account_id, 'user_id' => $user->id]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);+ $this->actingAs($user->fresh());++ $page = visit(route('app.workspaces.index'));+ waitFor($page, '@workspaces-back');++ $page->click('@workspaces-back');+ waitForPath($page, parse_url(route('app.calendar'), PHP_URL_PATH));++ $page->assertPathIs(parse_url(route('app.calendar'), PHP_URL_PATH))+ ->assertNoJavaScriptErrors();+});diff --git a/tests/Feature/Actions/Account/ResolveLifecycleStageTest.php b/tests/Feature/Actions/Account/ResolveLifecycleStageTest.phpnew file mode 100644index 000000000..107bffb04--- /dev/null+++ b/tests/Feature/Actions/Account/ResolveLifecycleStageTest.php@@ -0,0 +1,85 @@+<?php++declare(strict_types=1);++use App\Actions\Account\ResolveLifecycleStage;+use App\Enums\Account\LifecycleStage;+use App\Models\Account;++beforeEach(function () {+ config(['trypost.self_hosted' => false]);+});++test('each stage is resolved from access, channels and the last published post', function (?string $subscriptionStatus, bool $hasConnectedChannel, ?int $daysSinceLastPublish, LifecycleStage $expected) {+ $this->freezeTime();++ $account = Account::factory()->create(['trial_ends_at' => null, 'first_paid_at' => $subscriptionStatus === 'canceled' ? now()->subMonth() : null]);++ if (filled($subscriptionStatus)) {+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_'.fake()->uuid(),+ 'stripe_status' => $subscriptionStatus,+ 'stripe_price' => 'price_123',+ 'ends_at' => $subscriptionStatus === 'canceled' ? now()->subDay() : null,+ ]);+ }++ $lastPublishedAt = filled($daysSinceLastPublish) ? now()->subDays($daysSinceLastPublish) : null;++ expect(ResolveLifecycleStage::execute($account->load('subscriptions'), $lastPublishedAt, $hasConnectedChannel))->toBe($expected);+})->with([+ 'churned after a real subscription' => ['canceled', true, 1, LifecycleStage::Churned],+ 'signed up without a subscription' => [null, true, 1, LifecycleStage::SignedUp],+ 'signed up after an incomplete checkout' => ['incomplete', false, null, LifecycleStage::SignedUp],+ 'signed up after an expired incomplete checkout' => ['incomplete_expired', false, null, LifecycleStage::SignedUp],+ 'onboarding without a connected channel' => ['active', false, null, LifecycleStage::Onboarding],+ 'connected without a published post' => ['active', true, null, LifecycleStage::Connected],+ 'active when the last post went out 7 days ago' => ['active', true, ResolveLifecycleStage::ACTIVE_WITHIN_DAYS, LifecycleStage::Active],+ 'at risk when the last post went out 8 days ago' => ['active', true, ResolveLifecycleStage::ACTIVE_WITHIN_DAYS + 1, LifecycleStage::AtRisk],+ 'at risk when the last post went out 21 days ago' => ['trialing', true, ResolveLifecycleStage::AT_RISK_WITHIN_DAYS, LifecycleStage::AtRisk],+ 'dormant when the last post went out 22 days ago' => ['active', true, ResolveLifecycleStage::AT_RISK_WITHIN_DAYS + 1, LifecycleStage::Dormant],+]);++test('a card trial cancelled before its first charge is signed up, not churned', function () {+ $this->freezeTime();++ $account = Account::factory()->create(['trial_ends_at' => null, 'first_paid_at' => null]);+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_trial_cancelled',+ 'stripe_status' => 'canceled',+ 'stripe_price' => 'price_123',+ 'trial_ends_at' => null,+ 'ends_at' => now()->subDays(4),+ ]);++ expect(ResolveLifecycleStage::execute($account->load('subscriptions'), null, true))->toBe(LifecycleStage::SignedUp)+ ->and($account->hasHadBillableSubscription())->toBeTrue();+});++test('a paying account keeps its stage while past due or cancelled on its grace period', function (string $status, bool $onGracePeriod) {+ $this->freezeTime();++ $account = Account::factory()->create(['trial_ends_at' => null]);+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_'.fake()->uuid(),+ 'stripe_status' => $status,+ 'stripe_price' => 'price_123',+ 'ends_at' => $onGracePeriod ? now()->addDay() : null,+ ]);++ expect(ResolveLifecycleStage::execute($account->load('subscriptions'), now()->subDay(), true))->toBe(LifecycleStage::Active);+})->with([+ 'past due' => ['past_due', false],+ 'cancelled on its grace period' => ['active', true],+]);++test('a generic trial without a card and without channels is onboarding', function () {+ config(['trypost.billing.require_card_for_trial' => false]);++ $account = Account::factory()->create(['trial_ends_at' => now()->addDays(5)]);++ expect(ResolveLifecycleStage::execute($account->load('subscriptions'), null, false))->toBe(LifecycleStage::Onboarding);+});diff --git a/tests/Feature/Actions/Post/FinalizePostPublicationTest.php b/tests/Feature/Actions/Post/FinalizePostPublicationTest.phpindex 30a9d4c19..4e3aaee22 100644--- a/tests/Feature/Actions/Post/FinalizePostPublicationTest.php+++ b/tests/Feature/Actions/Post/FinalizePostPublicationTest.php@@ -7,6 +7,8 @@ use App\Enums\Notification\Type;use App\Enums\Post\PublishStatus;use App\Enums\Post\Status as PostStatus;use App\Enums\User\Locale;+use App\Jobs\PostHog\TrackPostFailed;+use App\Jobs\PostHog\TrackPostPublished;use App\Jobs\SendNotification;use App\Mail\PostPublished;use App\Mail\PostPublishFailed;@@ -209,3 +211,80 @@ test('a google review whose channel is gone is left to the review ceiling', func->publish_status->toBe(PublishStatus::PendingReview)->platform_post_id->toBe('accounts/1/locations/1/localPosts/9');});++test('finalize dispatches published or failed tracking once per settlement', function () {+ enablePostHog();+ $owner = User::factory()->create();+ $workspace = finalizeWorkspaceOf($owner);+ $published = Post::factory()->state(['workspace_id' => $workspace->id])->facebook()->publishing()->create([+ 'user_id' => $owner->id,+ 'publish_status' => PublishStatus::Published,+ 'platform_post_id' => 'fb-1',+ ]);+ $failed = Post::factory()->state(['workspace_id' => $workspace->id])->facebook()->publishing()->create([+ 'user_id' => $owner->id,+ 'publish_status' => PublishStatus::Failed,+ 'error_message' => 'Failed to publish',+ ]);++ $finalize = app(FinalizePostPublication::class);+ $finalize->handle($published);+ $finalize->handle($published->fresh());+ $finalize->handle($failed);+ $finalize->handle($failed->fresh());++ Queue::assertPushedOnce(TrackPostPublished::class);+ Queue::assertPushed(TrackPostPublished::class, fn (TrackPostPublished $job) => $job->postId === (string) $published->id);+ Queue::assertPushedOnce(TrackPostFailed::class);+ Queue::assertPushed(TrackPostFailed::class, fn (TrackPostFailed $job) => $job->postId === (string) $failed->id);+});++test('finalize does not dispatch tracking when PostHog is disabled', function () {+ config(['services.posthog.api_key' => null]);+ $owner = User::factory()->create();+ $workspace = finalizeWorkspaceOf($owner);+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->facebook()->publishing()->create([+ 'user_id' => $owner->id,+ 'publish_status' => PublishStatus::Published,+ 'platform_post_id' => 'fb-1',+ ]);++ $failed = Post::factory()->state(['workspace_id' => $workspace->id])->facebook()->publishing()->create([+ 'user_id' => $owner->id,+ 'publish_status' => PublishStatus::Failed,+ 'error_message' => 'Failed to publish',+ ]);++ app(FinalizePostPublication::class)->handle($post);+ app(FinalizePostPublication::class)->handle($failed);++ expect($post->fresh()->status)->toBe(PostStatus::Published)+ ->and($failed->fresh()->status)->toBe(PostStatus::Failed);+ Queue::assertNotPushed(TrackPostPublished::class);+ Queue::assertNotPushed(TrackPostFailed::class);+});++test('a post still settles and notifies when tracking its publication fails', function (PublishStatus $publishStatus, PostStatus $settled, Type $notification, string $trackingJob) {+ enablePostHog();+ $owner = User::factory()->create();+ $workspace = finalizeWorkspaceOf($owner);+ $member = workspaceMember($workspace, 'member');+ $post = Post::factory()->state(['workspace_id' => $workspace->id])->facebook()->publishing()->create([+ 'user_id' => $owner->id,+ 'publish_status' => $publishStatus,+ 'platform_post_id' => 'fb-1',+ 'error_message' => 'Failed to publish',+ ]);+ failDispatchOf($trackingJob);++ app(FinalizePostPublication::class)->handle($post);++ expect($post->fresh()->status)->toBe($settled)+ ->and(Queue::pushed(SendNotification::class, fn (SendNotification $job): bool => $job->type === $notification)+ ->map(fn (SendNotification $job): string => $job->user->id)->sort()->values()->all())+ ->toBe(collect([$owner->id, $member->id])->sort()->values()->all());+ Queue::assertNotPushed($trackingJob);+})->with([+ 'published' => [PublishStatus::Published, PostStatus::Published, Type::PostPublished, TrackPostPublished::class],+ 'failed' => [PublishStatus::Failed, PostStatus::Failed, Type::PostFailed, TrackPostFailed::class],+]);diff --git a/tests/Feature/Actions/User/CreateUserTest.php b/tests/Feature/Actions/User/CreateUserTest.phpindex 63fe7a5c7..0e5fb4c3a 100644--- a/tests/Feature/Actions/User/CreateUserTest.php+++ b/tests/Feature/Actions/User/CreateUserTest.php@@ -3,6 +3,7 @@declare(strict_types=1);use App\Actions\User\CreateUser;+use App\Enums\Account\LifecycleStage;use App\Enums\PostHog\UserEvent;use App\Jobs\PostHog\SendEvent;use App\Jobs\PostHog\SyncUser;@@ -39,6 +40,34 @@ test('CreateUser sets account owner_id to the new user', function () {expect($user->account->owner_id)->toBe($user->id);});+test('CreateUser starts the account at the signed_up lifecycle stage', function () {+ enablePostHog();+ $this->freezeTime();++ $user = CreateUser::execute([+ 'name' => 'Jane Doe',+ 'email' => '[email protected]',+ 'password' => 'secret123',+ ]);++ expect($user->account->lifecycle_stage)->toBe(LifecycleStage::SignedUp)+ ->and($user->account->lifecycle_stage_changed_at?->toIso8601String())->toBe(now()->toIso8601String())+ ->and($user->account->activated_at)->toBeNull();+});++test('CreateUser leaves the lifecycle stage empty when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);++ $user = CreateUser::execute([+ 'name' => 'Jane Doe',+ 'email' => '[email protected]',+ 'password' => 'secret123',+ ]);++ expect($user->account->lifecycle_stage)->toBeNull()+ ->and($user->account->lifecycle_stage_changed_at)->toBeNull();+});+test('CreateUser invite-style still creates user without workspace (workspace assignment happens via invite acceptance)', function () {$user = CreateUser::execute(['name' => 'Invited',@@ -52,7 +81,7 @@ test('CreateUser invite-style still creates user without workspace (workspace as});test('CreateUser dispatches SyncUser with the new user id when PostHog is enabled', function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();Bus::fake([SyncUser::class]);$user = CreateUser::execute([@@ -109,7 +138,7 @@ test('CreateUser dispatches SyncUser in the local environment even when PostHog});test('CreateUser captures user.signed_up with the auth provider when PostHog is enabled', function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();Bus::fake([SendEvent::class]);$user = CreateUser::execute([@@ -126,7 +155,7 @@ test('CreateUser captures user.signed_up with the auth provider when PostHog is});test('CreateUser defaults the auth provider to email when no OAuth id is present', function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();Bus::fake([SendEvent::class]);CreateUser::execute([@@ -142,7 +171,7 @@ test('CreateUser defaults the auth provider to email when no OAuth id is present});test('CreateUser does not capture user.signed_up for invite registrations', function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();Bus::fake([SendEvent::class]);CreateUser::execute([diff --git a/tests/Feature/Ai/PostAiAssistantTest.php b/tests/Feature/Ai/PostAiAssistantTest.phpindex 7d778d8b1..bcf2a372e 100644--- a/tests/Feature/Ai/PostAiAssistantTest.php+++ b/tests/Feature/Ai/PostAiAssistantTest.php@@ -5,8 +5,10 @@ declare(strict_types=1);use App\Ai\Agents\PostContentShortener;use App\Ai\Agents\PostWritingAssistant;use App\Enums\Ai\PostAssistantMode;+use App\Enums\PostHog\AiEvent;use App\Enums\SocialAccount\Platform;use App\Enums\User\Locale;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;@@ -15,6 +17,7 @@ use App\Support\AiPromptRules;use Illuminate\Auth\Access\Response as AuthResponse;use Illuminate\Http\Client\ConnectionException;use Illuminate\Support\Facades\Gate;+use Illuminate\Support\Facades\Queue;use Illuminate\Support\Facades\Route;use Laravel\Ai\Prompts\AgentPrompt;use Symfony\Component\HttpFoundation\Response;@@ -288,3 +291,53 @@ test('a failing provider returns a translated bad gateway', function () {->assertStatus(Response::HTTP_BAD_GATEWAY)->assertJsonPath('message', __('posts.composer.assistant_error'));});++test('ai assist tracks the mode', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);+ PostWritingAssistant::fake(['A fresh caption']);++ $this->actingAs($this->user)+ ->postJson(route('app.posts.ai.assist'), [+ 'mode' => PostAssistantMode::Generate->value,+ 'prompt' => 'Introduce our new product',+ ])+ ->assertOk();++ Queue::assertPushedOn('posthog', CaptureAccountEvent::class, fn (CaptureAccountEvent $job) => $job->event === AiEvent::AssistUsed+ && $job->distinctId === (string) $this->user->id+ && $job->accountId === (string) $this->workspace->account_id+ && $job->properties === [+ 'mode' => PostAssistantMode::Generate->value,+ 'workspace_id' => (string) $this->workspace->id,+ ]);+});++test('a failed ai assist is not tracked', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);+ PostWritingAssistant::fake([fn () => throw new ConnectionException('timeout')]);++ $this->actingAs($this->user)+ ->postJson(route('app.posts.ai.assist'), [+ 'mode' => PostAssistantMode::Generate->value,+ 'prompt' => 'Introduce our new product',+ ])+ ->assertStatus(Response::HTTP_BAD_GATEWAY);++ Queue::assertNotPushed(CaptureAccountEvent::class);+});++test('ai assist still returns the content when tracking it fails', function () {+ enablePostHog();+ PostWritingAssistant::fake(['A fresh caption']);+ failDispatchOf(CaptureAccountEvent::class);++ $this->actingAs($this->user)+ ->postJson(route('app.posts.ai.assist'), [+ 'mode' => PostAssistantMode::Generate->value,+ 'prompt' => 'Introduce our new product',+ ])+ ->assertOk()+ ->assertJsonPath('content', 'A fresh caption');+});diff --git a/tests/Feature/Api/ApiKeyApiTest.php b/tests/Feature/Api/ApiKeyApiTest.phpindex da8f42c1b..a3ece091a 100644--- a/tests/Feature/Api/ApiKeyApiTest.php+++ b/tests/Feature/Api/ApiKeyApiTest.php@@ -2,9 +2,12 @@declare(strict_types=1);+use App\Enums\PostHog\ApiKeyEvent;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Models\AccessToken;use App\Models\User;use App\Models\Workspace;+use Illuminate\Support\Facades\Queue;function createApiKeyApiToken(array $overrides = []): array{@@ -244,3 +247,31 @@ it('validates api key name max length', function () {->assertUnprocessable()->assertJsonValidationErrors(['name']);});++test('creating an api key through the api tracks api_key.created', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);+ $result = createApiKeyApiToken();++ $this->withHeaders(['Authorization' => "Bearer {$result['plain_token']}"])+ ->postJson(route('api.api-keys.store'), ['name' => 'CI/CD Token'], ['HTTP_HOST' => 'api.trypost.test'])+ ->assertCreated();++ Queue::assertPushed(CaptureAccountEvent::class, fn (CaptureAccountEvent $job) => $job->event === ApiKeyEvent::Created+ && $job->distinctId === (string) $result['user']->id+ && $job->accountId === (string) $result['workspace']->account_id+ && $job->properties === ['workspace_id' => (string) $result['workspace']->id]);+});++test('creating an api key through the api still returns the plain token when tracking it fails', function () {+ enablePostHog();+ $result = createApiKeyApiToken();+ failDispatchOf(CaptureAccountEvent::class);++ $this->withHeaders(['Authorization' => "Bearer {$result['plain_token']}"])+ ->postJson(route('api.api-keys.store'), ['name' => 'CI/CD Token'], ['HTTP_HOST' => 'api.trypost.test'])+ ->assertCreated()+ ->assertJsonStructure(['plain_token']);++ expect(AccessToken::where('workspace_id', $result['workspace']->id)->where('name', 'CI/CD Token')->exists())->toBeTrue();+});diff --git a/tests/Feature/Api/RepurposeApiTest.php b/tests/Feature/Api/RepurposeApiTest.phpindex 316881e9e..dc3d96244 100644--- a/tests/Feature/Api/RepurposeApiTest.php+++ b/tests/Feature/Api/RepurposeApiTest.php@@ -407,3 +407,20 @@ test('google business is rejected as a destination', function () {->assertUnprocessable()->assertJsonValidationErrors(['destinations.0.social_account_id' => __('repurposes.errors.destination_not_supported')]);});++test('activating returns the same body when PostHog is enabled', function () {+ enablePostHog();+ Queue::fake();++ $repurpose = Repurpose::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'source_social_account_id' => $this->source->id,+ 'destinations' => [tiktokDestinationPayload($this->tiktok)],+ ]);++ $this->withHeaders(apiHeaders($this->token))+ ->postJson(route('api.repurposes.activate', $repurpose))+ ->assertOk()+ ->assertJsonPath('status', Status::Active->value)+ ->assertJsonMissingPath('source_account');+});diff --git a/tests/Feature/ApiKeyControllerTest.php b/tests/Feature/ApiKeyControllerTest.phpindex dda80e10d..119cd4769 100644--- a/tests/Feature/ApiKeyControllerTest.php+++ b/tests/Feature/ApiKeyControllerTest.php@@ -2,11 +2,14 @@declare(strict_types=1);+use App\Enums\PostHog\ApiKeyEvent;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Models\AccessToken;use App\Models\User;use App\Models\Workspace;use Database\Seeders\PassportSeeder;use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Queue;use Laravel\Passport\ClientRepository;beforeEach(function () {@@ -309,3 +312,52 @@ it('marks each api key as active, expiring soon or expired', function () {->and($tokens[$soon->id])->toBe('expiring_soon')->and($tokens[$expired->id])->toBe('expired');});++it('creating an api key tracks api_key.created', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);++ $this->actingAs($this->user)+ ->post(route('app.api-keys.store'), ['name' => 'My API Key'])+ ->assertRedirect();++ Queue::assertPushedOn('posthog', CaptureAccountEvent::class, fn (CaptureAccountEvent $job) => $job->event === ApiKeyEvent::Created+ && $job->distinctId === (string) $this->user->id+ && $job->accountId === (string) $this->workspace->account_id+ && $job->properties === ['workspace_id' => (string) $this->workspace->id]);+});++it('regenerating an api key does not track api_key.created', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);+ $token = makeWorkspaceToken($this->user, $this->workspace);++ $this->actingAs($this->user)+ ->post(route('app.api-keys.regenerate', $token->id))+ ->assertRedirect();++ Queue::assertNotPushed(CaptureAccountEvent::class);+});++it('creating an api key does not track when posthog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ Queue::fake([CaptureAccountEvent::class]);++ $this->actingAs($this->user)+ ->post(route('app.api-keys.store'), ['name' => 'My API Key'])+ ->assertRedirect();++ Queue::assertNotPushed(CaptureAccountEvent::class);+});++it('creating an api key still returns the plain token when tracking it fails', function () {+ enablePostHog();+ failDispatchOf(CaptureAccountEvent::class);++ $this->actingAs($this->user)+ ->post(route('app.api-keys.store'), ['name' => 'My API Key'])+ ->assertRedirect()+ ->assertSessionHas('flash.plainToken');++ expect(AccessToken::where('user_id', $this->user->id)->where('workspace_id', $this->workspace->id)->where('name', 'My API Key')->exists())->toBeTrue();+});diff --git a/tests/Feature/Channels/DisconnectChannelPostsTest.php b/tests/Feature/Channels/DisconnectChannelPostsTest.phpindex 835e53722..82bd2d9bf 100644--- a/tests/Feature/Channels/DisconnectChannelPostsTest.php+++ b/tests/Feature/Channels/DisconnectChannelPostsTest.php@@ -7,9 +7,14 @@ use App\Actions\Post\ImportExternalPosts;use App\Dto\Analytics\DiscoveredPublication;use App\Enums\Analytics\PublicationContentType;use App\Enums\Post\PublishStatus;+use App\Enums\PostHog\SocialAccountEvent;+use App\Enums\SocialAccount\Platform;use App\Events\PostDeleted;+use App\Exceptions\Post\QueueBusyException;use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackSocialAccountRemoved;use App\Jobs\SendNotification;use App\Models\AnalyticsPublication;use App\Models\AnalyticsPublicationDailySnapshot;@@ -18,8 +23,10 @@ use App\Models\Post;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;+use App\Services\PostHogService;use App\Support\Social\GoogleBusinessDerivativeCleaner;use Carbon\CarbonImmutable;+use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Queue;@@ -202,3 +209,71 @@ test('a disconnect waits for the channel queue lock and changes nothing while aexpect(SocialAccount::query()->find($account->id))->not->toBeNull()->and(Post::query()->find($post->id))->not->toBeNull();});++test('disconnecting tracks social_account.disconnected with reason removed', function () {+ enablePostHog();+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);++ Bus::fake([TrackSocialAccountRemoved::class]);++ $this->actingAs($this->user)->delete(route('app.channels.disconnect', $account))->assertRedirect();++ expect(SocialAccount::find($account->id))->toBeNull();++ Bus::assertDispatchedOnce(TrackSocialAccountRemoved::class);+ Bus::assertDispatched(TrackSocialAccountRemoved::class, fn (TrackSocialAccountRemoved $job): bool => $job->userId === (string) $this->user->id+ && $job->socialAccountId === (string) $account->id+ && $job->workspaceId === (string) $this->workspace->id+ && $job->platform === Platform::LinkedIn);++ Queue::fake([SendEvent::class]);+ Bus::dispatched(TrackSocialAccountRemoved::class)->first()->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['event'] === SocialAccountEvent::Disconnected->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $job->payload['properties']['social_account_id'] === (string) $account->id+ && $job->payload['properties']['platform'] === Platform::LinkedIn->value+ && $job->payload['properties']['network'] === Platform::LinkedIn->network()+ && $job->payload['properties']['workspace_id'] === (string) $this->workspace->id+ && $job->payload['properties']['reason'] === TrackSocialAccountRemoved::REASON+ && $job->payload['properties']['$groups']['account'] === (string) $this->workspace->account_id);+});++test('disconnecting tracks nothing when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ $account = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);++ Bus::fake([TrackSocialAccountRemoved::class]);++ $this->actingAs($this->user)->delete(route('app.channels.disconnect', $account))->assertRedirect();++ Bus::assertNotDispatched(TrackSocialAccountRemoved::class);+});++test('disconnecting still succeeds when tracking it fails', function () {+ enablePostHog();+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);+ failDispatchOf(TrackSocialAccountRemoved::class);++ $this->actingAs($this->user)->delete(route('app.channels.disconnect', $account))->assertRedirect();++ expect(SocialAccount::find($account->id))->toBeNull();+});++test('a disconnect refused by a busy queue tracks nothing and shows the error', function () {+ enablePostHog();+ $account = SocialAccount::factory()->linkedin()->create(['workspace_id' => $this->workspace->id]);+ $lock = Cache::lock("queue:{$account->id}", 10);+ $lock->get();++ Bus::fake([TrackSocialAccountRemoved::class]);++ $this->actingAs($this->user)->delete(route('app.channels.disconnect', $account))+ ->assertRedirect()+ ->assertSessionHas('flash.error', (new QueueBusyException)->getMessage());++ $lock->release();++ expect(SocialAccount::find($account->id))->not->toBeNull();+ Bus::assertNotDispatched(TrackSocialAccountRemoved::class);+});diff --git a/tests/Feature/Commands/SyncPostHogLifecycleStagesTest.php b/tests/Feature/Commands/SyncPostHogLifecycleStagesTest.phpnew file mode 100644index 000000000..3cf68c958--- /dev/null+++ b/tests/Feature/Commands/SyncPostHogLifecycleStagesTest.php@@ -0,0 +1,289 @@+<?php++declare(strict_types=1);++use App\Actions\Account\ResolveLifecycleStage;+use App\Actions\User\CreateUser;+use App\Console\Commands\SyncPostHogLifecycleStages;+use App\Enums\Account\LifecycleStage;+use App\Enums\PostHog\ActivationEvent;+use App\Enums\PostHog\LifecycleEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackLifecycleChange;+use App\Models\Account;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Console\Scheduling\Event;+use Illuminate\Console\Scheduling\Schedule;+use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ config([+ 'services.posthog.enabled' => true,+ 'services.posthog.api_key' => 'phc_test_key',+ 'trypost.self_hosted' => false,+ ]);++ $this->account = Account::factory()->create(['trial_ends_at' => null]);+ $this->owner = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->owner->id]);+ $this->workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->owner->id,+ ]);+ subscribeAccount($this->account);+});++/**+ * @return list<SendEvent>+ */+function pushedLifecycleCaptures(): array+{+ $lifecycleEvents = array_column([...LifecycleEvent::cases(), ...ActivationEvent::cases()], 'value');++ return Queue::pushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && in_array($job->payload['event'], $lifecycleEvents, true))->all();+}++test('first run sets properties without capturing events', function () {+ $this->freezeTime();+ Queue::fake([SendEvent::class]);+ $this->account->forceFill(['lifecycle_stage' => null, 'lifecycle_stage_changed_at' => null])->saveQuietly();+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->forAccount($channel)->published()->create(['published_at' => now()->subDays(3)]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ $this->account->refresh();++ expect($this->account->lifecycle_stage)->toBe(LifecycleStage::Active)+ ->and($this->account->lifecycle_stage_changed_at?->toIso8601String())->toBe(now()->toIso8601String())+ ->and($this->account->activated_at?->toIso8601String())->toBe(now()->subDays(3)->toIso8601String())+ ->and(pushedLifecycleCaptures())->toBeEmpty();++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'groupIdentify'+ && $job->payload['groupKey'] === (string) $this->account->id+ && data_get($job->payload, 'properties.lifecycle_stage') === LifecycleStage::Active->value+ && data_get($job->payload, 'properties.activated_at') === now()->subDays(3)->toIso8601String());+ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'identify'+ && $job->payload['distinctId'] === (string) $this->owner->id+ && data_get($job->payload, 'properties.lifecycle_stage') === LifecycleStage::Active->value);+});++test('stage change captures previous and new stage', function () {+ Queue::fake([SendEvent::class]);+ $this->account->forceFill(['lifecycle_stage' => LifecycleStage::Onboarding])->saveQuietly();+ SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage)->toBe(LifecycleStage::Connected);++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === LifecycleEvent::StageChanged->value+ && $job->payload['distinctId'] === (string) $this->owner->id+ && $job->payload['properties']['stage'] === LifecycleStage::Connected->value+ && $job->payload['properties']['previous_stage'] === LifecycleStage::Onboarding->value+ && $job->payload['properties']['$groups']['account'] === (string) $this->account->id);+ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === ActivationEvent::Reached->value);+});++test('first publish captures activation.reached once', function () {+ Queue::fake([SendEvent::class]);+ $this->account->forceFill(['lifecycle_stage' => LifecycleStage::Connected])->saveQuietly();+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->forAccount($channel)->published()->create(['published_at' => now()->subHour()]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();+ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ $activations = collect(pushedLifecycleCaptures())->whereStrict('payload.event', ActivationEvent::Reached->value);++ expect($activations)->toHaveCount(1)+ ->and($activations->first()->payload['properties']['channels_count'])->toBe(1)+ ->and($activations->first()->payload['properties']['reached_at'])->toBe($this->account->refresh()->activated_at?->toIso8601String())+ ->and($this->account->lifecycle_stage)->toBe(LifecycleStage::Active);+});++test('activation keeps the first published post when the account already has an activation date', function () {+ Bus::fake([TrackLifecycleChange::class]);+ $activatedAt = now()->subDays(40)->startOfSecond();+ $this->account->forceFill(['lifecycle_stage' => LifecycleStage::Active, 'activated_at' => $activatedAt])->saveQuietly();+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->forAccount($channel)->published()->create(['published_at' => now()->subDay()]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->activated_at?->toIso8601String())->toBe($activatedAt->toIso8601String());+ Bus::assertNotDispatched(TrackLifecycleChange::class, fn (TrackLifecycleChange $job): bool => $job->accountId === (string) $this->account->id);+});++test('a new account that publishes before its first sync captures its activation and stage change', function () {+ Queue::fake([SendEvent::class]);+ $owner = CreateUser::execute([+ 'name' => 'Jane Doe',+ 'email' => '[email protected]',+ 'password' => 'secret123',+ ]);+ subscribeAccount($owner->account);+ $channel = SocialAccount::factory()->create(['workspace_id' => $owner->current_workspace_id]);+ Post::factory()->forAccount($channel)->published()->create(['published_at' => now()->subMinutes(10)]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ $captures = collect(pushedLifecycleCaptures())->whereStrict('payload.properties.account_id', (string) $owner->account_id);++ expect($captures->firstWhere('payload.event', ActivationEvent::Reached->value))->not->toBeNull()+ ->and($captures->firstWhere('payload.event', LifecycleEvent::StageChanged->value)?->payload['properties'])+ ->toMatchArray([+ 'stage' => LifecycleStage::Active->value,+ 'previous_stage' => LifecycleStage::SignedUp->value,+ ]);+});++test('the lifecycle write does not move the account updated_at', function () {+ Bus::fake([TrackLifecycleChange::class]);+ $updatedAt = now()->subWeek()->startOfSecond();+ $this->account->forceFill(['updated_at' => $updatedAt])->saveQuietly();++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ $this->account->refresh();++ expect($this->account->lifecycle_stage)->toBe(LifecycleStage::Onboarding)+ ->and($this->account->updated_at?->toIso8601String())->toBe($updatedAt->toIso8601String());+});++test('unchanged stage dispatches nothing', function () {+ Bus::fake([TrackLifecycleChange::class]);+ $changedAt = now()->subWeek()->startOfSecond();+ $this->account->forceFill([+ 'lifecycle_stage' => LifecycleStage::Onboarding,+ 'lifecycle_stage_changed_at' => $changedAt,+ ])->saveQuietly();++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage_changed_at?->toIso8601String())->toBe($changedAt->toIso8601String());+ Bus::assertNotDispatched(TrackLifecycleChange::class, fn (TrackLifecycleChange $job): bool => $job->accountId === (string) $this->account->id);+});++test('imported network posts do not activate', function () {+ Bus::fake([TrackLifecycleChange::class]);+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->forAccount($channel)->imported()->create();++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ $this->account->refresh();++ expect($this->account->lifecycle_stage)->toBe(LifecycleStage::Connected)+ ->and($this->account->activated_at)->toBeNull();+ Bus::assertDispatched(TrackLifecycleChange::class, fn (TrackLifecycleChange $job): bool => $job->accountId === (string) $this->account->id+ && $job->previousStage === null+ && $job->stage === LifecycleStage::Connected+ && $job->activatedNow === false);+});++test('a disconnected channel leaves onboarding and other accounts posts do not count', function () {+ Bus::fake([TrackLifecycleChange::class]);+ SocialAccount::factory()->disconnected()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->published()->create();++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage)->toBe(LifecycleStage::Connected);+});++test('an account that lost access after paying is churned', function () {+ Bus::fake([TrackLifecycleChange::class]);+ $this->account->forceFill(['first_paid_at' => now()->subMonth()])->save();+ $this->account->subscriptions()->update(['stripe_status' => 'canceled', 'ends_at' => now()->subDay()]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage)->toBe(LifecycleStage::Churned);+});++test('command writes nothing when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ Bus::fake([TrackLifecycleChange::class]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage)->toBeNull();+ Bus::assertNotDispatched(TrackLifecycleChange::class);+});++test('command is scheduled hourly', function () {+ $event = collect(app(Schedule::class)->events())+ ->first(fn (Event $event): bool => str_contains((string) $event->command, 'posthog:sync-lifecycle-stages'));++ expect($event)->not->toBeNull()+ ->and($event->expression)->toBe('0 * * * *')+ ->and($event->withoutOverlapping)->toBeTrue()+ ->and($event->onOneServer)->toBeTrue()+ ->and((new SyncPostHogLifecycleStages)->getName())->toBe('posthog:sync-lifecycle-stages');+});++test('the schedule only runs the command when PostHog is enabled', function () {+ $event = collect(app(Schedule::class)->events())+ ->first(fn (Event $event): bool => str_contains((string) $event->command, 'posthog:sync-lifecycle-stages'));++ expect($event->filtersPass(app()))->toBeTrue();++ config(['services.posthog.enabled' => false]);++ expect($event->filtersPass(app()))->toBeFalse();+});++test('an account whose only channel expired is not onboarding', function () {+ Queue::fake([SendEvent::class]);+ $this->account->forceFill(['lifecycle_stage' => LifecycleStage::Active])->saveQuietly();+ $channel = SocialAccount::factory()->tokenExpired()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->forAccount($channel)->published()->create(['published_at' => now()->subDay()]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage)->toBe(LifecycleStage::Active);+});++test('a stage going backwards captures the previous stage', function () {+ Queue::fake([SendEvent::class]);+ $this->account->forceFill(['lifecycle_stage' => LifecycleStage::Active, 'activated_at' => now()->subMonths(2)])->saveQuietly();+ $channel = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->forAccount($channel)->published()->create(['published_at' => now()->subDays(ResolveLifecycleStage::AT_RISK_WITHIN_DAYS + 5)]);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage)->toBe(LifecycleStage::Dormant);+ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === LifecycleEvent::StageChanged->value+ && data_get($job->payload, 'properties.previous_stage') === LifecycleStage::Active->value+ && data_get($job->payload, 'properties.stage') === LifecycleStage::Dormant->value);+});++test('an account whose change cannot be queued keeps its stage and the run goes on', function () {+ Queue::fake([SendEvent::class]);+ $this->account->forceFill(['lifecycle_stage' => LifecycleStage::Onboarding])->saveQuietly();+ SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);++ $otherAccount = Account::factory()->create(['trial_ends_at' => null, 'lifecycle_stage' => LifecycleStage::Onboarding]);+ $otherOwner = User::factory()->create(['account_id' => $otherAccount->id]);+ $otherAccount->update(['owner_id' => $otherOwner->id]);+ $otherWorkspace = Workspace::factory()->create(['account_id' => $otherAccount->id, 'user_id' => $otherOwner->id]);+ subscribeAccount($otherAccount);+ SocialAccount::factory()->create(['workspace_id' => $otherWorkspace->id]);++ failDispatchOf(TrackLifecycleChange::class, fn (TrackLifecycleChange $job): bool => $job->accountId === (string) $this->account->id);++ $this->artisan('posthog:sync-lifecycle-stages')->assertSuccessful();++ expect($this->account->refresh()->lifecycle_stage)->toBe(LifecycleStage::Onboarding)+ ->and($this->account->lifecycle_stage_changed_at)->toBeNull()+ ->and($otherAccount->refresh()->lifecycle_stage)->toBe(LifecycleStage::Connected);+});diff --git a/tests/Feature/Jobs/PostHog/CaptureAccountEventTest.php b/tests/Feature/Jobs/PostHog/CaptureAccountEventTest.phpnew file mode 100644index 000000000..ede06ec1c--- /dev/null+++ b/tests/Feature/Jobs/PostHog/CaptureAccountEventTest.php@@ -0,0 +1,54 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\WorkspaceEvent;+use App\Jobs\PostHog\CaptureAccountEvent;+use App\Jobs\PostHog\SendEvent;+use App\Models\Account;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ enablePostHog();+});++test('job is queued on the posthog queue', function () {+ $job = new CaptureAccountEvent('1', (string) Str::uuid(), WorkspaceEvent::MemberInvited, []);++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('captures the event with the account group', function () {+ Queue::fake();+ $account = Account::factory()->create();++ (new CaptureAccountEvent('user-1', (string) $account->id, WorkspaceEvent::MemberInvited, ['foo' => 'bar']))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['event'] === WorkspaceEvent::MemberInvited->value+ && $job->payload['distinctId'] === 'user-1'+ && $job->payload['properties']['foo'] === 'bar'+ && $job->payload['properties']['account_id'] === (string) $account->id+ && $job->payload['properties']['$groups']['account'] === (string) $account->id);+});++test('does nothing when the account is gone', function () {+ Queue::fake();++ (new CaptureAccountEvent('user-1', (string) Str::uuid(), WorkspaceEvent::MemberInvited, []))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+});++test('does nothing when PostHog is disabled', function () {+ config(['services.posthog.api_key' => null]);+ Queue::fake();+ $account = Account::factory()->create();++ (new CaptureAccountEvent('user-1', (string) $account->id, WorkspaceEvent::MemberInvited, []))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+});diff --git a/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.phpindex 954a2c361..33ec5693d 100644--- a/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php+++ b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php@@ -16,7 +16,7 @@ use Illuminate\Support\Facades\Cache;use Illuminate\Support\Str;beforeEach(function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();$this->account = Account::factory()->create();$this->user = User::factory()->create(['account_id' => $this->account->id]);@@ -171,3 +171,35 @@ test('overlap lock serializes processing for the same account', function () {expect($handled)->toBeTrue();});++test('an imported network post never becomes the account latest publication', function (bool $hasTryPostPost) {+ $workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+ $tryPostPublication = $hasTryPostPost+ ? Post::factory()->x()->published()->create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $this->user->id,+ 'published_at' => now()->subDay(),+ ])+ : null;+ Post::factory()->linkedin()->imported()->create([+ 'workspace_id' => $workspace->id,+ 'published_at' => now(),+ ]);++ $postHog = Mockery::mock(PostHogService::class);+ $postHog->shouldReceive('groupIdentifyNow')+ ->once()+ ->withArgs(fn (string $groupType, string $groupKey, array $properties): bool => $properties === [+ 'last_post_published_at' => $tryPostPublication?->published_at?->toIso8601String(),+ 'last_post_published_network' => $tryPostPublication?->platform?->network(),+ 'last_published_post_id' => $tryPostPublication?->id,+ ]);++ (new SyncAccountPublishingActivity((string) $this->account->id))->handle($postHog);+})->with([+ 'older TryPost post' => [true],+ 'no TryPost post' => [false],+]);diff --git a/tests/Feature/Jobs/PostHog/TrackBillingTest.php b/tests/Feature/Jobs/PostHog/TrackBillingTest.phpindex 0d7df5e50..cd004e7bb 100644--- a/tests/Feature/Jobs/PostHog/TrackBillingTest.php+++ b/tests/Feature/Jobs/PostHog/TrackBillingTest.php@@ -16,7 +16,7 @@ use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Queue;beforeEach(function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();config(['trypost.self_hosted' => false]);$this->account = Account::factory()->create([@@ -134,6 +134,93 @@ test('scheduled cancellation is canceled while access remains active during the});});+test('updated event carries the scheduled cancellation', function () {+ $cancelAt = now()->addWeek()->startOfSecond();+ $this->payload['data']['object']['cancel_at_period_end'] = true;+ $this->payload['data']['object']['cancel_at'] = $cancelAt->timestamp;+ Queue::fake();++ (new TrackBilling((string) $this->account->id, BillingEvent::Updated, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job) use ($cancelAt): bool {+ return $job->method === 'capture'+ && $job->payload['properties']['cancel_at_period_end'] === true+ && $job->payload['properties']['cancel_at'] === $cancelAt->toIso8601String()+ && ! array_key_exists('cancel_reason', $job->payload['properties']);+ });+});++test('account group exposes cancel_at_period_end and cancel_at from the stored subscription', function () {+ $cancelAt = now()->addWeek()->startOfSecond();+ $this->account->subscriptions()->update(['ends_at' => $cancelAt]);+ $this->payload['data']['object']['cancel_at_period_end'] = false;+ $this->payload['data']['object']['cancel_at'] = null;+ Queue::fake();++ (new TrackBilling((string) $this->account->id, BillingEvent::Updated, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job) use ($cancelAt): bool {+ return $job->method === 'groupIdentify'+ && $job->payload['properties']['cancel_at_period_end'] === true+ && $job->payload['properties']['cancel_at'] === $cancelAt->toIso8601String();+ });+});++test('cancelled event carries reason and feedback', function () {+ $this->payload['data']['object']['status'] = 'canceled';+ $this->payload['data']['object']['cancellation_details'] = [+ 'reason' => 'cancellation_requested',+ 'feedback' => 'too_expensive',+ ];+ Queue::fake();++ (new TrackBilling((string) $this->account->id, BillingEvent::Cancelled, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ return $job->method === 'capture'+ && $job->payload['properties']['cancel_reason'] === 'cancellation_requested'+ && $job->payload['properties']['cancel_feedback'] === 'too_expensive';+ });+});++test('a stale scheduled cancellation in the payload does not reach the group', function () {+ $this->payload['data']['object']['cancel_at_period_end'] = true;+ $this->payload['data']['object']['cancel_at'] = now()->addWeek()->timestamp;+ Queue::fake();++ (new TrackBilling((string) $this->account->id, BillingEvent::Updated, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ return $job->method === 'groupIdentify'+ && $job->payload['properties']['cancel_at_period_end'] === false+ && $job->payload['properties']['cancel_at'] === null;+ });+ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ return $job->method === 'capture'+ && $job->payload['properties']['cancel_at_period_end'] === true;+ });+});++test('resuming a scheduled cancellation clears cancel_at on the group', function () {+ $this->payload['data']['object']['cancel_at_period_end'] = false;+ $this->payload['data']['object']['cancel_at'] = null;+ Queue::fake();++ (new TrackBilling((string) $this->account->id, BillingEvent::Updated, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ return $job->method === 'groupIdentify'+ && $job->payload['properties']['cancel_at_period_end'] === false+ && array_key_exists('cancel_at', $job->payload['properties'])+ && $job->payload['properties']['cancel_at'] === null;+ });+});+test('handle does not forward persona — it is already an identified person property', function () {$this->user->update(['persona' => Persona::Agency->value]);Queue::fake();diff --git a/tests/Feature/Jobs/PostHog/TrackCheckoutExpiredTest.php b/tests/Feature/Jobs/PostHog/TrackCheckoutExpiredTest.phpnew file mode 100644index 000000000..95d192411--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackCheckoutExpiredTest.php@@ -0,0 +1,147 @@+<?php++declare(strict_types=1);++use App\Enums\Plan\Slug;+use App\Enums\PostHog\CheckoutEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackCheckoutExpired;+use App\Models\Account;+use App\Models\Plan;+use App\Models\User;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ enablePostHog();++ $this->account = Account::factory()->create(['plan_id' => null]);+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);++ $this->payload = [+ 'id' => 'evt_expired',+ 'type' => 'checkout.session.expired',+ 'data' => ['object' => [+ 'id' => 'cs_test_expired',+ 'mode' => 'subscription',+ 'customer' => 'cus_test',+ 'metadata' => [+ 'trypost_plan_slug' => 'socials',+ 'trypost_interval' => 'monthly',+ 'trypost_first_month_offer' => 'true',+ ],+ ]],+ ];+});++test('job is queued on the posthog queue', function () {+ $job = new TrackCheckoutExpired((string) $this->account->id, $this->payload);++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('captures checkout.expired on the owner with plan and offer', function () {+ Queue::fake();++ (new TrackCheckoutExpired((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $job->method === 'capture'+ && $job->payload['event'] === CheckoutEvent::Expired->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $properties['$groups']['account'] === (string) $this->account->id+ && $properties['plan_name'] === Plan::where('slug', Slug::Socials)->value('name')+ && $properties['interval'] === 'monthly'+ && $properties['is_first_month_offer'] === true+ && $properties['checkout_session_id'] === 'cs_test_expired';+ });+});++test('marks the offer false when the session had no first month offer', function () {+ $this->payload['data']['object']['metadata']['trypost_first_month_offer'] = 'false';+ Queue::fake();++ (new TrackCheckoutExpired((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['properties']['is_first_month_offer'] === false,+ );+});++test('sends a null plan when the session carries an unknown plan slug', function () {+ $this->payload['data']['object']['metadata']['trypost_plan_slug'] = 'unknown';+ Queue::fake();++ (new TrackCheckoutExpired((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['properties']['plan_name'] === null,+ );+});++test('sends empty plan, interval and offer when the session has no metadata', function () {+ unset($this->payload['data']['object']['metadata']);+ Queue::fake();++ (new TrackCheckoutExpired((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $properties['plan_name'] === null+ && $properties['interval'] === null+ && $properties['is_first_month_offer'] === false;+ });+});++test('skips when the account is already subscribed', function (string $status, bool $onGracePeriod) {+ $this->account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_existing',+ 'stripe_status' => $status,+ 'stripe_price' => 'price_123',+ 'trial_ends_at' => $status === 'trialing' ? now()->addDays(5) : null,+ 'ends_at' => $onGracePeriod ? now()->addDays(5) : null,+ ]);+ Queue::fake();++ (new TrackCheckoutExpired((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+})->with([+ 'active' => ['active', false],+ 'trialing' => ['trialing', false],+ 'past due' => ['past_due', false],+ 'canceled on grace period' => ['active', true],+]);++test('returns silently when the account does not exist', function () {+ Queue::fake();++ (new TrackCheckoutExpired('00000000-0000-0000-0000-000000000000', $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});++test('returns silently when the account has no owner', function () {+ $this->account->update(['owner_id' => null]);+ Queue::fake();++ (new TrackCheckoutExpired((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});diff --git a/tests/Feature/Jobs/PostHog/TrackInvoicePaymentFailedTest.php b/tests/Feature/Jobs/PostHog/TrackInvoicePaymentFailedTest.phpnew file mode 100644index 000000000..15cfe0c07--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackInvoicePaymentFailedTest.php@@ -0,0 +1,97 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\InvoiceEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackInvoicePaymentFailed;+use App\Models\Account;+use App\Models\User;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ enablePostHog();++ $this->account = Account::factory()->create(['plan_id' => null]);+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);++ $this->payload = [+ 'id' => 'evt_failed',+ 'type' => 'invoice.payment_failed',+ 'data' => ['object' => [+ 'id' => 'in_test_1',+ 'customer' => 'cus_test',+ 'attempt_count' => 2,+ 'amount_due' => 1900,+ 'currency' => 'usd',+ 'billing_reason' => 'subscription_cycle',+ 'next_payment_attempt' => 1792000000,+ ]],+ ];+});++test('job is queued on the posthog queue', function () {+ $job = new TrackInvoicePaymentFailed((string) $this->account->id, $this->payload);++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('captures invoice.payment_failed with attempt and amount', function () {+ Queue::fake();++ (new TrackInvoicePaymentFailed((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $job->payload['event'] === InvoiceEvent::PaymentFailed->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $properties['$groups']['account'] === (string) $this->account->id+ && $properties['attempt_count'] === 2+ && $properties['amount'] === 19.0+ && $properties['currency'] === 'USD'+ && $properties['next_attempt_at'] === '2026-10-14T17:46:40+00:00'+ && $properties['is_final_attempt'] === false+ && $properties['billing_reason'] === 'subscription_cycle'+ && $properties['invoice_id'] === 'in_test_1';+ });+});++test('marks the final attempt when Stripe schedules no retry', function () {+ $this->payload['data']['object']['next_payment_attempt'] = null;+ Queue::fake();++ (new TrackInvoicePaymentFailed((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $properties['is_final_attempt'] === true && $properties['next_attempt_at'] === null;+ });+});++test('sends a null amount when the invoice has none', function () {+ unset($this->payload['data']['object']['amount_due']);+ Queue::fake();++ (new TrackInvoicePaymentFailed((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['properties']['amount'] === null);+});++test('returns silently when the account has no owner', function () {+ $this->account->update(['owner_id' => null]);+ Queue::fake();++ (new TrackInvoicePaymentFailed((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});diff --git a/tests/Feature/Jobs/PostHog/TrackInvoiceUpcomingTest.php b/tests/Feature/Jobs/PostHog/TrackInvoiceUpcomingTest.phpnew file mode 100644index 000000000..b76d5145d--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackInvoiceUpcomingTest.php@@ -0,0 +1,186 @@+<?php++declare(strict_types=1);++use App\Enums\Plan\Slug;+use App\Enums\PostHog\InvoiceEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackInvoiceUpcoming;+use App\Models\Account;+use App\Models\Plan;+use App\Models\User;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ enablePostHog();++ Plan::query()->delete();+ Plan::factory()->create(['slug' => Slug::Socials, 'stripe_monthly_price_id' => 'price_socials_monthly', 'stripe_yearly_price_id' => 'price_socials_yearly']);++ $this->account = Account::factory()->create(['plan_id' => null]);+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);++ $this->payload = [+ 'id' => 'evt_upcoming',+ 'type' => 'invoice.upcoming',+ 'data' => ['object' => [+ 'customer' => 'cus_test',+ 'amount_due' => 1900,+ 'currency' => 'usd',+ 'next_payment_attempt' => 1792000000,+ 'lines' => ['data' => [invoiceLine('price_socials_monthly', proration: false)]],+ ]],+ ];+});++/**+ * @return array<string, mixed>+ */+function invoiceLine(string $priceId, bool $proration): array+{+ return [+ 'period' => ['start' => 1792000000, 'end' => 1794592000],+ 'pricing' => ['type' => 'price_details', 'price_details' => ['price' => $priceId, 'product' => 'prod_socials']],+ 'parent' => ['type' => 'subscription_item_details', 'subscription_item_details' => [+ 'proration' => $proration,+ 'subscription' => 'sub_upcoming',+ 'subscription_item' => 'si_upcoming',+ ]],+ ];+}++function createSubscriptionStartedAt(Account $account, string $startedAt, string $priceId = 'price_socials_monthly'): void+{+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_upcoming',+ 'stripe_status' => 'active',+ 'stripe_price' => $priceId,+ 'created_at' => $startedAt,+ ]);+}++test('job is queued on the posthog queue', function () {+ $job = new TrackInvoiceUpcoming((string) $this->account->id, $this->payload);++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('captures invoice.upcoming with amount and first charge flag', function () {+ createSubscriptionStartedAt($this->account, '2026-09-20');+ Queue::fake();++ (new TrackInvoiceUpcoming((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $job->payload['event'] === InvoiceEvent::Upcoming->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $properties['$groups']['account'] === (string) $this->account->id+ && $properties['amount'] === 19.0+ && $properties['currency'] === 'USD'+ && $properties['charge_at'] === '2026-10-14T17:46:40+00:00'+ && $properties['period_end'] === '2026-11-13T17:46:40+00:00'+ && $properties['interval'] === 'monthly'+ && $properties['is_first_full_charge'] === true;+ });+});++test('flags a later renewal as not the first full charge', function () {+ createSubscriptionStartedAt($this->account, '2026-06-01');+ Queue::fake();++ (new TrackInvoiceUpcoming((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['properties']['is_first_full_charge'] === false,+ );+});++test('sends a null first charge flag without a local subscription', function () {+ Queue::fake();++ (new TrackInvoiceUpcoming((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['properties']['is_first_full_charge'] === null,+ );+});++test('returns silently when the account has no owner', function () {+ $this->account->update(['owner_id' => null]);+ Queue::fake();++ (new TrackInvoiceUpcoming((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});++test('ignores a proration line ahead of the subscription line', function () {+ createSubscriptionStartedAt($this->account, '2025-10-20', 'price_socials_yearly');+ Queue::fake();++ $proration = invoiceLine('price_socials_monthly', proration: true);+ $proration['period'] = ['start' => 1780000000, 'end' => 1781000000];+ data_set($this->payload, 'data.object.lines.data', [$proration, invoiceLine('price_socials_yearly', proration: false)]);+ data_set($this->payload, 'data.object.next_payment_attempt', null);++ (new TrackInvoiceUpcoming((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $properties['interval'] === 'yearly'+ && $properties['charge_at'] === '2026-10-14T17:46:40+00:00'+ && $properties['period_end'] === '2026-11-13T17:46:40+00:00'+ && $properties['is_first_full_charge'] === true;+ });+});++test('falls back to the local subscription price without a subscription line', function () {+ createSubscriptionStartedAt($this->account, '2025-10-20', 'price_socials_yearly');+ Queue::fake();++ data_set($this->payload, 'data.object.lines.data', []);++ (new TrackInvoiceUpcoming((string) $this->account->id, $this->payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['properties']['interval'] === 'yearly'+ && $job->payload['properties']['period_end'] === null,+ );+});++test('sends nulls when lines, currency and the next attempt are missing', function () {+ Queue::fake();++ $payload = ['id' => 'evt_bare', 'type' => 'invoice.upcoming', 'data' => ['object' => ['customer' => 'cus_test']]];++ (new TrackInvoiceUpcoming((string) $this->account->id, $payload))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $properties['amount'] === null+ && $properties['currency'] === null+ && $properties['charge_at'] === null+ && $properties['period_end'] === null+ && $properties['interval'] === null+ && $properties['is_first_full_charge'] === null;+ });+});diff --git a/tests/Feature/Jobs/PostHog/TrackLifecycleChangeTest.php b/tests/Feature/Jobs/PostHog/TrackLifecycleChangeTest.phpnew file mode 100644index 000000000..8353fe222--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackLifecycleChangeTest.php@@ -0,0 +1,146 @@+<?php++declare(strict_types=1);++use App\Enums\Account\LifecycleStage;+use App\Enums\PostHog\ActivationEvent;+use App\Enums\PostHog\LifecycleEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackLifecycleChange;+use App\Models\Account;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ enablePostHog();++ $this->freezeTime();+ $this->account = Account::factory()->create();+ $this->account->forceFill(['created_at' => now()->subDays(5)])->saveQuietly();+ $this->owner = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->owner->id]);+ $this->workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->owner->id,+ ]);+});++test('job is queued on the posthog queue with retries and a timeout', function () {+ $job = new TrackLifecycleChange((string) Str::uuid(), null, LifecycleStage::SignedUp, null, null, false);++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('a first stage only identifies the account and its owner', function () {+ Queue::fake();++ (new TrackLifecycleChange((string) $this->account->id, null, LifecycleStage::Active, now(), now()->subDay(), true))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'groupIdentify'+ && $job->payload['groupType'] === 'account'+ && $job->payload['groupKey'] === (string) $this->account->id+ && $job->payload['properties'] === [+ 'lifecycle_stage' => LifecycleStage::Active->value,+ 'lifecycle_stage_changed_at' => now()->toIso8601String(),+ 'activated_at' => now()->subDay()->toIso8601String(),+ ]);+ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'identify'+ && $job->payload['distinctId'] === (string) $this->owner->id+ && $job->payload['properties'] === ['lifecycle_stage' => LifecycleStage::Active->value]);+ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture');+});++test('a stage change captures lifecycle_stage.changed for the owner', function () {+ Queue::fake();++ (new TrackLifecycleChange((string) $this->account->id, LifecycleStage::Active, LifecycleStage::AtRisk, now(), null, false))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === LifecycleEvent::StageChanged->value+ && $job->payload['distinctId'] === (string) $this->owner->id+ && $job->payload['properties']['stage'] === LifecycleStage::AtRisk->value+ && $job->payload['properties']['previous_stage'] === LifecycleStage::Active->value+ && $job->payload['properties']['reached_at'] === now()->toIso8601String()+ && $job->payload['properties']['account_id'] === (string) $this->account->id);+ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === ActivationEvent::Reached->value);+});++test('an activation captures activation.reached with signup age and connected channels', function () {+ Queue::fake();+ SocialAccount::factory()->count(2)->create(['workspace_id' => $this->workspace->id]);+ SocialAccount::factory()->disconnected()->create(['workspace_id' => $this->workspace->id]);++ (new TrackLifecycleChange((string) $this->account->id, LifecycleStage::Connected, LifecycleStage::Active, now(), now()->subDay(), true))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === ActivationEvent::Reached->value+ && $job->payload['distinctId'] === (string) $this->owner->id+ && $job->payload['properties']['reached_at'] === now()->subDay()->toIso8601String()+ && $job->payload['properties']['days_since_signup'] === 4+ && $job->payload['properties']['channels_count'] === 2);+});++test('an activation without a stage change captures only activation.reached', function () {+ Queue::fake();++ (new TrackLifecycleChange((string) $this->account->id, LifecycleStage::Churned, LifecycleStage::Churned, null, now(), true))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === ActivationEvent::Reached->value);+ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === LifecycleEvent::StageChanged->value);+});++test('an account without an owner only updates the account group', function () {+ Queue::fake();+ $this->account->forceFill(['owner_id' => null])->saveQuietly();++ (new TrackLifecycleChange((string) $this->account->id, LifecycleStage::AtRisk, LifecycleStage::Dormant, now(), null, false))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'groupIdentify');+ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method !== 'groupIdentify');+});++test('handle sends the values it was given, not what the account row holds when it runs', function () {+ Queue::fake();+ $this->account->forceFill(['lifecycle_stage' => LifecycleStage::Active, 'lifecycle_stage_changed_at' => now()->subWeek()])->saveQuietly();++ (new TrackLifecycleChange((string) $this->account->id, LifecycleStage::Active, LifecycleStage::AtRisk, now(), null, false))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'identify'+ && $job->payload['properties'] === ['lifecycle_stage' => LifecycleStage::AtRisk->value]);+ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['properties']['reached_at'] === now()->toIso8601String());+});++test('handle returns silently when the account is gone', function () {+ Queue::fake();++ (new TrackLifecycleChange((string) Str::uuid(), LifecycleStage::Active, LifecycleStage::AtRisk, now(), null, false))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});++test('handle does nothing when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ Queue::fake();++ (new TrackLifecycleChange((string) $this->account->id, LifecycleStage::Active, LifecycleStage::AtRisk, now(), null, false))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});diff --git a/tests/Feature/Jobs/PostHog/TrackPlanChangedTest.php b/tests/Feature/Jobs/PostHog/TrackPlanChangedTest.phpnew file mode 100644index 000000000..29cac0db0--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackPlanChangedTest.php@@ -0,0 +1,156 @@+<?php++declare(strict_types=1);++use App\Enums\Plan\Slug;+use App\Enums\PostHog\PlanEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackPlanChanged;+use App\Models\Account;+use App\Models\Plan;+use App\Models\User;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ enablePostHog();++ Plan::query()->delete();+ $this->legacy = Plan::factory()->create(['slug' => Slug::Workspace, 'name' => 'Workspace', 'stripe_monthly_price_id' => 'price_legacy_monthly']);+ $this->socials = Plan::factory()->create(['slug' => Slug::Socials, 'stripe_monthly_price_id' => 'price_socials_monthly', 'stripe_yearly_price_id' => 'price_socials_yearly']);+ $this->workspaces = Plan::factory()->unlimited()->create(['slug' => Slug::Workspaces, 'name' => 'Workspaces', 'stripe_monthly_price_id' => 'price_workspaces_monthly']);++ $this->account = Account::factory()->create(['plan_id' => $this->workspaces->id]);+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);+});++/**+ * @return array{id: string, type: string, data: array{object: array<string, mixed>, previous_attributes: array<string, mixed>}}+ */+function planChangePayload(string $fromId, int $fromAmount, string $fromInterval, string $toId, int $toAmount, string $toInterval, int $fromQuantity = 1): array+{+ return [+ 'id' => 'evt_plan',+ 'type' => 'customer.subscription.updated',+ 'data' => [+ 'object' => ['items' => ['data' => [['quantity' => 1, 'price' => ['id' => $toId, 'unit_amount' => $toAmount, 'currency' => 'usd', 'recurring' => ['interval' => $toInterval]]]]]],+ 'previous_attributes' => ['items' => ['data' => [['quantity' => $fromQuantity, 'price' => ['id' => $fromId, 'unit_amount' => $fromAmount, 'currency' => 'usd', 'recurring' => ['interval' => $fromInterval]]]]]],+ ],+ ];+}++/**+ * @param array<string, mixed> $payload+ */+function runPlanChanged(Account $account, array $payload): void+{+ (new TrackPlanChanged((string) $account->id, $payload))->handle(app(PostHogService::class));+}++test('job is queued on the posthog queue', function () {+ $job = new TrackPlanChanged((string) $this->account->id, []);++ expect($job->queue)->toBe('posthog')->and($job->tries)->toBe(3)->and($job->timeout)->toBe(30);+});++test('socials to workspaces is an upgrade even with the local plan already updated', function () {+ Queue::fake();++ runPlanChanged($this->account, planChangePayload('price_socials_monthly', 1900, 'month', 'price_workspaces_monthly', 9900, 'month'));++ Queue::assertPushed(SendEvent::class, function (SendEvent $job): bool {+ $properties = $job->payload['properties'];++ return $job->payload['event'] === PlanEvent::Upgraded->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $properties['plan_from'] === 'socials'+ && $properties['plan_to'] === 'workspaces'+ && $properties['interval_from'] === 'monthly'+ && $properties['interval_to'] === 'monthly'+ && $properties['monthly_amount_from'] === 19.0+ && $properties['monthly_amount_to'] === 99.0;+ });+});++test('workspaces to socials is a downgrade', function () {+ Queue::fake();++ runPlanChanged($this->account, planChangePayload('price_workspaces_monthly', 9900, 'month', 'price_socials_monthly', 1900, 'month'));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['event'] === PlanEvent::Downgraded->value+ && $job->payload['properties']['plan_from'] === 'workspaces'+ && $job->payload['properties']['plan_to'] === 'socials',+ );+});++test('legacy workspace to socials yearly is an upgrade', function () {+ Queue::fake();++ runPlanChanged($this->account, planChangePayload('price_legacy_monthly', 1200, 'month', 'price_socials_yearly', 19000, 'year'));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['event'] === PlanEvent::Upgraded->value+ && $job->payload['properties']['interval_to'] === 'yearly'+ && round($job->payload['properties']['monthly_amount_to'], 2) === 15.83,+ );+});++test('monthly to yearly on the same plan sends nothing', function () {+ Queue::fake();++ runPlanChanged($this->account, planChangePayload('price_socials_monthly', 1900, 'month', 'price_socials_yearly', 19000, 'year'));++ Queue::assertNotPushed(SendEvent::class);+});++test('sends nothing when a price is unknown', function () {+ Queue::fake();++ runPlanChanged($this->account, planChangePayload('price_unknown', 1900, 'month', 'price_workspaces_monthly', 9900, 'month'));++ Queue::assertNotPushed(SendEvent::class);+});++test('a legacy plan billed for three workspaces moving to socials is a downgrade', function () {+ Queue::fake();++ runPlanChanged($this->account, planChangePayload('price_legacy_monthly', 1200, 'month', 'price_socials_monthly', 1900, 'month', fromQuantity: 3));++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['event'] === PlanEvent::Downgraded->value+ && $job->payload['properties']['monthly_amount_from'] === 36.0+ && $job->payload['properties']['monthly_amount_to'] === 19.0,+ );+});++test('sends null amounts when the payload has no unit amount', function () {+ Queue::fake();++ $payload = planChangePayload('price_socials_monthly', 1900, 'month', 'price_workspaces_monthly', 9900, 'month');+ data_forget($payload, 'data.object.items.data.0.price.unit_amount');+ data_forget($payload, 'data.previous_attributes.items.data.0.price.unit_amount');++ runPlanChanged($this->account, $payload);++ Queue::assertPushed(+ SendEvent::class,+ fn (SendEvent $job): bool => $job->payload['event'] === PlanEvent::Downgraded->value+ && $job->payload['properties']['monthly_amount_from'] === null+ && $job->payload['properties']['monthly_amount_to'] === null,+ );+});++test('the direction does not depend on the price currency', function () {+ Queue::fake();+ $payload = planChangePayload('price_socials_monthly', 1900, 'month', 'price_workspaces_monthly', 9900, 'month');+ unset($payload['data']['object']['items']['data'][0]['price']['currency'], $payload['data']['previous_attributes']['items']['data'][0]['price']['currency']);++ runPlanChanged($this->account, $payload);++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['event'] === PlanEvent::Upgraded->value);+});diff --git a/tests/Feature/Jobs/PostHog/TrackPostFailedTest.php b/tests/Feature/Jobs/PostHog/TrackPostFailedTest.phpnew file mode 100644index 000000000..5215f528e--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackPostFailedTest.php@@ -0,0 +1,128 @@+<?php++declare(strict_types=1);++use App\Actions\Post\FinalizePostPublication;+use App\Enums\Post\CreatedVia;+use App\Enums\Post\Origin;+use App\Enums\Post\Status;+use App\Enums\PostHog\PostEvent;+use App\Enums\SocialAccount\Platform;+use App\Exceptions\Social\ErrorCategory;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackPostFailed;+use App\Models\Account;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ enablePostHog();++ $this->account = Account::factory()->create();+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);+ $this->workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+});++test('job is queued on the posthog queue', function () {+ expect((new TrackPostFailed((string) Str::uuid()))->queue)->toBe('posthog');+});++test('failed post captures error_type from the error category', function () {+ Queue::fake();++ $groupId = (string) Str::uuid();+ $page = SocialAccount::factory()->linkedinPage()->create(['workspace_id' => $this->workspace->id]);+ $post = Post::factory()->forAccount($page)->failed()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => $groupId,+ 'created_via' => CreatedVia::Api,+ 'error_context' => ['category' => ErrorCategory::RateLimit->value],+ ]);++ (new TrackPostFailed((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['event'] === PostEvent::Failed->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $job->payload['properties']['post_id'] === (string) $post->id+ && $job->payload['properties']['post_group_id'] === $groupId+ && $job->payload['properties']['platform'] === Platform::LinkedInPage->value+ && $job->payload['properties']['network'] === Platform::LinkedInPage->network()+ && $job->payload['properties']['created_via'] === CreatedVia::Api->value+ && $job->payload['properties']['error_type'] === ErrorCategory::RateLimit->value+ && $job->payload['properties']['$groups']['account'] === (string) $this->account->id);+});++test('failed post without a category reports unknown', function () {+ Queue::fake();++ $post = Post::factory()->x()->failed()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ (new TrackPostFailed((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['properties']['error_type'] === ErrorCategory::Unknown->value+ && $job->payload['distinctId'] === (string) $this->user->id);+});++test('handle does not push when PostHog is disabled', function () {+ config(['services.posthog.api_key' => null]);+ Queue::fake();++ $post = Post::factory()->x()->failed()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ (new TrackPostFailed((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+});++test('a post failed for having no channel reports no platform or network', function () {+ Queue::fake();++ $post = Post::factory()->publishing()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ app(FinalizePostPublication::class)->handle($post);++ expect($post->fresh()->status)->toBe(Status::Failed);++ (new TrackPostFailed((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['event'] === PostEvent::Failed->value+ && $job->payload['properties']['post_id'] === (string) $post->id+ && $job->payload['properties']['platform'] === null+ && $job->payload['properties']['network'] === null);+});++test('a post without an author or imported from the network sends no failed event', function (array $attributes) {+ Queue::fake();++ $post = Post::factory()->linkedin()->failed()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ...$attributes,+ ]);++ (new TrackPostFailed((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+})->with([+ 'without an author' => [['user_id' => null]],+ 'imported' => [['origin' => Origin::Network]],+]);diff --git a/tests/Feature/Jobs/PostHog/TrackPostPublishedTest.php b/tests/Feature/Jobs/PostHog/TrackPostPublishedTest.phpnew file mode 100644index 000000000..03e33110a--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackPostPublishedTest.php@@ -0,0 +1,238 @@+<?php++declare(strict_types=1);++use App\Enums\Post\CreatedVia;+use App\Enums\Post\Origin;+use App\Enums\Post\Status;+use App\Enums\PostHog\PostEvent;+use App\Enums\SocialAccount\Platform;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackPostPublished;+use App\Models\Account;+use App\Models\Post;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ enablePostHog();++ $this->account = Account::factory()->create();+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);+ $this->workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+});++test('job is queued on the posthog queue', function () {+ expect((new TrackPostPublished((string) Str::uuid()))->queue)->toBe('posthog');+});++test('group of three publishes one event', function () {+ Queue::fake();++ $groupId = (string) Str::uuid();+ $publishedAt = now()->subMinute()->startOfSecond();+ $posts = collect(['linkedin', 'x', 'facebook'])->map(fn (string $network) => Post::factory()+ ->{$network}()+ ->published()+ ->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => $groupId,+ 'created_via' => CreatedVia::Web,+ 'published_at' => $publishedAt,+ ]));++ $posts->shuffle()->each(fn (Post $post) => (new TrackPostPublished((string) $post->id))->handle(app(PostHogService::class)));++ Queue::assertPushedOnce(SendEvent::class);+ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['event'] === PostEvent::Published->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $job->payload['properties']['post_group_id'] === $groupId+ && $job->payload['properties']['created_via'] === CreatedVia::Web->value+ && $job->payload['properties']['channels_count'] === 3+ && $job->payload['properties']['$groups']['account'] === (string) $this->account->id);+});++test('posts of a group settling in the same second emit one event', function () {+ Queue::fake();++ $groupId = (string) Str::uuid();+ $attributes = [+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => $groupId,+ ];+ $first = Post::factory()->linkedin()->publishing()->create($attributes);+ $second = Post::factory()->x()->publishing()->create($attributes);+ $settledAt = now()->startOfSecond();++ $second->forceFill(['status' => Status::Published, 'published_at' => $settledAt])->save();+ (new TrackPostPublished((string) $second->id))->handle(app(PostHogService::class));++ $first->forceFill(['status' => Status::Published, 'published_at' => $settledAt])->save();+ (new TrackPostPublished((string) $first->id))->handle(app(PostHogService::class));++ Queue::assertPushedOnce(SendEvent::class);+});++test('platforms lists every network the group targeted', function () {+ Queue::fake();++ $groupId = (string) Str::uuid();+ $attributes = [+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => $groupId,+ ];+ $first = Post::factory()->linkedin()->published()->create([...$attributes, 'published_at' => now()->subMinutes(3)]);+ $page = SocialAccount::factory()->linkedinPage()->create(['workspace_id' => $this->workspace->id]);+ Post::factory()->forAccount($page)->published()->create([...$attributes, 'published_at' => now()->subMinutes(2)]);+ Post::factory()->x()->failed()->create($attributes);++ (new TrackPostPublished((string) $first->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['properties']['platforms'] === [Platform::LinkedIn->network(), Platform::X->network()]+ && $job->payload['properties']['channels_count'] === 3);+});++test('is_first is true for the account first group and false after', function () {+ Queue::fake();++ Post::factory()->linkedin()->imported()->create(['workspace_id' => $this->workspace->id]);++ $firstGroup = Post::factory()->linkedin()->published()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => (string) Str::uuid(),+ ]);++ (new TrackPostPublished((string) $firstGroup->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['properties']['is_first'] === true);++ Queue::fake();++ $otherWorkspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+ $secondGroup = Post::factory()->x()->published()->create([+ 'workspace_id' => $otherWorkspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => (string) Str::uuid(),+ ]);++ (new TrackPostPublished((string) $secondGroup->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['properties']['is_first'] === false);+});++test('is_first goes to exactly one group when two groups settle before either job runs', function (bool $sameSecond) {+ Queue::fake();++ $publishedAt = now()->subMinute()->startOfSecond();+ $attributes = ['workspace_id' => $this->workspace->id, 'user_id' => $this->user->id];++ $earlier = Post::factory()->linkedin()->published()->create([...$attributes, 'post_group_id' => (string) Str::uuid(), 'published_at' => $publishedAt]);+ $later = Post::factory()->x()->published()->create([...$attributes, 'post_group_id' => (string) Str::uuid(), 'published_at' => $sameSecond ? $publishedAt : $publishedAt->addSecond()]);++ (new TrackPostPublished((string) $later->id))->handle(app(PostHogService::class));+ (new TrackPostPublished((string) $earlier->id))->handle(app(PostHogService::class));++ $firsts = Queue::pushed(SendEvent::class)+ ->filter(fn (SendEvent $job): bool => $job->method === 'capture' && $job->payload['properties']['is_first'] === true);++ $expected = collect([$earlier, $later])->sortBy([['published_at', 'asc'], ['id', 'asc']])->first();++ expect($firsts)->toHaveCount(1)+ ->and($firsts->first()->payload['properties']['post_group_id'])->toBe($expected->post_group_id);+})->with([+ 'a second apart' => [false],+ 'in the same second' => [true],+]);++test('handle does not push when the post is missing or PostHog is disabled', function () {+ Queue::fake();++ (new TrackPostPublished((string) Str::uuid()))->handle(app(PostHogService::class));++ config(['services.posthog.api_key' => null]);++ $post = Post::factory()->linkedin()->published()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);++ (new TrackPostPublished((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+});++test('a post without a group publishes once, keyed by its own id', function () {+ Queue::fake();++ $post = Post::factory()->linkedin()->published()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => null,+ ]);++ (new TrackPostPublished((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertPushedOnce(SendEvent::class);+ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['properties']['post_group_id'] === null+ && $job->payload['properties']['channels_count'] === 1+ && $job->payload['properties']['platforms'] === [Platform::LinkedIn->network()]);++ Queue::fake();++ (new TrackPostPublished((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});++test('is_first ignores failed posts and posts published by other accounts', function () {+ Queue::fake();++ Post::factory()->x()->failed()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => (string) Str::uuid(),+ ]);+ Post::factory()->x()->published()->create(['post_group_id' => (string) Str::uuid()]);++ $post = Post::factory()->linkedin()->published()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'post_group_id' => (string) Str::uuid(),+ ]);++ (new TrackPostPublished((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job) => $job->payload['properties']['is_first'] === true);+});++test('a post without an author or imported from the network publishes no event', function (array $attributes) {+ Queue::fake();++ $post = Post::factory()->linkedin()->published()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ...$attributes,+ ]);++ (new TrackPostPublished((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+})->with([+ 'without an author' => [['user_id' => null]],+ 'imported' => [['origin' => Origin::Network]],+]);diff --git a/tests/Feature/Jobs/PostHog/TrackPostTest.php b/tests/Feature/Jobs/PostHog/TrackPostTest.phpindex 350042a8e..d60440ae6 100644--- a/tests/Feature/Jobs/PostHog/TrackPostTest.php+++ b/tests/Feature/Jobs/PostHog/TrackPostTest.php@@ -3,6 +3,7 @@declare(strict_types=1);use App\Enums\Post\CreatedVia;+use App\Enums\Post\Origin;use App\Enums\PostHog\PostEvent;use App\Jobs\PostHog\SendEvent;use App\Jobs\PostHog\TrackPost;@@ -15,7 +16,7 @@ use Illuminate\Support\Facades\Queue;use Illuminate\Support\Str;beforeEach(function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();$this->account = Account::factory()->create();$this->user = User::factory()->create(['account_id' => $this->account->id]);@@ -54,24 +55,6 @@ test('handle captures post.created with created_via and account group', function});});-test('handle falls back to account owner when post has no user', function () {- Queue::fake();-- $post = Post::factory()->create([- 'workspace_id' => $this->workspace->id,- 'user_id' => null,- 'created_via' => CreatedVia::Mcp,- ]);-- (new TrackPost((string) $post->id))->handle(app(PostHogService::class));-- Queue::assertPushed(- SendEvent::class,- fn ($job) => $job->payload['distinctId'] === (string) $this->user->id- && $job->payload['properties']['created_via'] === CreatedVia::Mcp->value,- );-});-test('handle returns silently when post does not exist', function () {Queue::fake();@@ -94,3 +77,20 @@ test('handle does not push when PostHog is disabled', function () {Queue::assertNotPushed(SendEvent::class);});++test('handle tracks nothing for an imported network post or a post without an author', function (array $attributes) {+ Queue::fake();++ $post = Post::factory()->imported()->create([+ 'workspace_id' => $this->workspace->id,+ ...$attributes,+ ]);++ (new TrackPost((string) $post->id))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class);+})->with([+ 'imported without an author' => fn () => [],+ 'imported with an author' => fn () => ['user_id' => $this->user->id],+ 'TryPost post without an author' => fn () => ['origin' => Origin::TryPost, 'user_id' => null],+]);diff --git a/tests/Feature/Jobs/PostHog/TrackRepurposeActivatedTest.php b/tests/Feature/Jobs/PostHog/TrackRepurposeActivatedTest.phpnew file mode 100644index 000000000..e56c15e1a--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackRepurposeActivatedTest.php@@ -0,0 +1,79 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\RepurposeEvent;+use App\Enums\SocialAccount\Platform;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackRepurposeActivated;+use App\Models\Repurpose;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ enablePostHog();+ Queue::fake([SendEvent::class]);++ $this->user = User::factory()->create();+ $this->workspace = Workspace::factory()->create(['account_id' => $this->user->account_id, 'user_id' => $this->user->id]);+ $this->source = SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id]);+});++test('job is queued on the posthog queue with retries and a timeout', function () {+ $job = new TrackRepurposeActivated((string) Str::uuid());++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('handle captures repurpose.activated for its creator with the source and destinations', function () {+ $repurpose = Repurpose::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ 'source_social_account_id' => $this->source->id,+ 'destinations' => [['social_account_id' => (string) Str::uuid()], ['social_account_id' => (string) Str::uuid()]],+ ]);++ (new TrackRepurposeActivated((string) $repurpose->id))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === RepurposeEvent::Activated->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $job->payload['properties']['repurpose_id'] === (string) $repurpose->id+ && $job->payload['properties']['source'] === Platform::Instagram->value+ && $job->payload['properties']['destinations_count'] === 2+ && $job->payload['properties']['$groups']['account'] === (string) $this->user->account_id);+});++test('handle attributes the event to who activated it, else its creator, else the account owner', function () {+ $this->user->account->update(['owner_id' => $this->user->id]);+ $member = User::factory()->create(['account_id' => $this->user->account_id]);+ $repurpose = fn (?string $creatorId): Repurpose => Repurpose::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $creatorId,+ 'source_social_account_id' => SocialAccount::factory()->instagram()->create(['workspace_id' => $this->workspace->id])->id,+ ]);++ (new TrackRepurposeActivated((string) $repurpose($member->id)->id, (string) $this->user->id))->handle(app(PostHogService::class));+ (new TrackRepurposeActivated((string) $repurpose($member->id)->id))->handle(app(PostHogService::class));+ (new TrackRepurposeActivated((string) $repurpose(null)->id))->handle(app(PostHogService::class));++ $distinctIds = Queue::pushed(SendEvent::class)+ ->filter(fn (SendEvent $job): bool => $job->method === 'capture')+ ->map(fn (SendEvent $job): string => $job->payload['distinctId'])+ ->values()+ ->all();++ expect($distinctIds)->toBe([(string) $this->user->id, (string) $member->id, (string) $this->user->id]);+});++test('handle captures nothing for a repurpose that is gone', function () {+ (new TrackRepurposeActivated((string) Str::uuid()))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture');+});diff --git a/tests/Feature/Jobs/PostHog/TrackSocialAccountConnectedTest.php b/tests/Feature/Jobs/PostHog/TrackSocialAccountConnectedTest.phpnew file mode 100644index 000000000..1c21aa87f--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackSocialAccountConnectedTest.php@@ -0,0 +1,129 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\SocialAccountEvent;+use App\Enums\SocialAccount\Platform;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackSocialAccountConnected;+use App\Models\Account;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ enablePostHog();++ $this->account = Account::factory()->create();+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);+ $this->workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+});++test('job is queued on the posthog queue with retries and a timeout', function () {+ $job = new TrackSocialAccountConnected((string) Str::uuid(), (string) Str::uuid(), 'app.workspace.channels');++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('handle captures social_account.connected with the channel properties', function () {+ Queue::fake();++ $socialAccount = SocialAccount::factory()->linkedinPage()->create(['workspace_id' => $this->workspace->id]);++ (new TrackSocialAccountConnected((string) $socialAccount->id, (string) $this->user->id, 'app.calendar'))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === SocialAccountEvent::Connected->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $job->payload['properties']['social_account_id'] === (string) $socialAccount->id+ && $job->payload['properties']['platform'] === Platform::LinkedInPage->value+ && $job->payload['properties']['network'] === Platform::LinkedInPage->network()+ && $job->payload['properties']['workspace_id'] === (string) $this->workspace->id+ && $job->payload['properties']['source'] === 'app.calendar'+ && $job->payload['properties']['nth_channel'] === 1+ && $job->payload['properties']['$groups']['account'] === (string) $this->account->id);+});++test('handle attributes a connect without a user to the account owner', function () {+ Queue::fake();++ $socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);++ (new TrackSocialAccountConnected((string) $socialAccount->id, null, TrackSocialAccountConnected::SOURCE_TELEGRAM))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['distinctId'] === (string) $this->user->id+ && $job->payload['properties']['source'] === TrackSocialAccountConnected::SOURCE_TELEGRAM);+});++test('nth_channel counts channels across every workspace of the account', function () {+ Queue::fake();++ $otherWorkspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+ $foreignWorkspace = Workspace::factory()->create();++ SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'created_at' => now()->subDays(3)]);+ SocialAccount::factory()->create(['workspace_id' => $otherWorkspace->id, 'created_at' => now()->subDays(2)]);+ SocialAccount::factory()->create(['workspace_id' => $foreignWorkspace->id, 'created_at' => now()->subDays(2)]);+ $socialAccount = SocialAccount::factory()->create(['workspace_id' => $otherWorkspace->id, 'created_at' => now()->subDay()]);+ SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'created_at' => now()]);++ (new TrackSocialAccountConnected((string) $socialAccount->id, (string) $this->user->id, 'app.workspace.channels'))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['properties']['nth_channel'] === 3);+});++test('handle returns silently when the channel is gone', function () {+ Queue::fake();++ (new TrackSocialAccountConnected((string) Str::uuid(), (string) $this->user->id, 'app.workspace.channels'))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});++test('handle returns silently when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ Queue::fake();++ $socialAccount = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id]);++ (new TrackSocialAccountConnected((string) $socialAccount->id, (string) $this->user->id, 'app.workspace.channels'))+ ->handle(app(PostHogService::class));++ Queue::assertNothingPushed();+});++test('nth_channel breaks a created_at tie by id', function () {+ Queue::fake();++ $at = now()->startOfSecond();+ $first = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'created_at' => $at]);+ $second = SocialAccount::factory()->create(['workspace_id' => $this->workspace->id, 'created_at' => $at]);++ [$lower, $higher] = strcmp((string) $first->id, (string) $second->id) < 0 ? [$first, $second] : [$second, $first];++ (new TrackSocialAccountConnected((string) $lower->id, (string) $this->user->id, 'app.workspace.channels'))+ ->handle(app(PostHogService::class));+ (new TrackSocialAccountConnected((string) $higher->id, (string) $this->user->id, 'app.workspace.channels'))+ ->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['properties']['social_account_id'] === (string) $lower->id+ && $job->payload['properties']['nth_channel'] === 1);+ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['properties']['social_account_id'] === (string) $higher->id+ && $job->payload['properties']['nth_channel'] === 2);+});diff --git a/tests/Feature/Jobs/PostHog/TrackSocialAccountConnectionLostTest.php b/tests/Feature/Jobs/PostHog/TrackSocialAccountConnectionLostTest.phpnew file mode 100644index 000000000..649505996--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackSocialAccountConnectionLostTest.php@@ -0,0 +1,54 @@+<?php++declare(strict_types=1);++use App\Enums\PostHog\SocialAccountEvent;+use App\Enums\SocialAccount\Platform;+use App\Enums\SocialAccount\Status;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackSocialAccountConnectionLost;+use App\Models\SocialAccount;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ enablePostHog();+ Queue::fake([SendEvent::class]);+});++test('job is queued on the posthog queue with retries and a timeout', function () {+ $job = new TrackSocialAccountConnectionLost((string) Str::uuid(), Status::TokenExpired);++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('handle captures social_account.disconnected for the account owner with the status as reason and error type', function () {+ $owner = User::factory()->create();+ $owner->account->update(['owner_id' => $owner->id]);+ $workspace = Workspace::factory()->create(['account_id' => $owner->account_id, 'user_id' => $owner->id]);+ $socialAccount = SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id]);++ (new TrackSocialAccountConnectionLost((string) $socialAccount->id, Status::TokenExpired))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === SocialAccountEvent::Disconnected->value+ && $job->payload['distinctId'] === (string) $owner->id+ && $job->payload['properties']['social_account_id'] === (string) $socialAccount->id+ && $job->payload['properties']['platform'] === Platform::X->value+ && $job->payload['properties']['network'] === Platform::X->network()+ && $job->payload['properties']['workspace_id'] === (string) $workspace->id+ && $job->payload['properties']['reason'] === Status::TokenExpired->value+ && $job->payload['properties']['error_type'] === Status::TokenExpired->value+ && $job->payload['properties']['$groups']['account'] === (string) $owner->account_id);+});++test('handle captures nothing for a channel that is gone', function () {+ (new TrackSocialAccountConnectionLost((string) Str::uuid(), Status::Disconnected))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture');+});diff --git a/tests/Feature/Jobs/PostHog/TrackWorkspaceLimitHitTest.php b/tests/Feature/Jobs/PostHog/TrackWorkspaceLimitHitTest.phpnew file mode 100644index 000000000..c6f6f6154--- /dev/null+++ b/tests/Feature/Jobs/PostHog/TrackWorkspaceLimitHitTest.php@@ -0,0 +1,68 @@+<?php++declare(strict_types=1);++use App\Enums\Plan\Slug;+use App\Enums\PostHog\WorkspaceEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackWorkspaceLimitHit;+use App\Models\Plan;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;++beforeEach(function () {+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key', 'trypost.self_hosted' => false]);+ Queue::fake([SendEvent::class]);+});++test('job is queued on the posthog queue with retries and a timeout', function () {+ $job = new TrackWorkspaceLimitHit((string) Str::uuid(), Slug::Socials->value, 1, now());++ expect($job->queue)->toBe('posthog')+ ->and($job->tries)->toBe(3)+ ->and($job->timeout)->toBe(30);+});++test('handle captures workspace.limit_hit with the plan and the account workspaces', function () {+ $user = User::factory()->create();+ $user->account->update(['plan_id' => Plan::query()->where('slug', Slug::Socials)->value('id')]);+ Workspace::factory()->count(2)->create(['account_id' => $user->account_id, 'user_id' => $user->id]);++ (new TrackWorkspaceLimitHit((string) $user->id, Slug::Socials->value, 1, now()))->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['event'] === WorkspaceEvent::LimitHit->value+ && $job->payload['distinctId'] === (string) $user->id+ && $job->payload['properties']['plan_slug'] === Slug::Socials->value+ && $job->payload['properties']['workspaces_count'] === $user->account->workspaces()->count()+ && $job->payload['properties']['workspace_limit'] === 1+ && $job->payload['properties']['$groups']['account'] === (string) $user->account_id);+});++test('handle reports the plan, limit and workspaces the refusal saw, even after an upgrade before the job ran', function () {+ $this->freezeTime();+ $user = User::factory()->create();+ $user->account->update(['plan_id' => Plan::query()->where('slug', Slug::Socials)->value('id')]);+ $workspacesAtHit = $user->account->workspaces()->count();+ $job = new TrackWorkspaceLimitHit((string) $user->id, Slug::Socials->value, 1, now());++ $this->travel(1)->minute();+ $user->account->update(['plan_id' => Plan::query()->where('slug', Slug::Workspaces)->value('id')]);+ Workspace::factory()->create(['account_id' => $user->account_id, 'user_id' => $user->id]);++ $job->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture'+ && $job->payload['properties']['plan_slug'] === Slug::Socials->value+ && $job->payload['properties']['workspace_limit'] === 1+ && $job->payload['properties']['workspaces_count'] === $workspacesAtHit);+});++test('handle captures nothing for a user that is gone', function () {+ (new TrackWorkspaceLimitHit((string) Str::uuid(), Slug::Socials->value, 1, now()))->handle(app(PostHogService::class));++ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => $job->method === 'capture');+});diff --git a/tests/Feature/Listeners/StripeBillingSignalListenerTest.php b/tests/Feature/Listeners/StripeBillingSignalListenerTest.phpnew file mode 100644index 000000000..1896de1be--- /dev/null+++ b/tests/Feature/Listeners/StripeBillingSignalListenerTest.php@@ -0,0 +1,186 @@+<?php++declare(strict_types=1);++use App\Enums\Plan\Slug;+use App\Jobs\PostHog\TrackBilling;+use App\Jobs\PostHog\TrackCheckoutExpired;+use App\Jobs\PostHog\TrackInvoicePaymentFailed;+use App\Jobs\PostHog\TrackInvoiceUpcoming;+use App\Listeners\StripeBillingSignalListener;+use App\Listeners\StripeEventListener;+use App\Models\Account;+use App\Models\Plan;+use App\Models\User;+use Illuminate\Support\Facades\Log;+use Illuminate\Support\Facades\Queue;+use Laravel\Cashier\Events\WebhookHandled;+use Laravel\Cashier\Events\WebhookReceived;++beforeEach(function () {+ enablePostHog();++ $this->account = Account::factory()->create(['stripe_id' => 'cus_signal']);+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);++ $this->expiredPayload = [+ 'id' => 'evt_expired_1',+ 'type' => 'checkout.session.expired',+ 'data' => ['object' => [+ 'id' => 'cs_test_expired',+ 'mode' => 'subscription',+ 'customer' => 'cus_signal',+ 'metadata' => [+ 'trypost_plan_slug' => 'socials',+ 'trypost_interval' => 'monthly',+ 'trypost_first_month_offer' => 'true',+ ],+ ]],+ ];+});++test('expired subscription checkout dispatches TrackCheckoutExpired', function () {+ Queue::fake();++ (new StripeBillingSignalListener)->handle(new WebhookReceived($this->expiredPayload));++ Queue::assertPushed(+ TrackCheckoutExpired::class,+ fn (TrackCheckoutExpired $job): bool => $job->accountId === (string) $this->account->id+ && data_get($job->payload, 'data.object.id') === 'cs_test_expired',+ );+});++test('same event id is handled once', function () {+ Queue::fake();+ $listener = new StripeBillingSignalListener;++ $listener->handle(new WebhookReceived($this->expiredPayload));+ $listener->handle(new WebhookReceived($this->expiredPayload));++ Queue::assertPushedOnce(TrackCheckoutExpired::class);+});++test('payment mode sessions are ignored', function () {+ Queue::fake();+ $this->expiredPayload['data']['object']['mode'] = 'payment';++ (new StripeBillingSignalListener)->handle(new WebhookReceived($this->expiredPayload));++ Queue::assertNotPushed(TrackCheckoutExpired::class);+});++test('expired checkout of an unknown customer is ignored', function () {+ Queue::fake();+ $this->expiredPayload['data']['object']['customer'] = 'cus_unknown';++ (new StripeBillingSignalListener)->handle(new WebhookReceived($this->expiredPayload));++ Queue::assertNotPushed(TrackCheckoutExpired::class);+});++test('expired checkout is not dispatched when posthog is off', function () {+ Queue::fake();+ config(['services.posthog.enabled' => false]);++ (new StripeBillingSignalListener)->handle(new WebhookReceived($this->expiredPayload));++ Queue::assertNotPushed(TrackCheckoutExpired::class);+});++test('subscription webhooks still reach StripeEventListener after WebhookReceived', function () {+ Queue::fake();++ $plan = Plan::where('slug', Slug::Socials)->firstOrFail();+ $plan->update(['stripe_monthly_price_id' => 'price_socials_monthly_signal']);++ $payload = [+ 'id' => 'evt_1',+ 'type' => 'customer.subscription.created',+ 'data' => ['object' => [+ 'id' => 'sub_signal',+ 'customer' => 'cus_signal',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly_signal']]]],+ ]],+ ];++ (new StripeBillingSignalListener)->handle(new WebhookReceived($payload));+ (new StripeEventListener)->handle(new WebhookHandled($payload));++ expect($this->account->fresh()->plan_id)->toBe($plan->id);+});++test('failed invoice payment dispatches TrackInvoicePaymentFailed', function () {+ Queue::fake();++ (new StripeBillingSignalListener)->handle(new WebhookReceived([+ 'id' => 'evt_failed_1',+ 'type' => 'invoice.payment_failed',+ 'data' => ['object' => ['id' => 'in_test_1', 'customer' => 'cus_signal', 'attempt_count' => 1]],+ ]));++ Queue::assertPushed(+ TrackInvoicePaymentFailed::class,+ fn (TrackInvoicePaymentFailed $job): bool => $job->accountId === (string) $this->account->id+ && data_get($job->payload, 'data.object.id') === 'in_test_1',+ );+});++test('upcoming invoice dispatches TrackInvoiceUpcoming', function () {+ Queue::fake();++ (new StripeBillingSignalListener)->handle(new WebhookReceived([+ 'id' => 'evt_upcoming_1',+ 'type' => 'invoice.upcoming',+ 'data' => ['object' => ['customer' => 'cus_signal', 'amount_due' => 1900]],+ ]));++ Queue::assertPushed(+ TrackInvoiceUpcoming::class,+ fn (TrackInvoiceUpcoming $job): bool => $job->accountId === (string) $this->account->id,+ );+});++test('a dispatched WebhookReceived reaches the billing signal listener once', function () {+ Queue::fake();+ unset($this->expiredPayload['id']);++ event(new WebhookReceived($this->expiredPayload));++ Queue::assertPushedOnce(TrackCheckoutExpired::class);+});++test('a dispatched WebhookHandled reaches the subscription listener once', function () {+ Queue::fake();++ $plan = Plan::where('slug', Slug::Socials)->firstOrFail();+ $plan->update(['stripe_monthly_price_id' => 'price_socials_monthly_signal']);++ event(new WebhookHandled([+ 'type' => 'customer.subscription.updated',+ 'data' => ['object' => [+ 'id' => 'sub_signal',+ 'customer' => 'cus_signal',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly_signal']]]],+ ]],+ ]));++ Queue::assertPushedOnce(TrackBilling::class);+});++test('a failing dispatch is swallowed and Cashier still handles the webhook', function () {+ config(['cashier.webhook.secret' => null]);+ failDispatchOf(TrackInvoicePaymentFailed::class);+ Log::spy();++ $this->postJson(route('cashier.webhook'), [+ 'id' => 'evt_payment_failed_dispatch',+ 'type' => 'invoice.payment_failed',+ 'data' => ['object' => ['id' => 'in_failed', 'customer' => 'cus_signal']],+ ])->assertOk();++ Log::shouldHaveReceived('error')->withArgs(fn (string $message): bool => str_contains($message, 'Queue is down.'))->once();+});diff --git a/tests/Feature/Listeners/StripeEventListenerTest.php b/tests/Feature/Listeners/StripeEventListenerTest.phpindex 9849d263a..43d9e5830 100644--- a/tests/Feature/Listeners/StripeEventListenerTest.php+++ b/tests/Feature/Listeners/StripeEventListenerTest.php@@ -2,10 +2,13 @@declare(strict_types=1);+use App\Actions\Account\ResolveLifecycleStage;+use App\Enums\Account\LifecycleStage;use App\Enums\Plan\Slug;use App\Enums\PostHog\BillingEvent;use App\Jobs\PostHog\TrackBilling;use App\Jobs\PostHog\TrackCheckoutCompleted;+use App\Jobs\PostHog\TrackPlanChanged;use App\Jobs\PostHog\TrackTrialConverted;use App\Jobs\PostHog\TrackTrialStarted;use App\Listeners\StripeEventListener;@@ -16,7 +19,7 @@ use Illuminate\Support\Facades\Bus;use Laravel\Cashier\Events\WebhookHandled;beforeEach(function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();// Use the seeded Workspace plan; set deterministic price ids so the// assertions don't depend on `.env.testing`.@@ -507,6 +510,37 @@ test('subscription updated forwards the previous plan name to TrackBilling', fun);});+test('a paid subscription deleted after dunning cleared its plan still sends subscription.cancelled once', function () {+ $this->account->forceFill(['plan_id' => null, 'first_paid_at' => now()->subMonth()])->save();++ Bus::fake([TrackBilling::class]);++ foreach (['evt_deleted_after_unpaid', 'evt_deleted_redelivered'] as $eventId) {+ $this->listener->handle(new WebhookHandled([+ 'id' => $eventId,+ 'type' => 'customer.subscription.deleted',+ 'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_unpaid', 'status' => 'canceled']],+ ]));+ }++ Bus::assertDispatchedOnce(TrackBilling::class);+ Bus::assertDispatched(TrackBilling::class, fn (TrackBilling $job): bool => $job->event === BillingEvent::Cancelled);+});++test('an abandoned checkout deleted without a plan or a payment sends nothing', function () {+ $this->account->forceFill(['plan_id' => null, 'first_paid_at' => null])->save();++ Bus::fake([TrackBilling::class]);++ $this->listener->handle(new WebhookHandled([+ 'id' => 'evt_deleted_abandoned',+ 'type' => 'customer.subscription.deleted',+ 'data' => ['object' => ['customer' => 'cus_test123', 'id' => 'sub_abandoned', 'status' => 'incomplete_expired']],+ ]));++ Bus::assertNotDispatched(TrackBilling::class);+});+test('subscription deleted forwards the previous plan name to TrackBilling', function () {$this->account->update(['plan_id' => $this->plan->id]);@@ -890,3 +924,228 @@ test('an event without an id is still processed (no idempotency key available)',Bus::assertDispatchedTimes(TrackTrialConverted::class, 1);});++// ========================================+// plan.upgraded / plan.downgraded dispatch+// ========================================++test('subscription updated with previous items dispatches TrackPlanChanged even when the local plan is already the new one', function () {+ Bus::fake([TrackPlanChanged::class]);+ $this->account->update(['plan_id' => $this->workspaces->id]);++ $this->listener->handle(new WebhookHandled([+ 'type' => 'customer.subscription.updated',+ 'data' => [+ 'object' => [+ 'customer' => 'cus_test123',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_workspaces_monthly']]]],+ ],+ 'previous_attributes' => ['items' => ['data' => [['price' => ['id' => 'price_socials_monthly']]]]],+ ],+ ]));++ Bus::assertDispatched(TrackPlanChanged::class, fn ($job) => $job->accountId === (string) $this->account->id);+});++test('subscription updated without previous items does not dispatch TrackPlanChanged', function () {+ Bus::fake([TrackPlanChanged::class]);++ $this->listener->handle(new WebhookHandled([+ 'type' => 'customer.subscription.updated',+ 'data' => [+ 'object' => ['customer' => 'cus_test123', 'status' => 'active'],+ 'previous_attributes' => ['status' => 'trialing'],+ ],+ ]));++ Bus::assertNotDispatched(TrackPlanChanged::class);+});++test('a renewal whose previous items keep the same price does not dispatch TrackPlanChanged', function () {+ Bus::fake([TrackPlanChanged::class]);++ $this->listener->handle(new WebhookHandled([+ 'type' => 'customer.subscription.updated',+ 'data' => [+ 'object' => [+ 'customer' => 'cus_test123',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly'], 'current_period_start' => 1792000000]]],+ ],+ 'previous_attributes' => ['items' => ['data' => [['price' => ['id' => 'price_socials_monthly'], 'current_period_start' => 1789000000]]]],+ ],+ ]));++ Bus::assertNotDispatched(TrackPlanChanged::class);+});++// ========================================+// A failing tracking dispatch never undoes the plan sync+// ========================================++test('subscription updated still syncs plan_id when TrackBilling dispatch fails', function () {+ $this->account->update(['plan_id' => $this->socials->id]);+ failDispatchOf(TrackBilling::class);++ $this->listener->handle(new WebhookHandled([+ 'type' => 'customer.subscription.updated',+ 'data' => ['object' => [+ 'customer' => 'cus_test123',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_workspaces_monthly']]]],+ ]],+ ]));++ expect($this->account->fresh()->plan_id)->toBe($this->workspaces->id);+});++test('subscription updated still syncs plan_id when TrackPlanChanged dispatch fails', function () {+ $this->account->update(['plan_id' => $this->socials->id]);+ failDispatchOf(TrackPlanChanged::class);++ $this->listener->handle(new WebhookHandled([+ 'type' => 'customer.subscription.updated',+ 'data' => [+ 'object' => [+ 'customer' => 'cus_test123',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_workspaces_monthly']]]],+ ],+ 'previous_attributes' => ['items' => ['data' => [['price' => ['id' => 'price_socials_monthly']]]]],+ ],+ ]));++ expect($this->account->fresh()->plan_id)->toBe($this->workspaces->id);+});++test('subscription created still syncs plan_id and clears trial_ends_at when the start tracking dispatch fails', function (string $status, string $job) {+ $this->account->update(['plan_id' => null, 'trial_ends_at' => now()->addDays(3)]);+ failDispatchOf($job);++ $this->listener->handle(new WebhookHandled([+ 'type' => 'customer.subscription.created',+ 'data' => ['object' => [+ 'customer' => 'cus_test123',+ 'id' => 'sub_123',+ 'status' => $status,+ 'trial_end' => now()->addDays(8)->timestamp,+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly']]]],+ ]],+ ]));++ $account = $this->account->fresh();++ expect($account->plan_id)->toBe($this->socials->id)+ ->and($account->trial_ends_at)->toBeNull();+})->with([+ 'trialing' => ['trialing', TrackTrialStarted::class],+ 'active' => ['active', TrackCheckoutCompleted::class],+]);++test('subscription deleted still clears plan_id when TrackBilling dispatch fails', function () {+ $this->account->update(['plan_id' => $this->plan->id]);+ failDispatchOf(TrackBilling::class);++ $this->listener->handle(new WebhookHandled([+ 'type' => 'customer.subscription.deleted',+ 'data' => ['object' => ['customer' => 'cus_test123', 'status' => 'canceled']],+ ]));++ expect($this->account->fresh()->plan_id)->toBeNull();+});++// ========================================+// first payment+// ========================================++test('a subscription born active records the first payment on the account', function () {+ $this->freezeTime();++ $this->listener->handle(new WebhookHandled([+ 'id' => 'evt_first_paid_created',+ 'type' => 'customer.subscription.created',+ 'data' => ['object' => [+ 'customer' => 'cus_test123',+ 'id' => 'sub_123',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly']]]],+ ]],+ ]));++ expect($this->account->fresh()->first_paid_at?->toIso8601String())->toBe(now()->toIso8601String());+});++test('a trial records no payment until it converts, and a later activation keeps the first one', function () {+ $this->freezeTime();++ $this->listener->handle(new WebhookHandled([+ 'id' => 'evt_first_paid_trial',+ 'type' => 'customer.subscription.created',+ 'data' => ['object' => [+ 'customer' => 'cus_test123',+ 'id' => 'sub_123',+ 'status' => 'trialing',+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly']]]],+ ]],+ ]));++ expect($this->account->fresh()->first_paid_at)->toBeNull();++ $convertedAt = now();++ $this->listener->handle(new WebhookHandled([+ 'id' => 'evt_first_paid_converted',+ 'type' => 'customer.subscription.updated',+ 'data' => [+ 'object' => [+ 'customer' => 'cus_test123',+ 'id' => 'sub_123',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly']]]],+ ],+ 'previous_attributes' => ['status' => 'trialing'],+ ],+ ]));++ $this->travel(1)->month();++ $this->listener->handle(new WebhookHandled([+ 'id' => 'evt_first_paid_renewed',+ 'type' => 'customer.subscription.updated',+ 'data' => ['object' => [+ 'customer' => 'cus_test123',+ 'id' => 'sub_123',+ 'status' => 'active',+ 'items' => ['data' => [['price' => ['id' => 'price_socials_monthly']]]],+ ]],+ ]));++ expect($this->account->fresh()->first_paid_at?->toIso8601String())->toBe($convertedAt->toIso8601String());+});++test('a trial cancelled through the real Cashier webhook is signed up, a paid subscription cancelled the same way is churned', function (bool $paid, LifecycleStage $expected) {+ config(['cashier.webhook.secret' => null, 'trypost.self_hosted' => false, 'trypost.billing.require_card_for_trial' => true]);+ $this->account->forceFill(['trial_ends_at' => null, 'first_paid_at' => $paid ? now()->subMonth() : null])->save();+ $this->account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_cancelled',+ 'stripe_status' => $paid ? 'active' : 'trialing',+ 'stripe_price' => 'price_socials_monthly',+ 'trial_ends_at' => $paid ? null : now()->addDays(5),+ ]);++ $this->postJson(route('cashier.webhook'), [+ 'id' => "evt_cancelled_{$expected->value}",+ 'type' => 'customer.subscription.deleted',+ 'data' => ['object' => ['id' => 'sub_cancelled', 'customer' => 'cus_test123', 'status' => 'canceled']],+ ])->assertOk();++ $account = $this->account->fresh()->load('subscriptions');++ expect($account->subscriptions->first()->trial_ends_at)->toBeNull()+ ->and(ResolveLifecycleStage::execute($account, null, true))->toBe($expected);+})->with([+ 'trial' => [false, LifecycleStage::SignedUp],+ 'paid' => [true, LifecycleStage::Churned],+]);diff --git a/tests/Feature/Mcp/ApiKeyToolTest.php b/tests/Feature/Mcp/ApiKeyToolTest.phpindex a8a73332c..80ac2b1ca 100644--- a/tests/Feature/Mcp/ApiKeyToolTest.php+++ b/tests/Feature/Mcp/ApiKeyToolTest.php@@ -2,6 +2,8 @@declare(strict_types=1);+use App\Enums\PostHog\ApiKeyEvent;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Mcp\Servers\TryPostServer;use App\Mcp\Tools\ApiKey\CreateApiKeyTool;use App\Mcp\Tools\ApiKey\DeleteApiKeyTool;@@ -9,6 +11,7 @@ use App\Mcp\Tools\ApiKey\ListApiKeysTool;use App\Models\AccessToken;use App\Models\User;use App\Models\Workspace;+use Illuminate\Support\Facades\Queue;use Illuminate\Testing\Fluent\AssertableJson;beforeEach(function () {@@ -228,3 +231,28 @@ test('delete api key validates api_key_id required', function () {$response->assertHasErrors();});++test('creating an api key through mcp tracks api_key.created', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);++ TryPostServer::actingAs($this->user)+ ->tool(CreateApiKeyTool::class, ['name' => 'My Key'])+ ->assertOk();++ Queue::assertPushed(CaptureAccountEvent::class, fn (CaptureAccountEvent $job) => $job->event === ApiKeyEvent::Created+ && $job->distinctId === (string) $this->user->id+ && $job->properties === ['workspace_id' => (string) $this->workspace->id]);+});++test('creating an api key through mcp still returns the plain token when tracking it fails', function () {+ enablePostHog();+ failDispatchOf(CaptureAccountEvent::class);++ TryPostServer::actingAs($this->user)+ ->tool(CreateApiKeyTool::class, ['name' => 'My Key'])+ ->assertOk()+ ->assertStructuredContent(fn (AssertableJson $json) => $json->has('plain_token')->etc());++ expect(AccessToken::where('workspace_id', $this->workspace->id)->where('name', 'My Key')->exists())->toBeTrue();+});diff --git a/tests/Feature/Mcp/McpToolCalledTrackingTest.php b/tests/Feature/Mcp/McpToolCalledTrackingTest.phpnew file mode 100644index 000000000..ae103a799--- /dev/null+++ b/tests/Feature/Mcp/McpToolCalledTrackingTest.php@@ -0,0 +1,152 @@+<?php++declare(strict_types=1);++use App\Enums\AccessToken\McpClient;+use App\Enums\Mcp\Method;+use App\Enums\PostHog\McpEvent;+use App\Jobs\PostHog\SendEvent;+use App\Jobs\PostHog\TrackMcpToolCalled;+use App\Services\PostHogService;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Facades\Queue;+use Illuminate\Testing\TestResponse;++beforeEach(function () {+ enablePostHog();+ Queue::fake([TrackMcpToolCalled::class, SendEvent::class]);++ $result = createApiTestToken();+ subscribeAccount($result['user']->account);++ $this->user = $result['user'];+ $this->workspace = $result['workspace'];+ $this->apiToken = $result['plain_token'];++ $this->mcpToken = mcpBearerToken($this->user, $this->workspace, clientName: 'Claude')['plain_token'];+});++/**+ * @param array<string, mixed> $params+ */+function mcpToolCalledRequest(object $test, string $token, string $method, array $params = []): TestResponse+{+ return $test->withHeaders([+ 'Authorization' => "Bearer {$token}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => $method,+ 'params' => (object) $params,+ ]);+}++/**+ * @return array{name: string, arguments: object}+ */+function mcpToolCalledGetWorkspace(): array+{+ return ['name' => 'get-workspace-tool', 'arguments' => (object) []];+}++test('first tool call of the day is tracked with tool and client', function () {+ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, mcpToolCalledGetWorkspace())->assertOk();++ Queue::assertPushedOn('posthog', TrackMcpToolCalled::class, fn (TrackMcpToolCalled $job) => $job->userId === (string) $this->user->id+ && $job->workspaceId === (string) $this->workspace->id+ && $job->tool === 'get-workspace-tool'+ && filled($job->accessTokenId));++ Queue::pushed(TrackMcpToolCalled::class)->first()->handle(app(PostHogService::class));++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => $job->payload['event'] === McpEvent::ToolCalled->value+ && $job->payload['distinctId'] === (string) $this->user->id+ && $job->payload['properties']['tool'] === 'get-workspace-tool'+ && $job->payload['properties']['client'] === McpClient::Claude->value+ && $job->payload['properties']['workspace_id'] === (string) $this->workspace->id+ && $job->payload['properties']['$groups']['account'] === (string) $this->workspace->account_id);+});++test('second call the same day is not tracked', function () {+ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, mcpToolCalledGetWorkspace())->assertOk();+ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, ['name' => 'list-labels-tool', 'arguments' => (object) []])->assertOk();++ Queue::assertPushedOnce(TrackMcpToolCalled::class);+});++test('the first call of the next day is tracked again', function () {+ $this->travelTo(now()->utc()->setTime(23, 0));+ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, mcpToolCalledGetWorkspace())->assertOk();++ $this->travelTo(now()->utc()->addDay()->setTime(1, 0));+ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, mcpToolCalledGetWorkspace())->assertOk();++ Queue::assertPushedTimes(TrackMcpToolCalled::class, 2);+});++test('tools/list is not tracked', function () {+ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsList->value)->assertOk();++ Queue::assertNotPushed(TrackMcpToolCalled::class);+});++test('api key requests are not tracked, even with a tool call body', function () {+ $this->withToken($this->apiToken)->getJson(route('api.workspace.show'))->assertOk();+ $this->withToken($this->apiToken)->postJson(route('api.labels.store'), [+ 'method' => Method::ToolsCall->value,+ 'params' => ['name' => 'x'],+ ]);++ Queue::assertNotPushed(TrackMcpToolCalled::class);+});++test('nothing is tracked or cached when PostHog is disabled', function () {+ config(['services.posthog.api_key' => null]);++ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, mcpToolCalledGetWorkspace())->assertOk();++ $today = now()->utc()->toDateString();++ Queue::assertNotPushed(TrackMcpToolCalled::class);+ expect(Cache::has("posthog:mcp_tool_called:{$this->user->id}:{$today}"))->toBeFalse();+});++test('a tracking failure never fails the tool call', function () {+ Cache::shouldReceive('add')->andThrow(new RuntimeException('cache down'));++ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, mcpToolCalledGetWorkspace())->assertOk();++ Queue::assertNotPushed(TrackMcpToolCalled::class);+});++test('a tool call still runs when the tracking dispatch fails', function () {+ failDispatchOf(TrackMcpToolCalled::class);++ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, mcpToolCalledGetWorkspace())+ ->assertOk()+ ->assertJsonPath('result.isError', false)+ ->assertSee((string) $this->workspace->id);++ Queue::assertNotPushed(TrackMcpToolCalled::class);+});++test('a method that is not a string still gets the JSON-RPC error, not a server error', function (mixed $method) {+ $this->withHeaders([+ 'Authorization' => "Bearer {$this->mcpToken}",+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson(route('mcp.trypost'), ['jsonrpc' => '2.0', 'id' => 1, 'method' => $method])+ ->assertOk()+ ->assertJsonPath('error.code', -32600);++ Queue::assertNotPushed(TrackMcpToolCalled::class);+})->with([+ 'array' => [[Method::ToolsCall->value]],+ 'object' => [['name' => Method::ToolsCall->value]],+]);++test('a tool name that is not a string is tracked without it', function () {+ mcpToolCalledRequest($this, $this->mcpToken, Method::ToolsCall->value, ['name' => ['get-workspace-tool'], 'arguments' => (object) []]);++ Queue::assertPushedOn('posthog', TrackMcpToolCalled::class, fn (TrackMcpToolCalled $job) => $job->tool === null);+});diff --git a/tests/Feature/Mcp/RepurposeToolTest.php b/tests/Feature/Mcp/RepurposeToolTest.phpindex 87970b8e7..8d744ed3f 100644--- a/tests/Feature/Mcp/RepurposeToolTest.php+++ b/tests/Feature/Mcp/RepurposeToolTest.php@@ -401,3 +401,22 @@ test('google business is rejected as a destination', function () {expect(Repurpose::count())->toBe(0);});++test('activating through the tool returns the same body when PostHog is enabled', function () {+ enablePostHog();+ Queue::fake();++ $repurpose = Repurpose::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'source_social_account_id' => $this->source->id,+ 'destinations' => [tiktokDestinationForMcp($this->tiktok)],+ ]);++ TryPostServer::actingAs($this->user)+ ->tool(ActivateRepurposeTool::class, ['repurpose_id' => $repurpose->id])+ ->assertOk()+ ->assertStructuredContent(fn (AssertableJson $json) => $json+ ->where('status', Status::Active->value)+ ->missing('source_account')+ ->etc());+});diff --git a/tests/Feature/Migrations/BackfillFirstPaidAtMigrationTest.php b/tests/Feature/Migrations/BackfillFirstPaidAtMigrationTest.phpnew file mode 100644index 000000000..a5ab65878--- /dev/null+++ b/tests/Feature/Migrations/BackfillFirstPaidAtMigrationTest.php@@ -0,0 +1,64 @@+<?php++declare(strict_types=1);++use App\Models\Account;++beforeEach(function () {+ $this->runBackfill = function (): void {+ $migration = require database_path('migrations/2026_10_19_143226_add_lifecycle_to_accounts_table.php');++ $migration->backfillFirstPaidAt();+ };++ $this->subscribe = function (Account $account, string $status, array $attributes = []): void {+ $account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_'.fake()->uuid(),+ 'stripe_status' => $status,+ 'stripe_price' => 'price_123',+ ...$attributes,+ ]);+ };+});++test('marks accounts whose subscription went past checkout and trial', function (string $status, array $attributes) {+ $account = Account::factory()->create();+ ($this->subscribe)($account, $status, $attributes);++ ($this->runBackfill)();++ expect($account->fresh()->first_paid_at)->not->toBeNull();+})->with([+ 'active' => ['active', []],+ 'past due' => ['past_due', []],+ 'past due on a later renewal' => ['past_due', ['trial_ends_at' => now()->subMonths(3)]],+ 'cancelled after its trial' => ['canceled', ['trial_ends_at' => now()->subMonth(), 'ends_at' => now()->subDay()]],+]);++test('leaves accounts that were never charged', function (string $status, array $attributes) {+ $account = Account::factory()->create();+ ($this->subscribe)($account, $status, $attributes);++ ($this->runBackfill)();++ expect($account->fresh()->first_paid_at)->toBeNull();+})->with([+ 'trialing' => ['trialing', ['trial_ends_at' => now()->addDays(3)]],+ 'incomplete' => ['incomplete', []],+ 'incomplete expired' => ['incomplete_expired', []],+ 'past due on the first charge after its trial' => ['past_due', ['trial_ends_at' => now()->subDays(3)]],+ 'unpaid after the first charge after its trial' => ['unpaid', ['trial_ends_at' => now()->subDays(10)]],+ 'cancelled inside its trial' => ['canceled', ['trial_ends_at' => now()->addDays(3), 'ends_at' => now()->subDay()]],+]);++test('keeps a first payment already recorded', function () {+ $this->freezeTime();+ $account = Account::factory()->create();+ $account->forceFill(['first_paid_at' => now()->subYear()->startOfSecond()])->save();+ ($this->subscribe)($account, 'active');++ ($this->runBackfill)();++ expect($account->fresh()->first_paid_at->equalTo(now()->subYear()->startOfSecond()))->toBeTrue();+});diff --git a/tests/Feature/Observers/SocialAccountObserverTest.php b/tests/Feature/Observers/SocialAccountObserverTest.phpindex f8a4b61e8..ea66dd7a3 100644--- a/tests/Feature/Observers/SocialAccountObserverTest.php+++ b/tests/Feature/Observers/SocialAccountObserverTest.php@@ -2,20 +2,25 @@declare(strict_types=1);+use App\Enums\PostHog\SocialAccountEvent;use App\Enums\SocialAccount\Status;use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;use App\Jobs\PostHog\IdentifyConnectedPlatforms;use App\Jobs\PostHog\SendEvent;use App\Jobs\PostHog\SyncAccountUsage;+use App\Jobs\PostHog\TrackSocialAccountConnectionLost;use App\Models\Account;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;+use Illuminate\Queue\Events\JobProcessing;use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Queue;beforeEach(function () {- config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ enablePostHog();$this->account = Account::factory()->create();$this->user = User::factory()->create(['account_id' => $this->account->id]);@@ -166,3 +171,110 @@ test('connecting an excluded account does not dispatch follower collection', funBus::assertNotDispatched(CollectAccountDailySnapshot::class);Bus::assertNotDispatched(BootstrapAccountAnalytics::class);});++test('token expiry dispatches the lost connection with its status', function () {+ $socialAccount = SocialAccount::factory()->x()->create([+ 'workspace_id' => $this->workspace->id,+ 'status' => Status::Connected,+ ]);++ Bus::fake([TrackSocialAccountConnectionLost::class]);++ $socialAccount->markAsTokenExpired('Token revoked', notify: false);++ Bus::assertDispatchedOnce(TrackSocialAccountConnectionLost::class);+ Bus::assertDispatched(TrackSocialAccountConnectionLost::class, fn (TrackSocialAccountConnectionLost $job): bool => $job->socialAccountId === (string) $socialAccount->id+ && $job->status === Status::TokenExpired);+});++test('a status change to disconnected dispatches the lost connection with that status', function () {+ $socialAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'status' => Status::Connected,+ ]);++ Bus::fake([TrackSocialAccountConnectionLost::class]);++ $socialAccount->update(['status' => Status::Disconnected]);++ Bus::assertDispatched(TrackSocialAccountConnectionLost::class, fn (TrackSocialAccountConnectionLost $job): bool => $job->status === Status::Disconnected);+});++test('a channel that was not connected does not dispatch disconnected again', function () {+ $socialAccount = SocialAccount::factory()->tokenExpired()->create(['workspace_id' => $this->workspace->id]);++ Bus::fake([TrackSocialAccountConnectionLost::class]);++ $socialAccount->update(['status' => Status::Disconnected]);+ $socialAccount->update(['status' => Status::Connected]);++ Bus::assertNotDispatched(TrackSocialAccountConnectionLost::class);+});++test('a status change does not dispatch disconnected when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);++ $socialAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'status' => Status::Connected,+ ]);++ Bus::fake([TrackSocialAccountConnectionLost::class]);++ $socialAccount->update(['status' => Status::TokenExpired]);++ Bus::assertNotDispatched(TrackSocialAccountConnectionLost::class);+});++test('a token expiry rolled back with its transaction sends no disconnected event', function () {+ $socialAccount = SocialAccount::factory()->x()->create([+ 'workspace_id' => $this->workspace->id,+ 'status' => Status::Connected,+ ]);++ Queue::fake([SendEvent::class]);++ rescue(fn () => DB::transaction(function () use ($socialAccount): void {+ $socialAccount->markAsTokenExpired('Token revoked', notify: false);++ throw new RuntimeException('Rolled back.');+ }), report: false);++ expect($socialAccount->fresh()->status)->toBe(Status::Connected);+ Queue::assertNotPushed(SendEvent::class, fn (SendEvent $job): bool => data_get($job->payload, 'event') === SocialAccountEvent::Disconnected->value);++ $socialAccount->fresh()->markAsTokenExpired('Token revoked', notify: false);++ Queue::assertPushed(SendEvent::class, fn (SendEvent $job): bool => data_get($job->payload, 'event') === SocialAccountEvent::Disconnected->value);+});++test('a status save survives a failing disconnected dispatch', function () {+ $socialAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'status' => Status::Connected,+ ]);++ failDispatchOf(TrackSocialAccountConnectionLost::class);++ $socialAccount->update(['status' => Status::TokenExpired]);++ expect(SocialAccount::query()->find($socialAccount->id)->status)->toBe(Status::TokenExpired);+});++test('a status saved inside a transaction survives a disconnected push that fails at commit', function () {+ $socialAccount = SocialAccount::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'status' => Status::Connected,+ ]);++ Queue::fake([SyncAccountUsage::class, IdentifyConnectedPlatforms::class]);+ Queue::before(function (JobProcessing $event): void {+ if ($event->job->resolveName() === TrackSocialAccountConnectionLost::class) {+ throw new RuntimeException('Queue is down.');+ }+ });++ DB::transaction(fn () => $socialAccount->update(['status' => Status::TokenExpired]));++ expect(SocialAccount::query()->find($socialAccount->id)->status)->toBe(Status::TokenExpired);+});diff --git a/tests/Feature/Repurpose/ActionsTest.php b/tests/Feature/Repurpose/ActionsTest.phpindex bf12cb5f5..07626b675 100644--- a/tests/Feature/Repurpose/ActionsTest.php+++ b/tests/Feature/Repurpose/ActionsTest.php@@ -17,6 +17,7 @@ use App\Enums\SocialAccount\Platform;use App\Enums\TikTok\PrivacyLevel;use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;+use App\Jobs\PostHog\TrackRepurposeActivated;use App\Models\Post;use App\Models\Repurpose;use App\Models\RepurposeItem;@@ -50,6 +51,12 @@ function tiktokDestination(Workspace $workspace): array];}+function enableRepurposeTracking(): void+{+ enablePostHog();+ Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class, TrackRepurposeActivated::class]);+}+test('a repurpose is created as a draft with its source account', function () {[$workspace, $user, $account] = repurposeWorkspace();@@ -447,3 +454,56 @@ test('an update that repeats the current source and format leaves the watermarkexpect($fresh->activated_at->equalTo($watermark))->toBeTrue()->and($fresh->publish_mode)->toBe(PublishMode::Draft);});++test('activating a repurpose tracks it', function () {+ [$workspace, $user, $account] = repurposeWorkspace();++ $repurpose = Repurpose::factory()->create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $user->id,+ 'source_social_account_id' => $account->id,+ 'destinations' => [tiktokDestination($workspace), tiktokDestination($workspace)],+ ]);++ enableRepurposeTracking();++ $this->actingAs($user);++ ActivateRepurpose::execute($repurpose);++ Queue::assertPushedOn('posthog', TrackRepurposeActivated::class, fn (TrackRepurposeActivated $job) => $job->repurposeId === (string) $repurpose->id+ && $job->userId === (string) $user->id);+});++test('a rejected activation is not tracked', function () {+ $repurpose = Repurpose::factory()->create();++ enableRepurposeTracking();++ expect(fn () => ActivateRepurpose::execute($repurpose))->toThrow(ValidationException::class);++ Queue::assertNotPushed(TrackRepurposeActivated::class);+});++test('a repurpose still activates when tracking it fails', function () {+ [$workspace, $user, $account] = repurposeWorkspace();++ $repurpose = Repurpose::factory()->create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $user->id,+ 'source_social_account_id' => $account->id,+ 'destinations' => [tiktokDestination($workspace)],+ ]);++ enableRepurposeTracking();+ failDispatchOf(TrackRepurposeActivated::class);++ $activated = ActivateRepurpose::execute($repurpose);++ $fresh = $repurpose->fresh();++ expect($activated->status)->toBe(Status::Active)+ ->and($fresh->status)->toBe(Status::Active)+ ->and($fresh->activated_at)->not->toBeNull();+ Queue::assertNotPushed(TrackRepurposeActivated::class);+});diff --git a/tests/Feature/Social/ConnectConfirmationTest.php b/tests/Feature/Social/ConnectConfirmationTest.phpindex a65bc391b..90db632c4 100644--- a/tests/Feature/Social/ConnectConfirmationTest.php+++ b/tests/Feature/Social/ConnectConfirmationTest.php@@ -5,11 +5,13 @@ declare(strict_types=1);use App\Enums\Plan\Slug;use App\Enums\SocialAccount\Platform;use App\Enums\SocialAccount\Status;+use App\Jobs\PostHog\TrackSocialAccountConnected;use App\Models\Plan;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;use App\Support\Social\PendingConnection;+use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Route;use Inertia\Testing\AssertableInertia;@@ -436,3 +438,70 @@ test('several channels connect at once on any plan, since channels have no cap',expect($this->workspace->socialAccounts()->count())->toBe(3);});++test('finishing a new connection dispatches social_account.connected with source', function () {+ enablePostHog();+ Bus::fake([TrackSocialAccountConnected::class]);++ startSocialConnect($this->workspace, Platform::Facebook, null, route('app.calendar', ['view' => 'week'], false))->offer([+ offeredFacebookPage('p1', 'One'),+ offeredFacebookPage('p2', 'Two'),+ ]);++ assertFinishedOnChannel($this->actingAs($this->user)->post(route('app.social.connect.finish', Platform::Facebook), [+ 'identities' => ['facebook:p1', 'facebook:p2'],+ ]));++ $accountIds = $this->workspace->socialAccounts()->pluck('id')->map(strval(...))->sort()->values()->all();++ Bus::assertDispatchedTimes(TrackSocialAccountConnected::class, 2);+ Bus::assertDispatched(TrackSocialAccountConnected::class, fn (TrackSocialAccountConnected $job): bool => in_array($job->socialAccountId, $accountIds, true)+ && $job->userId === (string) $this->user->id+ && $job->source === 'app.calendar');+});++test('reconnecting does not dispatch connected', function () {+ enablePostHog();+ Bus::fake([TrackSocialAccountConnected::class]);++ $account = SocialAccount::factory()->x()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform_user_id' => 'x-1',+ ]);++ startSocialConnect($this->workspace, Platform::X, $account);+ fakeXLogin();++ $this->actingAs($this->user)->get(route('app.social.x.callback'))->assertRedirect();++ finishSocialConnect(Platform::X)->assertInertiaFlash('connectedChannel.created', false);++ Bus::assertNotDispatched(TrackSocialAccountConnected::class);+});++test('finishing a connection does not dispatch connected when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ Bus::fake([TrackSocialAccountConnected::class]);++ startSocialConnect($this->workspace, Platform::Facebook)->offer([offeredFacebookPage('p1', 'One')]);++ assertFinishedOnChannel($this->actingAs($this->user)->post(route('app.social.connect.finish', Platform::Facebook), [+ 'identities' => ['facebook:p1'],+ ]));++ Bus::assertNotDispatched(TrackSocialAccountConnected::class);+});++test('finishing a connection still lands on the channel when tracking it fails', function () {+ enablePostHog();+ failDispatchOf(TrackSocialAccountConnected::class);++ startSocialConnect($this->workspace, Platform::Facebook)->offer([offeredFacebookPage('p1', 'One')]);++ assertFinishedOnChannel($this->actingAs($this->user)->post(route('app.social.connect.finish', Platform::Facebook), [+ 'identities' => ['facebook:p1'],+ ]));++ expect($this->workspace->socialAccounts()->count())->toBe(1)+ ->and(PendingConnection::current())->toBeNull();+});diff --git a/tests/Feature/Social/TelegramConnectionTest.php b/tests/Feature/Social/TelegramConnectionTest.phpindex 1fc968a1e..a9c33d4da 100644--- a/tests/Feature/Social/TelegramConnectionTest.php+++ b/tests/Feature/Social/TelegramConnectionTest.php@@ -7,12 +7,14 @@ use App\Events\TelegramChannelConnected;use App\Events\TelegramConnectFailed;use App\Exceptions\PlatformUnavailableException;use App\Exceptions\TokenExpiredException;+use App\Jobs\PostHog\TrackSocialAccountConnected;use App\Models\Post;use App\Models\SocialAccount;use App\Models\User;use App\Models\Workspace;use App\Services\Social\ConnectionVerifier;use App\Services\Social\Telegram\TelegramConnectCode;+use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Http;@@ -499,3 +501,76 @@ it('reports a busy connect instead of letting the webhook fail', function () {expect($this->workspace->socialAccounts()->count())->toBe(0);});++it('telegram connection uses source telegram', function () {+ enablePostHog();+ Http::fake();+ Bus::fake([TrackSocialAccountConnected::class]);++ $owner = User::factory()->create(['account_id' => $this->workspace->account_id]);+ $this->workspace->account->update(['owner_id' => $owner->id]);++ $code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));++ $this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')+ ->postJson(route('telegram.webhook'), telegramUpdate($code))+ ->assertNoContent();++ $account = SocialAccount::where('platform', Platform::Telegram)->firstOrFail();++ Bus::assertDispatchedOnce(TrackSocialAccountConnected::class);+ Bus::assertDispatched(TrackSocialAccountConnected::class, fn (TrackSocialAccountConnected $job): bool => $job->socialAccountId === (string) $account->id+ && $job->userId === null+ && $job->source === TrackSocialAccountConnected::SOURCE_TELEGRAM);+});++it('a telegram reconnect does not dispatch connected', function () {+ enablePostHog();+ Http::fake();+ Bus::fake([TrackSocialAccountConnected::class]);++ $account = SocialAccount::factory()->telegram()->create([+ 'workspace_id' => $this->workspace->id,+ 'platform_user_id' => '-1001234567890',+ ]);++ $code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15), $account->id);++ $this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')+ ->postJson(route('telegram.webhook'), telegramUpdate($code))+ ->assertNoContent();++ Bus::assertNotDispatched(TrackSocialAccountConnected::class);+});++it('a telegram connection still succeeds when tracking it fails', function () {+ enablePostHog();+ Http::fake();+ failDispatchOf(TrackSocialAccountConnected::class);++ $owner = User::factory()->create(['account_id' => $this->workspace->account_id]);+ $this->workspace->account->update(['owner_id' => $owner->id]);++ $code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));++ $this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')+ ->postJson(route('telegram.webhook'), telegramUpdate($code))+ ->assertNoContent();++ expect(SocialAccount::where('platform', Platform::Telegram)->exists())->toBeTrue();+});++it('a telegram connection does not dispatch connected when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ Http::fake();+ Bus::fake([TrackSocialAccountConnected::class]);++ $code = TelegramConnectCode::issue($this->workspace->id, now()->addMinutes(15));++ $this->withHeader('X-Telegram-Bot-Api-Secret-Token', 'shh-secret')+ ->postJson(route('telegram.webhook'), telegramUpdate($code))+ ->assertNoContent();++ expect(SocialAccount::where('platform', Platform::Telegram)->exists())->toBeTrue();+ Bus::assertNotDispatched(TrackSocialAccountConnected::class);+});diff --git a/tests/Feature/Workspace/WorkspaceLimitTest.php b/tests/Feature/Workspace/WorkspaceLimitTest.phpindex a7e93f7d9..7a6ba8350 100644--- a/tests/Feature/Workspace/WorkspaceLimitTest.php+++ b/tests/Feature/Workspace/WorkspaceLimitTest.php@@ -3,11 +3,13 @@declare(strict_types=1);use App\Enums\Plan\Slug;+use App\Jobs\PostHog\TrackWorkspaceLimitHit;use App\Models\Plan;use App\Models\User;use App\Models\Workspace;use Illuminate\Database\Events\QueryExecuted;use Illuminate\Support\Facades\DB;+use Illuminate\Support\Facades\Queue;use Illuminate\Support\Str;beforeEach(function () {@@ -22,10 +24,12 @@ $onPlan = function (Slug $slug): User {$user = User::factory()->create();$user->account->update(['plan_id' => Plan::where('slug', $slug)->value('id')]);- Workspace::factory()->create([+ $workspace = Workspace::factory()->create(['account_id' => $user->account_id,'user_id' => $user->id,]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);// The controller guard checks hasActiveSubscription() *before* the cap.// Without this, GET at the Socials cap still renders, but store flashes@@ -61,20 +65,19 @@ test('a subscribed account without a plan is still capped at one workspace', fun$user = User::factory()->create();$user->account->update(['plan_id' => null]);- Workspace::factory()->create([+ $workspace = Workspace::factory()->create(['account_id' => $user->account_id,'user_id' => $user->id,]);+ $workspace->members()->attach($user->id, membershipPivot('admin'));+ $user->update(['current_workspace_id' => $workspace->id]);subscribeAccount($user->account);$this->actingAs($user->fresh())->get(route('app.workspaces.create'))- ->assertOk()- ->assertInertia(fn ($page) => $page- ->component('workspaces/Create', false)- ->where('features.workspaceLimit', 1)- );+ ->assertRedirect(route('app.workspaces.index'))+ ->assertSessionHas('flash.error', __('workspaces.limit_reached'));});test('the socials plan blocks a second workspace', function () use ($onPlan) {@@ -109,14 +112,25 @@ test('self-hosted ignores the cap', function () use ($onPlan) {expect($user->account->canCreateWorkspace())->toBeTrue();});-test('the create form is available when the plan is at its cap', function () use ($onPlan) {+test('the create page sends the user to the workspaces list when the plan is at its cap', function () use ($onPlan) {$user = $onPlan(Slug::Socials);+ $this->actingAs($user)+ ->from(route('app.posts.index'))+ ->get(route('app.workspaces.create'))+ ->assertRedirect(route('app.workspaces.index'))+ ->assertSessionHas('flash.error', __('workspaces.limit_reached'));+});++test('the create page renders below the cap', function () use ($onPlan) {+ $user = $onPlan(Slug::Workspaces);+$this->actingAs($user)->get(route('app.workspaces.create'))->assertOk()->assertInertia(fn ($page) => $page->component('workspaces/Create', false)+ ->missing('upgradeRequired'));});@@ -132,8 +146,9 @@ test('a subscribed account without a plan cannot store a second workspace', funcsubscribeAccount($user->account);$this->actingAs($user->fresh())+ ->from(route('app.posts.index'))->post(route('app.workspaces.store'), ['name' => 'Second'])- ->assertRedirect(route('app.workspaces.create'))+ ->assertRedirect(route('app.workspaces.index'))->assertSessionHas('flash.error', __('workspaces.limit_reached'));expect($user->account->workspaces()->count())->toBe(1);@@ -143,8 +158,9 @@ test('a direct store POST cannot exceed the cap', function () use ($onPlan) {$user = $onPlan(Slug::Socials);$this->actingAs($user)+ ->from(route('app.workspaces.create'))->post(route('app.workspaces.store'), ['name' => 'Second'])- ->assertRedirect(route('app.workspaces.create'))+ ->assertRedirect(route('app.workspaces.index'))->assertSessionHas('flash.error', __('workspaces.limit_reached'));expect($user->account->workspaces()->count())->toBe(1);@@ -178,3 +194,192 @@ test('storing a workspace checks the cap under a lock on the account row', funct->and($insert)->toBeInt()->and($lock)->toBeLessThan($insert);});++$enablePostHog = function (): void {+ enablePostHog();+ Queue::fake([TrackWorkspaceLimitHit::class]);+};++$limitHitPushed = fn (User $user) => fn (TrackWorkspaceLimitHit $job): bool => $job->userId === (string) $user->id+ && $job->planSlug === $user->account->plan?->slug->value+ && $job->workspaceLimit === $user->account->workspaceLimit();++test('the creation check at the limit refuses and tracks limit_hit', function () use ($onPlan, $enablePostHog, $limitHitPushed) {+ $enablePostHog();+ $user = $onPlan(Slug::Socials);++ $this->actingAs($user)+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertOk()+ ->assertExactJson(['allowed' => false]);++ Queue::assertPushedOn('posthog', TrackWorkspaceLimitHit::class, $limitHitPushed($user));+ Queue::assertPushedTimes(TrackWorkspaceLimitHit::class, 1);+});++test('the creation check below the limit allows and does not track', function () use ($onPlan, $enablePostHog) {+ $enablePostHog();+ $user = $onPlan(Slug::Workspaces);++ $this->actingAs($user)+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertOk()+ ->assertExactJson(['allowed' => true]);++ Queue::assertNotPushed(TrackWorkspaceLimitHit::class);+});++test('the creation check allows self-hosted at any count and does not track', function () use ($onPlan, $enablePostHog) {+ $enablePostHog();+ $user = $onPlan(Slug::Socials);+ config(['trypost.self_hosted' => true]);++ $this->actingAs($user)+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertExactJson(['allowed' => true]);++ Queue::assertNotPushed(TrackWorkspaceLimitHit::class);+});++test('the creation check allows the first workspace and does not track', function () use ($enablePostHog) {+ $enablePostHog();+ $user = User::factory()->create();+ $user->account->update(['plan_id' => Plan::where('slug', Slug::Socials)->value('id')]);+ subscribeAccount($user->account);++ $this->actingAs($user->fresh())+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertExactJson(['allowed' => true]);++ Queue::assertNotPushed(TrackWorkspaceLimitHit::class);+});++test('the creation check refuses an account without a plan at one workspace, as the props did on main', function () use ($enablePostHog) {+ $enablePostHog();+ $user = User::factory()->create();+ $user->account->update(['plan_id' => null]);+ Workspace::factory()->create(['account_id' => $user->account_id, 'user_id' => $user->id]);++ $this->actingAs($user->fresh())+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertExactJson(['allowed' => false]);+});++test('the creation check counts the account workspaces, not the ones the owner created, as the props did on main', function () use ($enablePostHog, $limitHitPushed) {+ $enablePostHog();+ $owner = User::factory()->create();+ $owner->account->update(['plan_id' => Plan::where('slug', Slug::Socials)->value('id')]);+ subscribeAccount($owner->account);+ $creator = User::factory()->create(['account_id' => $owner->account_id]);+ Workspace::factory()->create(['account_id' => $owner->account_id, 'user_id' => $creator->id]);++ expect($owner->fresh()->ownedWorkspacesCount())->toBe(0);++ $this->actingAs($owner->fresh())+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertOk()+ ->assertExactJson(['allowed' => false]);++ Queue::assertPushedOn('posthog', TrackWorkspaceLimitHit::class, $limitHitPushed($owner));+ Queue::assertPushedTimes(TrackWorkspaceLimitHit::class, 1);+});++test('the creation check is for the account owner only', function () use ($onPlan) {+ $owner = $onPlan(Slug::Socials);+ $member = User::factory()->create(['account_id' => $owner->account_id]);+ $workspace = $owner->account->workspaces()->first();+ $workspace->members()->attach($member->id, membershipPivot('admin'));+ $member->update(['current_workspace_id' => $workspace->id]);++ $this->actingAs($member->fresh())+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertForbidden();+});++test('a failed limit_hit dispatch still refuses the creation check', function () use ($onPlan) {+ enablePostHog();+ failDispatchOf(TrackWorkspaceLimitHit::class);+ $user = $onPlan(Slug::Socials);++ $this->actingAs($user)+ ->postJson(route('app.workspaces.creation-check.store'))+ ->assertOk()+ ->assertExactJson(['allowed' => false]);+});++test('opening the create page at the limit sends the user to the workspaces list and tracks limit_hit once', function () use ($onPlan, $enablePostHog, $limitHitPushed) {+ $enablePostHog();+ $user = $onPlan(Slug::Socials);++ $this->actingAs($user)+ ->from(route('app.posts.index'))+ ->get(route('app.workspaces.create'))+ ->assertRedirect(route('app.workspaces.index'))+ ->assertSessionHas('flash.error', __('workspaces.limit_reached'));++ Queue::assertPushedOn('posthog', TrackWorkspaceLimitHit::class, $limitHitPushed($user));+ Queue::assertPushedTimes(TrackWorkspaceLimitHit::class, 1);+});++test('the create page at the limit still renders for a user without a current workspace, so it never loops with the workspace guard', function () use ($onPlan) {+ $user = $onPlan(Slug::Socials);+ $user->update(['current_workspace_id' => null]);++ $this->actingAs($user->fresh())+ ->get(route('app.workspaces.create'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page->component('workspaces/Create', false));+});++test('opening the create page below the limit renders it and does not track', function () use ($onPlan, $enablePostHog) {+ $enablePostHog();+ $user = $onPlan(Slug::Workspaces);++ $this->actingAs($user)+ ->get(route('app.workspaces.create'))+ ->assertOk()+ ->assertInertia(fn ($page) => $page->component('workspaces/Create', false));++ Queue::assertNotPushed(TrackWorkspaceLimitHit::class);+});++test('a store refused at the limit creates nothing and is tracked once', function () use ($onPlan, $enablePostHog, $limitHitPushed) {+ $enablePostHog();+ $user = $onPlan(Slug::Socials);++ $this->actingAs($user)+ ->from(route('app.workspaces.create'))+ ->followingRedirects()+ ->post(route('app.workspaces.store'), ['name' => 'Second'])+ ->assertOk()+ ->assertInertia(fn ($page) => $page->component('workspaces/Index', false));++ Queue::assertPushedOn('posthog', TrackWorkspaceLimitHit::class, $limitHitPushed($user));+ Queue::assertPushedTimes(TrackWorkspaceLimitHit::class, 1);+ expect($user->account->workspaces()->count())->toBe(1)+ ->and(Workspace::where('name', 'Second')->exists())->toBeFalse();+});++test('a store refused for a missing subscription does not track limit_hit', function () use ($enablePostHog) {+ $enablePostHog();+ $user = User::factory()->create();+ $user->account->update(['plan_id' => Plan::where('slug', Slug::Socials)->value('id')]);+ Workspace::factory()->create(['account_id' => $user->account_id, 'user_id' => $user->id]);++ $this->actingAs($user->fresh())+ ->post(route('app.workspaces.store'), ['name' => 'Second'])+ ->assertRedirect(route('app.billing.index'));++ Queue::assertNotPushed(TrackWorkspaceLimitHit::class);+});++test('a failed limit_hit dispatch still sends the user away from the create page', function () use ($onPlan) {+ enablePostHog();+ failDispatchOf(TrackWorkspaceLimitHit::class);+ $user = $onPlan(Slug::Socials);++ $this->actingAs($user)+ ->get(route('app.workspaces.create'))+ ->assertRedirect(route('app.workspaces.index'))+ ->assertSessionHas('flash.error', __('workspaces.limit_reached'));+});diff --git a/tests/Feature/WorkspaceInviteControllerTest.php b/tests/Feature/WorkspaceInviteControllerTest.phpindex 45893c2a0..393111f21 100644--- a/tests/Feature/WorkspaceInviteControllerTest.php+++ b/tests/Feature/WorkspaceInviteControllerTest.php@@ -2,6 +2,8 @@declare(strict_types=1);+use App\Enums\PostHog\WorkspaceEvent;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Mail\WorkspaceInvite as WorkspaceInviteMail;use App\Models\AccessToken;use App\Models\Account;@@ -10,6 +12,7 @@ use App\Models\User;use App\Models\Workspace;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Mail;+use Illuminate\Support\Facades\Queue;use Illuminate\Support\Str;beforeEach(function () {@@ -414,3 +417,44 @@ test('update member of a user outside the workspace is not found and revokes notexpect($token->fresh()->revoked)->toBeFalse();});++test('inviting a member tracks admin and approval flags', function () {+ enablePostHog();+ Queue::fake([CaptureAccountEvent::class]);+ $admin = workspaceMember($this->workspace, 'admin');++ $this->actingAs($admin)->post(route('app.invites.store'), [+ 'email' => '[email protected]',+ 'is_admin' => '0',+ 'requires_approval' => '1',+ ])->assertSessionHasNoErrors();++ Queue::assertPushedOn('posthog', CaptureAccountEvent::class, fn (CaptureAccountEvent $job) => $job->event === WorkspaceEvent::MemberInvited+ && $job->distinctId === (string) $admin->id+ && $job->accountId === (string) $this->account->id+ && $job->properties === [+ 'is_admin' => false,+ 'requires_approval' => true,+ ]);+});++test('inviting a member still creates and mails the invite when tracking it fails', function () {+ enablePostHog();+ failDispatchOf(CaptureAccountEvent::class);++ $this->actingAs($this->user)+ ->from(route('app.members'))+ ->post(route('app.invites.store'), [+ 'email' => '[email protected]',+ ...membershipPivot('member'),+ ])+ ->assertRedirect(route('app.members'))+ ->assertSessionHasNoErrors()+ ->assertSessionHas('flash.banner', __('settings.members.flash.invite_sent'));++ $this->assertDatabaseHas('invites', [+ 'account_id' => $this->account->id,+ 'email' => '[email protected]',+ ]);+ Mail::assertQueued(WorkspaceInviteMail::class);+});diff --git a/tests/Pest.php b/tests/Pest.phpindex c29c121af..6f95121ea 100644--- a/tests/Pest.php+++ b/tests/Pest.php@@ -16,6 +16,7 @@ use App\Services\Http\HostResolver;use App\Support\Social\PendingConnection;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Http\Client\Request as HttpClientRequest;+use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Http;use Illuminate\Support\Facades\Queue;@@ -349,6 +350,34 @@ function subscribeAccount(Account $account): void]);}+/**+ * Turns PostHog on for the test, as on an install with an API key.+ */+function enablePostHog(): void+{+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+}++/**+ * Make dispatching the given job throw, as when the queue is down, while every+ * other job dispatches as usual. `$when` narrows the failure to the jobs it+ * accepts.+ *+ * @param class-string $jobClass+ * @param (Closure(object): bool)|null $when+ */+function failDispatchOf(string $jobClass, ?Closure $when = null): void+{+ $dispatcher = Bus::getFacadeRoot();+ $bus = Mockery::mock($dispatcher);+ $bus->shouldReceive('dispatch')+ ->with(Mockery::on(fn (mixed $job): bool => $job instanceof $jobClass && ($when === null || $when($job))))+ ->andThrow(new RuntimeException('Queue is down.'));+ $bus->shouldReceive('dispatch')->andReturnUsing(fn (mixed $job, mixed $handler = null): mixed => $dispatcher->dispatch($job, $handler));++ Bus::swap($bus);+}+/*** Insert an OAuth client suitable for MCP connection tests.*/@@ -427,7 +456,7 @@ function mcpAccessToken(* @param list<string> $scopes* @return array{token: AccessToken, plain_token: string}*/-function mcpBearerToken(User $user, Workspace $workspace, array $scopes = ['mcp:use']): array+function mcpBearerToken(User $user, Workspace $workspace, array $scopes = ['mcp:use'], string $clientName = 'My Agent'): array{$result = $user->createToken('MCP', $scopes);$token = AccessToken::query()->findOrFail($result->token->id);@@ -435,7 +464,7 @@ function mcpBearerToken(User $user, Workspace $workspace, array $scopes = ['mcp:// Reassign to a dedicated MCP client so we never mutate Passport's shared// personal-access client (which would poison PAT fixtures in the same run).$token->forceFill([- 'client_id' => mcpOauthClient(),+ 'client_id' => mcpOauthClient($clientName),'workspace_id' => $workspace->id,])->saveQuietly();diff --git a/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.php b/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.phpindex 37b6fc8b9..935aa25b5 100644--- a/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.php+++ b/tests/Unit/Actions/Billing/StartSubscriptionCheckoutTest.php@@ -101,6 +101,10 @@ test('redirect keeps the attribution metadata on the stripe customer, not on the->with(['success_url' => route('app.billing.processing').'?session_id={CHECKOUT_SESSION_ID}','cancel_url' => $cancelUrl,+ 'metadata' => [+ 'trypost_interval' => 'monthly',+ 'trypost_first_month_offer' => 'false',+ ],])->andReturn((object) ['url' => 'https://checkout.stripe.test/session']);@@ -254,6 +258,95 @@ test('redirect applies the plan first-month coupon on a monthly price', function);});+test('checkout session carries plan, interval and first month offer metadata', function () {+ config([+ 'trypost.billing.require_card_for_trial' => true,+ 'cashier.trial_days' => 8,+ 'cashier.first_month_coupon_ids.socials' => 'SOCIALS_18USD',+ 'cashier.allow_promotion_codes' => false,+ ]);++ $plan = Plan::where('slug', Slug::Socials)->firstOrFail();+ $plan->update(['stripe_monthly_price_id' => 'price_socials_monthly']);++ $account = Account::factory()->create();+ Workspace::factory()->create(['account_id' => $account->id]);+ User::factory()->create(['account_id' => $account->id, 'referral_source' => null]);+ $account->refresh();++ $builder = Mockery::mock(SubscriptionBuilder::class);+ $builder->shouldReceive('withCoupon')->once()->andReturnUsing(function () use ($builder): SubscriptionBuilder {+ $builder->couponId = 'SOCIALS_18USD';++ return $builder;+ });+ $builder->shouldReceive('withMetadata')->once()->andReturnSelf();+ $builder->shouldReceive('checkout')+ ->once()+ ->withArgs(fn (array $options): bool => data_get($options, 'metadata') === [+ 'trypost_plan_slug' => 'socials',+ 'trypost_interval' => 'monthly',+ 'trypost_first_month_offer' => 'true',+ ])+ ->andReturn((object) ['url' => 'https://checkout.stripe.test/session']);++ /** @var Account&MockInterface $accountMock */+ $accountMock = Mockery::mock($account)->makePartial();+ $accountMock->shouldReceive('syncOrCreateStripeCustomer')->once()->andReturnNull();+ $accountMock->shouldReceive('newSubscription')->once()->andReturn($builder);++ app(StartSubscriptionCheckout::class)->redirect(+ $accountMock,+ 'price_socials_monthly',+ route('app.welcome.plan'),+ $plan,+ );+});++test('checkout session marks a yearly price without the first month offer', function () {+ config([+ 'trypost.billing.require_card_for_trial' => true,+ 'cashier.trial_days' => 8,+ 'cashier.first_month_coupon_ids.workspaces' => 'WORKSPACES_88USD',+ 'cashier.allow_promotion_codes' => false,+ ]);++ $plan = Plan::where('slug', Slug::Workspaces)->firstOrFail();+ $plan->update([+ 'stripe_monthly_price_id' => 'price_workspaces_monthly',+ 'stripe_yearly_price_id' => 'price_workspaces_yearly',+ ]);++ $account = Account::factory()->create();+ Workspace::factory()->create(['account_id' => $account->id]);+ User::factory()->create(['account_id' => $account->id, 'referral_source' => null]);+ $account->refresh();++ $builder = Mockery::mock(SubscriptionBuilder::class);+ $builder->shouldReceive('withMetadata')->once()->andReturnSelf();+ $builder->shouldReceive('trialDays')->once()->andReturnSelf();+ $builder->shouldReceive('checkout')+ ->once()+ ->withArgs(fn (array $options): bool => data_get($options, 'metadata') === [+ 'trypost_plan_slug' => 'workspaces',+ 'trypost_interval' => 'yearly',+ 'trypost_first_month_offer' => 'false',+ ])+ ->andReturn((object) ['url' => 'https://checkout.stripe.test/session']);++ /** @var Account&MockInterface $accountMock */+ $accountMock = Mockery::mock($account)->makePartial();+ $accountMock->shouldReceive('syncOrCreateStripeCustomer')->once()->andReturnNull();+ $accountMock->shouldReceive('newSubscription')->once()->andReturn($builder);++ app(StartSubscriptionCheckout::class)->redirect(+ $accountMock,+ 'price_workspaces_yearly',+ route('app.welcome.plan'),+ $plan,+ );+});+test('redirect skips the first-month coupon on a yearly price', function () {config(['trypost.billing.require_card_for_trial' => true,diff --git a/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.php b/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.phpindex bd8f7d99b..3f8501e19 100644--- a/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.php+++ b/tests/Unit/Actions/Workspace/PurgeWorkspaceTest.php@@ -3,6 +3,7 @@declare(strict_types=1);use App\Actions\Workspace\PurgeWorkspace;+use App\Jobs\PostHog\CaptureAccountEvent;use App\Models\Media;use App\Models\Post;use App\Models\SocialAccount;@@ -10,6 +11,7 @@ use App\Models\User;use App\Models\Workspace;use App\Support\Social\GoogleBusinessDerivativeCleaner;use Illuminate\Http\UploadedFile;+use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Storage;@@ -60,3 +62,20 @@ test('purge workspace prunes google business jpegs before the cascade', functionexpect(Workspace::find($workspace->id))->toBeNull();Storage::assertMissing($path);});++test('purge workspace does not track its channels as disconnected', function () {+ enablePostHog();+ $owner = User::factory()->create();+ $workspace = Workspace::factory()->create([+ 'account_id' => $owner->account_id,+ 'user_id' => $owner->id,+ ]);+ SocialAccount::factory()->count(2)->create(['workspace_id' => $workspace->id]);++ Bus::fake([CaptureAccountEvent::class]);++ PurgeWorkspace::execute($workspace);++ expect(SocialAccount::query()->where('workspace_id', $workspace->id)->exists())->toBeFalse();+ Bus::assertNotDispatched(CaptureAccountEvent::class);+});diff --git a/tests/Unit/Support/Billing/FirstFullChargeTest.php b/tests/Unit/Support/Billing/FirstFullChargeTest.phpnew file mode 100644index 000000000..e4dd7415f--- /dev/null+++ b/tests/Unit/Support/Billing/FirstFullChargeTest.php@@ -0,0 +1,47 @@+<?php++declare(strict_types=1);++use App\Enums\Billing\Interval;+use App\Support\Billing\FirstFullCharge;+use Carbon\CarbonImmutable;++test('first renewal after a $1 month is the first full charge', function () {+ expect(FirstFullCharge::isFirst(+ CarbonImmutable::parse('2026-10-01'),+ CarbonImmutable::parse('2026-10-31'),+ Interval::Monthly,+ ))->toBeTrue();+});++test('second renewal is not', function () {+ expect(FirstFullCharge::isFirst(+ CarbonImmutable::parse('2026-09-01'),+ CarbonImmutable::parse('2026-10-31'),+ Interval::Monthly,+ ))->toBeFalse();+});++test('trial end is the first full charge', function () {+ expect(FirstFullCharge::isFirst(+ CarbonImmutable::parse('2026-10-01'),+ CarbonImmutable::parse('2026-10-09'),+ Interval::Monthly,+ ))->toBeTrue();+});++test('yearly first renewal', function () {+ expect(FirstFullCharge::isFirst(+ CarbonImmutable::parse('2025-10-01'),+ CarbonImmutable::parse('2026-10-01'),+ Interval::Yearly,+ ))->toBeTrue();+});++test('yearly second renewal is not', function () {+ expect(FirstFullCharge::isFirst(+ CarbonImmutable::parse('2024-10-01'),+ CarbonImmutable::parse('2026-10-01'),+ Interval::Yearly,+ ))->toBeFalse();+});diff --git a/tests/Unit/Support/Billing/StripeValueTest.php b/tests/Unit/Support/Billing/StripeValueTest.phpnew file mode 100644index 000000000..0804e1a28--- /dev/null+++ b/tests/Unit/Support/Billing/StripeValueTest.php@@ -0,0 +1,32 @@+<?php++declare(strict_types=1);++use App\Support\Billing\StripeValue;++test('converts an amount in cents to its main unit', function () {+ expect(StripeValue::amount(1900))->toBe(19.0)+ ->and(StripeValue::amount(1999))->toBe(19.99)+ ->and(StripeValue::amount(0))->toBe(0.0);+});++test('returns no amount without an integer', function (mixed $cents) {+ expect(StripeValue::amount($cents))->toBeNull();+})->with([+ 'null' => [null],+ 'string' => ['1900'],+ 'float' => [19.0],+]);++test('upper-cases a currency and returns none without one', function () {+ expect(StripeValue::currency('brl'))->toBe('BRL')+ ->and(StripeValue::currency(null))->toBeNull()+ ->and(StripeValue::currency(' '))->toBeNull()+ ->and(StripeValue::currency(['usd']))->toBeNull();+});++test('reads a unix timestamp as a UTC instant and returns none without one', function () {+ expect(StripeValue::timestamp(1_790_003_600)?->toIso8601String())->toBe('2026-09-21T15:13:20+00:00')+ ->and(StripeValue::timestamp(null))->toBeNull()+ ->and(StripeValue::timestamp('soon'))->toBeNull();+});