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
Track latest account publishing activity in PostHog (#368)
Paulo Castellanod2d3c55c92eb
diff --git a/.ai/rules/index.md b/.ai/rules/index.mdindex 5832afebe..09b33beb2 100644--- a/.ai/rules/index.md+++ b/.ai/rules/index.md@@ -7,6 +7,8 @@ Before planning or editing, find the row whose globs match the file's path and r| app/Http/Controllers/Auth/GoogleBusinessController.php | .ai/rules/auth.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, app/Services/Social/GoogleBusinessAnalytics.php | .ai/rules/google-business.md || app/Jobs/ReconcileGoogleBusinessPost.php, app/Console/Commands/RecoverStuckPosts.php | .ai/rules/jobs.md |+| app/Jobs/PostHog/**, app/Models/PostPlatform.php, database/migrations/** | .ai/rules/migrations.md |+| app/Jobs/PostHog/** | .ai/rules/post-hog.md || app/Actions/Post/FinalizePostPublication.php, app/Jobs/PublishPost.php, app/Actions/Post/UpdatePost.php | .ai/rules/post.md || app/Enums/SocialAccount/Platform.php | .ai/rules/social-account.md || app/Services/Social/GoogleBusinessPublisher.php, app/Support/Social/GoogleBusinessDerivativeCleaner.php, app/Actions/Post/DeletePost.php, app/Actions/Post/UpdatePost.php, app/Support/Social/AbandonGoogleBusinessReview.php, app/Actions/Workspace/PurgeWorkspace.php, app/Http/Controllers/Auth/SocialController.php | .ai/rules/social.md |diff --git a/.ai/rules/migrations.md b/.ai/rules/migrations.mdnew file mode 100644index 000000000..acf96ac89--- /dev/null+++ b/.ai/rules/migrations.md@@ -0,0 +1,11 @@+---+paths:+ - 'app/Jobs/PostHog/**'+ - 'app/Models/PostPlatform.php'+ - 'database/migrations/**'+---++# Migrations++## Keep publishing activity lookup scoped and minimal+Account publishing activity must scope through indexed account workspace/post IDs before ordering PostPlatform rows. Its migration only adds conventional Laravel indexes and must not change PostPlatform.published_at precision. PostHog snapshot retries must keep progressive backoff so transient outages do not exhaust attempts immediately.diff --git a/.ai/rules/post-hog.md b/.ai/rules/post-hog.mdnew file mode 100644index 000000000..acdaf1df5--- /dev/null+++ b/.ai/rules/post-hog.md@@ -0,0 +1,9 @@+---+paths:+ - 'app/Jobs/PostHog/**'+---++# Post Hog++## Serialize account publishing snapshots at the final send+Publishing activity uses SyncAccountPublishingActivity with per-account debounce and overlap protection. It must re-query the latest confirmed PostPlatform when it executes and send the group update in that same job; routing the snapshot through SendEvent can reorder payloads and regress the account's last publication. The backfill command must reuse this job.diff --git a/app/Console/Commands/BackfillPostHogPublishingActivity.php b/app/Console/Commands/BackfillPostHogPublishingActivity.phpnew file mode 100644index 000000000..1fe798d0c--- /dev/null+++ b/app/Console/Commands/BackfillPostHogPublishingActivity.php@@ -0,0 +1,40 @@+<?php++declare(strict_types=1);++namespace App\Console\Commands;++use App\Jobs\PostHog\SyncAccountPublishingActivity;+use App\Models\Account;+use App\Services\PostHogService;+use Illuminate\Console\Command;++class BackfillPostHogPublishingActivity extends Command+{+ protected $signature = 'posthog:backfill-publishing-activity';++ protected $description = 'Queue the latest confirmed publishing activity for every PostHog account group';++ public function handle(): int+ {+ if (! PostHogService::isEnabled()) {+ $this->components->warn('PostHog is disabled; no accounts were queued.');++ return self::SUCCESS;+ }++ $queued = 0;++ Account::query()+ ->select('id')+ ->lazyById()+ ->each(function (Account $account) use (&$queued): void {+ SyncAccountPublishingActivity::dispatch((string) $account->id);+ $queued++;+ });++ $this->components->info("Queued publishing activity sync for {$queued} accounts.");++ return self::SUCCESS;+ }+}diff --git a/app/Jobs/PostHog/SyncAccountPublishingActivity.php b/app/Jobs/PostHog/SyncAccountPublishingActivity.phpnew file mode 100644index 000000000..749a79213--- /dev/null+++ b/app/Jobs/PostHog/SyncAccountPublishingActivity.php@@ -0,0 +1,89 @@+<?php++declare(strict_types=1);++namespace App\Jobs\PostHog;++use App\Models\Account;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Services\PostHogService;+use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Foundation\Queue\Queueable;+use Illuminate\Queue\Middleware\WithoutOverlapping;++class SyncAccountPublishingActivity implements ShouldBeUniqueUntilProcessing, ShouldQueue+{+ use Queueable;++ public const DEBOUNCE_SECONDS = 300;++ public int $tries = 10;++ public int $timeout = 30;++ public int $uniqueFor = 3600;++ public function __construct(public string $accountId)+ {+ $this->onQueue('posthog');+ }++ /**+ * @return array<int, object>+ */+ public function middleware(): array+ {+ return [+ (new WithoutOverlapping("posthog-account-publishing:{$this->accountId}"))+ ->releaseAfter(30)+ ->expireAfter($this->timeout + 30),+ ];+ }++ public function uniqueId(): string+ {+ return $this->accountId;+ }++ /**+ * @return list<int>+ */+ public function backoff(): array+ {+ return [60, 300, 900, 1800, 3600];+ }++ public function handle(PostHogService $postHog): void+ {+ if (! PostHogService::isEnabled()) {+ return;+ }++ $account = Account::find($this->accountId);++ if (! $account) {+ return;+ }++ $postIds = Post::query()+ ->select('posts.id')+ ->whereRelation('workspace', 'account_id', $account->id);++ $latestPublication = PostPlatform::query()+ ->published()+ ->whereNotNull('published_at')+ ->whereIn('post_id', $postIds)+ ->latest('published_at')+ ->latest('updated_at')+ ->latest('id')+ ->first();++ $postHog->groupIdentifyNow('account', (string) $account->id, [+ 'last_post_published_at' => $latestPublication?->published_at?->toIso8601String(),+ 'last_post_published_network' => $latestPublication?->platform->network(),+ 'last_published_post_id' => $latestPublication?->post_id,+ ]);+ }+}diff --git a/app/Models/PostPlatform.php b/app/Models/PostPlatform.phpindex 2e650a308..c0b0ffbf4 100644--- a/app/Models/PostPlatform.php+++ b/app/Models/PostPlatform.php@@ -7,7 +7,9 @@ namespace App\Models;use App\Enums\PostPlatform\ContentType;use App\Enums\PostPlatform\Status;use App\Enums\SocialAccount\Platform as SocialPlatform;+use App\Observers\PostPlatformObserver;use Database\Factories\PostPlatformFactory;+use Illuminate\Database\Eloquent\Attributes\ObservedBy;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Concerns\HasUuids;use Illuminate\Database\Eloquent\Factories\HasFactory;@@ -15,6 +17,7 @@ use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Support\Facades\Storage;+#[ObservedBy(PostPlatformObserver::class)]class PostPlatform extends Model{/** @use HasFactory<PostPlatformFactory> */@@ -82,6 +85,11 @@ class PostPlatform extends Modelreturn $query->where('post_platforms.enabled', false);}+ public function scopePublished(Builder $query): Builder+ {+ return $query->where('post_platforms.status', Status::Published);+ }+/*** Get display name, falling back to snapshot if account was deleted.*/diff --git a/app/Observers/PostPlatformObserver.php b/app/Observers/PostPlatformObserver.phpnew file mode 100644index 000000000..b56da0b09--- /dev/null+++ b/app/Observers/PostPlatformObserver.php@@ -0,0 +1,34 @@+<?php++declare(strict_types=1);++namespace App\Observers;++use App\Enums\PostPlatform\Status;+use App\Jobs\PostHog\SyncAccountPublishingActivity;+use App\Models\PostPlatform;+use App\Services\PostHogService;++class PostPlatformObserver+{+ public function updated(PostPlatform $postPlatform): void+ {+ if (! PostHogService::isEnabled()+ || ! $postPlatform->wasChanged('status')+ || $postPlatform->status !== Status::Published) {+ return;+ }++ $accountId = $postPlatform+ ->loadMissing('post.workspace')+ ->post?->workspace?->account_id;++ if (! $accountId) {+ return;+ }++ SyncAccountPublishingActivity::dispatch((string) $accountId)+ ->delay(now()->addSeconds(SyncAccountPublishingActivity::DEBOUNCE_SECONDS))+ ->afterCommit();+ }+}diff --git a/app/Services/PostHogService.php b/app/Services/PostHogService.phpindex 1f6753df8..87e7ca6a5 100644--- a/app/Services/PostHogService.php+++ b/app/Services/PostHogService.php@@ -7,6 +7,8 @@ namespace App\Services;use App\Jobs\PostHog\SendEvent;use App\Models\Account;use Illuminate\Support\Facades\Log;+use PostHog\PostHog;+use RuntimeException;use Throwable;class PostHogService@@ -106,6 +108,31 @@ class PostHogService}}+ /**+ * Send a group update in the current job so its uniqueness and overlap+ * locks remain held until PostHog has accepted the latest snapshot.+ *+ * @param array<string, mixed> $properties+ */+ public function groupIdentifyNow(string $groupType, string $groupKey, array $properties = []): void+ {+ $payload = [+ 'groupType' => $groupType,+ 'groupKey' => $groupKey,+ 'properties' => $properties,+ ];++ $this->logLocally('groupIdentify', $payload);++ if (! self::isEnabled()) {+ return;+ }++ if (! PostHog::groupIdentify($payload) || ! PostHog::flush()) {+ throw new RuntimeException('PostHog group identify failed.');+ }+ }+/*** Local-only visibility into what would be sent to PostHog, so events can* be verified from laravel.log without a real API key configured.diff --git a/database/migrations/2026_09_22_150817_optimize_posthog_publishing_activity_lookup.php b/database/migrations/2026_09_22_150817_optimize_posthog_publishing_activity_lookup.phpnew file mode 100644index 000000000..baddbe0f7--- /dev/null+++ b/database/migrations/2026_09_22_150817_optimize_posthog_publishing_activity_lookup.php@@ -0,0 +1,46 @@+<?php++declare(strict_types=1);++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::table('workspaces', function (Blueprint $table) {+ $table->index(['account_id', 'id']);+ });++ Schema::table('post_platforms', function (Blueprint $table) {+ $table->index(['post_id', 'status', 'published_at']);+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('post_platforms', function (Blueprint $table) {+ $table->dropIndex(['post_id', 'status', 'published_at']);+ });++ Schema::table('workspaces', function (Blueprint $table) {+ $table->dropForeign(['account_id']);+ });++ Schema::table('workspaces', function (Blueprint $table) {+ $table->dropIndex(['account_id', 'id']);+ });++ Schema::table('workspaces', function (Blueprint $table) {+ $table->foreign('account_id')->references('id')->on('accounts')->cascadeOnDelete();+ });+ }+};diff --git a/tests/Feature/Commands/BackfillPostHogPublishingActivityTest.php b/tests/Feature/Commands/BackfillPostHogPublishingActivityTest.phpnew file mode 100644index 000000000..8e52e1b8a--- /dev/null+++ b/tests/Feature/Commands/BackfillPostHogPublishingActivityTest.php@@ -0,0 +1,41 @@+<?php++declare(strict_types=1);++use App\Jobs\PostHog\SyncAccountPublishingActivity;+use App\Models\Account;+use Illuminate\Support\Facades\Bus;++beforeEach(function () {+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+});++test('command queues publishing activity for every existing account', function () {+ $accounts = Account::factory()->count(3)->create();+ Bus::fake([SyncAccountPublishingActivity::class]);++ $this->artisan('posthog:backfill-publishing-activity')+ ->expectsOutputToContain('Queued publishing activity sync for 3 accounts.')+ ->assertSuccessful();++ Bus::assertDispatchedTimes(SyncAccountPublishingActivity::class, 3);++ foreach ($accounts as $account) {+ Bus::assertDispatched(+ SyncAccountPublishingActivity::class,+ fn (SyncAccountPublishingActivity $job): bool => $job->accountId === (string) $account->id,+ );+ }+});++test('command does not queue jobs when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ Account::factory()->create();+ Bus::fake([SyncAccountPublishingActivity::class]);++ $this->artisan('posthog:backfill-publishing-activity')+ ->expectsOutputToContain('PostHog is disabled; no accounts were queued.')+ ->assertSuccessful();++ Bus::assertNotDispatched(SyncAccountPublishingActivity::class);+});diff --git a/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.phpnew file mode 100644index 000000000..93406eed3--- /dev/null+++ b/tests/Feature/Jobs/PostHog/SyncAccountPublishingActivityTest.php@@ -0,0 +1,179 @@+<?php++declare(strict_types=1);++use App\Enums\PostPlatform\Status;+use App\Enums\SocialAccount\Platform;+use App\Jobs\PostHog\SyncAccountPublishingActivity;+use App\Models\Account;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Models\User;+use App\Models\Workspace;+use App\Services\PostHogService;+use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;+use Illuminate\Queue\Middleware\WithoutOverlapping;+use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Cache;+use Illuminate\Support\Str;++beforeEach(function () {+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);++ $this->account = Account::factory()->create();+ $this->user = User::factory()->create(['account_id' => $this->account->id]);+ $this->account->update(['owner_id' => $this->user->id]);+});++test('handle sends the latest confirmed account publication directly to PostHog', function () {+ $job = new SyncAccountPublishingActivity((string) $this->account->id);+ $olderWorkspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+ $latestWorkspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+ $olderPost = Post::factory()->create([+ 'workspace_id' => $olderWorkspace->id,+ 'user_id' => $this->user->id,+ ]);+ $latestPost = Post::factory()->create([+ 'workspace_id' => $latestWorkspace->id,+ 'user_id' => $this->user->id,+ ]);+ PostPlatform::factory()->published()->recycle($olderPost)->create([+ 'platform' => Platform::X,+ 'published_at' => now()->subDay(),+ ]);+ $latestPublication = PostPlatform::factory()->published()->recycle($latestPost)->create([+ 'platform' => Platform::LinkedInPage,+ 'published_at' => now()->subHour(),+ ]);+ PostPlatform::factory()->published()->create(['published_at' => now()]);+ PostPlatform::factory()->recycle($latestPost)->create([+ 'status' => Status::PendingReview,+ 'published_at' => now()->addHour(),+ ]);+ PostPlatform::factory()->recycle($latestPost)->create([+ 'status' => Status::Published,+ 'published_at' => null,+ ]);++ $postHog = Mockery::mock(PostHogService::class);+ $postHog->shouldReceive('groupIdentifyNow')+ ->once()+ ->withArgs(function (string $groupType, string $groupKey, array $properties) use ($latestPublication): bool {+ return $groupType === 'account'+ && $groupKey === (string) $this->account->id+ && $properties['last_post_published_at'] === $latestPublication->published_at->toIso8601String()+ && $properties['last_post_published_network'] === 'linkedin'+ && $properties['last_published_post_id'] === $latestPublication->post_id;+ });++ $job->handle($postHog);+});++test('handle clears publishing activity when the account has no confirmed publication', function () {+ $workspace = Workspace::factory()->create([+ 'account_id' => $this->account->id,+ 'user_id' => $this->user->id,+ ]);+ $post = Post::factory()->create([+ 'workspace_id' => $workspace->id,+ 'user_id' => $this->user->id,+ ]);+ PostPlatform::factory()->recycle($post)->create(['status' => Status::PendingReview]);++ $postHog = Mockery::mock(PostHogService::class);+ $postHog->shouldReceive('groupIdentifyNow')+ ->once()+ ->with('account', (string) $this->account->id, [+ 'last_post_published_at' => null,+ 'last_post_published_network' => null,+ 'last_published_post_id' => null,+ ]);++ (new SyncAccountPublishingActivity((string) $this->account->id))->handle($postHog);+});++test('handle is a no-op when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);++ $postHog = Mockery::mock(PostHogService::class);+ $postHog->shouldNotReceive('groupIdentifyNow');++ (new SyncAccountPublishingActivity((string) $this->account->id))->handle($postHog);+});++test('handle returns silently when the account no longer exists', function () {+ $postHog = Mockery::mock(PostHogService::class);+ $postHog->shouldNotReceive('groupIdentifyNow');++ (new SyncAccountPublishingActivity((string) Str::uuid()))->handle($postHog);+});++test('job is unique while delayed and serializes sends per account', function () {+ $job = new SyncAccountPublishingActivity((string) $this->account->id);+ $middleware = $job->middleware();++ expect($job)->toBeInstanceOf(ShouldBeUniqueUntilProcessing::class)+ ->and($job->uniqueId())->toBe((string) $this->account->id)+ ->and($job->uniqueFor)->toBe(3600)+ ->and($job->backoff())->toBe([60, 300, 900, 1800, 3600])+ ->and($job->queue)->toBe('posthog')+ ->and($middleware)->toHaveCount(1)+ ->and($middleware[0])->toBeInstanceOf(WithoutOverlapping::class)+ ->and($middleware[0]->key)->toBe("posthog-account-publishing:{$this->account->id}")+ ->and($middleware[0]->releaseAfter)->toBe(30)+ ->and($middleware[0]->expiresAfter)->toBe($job->timeout + 30);+});++test('unique lock drops duplicate pending syncs for the same account', function () {+ Bus::fake([SyncAccountPublishingActivity::class]);++ SyncAccountPublishingActivity::dispatch((string) $this->account->id)->delay(now()->addMinutes(5));+ SyncAccountPublishingActivity::dispatch((string) $this->account->id)->delay(now()->addMinutes(5));++ Bus::assertDispatchedTimes(SyncAccountPublishingActivity::class, 1);+});++test('unique lock allows pending syncs for different accounts', function () {+ $otherAccount = Account::factory()->create();+ Bus::fake([SyncAccountPublishingActivity::class]);++ SyncAccountPublishingActivity::dispatch((string) $this->account->id)->delay(now()->addMinutes(5));+ SyncAccountPublishingActivity::dispatch((string) $otherAccount->id)->delay(now()->addMinutes(5));++ Bus::assertDispatchedTimes(SyncAccountPublishingActivity::class, 2);+});++test('overlap lock serializes processing for the same account', function () {+ $runningJob = new SyncAccountPublishingActivity((string) $this->account->id);+ $overlappingJob = (new SyncAccountPublishingActivity((string) $this->account->id))+ ->withFakeQueueInteractions();+ /** @var WithoutOverlapping $middleware */+ $middleware = $overlappingJob->middleware()[0];+ $lock = Cache::lock($middleware->getLockKey($runningJob), $runningJob->timeout + 30);+ $handled = false;++ expect($lock->get())->toBeTrue();++ try {+ $middleware->handle($overlappingJob, function () use (&$handled): void {+ $handled = true;+ });+ } finally {+ $lock->release();+ }++ expect($handled)->toBeFalse();+ $overlappingJob->assertReleased(30);++ $middleware->handle($overlappingJob, function () use (&$handled): void {+ $handled = true;+ });++ expect($handled)->toBeTrue();+});diff --git a/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php b/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.phpindex 9df738d35..42f177121 100644--- a/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php+++ b/tests/Feature/Jobs/ReconcileGoogleBusinessPostTest.php@@ -5,6 +5,7 @@ declare(strict_types=1);use App\Enums\Post\Status as PostStatus;use App\Enums\PostPlatform\Status as PlatformStatus;use App\Enums\SocialAccount\Status as AccountStatus;+use App\Jobs\PostHog\SyncAccountPublishingActivity;use App\Jobs\ReconcileGoogleBusinessPost;use App\Jobs\SendNotification;use App\Models\Post;@@ -67,7 +68,8 @@ test('settling a live review prunes the JPEG derivative', function () {});test('a live review on a publishing parent settles the post as published', function () {- Queue::fake([SendNotification::class]);+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ Queue::fake([SendNotification::class, SyncAccountPublishingActivity::class]);$this->post->update(['status' => PostStatus::Publishing]);Http::fake([config('trypost.platforms.google_business.local_posts_api').'/*' => Http::response([@@ -83,6 +85,10 @@ test('a live review on a publishing parent settles the post as published', funct->and($this->target->fresh()->platform_url)->toBe('https://posts.google.com/999')->and($this->post->fresh()->status)->toBe(PostStatus::Published);Queue::assertPushed(SendNotification::class, 1);+ Queue::assertPushed(+ SyncAccountPublishingActivity::class,+ fn (SyncAccountPublishingActivity $job): bool => $job->accountId === (string) $this->workspace->account_id,+ );});test('a post that went live is published with the search URL Google returned', function () {diff --git a/tests/Feature/Observers/PostPlatformObserverTest.php b/tests/Feature/Observers/PostPlatformObserverTest.phpnew file mode 100644index 000000000..66495c7c5--- /dev/null+++ b/tests/Feature/Observers/PostPlatformObserverTest.php@@ -0,0 +1,74 @@+<?php++declare(strict_types=1);++use App\Enums\PostPlatform\Status;+use App\Jobs\PostHog\SyncAccountPublishingActivity;+use App\Models\Account;+use App\Models\Post;+use App\Models\PostPlatform;+use App\Models\User;+use App\Models\Workspace;+use Illuminate\Support\Facades\Queue;++beforeEach(function () {+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);++ $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,+ ]);+ $this->post = Post::factory()->create([+ 'workspace_id' => $this->workspace->id,+ 'user_id' => $this->user->id,+ ]);+});++test('confirmed publication queues an account activity sync', function () {+ $this->freezeTime();+ $postPlatform = PostPlatform::factory()->recycle($this->post)->create();++ Queue::fake();++ $postPlatform->markAsPublished('remote-post-id');++ Queue::assertPushed(+ SyncAccountPublishingActivity::class,+ fn (SyncAccountPublishingActivity $job): bool => $job->accountId === (string) $this->account->id+ && $job->delay?->equalTo(now()->addSeconds(SyncAccountPublishingActivity::DEBOUNCE_SECONDS))+ && $job->afterCommit === true,+ );+});++test('non-published status changes do not queue an account activity sync', function () {+ $postPlatform = PostPlatform::factory()->recycle($this->post)->create();++ Queue::fake();++ $postPlatform->update(['status' => Status::Publishing]);++ Queue::assertNotPushed(SyncAccountPublishingActivity::class);+});++test('account activity sync is not queued when PostHog is disabled', function () {+ config(['services.posthog.enabled' => false]);+ $postPlatform = PostPlatform::factory()->recycle($this->post)->create();++ Queue::fake();++ $postPlatform->markAsPublished('remote-post-id');++ Queue::assertNotPushed(SyncAccountPublishingActivity::class);+});++test('updating an already published platform does not queue another sync', function () {+ $postPlatform = PostPlatform::factory()->published()->recycle($this->post)->create();+ Queue::fake();++ $postPlatform->update(['platform_url' => 'https://example.com/published-post']);++ Queue::assertNotPushed(SyncAccountPublishingActivity::class);+});diff --git a/tests/Unit/PostHogServiceTest.php b/tests/Unit/PostHogServiceTest.phpindex 0428bf849..85ab8ede4 100644--- a/tests/Unit/PostHogServiceTest.php+++ b/tests/Unit/PostHogServiceTest.php@@ -9,6 +9,8 @@ use App\Services\PostHogService;use Illuminate\Foundation\Testing\RefreshDatabase;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Queue;+use PostHog\Client;+use PostHog\PostHog;uses(RefreshDatabase::class);@@ -83,6 +85,37 @@ test('group identify does not dispatch job when api key is missing', function ()Queue::assertNothingPushed();});+test('group identify now sends without dispatching a second job', function () {+ Queue::fake();+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ $client = Mockery::mock(Client::class);+ $client->shouldReceive('capture')+ ->once()+ ->withArgs(fn (array $payload): bool => $payload['event'] === '$groupidentify'+ && $payload['properties']['$group_type'] === 'account'+ && $payload['properties']['$group_key'] === 'account-123')+ ->andReturnTrue();+ $client->shouldReceive('flush')->once()->andReturnTrue();+ PostHog::init(client: $client);++ (new PostHogService)->groupIdentifyNow('account', 'account-123', [+ 'last_post_published_at' => now()->toIso8601String(),+ ]);++ Queue::assertNothingPushed();+});++test('group identify now throws when PostHog rejects the payload', function () {+ config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);+ $client = Mockery::mock(Client::class);+ $client->shouldReceive('capture')->once()->andReturnFalse();+ $client->shouldNotReceive('flush');+ PostHog::init(client: $client);++ expect(fn () => (new PostHogService)->groupIdentifyNow('account', 'account-123'))+ ->toThrow(RuntimeException::class, 'PostHog group identify failed.');+});+test('capture auto-attaches account groups when account is supplied', function () {Queue::fake();config(['services.posthog.enabled' => true, 'services.posthog.api_key' => 'phc_test_key']);diff --git a/tests/Unit/PostPlatformTest.php b/tests/Unit/PostPlatformTest.phpindex 5179fcbc6..c3a1efb51 100644--- a/tests/Unit/PostPlatformTest.php+++ b/tests/Unit/PostPlatformTest.php@@ -45,6 +45,23 @@ test('markAsPublished clears stale error_message and error_context', function ()->and($this->postPlatform->error_context)->toBeNull();});+test('published scope only includes published platforms', function () {+ $publishedPostPlatform = PostPlatform::factory()->published()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $this->socialAccount->id,+ ]);+ PostPlatform::factory()->create([+ 'post_id' => $this->post->id,+ 'social_account_id' => $this->socialAccount->id,+ 'status' => Status::Failed,+ ]);++ $publishedPlatforms = PostPlatform::query()->published()->get();++ expect($publishedPlatforms)->toHaveCount(1)+ ->and($publishedPlatforms->first()->is($publishedPostPlatform))->toBeTrue();+});+test('display_name falls back to the account username when display_name is not set', function () {$this->socialAccount->update(['display_name' => null, 'username' => 'acme_handle']);