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
<?php
declare(strict_types=1);
use App\Actions\Analytics\BuildWorkspaceAnalyticsReport;
use App\Actions\Analytics\GetAnalyticsBounds;
use App\Actions\Analytics\ReadPublicationAnalytics;
use App\Dto\Analytics\DateRange;
use App\Enums\Analytics\MetricsUnavailableReason;
use App\Enums\Analytics\ObservationProvenance;
use App\Enums\Analytics\PublicationAvailability;
use App\Enums\Analytics\PublicationContentType;
use App\Enums\Analytics\SyncStatus;
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\AnalyticsSyncState;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\Workspace;
use App\Support\Analytics\PeriodBuckets;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
beforeEach(function () {
Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
});
function analyticsReportAccount(Workspace $workspace, Platform $platform): SocialAccount
{
return SocialAccount::factory()->create(['workspace_id' => $workspace->id, 'platform' => $platform]);
}
function analyticsReportFollower(SocialAccount $account, string $date, int $followers, ObservationProvenance $provenance = ObservationProvenance::Actual): void
{
AnalyticsAccountDailySnapshot::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
'network' => $account->platform->network(),
'platform_user_id' => $account->platform_user_id,
'platform' => $account->platform,
'date' => $date,
'followers_count' => $followers,
'provenance' => $provenance,
]);
}
function analyticsReportPublication(SocialAccount $account, string $publishedAt, ?int $reactions, ?int $comments, ?int $engagement, ?int $exposure): AnalyticsPublication
{
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $account->workspace_id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
'network' => $account->platform->network(),
'platform_user_id' => $account->platform_user_id,
'platform' => $account->platform,
'provider_published_at' => CarbonImmutable::parse($publishedAt, 'UTC'),
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
'date' => '2026-09-12',
'reactions_count' => $reactions,
'comments_count' => $comments,
'engagement_count' => $engagement,
'exposure_count' => $exposure,
]);
return $publication;
}
test('workspace report keeps accounts separate and aggregates only latest normalized facts', function () {
$workspace = Workspace::factory()->create();
$instagramA = analyticsReportAccount($workspace, Platform::Instagram);
$instagramB = analyticsReportAccount($workspace, Platform::Instagram);
$x = analyticsReportAccount($workspace, Platform::X);
$linkedIn = analyticsReportAccount($workspace, Platform::LinkedIn);
$foreign = analyticsReportAccount(Workspace::factory()->create(), Platform::Instagram);
foreach ([[$instagramA, 95], [$instagramB, 19], [$x, 45]] as [$account, $followers]) {
analyticsReportFollower($account, '2026-08-31', $followers);
}
analyticsReportFollower($instagramA, '2026-09-10', 100);
analyticsReportFollower($instagramB, '2026-09-10', 20, ObservationProvenance::CarriedForward);
analyticsReportFollower($x, '2026-09-10', 50);
analyticsReportFollower($linkedIn, '2026-09-10', 1000);
analyticsReportFollower($foreign, '2026-09-10', 999);
$first = analyticsReportPublication($instagramA, '2026-09-05 10:00:00', 10, 2, 12, 100);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $first->id,
'date' => '2026-09-11',
'reactions_count' => 999,
'comments_count' => 999,
'engagement_count' => 999,
'exposure_count' => 999,
]);
analyticsReportPublication($instagramB, '2026-09-06 10:00:00', 5, 1, 6, 900);
analyticsReportPublication($x, '2026-09-07 10:00:00', null, 0, null, null);
analyticsReportPublication($instagramA, '2026-08-25 10:00:00', 2, 1, 3, 30);
analyticsReportPublication($linkedIn, '2026-09-05 10:00:00', 900, 900, 900, 1);
analyticsReportPublication($foreign, '2026-09-05 10:00:00', 900, 900, 900, 1);
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
expect(array_keys($report['summary']))->toBe([
'posts', 'followers', 'net_followers', 'reactions', 'comments', 'engagement_rate', 'views', 'impressions',
'clicks', 'reposts', 'quotes', 'reach', 'shares', 'saves', 'watch_time_minutes', 'average_watch_time_seconds', 'follows_gained',
])
->and($report['summary']['posts']['value'])->toBe(3)
->and($report['summary']['posts']['previous'])->toBe(1)
->and($report['summary']['posts']['change'])->toBe(200.0)
->and($report['summary']['followers']['value'])->toBe(170)
->and($report['summary']['followers']['change'])->toBe(11)
->and($report['summary']['reactions']['value'])->toBe(15)
->and($report['summary']['reactions']['previous'])->toBe(2)
->and($report['summary']['comments']['value'])->toBe(3)
->and($report['summary']['engagement_rate']['value'])->toBe(1.8)
->and($report['summary']['engagement_rate']['previous'])->toBe(10.0)
->and($report['bounds'])->toBe(['min' => '2026-08-25', 'max' => '2026-09-10'])
->and($report['posts']['resolution'])->toBe('daily')
->and($report['posts']['total'])->toBe(3)
->and(count($report['posts']['buckets']))->toBe(10)
->and(array_column($report['posts']['buckets'], 'total'))->toBe([0, 0, 0, 0, 1, 1, 1, 0, 0, 0])
->and(array_key_exists('label', $report['posts']['buckets'][0]))->toBeFalse()
->and(count($report['performance']))->toBe(3)
->and(count($report['followers']['accounts']))->toBe(3)
->and($report['followers']['total'])->toBe(170)
->and($report['top_posts']['reactions'][0]['social_account_key'])->toBe($instagramA->id)
->and($report['top_posts']['reactions'][0]['post_id'])->toBeNull()
->and($report['top_posts']['reactions'][0]['reactions'])->toBe(10)
->and(array_column($report['top_posts']['reactions'], 'rank'))->toBe(range(1, count($report['top_posts']['reactions'])));
$performanceKeys = array_column($report['performance'], 'social_account_key');
expect($performanceKeys)->toContain($instagramA->id, $instagramB->id, $x->id);
});
test('top posts include the source post id for TryPost publications', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$post = Post::factory()->forAccount($account)->published()->create();
$publication = analyticsReportPublication($account, '2026-09-05 10:00:00', 5, 1, 6, 100);
$publication->update(['post_id' => $post->id]);
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
expect($report['top_posts']['reactions'][0]['post_id'])->toBe($post->id);
});
test('top posts carry the post media from our bucket instead of the network preview', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$video = ['id' => 'video', 'path' => 'medias/reel.mp4', 'url' => 'https://cdn.trypost.test/medias/reel.mp4', 'type' => 'video', 'mime_type' => 'video/mp4', 'meta' => ['cover_offset_ms' => 1500]];
$document = ['id' => 'document', 'path' => 'medias/deck.pdf', 'url' => 'https://cdn.trypost.test/medias/deck.pdf', 'type' => 'document', 'mime_type' => 'application/pdf'];
$post = Post::factory()->forAccount($account)->published()->create(['media' => [$document, $video]]);
$other = Post::factory()->forAccount($account)->published()->create(['media' => [$video]]);
$linked = analyticsReportPublication($account, '2026-09-05 10:00:00', 9, 1, 10, 100);
$linked->update(['post_id' => $post->id, 'preview_metadata' => ['thumbnail_url' => 'https://scontent.cdninstagram.com/expired.jpg?oe=6ACC450F']]);
$commented = analyticsReportPublication($account, '2026-09-06 10:00:00', 1, 9, 10, 100);
$commented->update(['post_id' => $other->id]);
$external = analyticsReportPublication($account, '2026-09-07 10:00:00', 5, 5, 10, 100);
$external->update(['preview_metadata' => ['thumbnail_url' => 'https://pbs.twimg.com/media/external.jpg']]);
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
$reactions = collect($report['top_posts']['reactions'])->keyBy('id');
$comments = collect($report['top_posts']['comments'])->keyBy('id');
expect($reactions[$linked->id]['media'])->toMatchArray(['url' => $video['url'], 'type' => 'video', 'meta' => ['cover_offset_ms' => 1500]])
->and($comments[$commented->id]['media'])->toMatchArray(['url' => $video['url'], 'type' => 'video'])
->and($reactions[$external->id]['media'])->toBeNull()
->and($reactions[$external->id]['preview_metadata']['thumbnail_url'])->toBe('https://pbs.twimg.com/media/external.jpg');
});
test('workspace follower total stays unavailable until every connected account has an observation', function () {
$workspace = Workspace::factory()->create();
$first = analyticsReportAccount($workspace, Platform::Instagram);
$second = analyticsReportAccount($workspace, Platform::Instagram);
$first->forceFill(['created_at' => '2026-09-01 00:00:00'])->saveQuietly();
$second->forceFill(['created_at' => '2026-09-01 00:00:00'])->saveQuietly();
analyticsReportFollower($first, '2026-09-10', 100);
$range = new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC'));
$incomplete = app(BuildWorkspaceAnalyticsReport::class)->execute($workspace, $range);
expect($incomplete['summary']['followers']['value'])->toBeNull()
->and($incomplete['followers']['total'])->toBeNull();
analyticsReportFollower($second, '2026-09-10', 50, ObservationProvenance::CarriedForward);
$complete = app(BuildWorkspaceAnalyticsReport::class)->execute($workspace, $range);
expect($complete['summary']['followers']['value'])->toBe(150)
->and($complete['followers']['total'])->toBe(150);
});
test('workspace import coverage includes every connected account and excludes disconnected ones', function () {
$workspace = Workspace::factory()->create();
$active = analyticsReportAccount($workspace, Platform::Instagram);
$second = analyticsReportAccount($workspace, Platform::Instagram);
$disconnected = analyticsReportAccount($workspace, Platform::Instagram);
$foreign = analyticsReportAccount(Workspace::factory()->create(), Platform::Instagram);
foreach ([$active, $second, $disconnected, $foreign] as $account) {
AnalyticsSyncState::factory()->create([
...AnalyticsSyncState::identityFor($account),
'social_account_id' => $account->id,
'status' => SyncStatus::Pending,
]);
}
$disconnected->update(['status' => Status::Disconnected]);
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
expect(array_column($report['coverage'], 'social_account_id'))->toEqualCanonicalizing([$active->id, $second->id]);
});
test('reauthorizing an already connected account resumes analytics without treating a token refresh as a reconnect', function () {
$workspace = Workspace::factory()->create();
$account = SocialAccount::factory()->instagram()->create(['workspace_id' => $workspace->id]);
Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
SocialAccount::connectIdentity(
$workspace,
Platform::Instagram,
$account->platform_user_id,
['access_token' => 'new-oauth-token', 'status' => Status::Connected],
);
Queue::assertPushed(BootstrapAccountAnalytics::class, fn ($job): bool => $job->socialAccountId === $account->id
&& $job->refreshOnTerminal);
Queue::assertPushed(CollectAccountDailySnapshot::class, fn ($job): bool => $job->socialAccountId === $account->id);
Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
SocialAccount::connectIdentity(
$workspace,
Platform::Instagram,
$account->platform_user_id,
['access_token' => 'another-oauth-token', 'status' => Status::Connected],
$account,
);
Queue::assertPushed(BootstrapAccountAnalytics::class, 1);
Queue::assertPushed(CollectAccountDailySnapshot::class, 1);
Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
$account->refresh()->update(['access_token' => 'automatic-token-refresh']);
Queue::assertNotPushed(BootstrapAccountAnalytics::class);
Queue::assertNotPushed(CollectAccountDailySnapshot::class);
});
test('range boundaries and bucket resolutions are deterministic', function (int $days, string $resolution) {
$range = new DateRange(
CarbonImmutable::parse('2026-09-23', 'UTC')->subDays($days - 1),
CarbonImmutable::parse('2026-09-23', 'UTC'),
);
expect(app(PeriodBuckets::class)->resolution($range))->toBe($resolution)
->and($range->previous()->days())->toBe($days);
})->with([[14, 'daily'], [15, 'weekly'], [90, 'weekly'], [91, 'monthly']]);
test('date ranges count both endpoints and preserve length across month boundaries', function (string $start, string $end, int $days, string $previousStart, string $previousEnd) {
$range = new DateRange(
CarbonImmutable::parse($start, 'UTC'),
CarbonImmutable::parse($end, 'UTC'),
);
expect($range->days())->toBe($days)
->and($range->previous()->days())->toBe($days)
->and($range->previous()->toArray())->toBe(['start' => $previousStart, 'end' => $previousEnd]);
})->with([
['2026-09-01', '2026-09-01', 1, '2026-08-31', '2026-08-31'],
['2026-09-01', '2026-09-10', 10, '2026-08-22', '2026-08-31'],
['2024-02-28', '2024-03-01', 3, '2024-02-25', '2024-02-27'],
]);
test('invalid reversed date range is rejected', function () {
expect(fn () => new DateRange(
CarbonImmutable::parse('2026-09-10', 'UTC'),
CarbonImmutable::parse('2026-09-01', 'UTC'),
))->toThrow(InvalidArgumentException::class);
});
test('a deleted social account retains its historical performance row', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
analyticsReportPublication($account, '2026-09-05 10:00:00', 0, null, 0, 100);
$account->delete();
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
expect($report['performance'][0]['social_account_key'])->toBe($account->id)
->and($report['summary']['reactions']['value'])->toBe(0)
->and($report['summary']['comments']['value'])->toBeNull();
});
test('workspace report keeps only the five highest-ranked posts while streaming publication rows', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$publications = [];
foreach ([0, 7, 2, 5, 9, 3, 8] as $reactions) {
$publications[$reactions] = analyticsReportPublication(
$account,
'2026-09-05 10:00:00',
$reactions,
0,
$reactions,
100,
);
}
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
expect($report['summary']['posts']['value'])->toBe(7)
->and($report['summary']['reactions']['value'])->toBe(34)
->and($report['posts']['buckets'][4]['total'])->toBe(7)
->and($report['performance'][0]['posts']['value'])->toBe(7)
->and(array_column($report['top_posts']['reactions'], 'id'))->toBe(array_map(
fn (int $reactions): string => $publications[$reactions]->id,
[9, 8, 7, 5, 3],
));
});
test('publication detail uses the latest persisted metric snapshot without provider reads', function () {
Http::fake();
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$post = Post::factory()->forAccount($account)->published()->create();
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
'post_id' => $post->id,
'platform' => Platform::Instagram,
'content_type' => PublicationContentType::Reel,
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
'date' => '2026-09-10',
'reactions_count' => 50,
'metrics' => ['reactions' => ['value' => 50, 'unit' => 'count', 'availability' => 'available']],
]);
AnalyticsPublicationDailySnapshot::factory()->create([
'publication_id' => $publication->id,
'date' => '2026-09-11',
'reactions_count' => 0,
'watch_time_milliseconds' => 185000,
'metrics' => [
'reactions' => ['value' => 0, 'unit' => 'count', 'availability' => 'available'],
'watch_time_milliseconds' => ['value' => 185000, 'unit' => 'milliseconds', 'availability' => 'available'],
],
]);
$detail = app(ReadPublicationAnalytics::class)->latestFor($post);
expect($detail['available'])->toBeTrue()
->and($detail['publication']['content_type'])->toBe('reel')
->and($detail['snapshot']['reactions_count'])->toBe(0)
->and($detail['snapshot']['watch_time_milliseconds'])->toBe(185000)
->and($detail['metrics']['watch_time_milliseconds']['unit'])->toBe('milliseconds');
Http::assertNothingSent();
});
test('publication detail remains scoped to the post workspace and excludes unsupported networks', function () {
$workspace = Workspace::factory()->create();
$foreign = analyticsReportAccount(Workspace::factory()->create(), Platform::Instagram);
$post = Post::factory()->forAccount($foreign)->published()->create(['workspace_id' => $workspace->id]);
AnalyticsPublication::factory()->create([
'workspace_id' => $foreign->workspace_id,
'post_id' => $post->id,
'platform' => Platform::Instagram,
]);
expect(app(ReadPublicationAnalytics::class)->latestFor($post)['available'])->toBeFalse();
$post->update(['platform' => Platform::LinkedIn]);
expect(app(ReadPublicationAnalytics::class)->latestFor($post)['reason'])->toBe(MetricsUnavailableReason::PlatformNotSupported->value);
});
test('external YouTube upload stays a video and not a short without authoritative metadata', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::YouTube);
$publication = AnalyticsPublication::factory()->create([
'workspace_id' => $workspace->id,
'social_account_id' => $account->id,
'social_account_key' => $account->id,
'platform' => Platform::YouTube,
'content_type' => PublicationContentType::Video,
]);
$detail = app(ReadPublicationAnalytics::class)->latestForPublication($publication);
expect($detail['publication']['content_type'])->toBe('video')
->and($detail['snapshot'])->toBeNull();
});
test('dashboard query count is independent of the number of account rows', function () {
$workspace = Workspace::factory()->create();
$range = new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC'));
$queries = [];
DB::listen(function ($query) use (&$queries): void {
$queries[] = $query->sql;
});
app(BuildWorkspaceAnalyticsReport::class)->execute($workspace, $range);
$baseCount = count($queries);
$queries = [];
foreach (range(1, 3) as $index) {
$account = analyticsReportAccount($workspace, Platform::Instagram);
analyticsReportFollower($account, '2026-09-10', $index);
analyticsReportPublication($account, '2026-09-05 10:00:00', $index, 0, $index, 100);
}
$queries = [];
app(BuildWorkspaceAnalyticsReport::class)->execute($workspace, $range);
expect(count($queries))->toBe($baseCount);
});
test('workspace report reuses date bounds already read by the controller', function () {
$workspace = Workspace::factory()->create();
$range = new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC'));
$bounds = ['min' => '2026-08-01', 'max' => '2026-09-10'];
$this->mock(GetAnalyticsBounds::class)->shouldNotReceive('execute');
$report = app(BuildWorkspaceAnalyticsReport::class)->execute($workspace, $range, $bounds);
expect($report['bounds'])->toBe($bounds);
});
test('a live account shows its current avatar instead of the url frozen in the analytics rows', function () {
Storage::fake(null, ['url' => 'https://current-cdn.test']);
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$account->forceFill(['avatar_url' => 'social-accounts/avatar.jpg'])->save();
analyticsReportFollower($account, '2026-09-05', 100);
$publication = analyticsReportPublication($account, '2026-09-05 10:00:00', 5, 1, 6, 100);
$publication->forceFill(['account_avatar_url' => 'https://old-cdn.test/social-accounts/avatar.jpg'])->save();
AnalyticsAccountDailySnapshot::query()->where('social_account_key', $account->id)->update(['account_avatar_url' => 'https://old-cdn.test/social-accounts/avatar.jpg']);
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
$current = 'https://current-cdn.test/social-accounts/avatar.jpg';
expect($report['followers']['accounts'][0]['avatar_url'])->toBe($current)
->and($report['posts']['accounts'][0]['avatar_url'])->toBe($current)
->and($report['performance'][0]['avatar_url'])->toBe($current)
->and($report['top_posts']['reactions'][0]['avatar_url'])->toBe($current);
});
test('a deleted account keeps the avatar stored in its analytics rows', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$publication = analyticsReportPublication($account, '2026-09-05 10:00:00', 5, 1, 6, 100);
$publication->forceFill(['account_avatar_url' => 'https://old-cdn.test/avatar.jpg'])->save();
$account->delete();
$report = app(BuildWorkspaceAnalyticsReport::class)->execute(
$workspace,
new DateRange(CarbonImmutable::parse('2026-09-01', 'UTC'), CarbonImmutable::parse('2026-09-10', 'UTC')),
);
expect($report['performance'][0]['avatar_url'])->toBe('https://old-cdn.test/avatar.jpg');
});
test('publication detail shows the current avatar of a live account', function () {
Storage::fake(null, ['url' => 'https://current-cdn.test']);
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$account->forceFill(['avatar_url' => 'social-accounts/avatar.jpg'])->save();
$publication = analyticsReportPublication($account, '2026-09-05 10:00:00', 5, 1, 6, 100);
$publication->forceFill(['account_avatar_url' => 'https://old-cdn.test/social-accounts/avatar.jpg'])->save();
$detail = app(ReadPublicationAnalytics::class)->latestForWorkspacePublication($workspace, $publication->id);
expect(data_get($detail, 'publication.account_avatar_url'))->toBe('https://current-cdn.test/social-accounts/avatar.jpg');
});
test('top posts drop the link of a publication the network deleted', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$start = now('UTC')->subDays(10)->startOfDay();
$live = analyticsReportPublication($account, $start->addDays(2)->toDateTimeString(), 9, 1, 10, 100);
$deleted = analyticsReportPublication($account, $start->addDays(3)->toDateTimeString(), 5, 1, 6, 100);
$deleted->update(['availability' => PublicationAvailability::Deleted]);
$report = app(BuildWorkspaceAnalyticsReport::class)->execute($workspace, new DateRange($start, $start->addDays(9)));
$top = collect($report['top_posts']['reactions'])->keyBy('id');
expect(data_get($top->get($live->id), 'permalink'))->toBe($live->permalink)
->and($top->has($deleted->id))->toBeTrue()
->and(data_get($top->get($deleted->id), 'permalink'))->toBeNull();
});
test('publication detail opens a publication the network deleted, without its link', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$publication = analyticsReportPublication($account, now('UTC')->subDays(3)->toDateTimeString(), 5, 1, 6, 100);
$publication->update(['availability' => PublicationAvailability::Deleted]);
$detail = app(ReadPublicationAnalytics::class)->latestForWorkspacePublication($workspace, $publication->id);
expect(data_get($detail, 'publication.availability'))->toBe(PublicationAvailability::Deleted->value)
->and(data_get($detail, 'publication.permalink'))->toBeNull()
->and(data_get($detail, 'metrics'))->not->toBeEmpty();
});
test('publication detail never opens a publication that is no longer available', function () {
$workspace = Workspace::factory()->create();
$account = analyticsReportAccount($workspace, Platform::Instagram);
$publication = analyticsReportPublication($account, now('UTC')->subDays(3)->toDateTimeString(), 5, 1, 6, 100);
$publication->update(['availability' => PublicationAvailability::Unavailable]);
expect(fn () => app(ReadPublicationAnalytics::class)->latestForWorkspacePublication($workspace, $publication->id))
->toThrow(ModelNotFoundException::class);
});