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
Cut the X analytics bill and stop collecting for accounts without access (#399)
Paulo Castellanobe73d0b2245b
diff --git a/app/Actions/Analytics/AdvanceAnalyticsSyncState.php b/app/Actions/Analytics/AdvanceAnalyticsSyncState.phpindex 188fed3bd..d154cb09c 100644--- a/app/Actions/Analytics/AdvanceAnalyticsSyncState.php+++ b/app/Actions/Analytics/AdvanceAnalyticsSyncState.php@@ -17,7 +17,8 @@ use Illuminate\Support\Facades\DB;class AdvanceAnalyticsSyncState{- private const X_TIMELINE_LIMIT = 3200;+ /** X serves only the 800 most recent posts of a timeline read with exclude=replies. */+ private const X_TIMELINE_LIMIT = 800;public function __construct(private readonly UpsertAnalyticsPublication $publications,@@ -133,13 +134,10 @@ class AdvanceAnalyticsSyncState&& $oldest->lessThanOrEqualTo($state->target_since);$isXBackfill = $state->collector === SyncCollector::PublicationBackfill&& $account->platform === Platform::X;- $seenCount = (int) data_get($checkpoint, 'seen_count', 0) + count($page->publications);+ $seenCount = (int) data_get($checkpoint, 'seen_count', 0) + ($page->providerRowCount ?? count($page->publications));$xTimelineLimited = $isXBackfill&& $page->providerExhausted&& ! $reachedTarget- && $state->target_since- && $oldest- && $oldest->greaterThan($state->target_since)&& $seenCount >= self::X_TIMELINE_LIMIT;$hadProviderLimit = $page->providerLimited || data_get($checkpoint, 'had_provider_limit');$finished = $page->providerExhausted || $reachedTarget;@@ -174,7 +172,7 @@ class AdvanceAnalyticsSyncState'last_success_at' => CarbonImmutable::now('UTC'),'last_error_category' => match (true) {$hadProviderLimit => 'provider_limited',- $xTimelineLimited => 'x_timeline_3200',+ $xTimelineLimited => 'x_timeline_limit',default => $page->partialReason,},]);diff --git a/app/Actions/Analytics/DispatchAccountAnalytics.php b/app/Actions/Analytics/DispatchAccountAnalytics.phpindex 87a22f040..17b5535b3 100644--- a/app/Actions/Analytics/DispatchAccountAnalytics.php+++ b/app/Actions/Analytics/DispatchAccountAnalytics.php@@ -18,23 +18,23 @@ class DispatchAccountAnalyticspublic function handle(SocialAccount $socialAccount): void{try {- $currentAccount = SocialAccount::query()+ $connectedChannel = SocialAccount::query()->connected()->includedInAnalytics()->find($socialAccount->id);- if (! $currentAccount) {+ if (! $connectedChannel?->workspace->account->hasAppAccess()) {return;}- if ($this->collectors->supports($currentAccount->platform)) {+ if ($this->collectors->supports($connectedChannel->platform)) {CollectAccountDailySnapshot::dispatch(- $currentAccount->id,+ $connectedChannel->id,CarbonImmutable::now('UTC')->toDateString(),)->afterCommit();}- BootstrapAccountAnalytics::dispatch($currentAccount->id, true)->afterCommit();+ BootstrapAccountAnalytics::dispatch($connectedChannel->id, true)->afterCommit();} catch (Throwable $exception) {report($exception);}diff --git a/app/Actions/Analytics/QueuePublicationMetricsForPage.php b/app/Actions/Analytics/QueuePublicationMetricsForPage.phpindex 6e5aebd56..4db397c27 100644--- a/app/Actions/Analytics/QueuePublicationMetricsForPage.php+++ b/app/Actions/Analytics/QueuePublicationMetricsForPage.php@@ -13,12 +13,13 @@ use App\Models\AnalyticsPublication;use App\Models\SocialAccount;use App\Support\Analytics\SyncCadence;use Carbon\CarbonImmutable;+use Illuminate\Support\Arr;class QueuePublicationMetricsForPage{public function handle(SocialAccount $account, PublicationPage $page): void{- $providerIds = array_map(fn ($item): string => $item->providerPostId, $page->publications);+ $providerIds = Arr::pluck($page->publications, 'providerPostId');if ($providerIds === []) {return;@@ -28,14 +29,23 @@ class QueuePublicationMetricsForPage->available()->where('social_account_id', $account->id)->whereIn('remote_id', $providerIds)- ->each(function (AnalyticsPublication $publication): void {- $this->queue($publication);- });+ ->whereDoesntHave('dailySnapshots')+ ->each($this->dispatchFirstRead(...));}+ /**+ * Queues the first read of a publication that has not been measured yet.+ */public function queue(AnalyticsPublication $publication): void{- if (! in_array($publication->platform->value, Platform::analyticsValues(), true)) {+ if (! $publication->dailySnapshots()->exists()) {+ $this->dispatchFirstRead($publication);+ }+ }++ private function dispatchFirstRead(AnalyticsPublication $publication): void+ {+ if (! $publication->platform->isIncludedInAnalytics()) {return;}@@ -51,17 +61,13 @@ class QueuePublicationMetricsForPagereturn;}- $days = SyncCadence::metricsWindowDays($publication->platform);- $recent = $publication->provider_published_at->greaterThanOrEqualTo($now->subDays($days)->startOfDay());-- if (! $recent && $publication->dailySnapshots()->exists()) {- return;- }+ $baseline = $publication->provider_published_at->lessThan(SyncCadence::metricsWindowStart($publication->platform, $now));+ $readAt = $publication->provider_published_at->toImmutable()+ ->addMinutes(SyncCadence::FIRST_READ_DELAY_MINUTES)+ ->max($now);- CollectPublicationMetrics::dispatch(- $publication->id,- $now->toDateString(),- ! $recent,- )->afterCommit();+ CollectPublicationMetrics::dispatch($publication->id, $readAt->toDateString(), $baseline)+ ->delay($readAt)+ ->afterCommit();}}diff --git a/app/Console/Commands/Analytics/DispatchAccountDailyAnalytics.php b/app/Console/Commands/Analytics/DispatchAccountDailyAnalytics.phpindex 2724d1c4d..1bce69144 100644--- a/app/Console/Commands/Analytics/DispatchAccountDailyAnalytics.php+++ b/app/Console/Commands/Analytics/DispatchAccountDailyAnalytics.php@@ -22,10 +22,11 @@ class DispatchAccountDailyAnalytics extends CommandSocialAccount::query()->connected()+ ->with('workspace.account.subscriptions')->lazyById(200)- ->each(function (SocialAccount $account) use ($collectors, $date): void {- if ($collectors->supports($account->platform)) {- CollectAccountDailySnapshot::dispatch($account->id, $date);+ ->each(function (SocialAccount $channel) use ($collectors, $date): void {+ if ($channel->workspace->account->hasAppAccess() && $collectors->supports($channel->platform)) {+ CollectAccountDailySnapshot::dispatch($channel->id, $date);}});diff --git a/app/Console/Commands/Analytics/DispatchPublicationDiscovery.php b/app/Console/Commands/Analytics/DispatchPublicationDiscovery.phpindex 1fbedb5c7..c8768a7e4 100644--- a/app/Console/Commands/Analytics/DispatchPublicationDiscovery.php+++ b/app/Console/Commands/Analytics/DispatchPublicationDiscovery.php@@ -31,38 +31,45 @@ class DispatchPublicationDiscovery extends Command->includedInAnalytics()->when($only !== [], fn (Builder $query): Builder => $query->whereIn('platform', $only))->when($except !== [], fn (Builder $query): Builder => $query->whereNotIn('platform', $except))- ->with('analyticsSyncStates')+ ->with(['analyticsSyncStates', 'workspace.account.subscriptions'])->lazyById(100)- ->each(function (SocialAccount $account) use ($staleBefore): void {- $backfill = $account->analyticsSyncStates+ ->each(function (SocialAccount $channel) use ($staleBefore): void {+ if (! $channel->workspace->account->hasAppAccess()) {+ return;+ }++ $backfill = $channel->analyticsSyncStates->first(fn ($state): bool => $state->collector === SyncCollector::PublicationBackfill);- if ($backfill?->status === SyncStatus::Failed) {+ if (! $backfill) {+ BootstrapAccountAnalytics::dispatch($channel->id);++ return;+ }++ if ($backfill->status === SyncStatus::Failed) {if ($backfill->last_error_category === 'queue_failed') {- BootstrapAccountAnalytics::dispatch($account->id);+ BootstrapAccountAnalytics::dispatch($channel->id);}return;}- $staleBackfill = $backfill- && ($backfill->status === SyncStatus::Pending- || ($backfill->status === SyncStatus::Running && $backfill->last_error_category === null))+ $staleBackfill = ($backfill->status === SyncStatus::Pending+ || ($backfill->status === SyncStatus::Running && $backfill->last_error_category === null))&& $backfill->updated_at?->lessThan($staleBefore);if ($staleBackfill) {- BootstrapAccountAnalytics::dispatch($account->id);+ BootstrapAccountAnalytics::dispatch($channel->id);return;}- $backfillIsTerminal = $account->analyticsSyncStates- ->contains(fn ($state): bool => $state->collector === SyncCollector::PublicationBackfill && $state->isTerminal());- $discovery = $account->analyticsSyncStates+ $discovery = $channel->analyticsSyncStates->first(fn ($state): bool => $state->collector === SyncCollector::PublicationDiscovery);- if ($backfillIsTerminal && $discovery) {- DiscoverAccountPublications::dispatch($account->id, $discovery->id);+ if ($backfill->isTerminal() && $discovery) {+ DiscoverAccountPublications::dispatch($channel->id, $discovery->id);}});diff --git a/app/Console/Commands/Analytics/DispatchPublicationMetrics.php b/app/Console/Commands/Analytics/DispatchPublicationMetrics.phpindex 266b53a21..874794b20 100644--- a/app/Console/Commands/Analytics/DispatchPublicationMetrics.php+++ b/app/Console/Commands/Analytics/DispatchPublicationMetrics.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Console\Commands\Analytics;use App\Enums\Analytics\PublicationContentType;+use App\Enums\SocialAccount\Platform;use App\Jobs\Analytics\CollectPublicationMetrics;use App\Models\AnalyticsPublication;use App\Models\SocialAccount;@@ -13,6 +14,7 @@ use Carbon\CarbonImmutable;use Illuminate\Console\Attributes\Description;use Illuminate\Console\Attributes\Signature;use Illuminate\Console\Command;+use Illuminate\Database\Eloquent\Builder;#[Signature('analytics:dispatch-publication-metrics')]#[Description('Dispatch daily publication metric collection for eligible accounts')]@@ -25,17 +27,22 @@ class DispatchPublicationMetrics extends CommandSocialAccount::query()->connected()->includedInAnalytics()+ ->with('workspace.account.subscriptions')->lazyById(100)- ->each(function (SocialAccount $account) use ($now): void {- $days = SyncCadence::metricsWindowDays($account->platform);+ ->each(function (SocialAccount $channel) use ($now): void {+ if (! $channel->workspace->account->hasAppAccess()) {+ return;+ }++ $windowStart = SyncCadence::metricsWindowStart($channel->platform, $now);AnalyticsPublication::query()->available()- ->where('social_account_id', $account->id)- ->where(function ($query) use ($days, $now): void {- $query->where('provider_published_at', '>=', $now->subDays($days)->startOfDay())- ->orWhereDoesntHave('dailySnapshots');- })+ ->where('social_account_id', $channel->id)+ ->where('provider_published_at', '<=', $now->subMinutes(SyncCadence::FIRST_READ_DELAY_MINUTES))+ ->where(fn (Builder $query): Builder => $query+ ->where(fn (Builder $due): Builder => $this->whereDueForRead($due, $channel->platform, $now, $windowStart))+ ->orWhereDoesntHave('dailySnapshots'))->where(function ($query) use ($now): void {$query->where('content_type', '!=', PublicationContentType::Story)->orWhere('provider_published_at', '>=', $now->subDay());@@ -44,10 +51,28 @@ class DispatchPublicationMetrics extends Command->each(fn (AnalyticsPublication $publication) => CollectPublicationMetrics::dispatch($publication->id,$now->toDateString(),- $publication->provider_published_at->lessThan($now->subDays($days)->startOfDay()),+ $publication->provider_published_at->lessThan($windowStart),));});return self::SUCCESS;}++ /**+ * Posts the daily run reads again: every day of the window, or only the scheduled ages on X.+ */+ private function whereDueForRead(Builder $query, Platform $platform, CarbonImmutable $now, CarbonImmutable $windowStart): Builder+ {+ return $query->when(+ SyncCadence::metricsDays($platform),+ fn (Builder $scheduled, array $ages): Builder => collect($ages)->reduce(+ fn (Builder $scheduled, int $age): Builder => $scheduled->orWhereBetween('provider_published_at', [+ $now->subDays($age)->startOfDay(),+ $now->subDays($age)->endOfDay(),+ ]),+ $scheduled,+ ),+ fn (Builder $daily): Builder => $daily->where('provider_published_at', '>=', $windowStart),+ );+ }}diff --git a/app/Dto/Analytics/PublicationPage.php b/app/Dto/Analytics/PublicationPage.phpindex 8d9bb7383..3fb74e869 100644--- a/app/Dto/Analytics/PublicationPage.php+++ b/app/Dto/Analytics/PublicationPage.php@@ -8,6 +8,7 @@ final readonly class PublicationPage{/*** @param list<DiscoveredPublication> $publications+ * @param int|null $providerRowCount Rows the network returned, including the replies left out of $publications; a provider cap counts these.*/public function __construct(public array $publications,@@ -16,6 +17,7 @@ final readonly class PublicationPagepublic bool $providerLimited = false,public ?string $partialReason = null,public bool $canStopAtTarget = true,+ public ?int $providerRowCount = null,) {}/**diff --git a/app/Jobs/Analytics/AbstractPublicationSync.php b/app/Jobs/Analytics/AbstractPublicationSync.phpindex b23d16ab4..5a9b6fa31 100644--- a/app/Jobs/Analytics/AbstractPublicationSync.php+++ b/app/Jobs/Analytics/AbstractPublicationSync.php@@ -79,19 +79,19 @@ abstract class AbstractPublicationSync implements ShouldQueueQueuePublicationMetricsForPage $metrics,AnalyticsJobLog $log,): void {- $account = SocialAccount::query()+ $channel = SocialAccount::query()->connected()->includedInAnalytics()->find($this->socialAccountId);- if (! $account || ! $this->mayStart($account)) {+ if (! $channel?->workspace->account->hasAppAccess() || ! $this->mayStart($channel)) {return;}$capture = $sync->begin($this->syncStateId,restartTerminal: $this->restartTerminal(),- socialAccountId: $account->id,+ socialAccountId: $channel->id,);if (! $capture) {@@ -100,36 +100,36 @@ abstract class AbstractPublicationSync implements ShouldQueue$collector = $this->collector()->value;$cursorLabel = $capture['cursor'] === null ? 'cursor:start' : 'cursor:'.hash('sha256', $capture['cursor']);- $log->record($account, $collector, $cursorLabel, $this->attempts(), 'started');+ $log->record($channel, $collector, $cursorLabel, $this->attempts(), 'started');try {- $page = $collectors->for($account)->page($account, $capture['cursor'], $capture['cutoff']);- $result = $sync->handle($this->syncStateId, $capture['revision'], $account, $page);+ $page = $collectors->for($channel)->page($channel, $capture['cursor'], $capture['cutoff']);+ $result = $sync->handle($this->syncStateId, $capture['revision'], $channel, $page);} catch (AnalyticsCollectionException $exception) {if ($exception->category === 'invalid_cursor') {- $log->record($account, $collector, $cursorLabel, $this->attempts(), $exception->category);- $this->handleInvalidCursor($sync, $account, $capture['revision']);+ $log->record($channel, $collector, $cursorLabel, $this->attempts(), $exception->category);+ $this->handleInvalidCursor($sync, $channel, $capture['revision']);return;}- $this->recordFailure($sync, $log, $account, $capture['revision'], $cursorLabel, $exception->category, $exception->retryAt);+ $this->recordFailure($sync, $log, $channel, $capture['revision'], $cursorLabel, $exception->category, $exception->retryAt);return;} catch (ConnectionException) {- $this->recordFailure($sync, $log, $account, $capture['revision'], $cursorLabel, 'transient', null);+ $this->recordFailure($sync, $log, $channel, $capture['revision'], $cursorLabel, 'transient', null);return;}- $log->record($account, $collector, $cursorLabel, $this->attempts(), $result['terminal'] ? 'completed' : 'page_advanced');- foreach (rescue(fn (): array => ImportExternalPosts::execute($account), []) as $postId) {+ $log->record($channel, $collector, $cursorLabel, $this->attempts(), $result['terminal'] ? 'completed' : 'page_advanced');+ foreach (rescue(fn (): array => ImportExternalPosts::execute($channel), []) as $postId) {ImportExternalPostMedia::dispatch($postId);}- $metrics->handle($account, $page);+ $metrics->handle($channel, $page);if ($result['advanced'] && ! $result['terminal']) {- static::dispatch($account->id, $this->syncStateId)->afterCommit();+ static::dispatch($channel->id, $this->syncStateId)->afterCommit();}}diff --git a/app/Jobs/Analytics/CollectAccountDailySnapshot.php b/app/Jobs/Analytics/CollectAccountDailySnapshot.phpindex 12e15d167..832f72aa8 100644--- a/app/Jobs/Analytics/CollectAccountDailySnapshot.php+++ b/app/Jobs/Analytics/CollectAccountDailySnapshot.php@@ -70,18 +70,18 @@ class CollectAccountDailySnapshot implements ShouldQueuereturn;}- $account = SocialAccount::query()+ $channel = SocialAccount::query()->connected()->find($this->socialAccountId);- if (! $account- || ! $collectors->supports($account->platform)) {+ if (! $channel?->workspace->account->hasAppAccess()+ || ! $collectors->supports($channel->platform)) {return;}$alreadyCollected = AnalyticsAccountDailySnapshot::query()- ->where('workspace_id', $account->workspace_id)- ->where('social_account_key', $accountKeys->for($account))+ ->where('workspace_id', $channel->workspace_id)+ ->where('social_account_key', $accountKeys->for($channel))->where('date', $this->observationDate)->where('provenance', ObservationProvenance::Actual)->exists();@@ -91,28 +91,28 @@ class CollectAccountDailySnapshot implements ShouldQueue}try {- $observation = $collectors->for($account->platform)->collect(- $account,+ $observation = $collectors->for($channel->platform)->collect(+ $channel,CarbonImmutable::parse($this->observationDate, 'UTC'),);- $writer->handle($account, $observation);- $log->record($account, 'followers', $this->observationDate, $this->attempts(), 'actual');+ $writer->handle($channel, $observation);+ $log->record($channel, 'followers', $this->observationDate, $this->attempts(), 'actual');} catch (AnalyticsCollectionException $exception) {if (in_array($exception->category, ['authentication', 'permission'], true)) {- $log->record($account, 'followers', $this->observationDate, $this->attempts(), $exception->category);+ $log->record($channel, 'followers', $this->observationDate, $this->attempts(), $exception->category);return;}if (! in_array($exception->category, ['transient', 'rate_limited'], true)) {- $log->record($account, 'followers', $this->observationDate, $this->attempts(), $exception->category);+ $log->record($channel, 'followers', $this->observationDate, $this->attempts(), $exception->category);return;}- $this->retryTransient($account, $exception->category, $exception->retryAt, $log);+ $this->retryTransient($channel, $exception->category, $exception->retryAt, $log);} catch (ConnectionException) {- $this->retryTransient($account, 'transient', null, $log);+ $this->retryTransient($channel, 'transient', null, $log);}}diff --git a/app/Jobs/Analytics/CollectPublicationMetrics.php b/app/Jobs/Analytics/CollectPublicationMetrics.phpindex 981415bfe..b44e85611 100644--- a/app/Jobs/Analytics/CollectPublicationMetrics.php+++ b/app/Jobs/Analytics/CollectPublicationMetrics.php@@ -96,16 +96,18 @@ class CollectPublicationMetrics implements ShouldQueue}$publication = AnalyticsPublication::query()->available()->find($this->publicationId);- $account = $publication ? SocialAccount::query()+ $channel = $publication ? SocialAccount::query()->connected()->includedInAnalytics()->find($publication->social_account_id) : null;- if (! $publication || ! $account || ! $this->eligible($publication, $account, $date)) {+ if (! $publication+ || ! $channel?->workspace->account->hasAppAccess()+ || ! $this->eligible($publication, $channel, $date)) {return;}- $publication->setRelation('socialAccount', $account);+ $publication->setRelation('socialAccount', $channel);try {$collector = $collectors->for($publication->platform);@@ -118,17 +120,17 @@ class CollectPublicationMetrics implements ShouldQueue$observation = $collector->collect($publication, $date);$writer->handle($publication, $observation);- $log->record($account, 'publication_metrics', $this->observationDate, $this->attempts(), 'actual');+ $log->record($channel, 'publication_metrics', $this->observationDate, $this->attempts(), 'actual');if ($publication->metric_failures > 0) {$publication->forceFill(['metric_failures' => 0])->save();}} catch (AnalyticsCollectionException $exception) {- $log->record($account, 'publication_metrics', $this->observationDate, $this->attempts(), $exception->category);+ $log->record($channel, 'publication_metrics', $this->observationDate, $this->attempts(), $exception->category);$this->recordTerminalFailure($publication, $exception);$this->retry($publication, $date, $exception->category, $exception->retryAt, $log);} catch (ConnectionException) {- $log->record($account, 'publication_metrics', $this->observationDate, $this->attempts(), 'transient');+ $log->record($channel, 'publication_metrics', $this->observationDate, $this->attempts(), 'transient');$this->retry($publication, $date, 'transient', null, $log);}}@@ -170,12 +172,9 @@ class CollectPublicationMetrics implements ShouldQueuereturn false;}- if (! $this->baseline && ! $isStory) {- $ageLimit = SyncCadence::metricsWindowDays($publication->platform);-- if ($publication->provider_published_at->lessThan($date->subDays($ageLimit)->startOfDay())) {- return false;- }+ if (! $this->baseline && ! $isStory+ && $publication->provider_published_at->lessThan(SyncCadence::metricsWindowStart($publication->platform, $date))) {+ return false;}return $this->refreshSameDay || ! AnalyticsPublicationDailySnapshot::query()diff --git a/app/Jobs/Analytics/FinalizeAccountDailySnapshot.php b/app/Jobs/Analytics/FinalizeAccountDailySnapshot.phpindex 53164b8e0..75fbeecc1 100644--- a/app/Jobs/Analytics/FinalizeAccountDailySnapshot.php+++ b/app/Jobs/Analytics/FinalizeAccountDailySnapshot.php@@ -50,20 +50,20 @@ class FinalizeAccountDailySnapshot implements ShouldQueueWriteAccountDailySnapshot $writer,AnalyticsJobLog $log,): void {- $account = SocialAccount::query()+ $channel = SocialAccount::query()->connected()->includedInAnalytics()->find($this->socialAccountId);- if (! $account) {+ if (! $channel?->workspace->account->hasAppAccess()) {return;}$date = CarbonImmutable::parse($this->observationDate, 'UTC');$hasActual = AnalyticsAccountDailySnapshot::query()- ->where('workspace_id', $account->workspace_id)+ ->where('workspace_id', $channel->workspace_id)->where('date', $this->observationDate)- ->where('social_account_key', $accountKeys->for($account))+ ->where('social_account_key', $accountKeys->for($channel))->where('provenance', ObservationProvenance::Actual)->exists();@@ -72,21 +72,21 @@ class FinalizeAccountDailySnapshot implements ShouldQueue}$previous = AnalyticsAccountDailySnapshot::query()- ->where('workspace_id', $account->workspace_id)- ->where('network', $account->platform->network())- ->where('platform_user_id', $account->platform_user_id)+ ->where('workspace_id', $channel->workspace_id)+ ->where('network', $channel->platform->network())+ ->where('platform_user_id', $channel->platform_user_id)->where('date', '<', $this->observationDate)->whereNotNull('followers_count')->latest('date')->first();if (! $previous) {- $log->record($account, 'followers', $this->observationDate, $this->attempts(), 'unavailable_no_history');+ $log->record($channel, 'followers', $this->observationDate, $this->attempts(), 'unavailable_no_history');return;}- $writer->handle($account, new AccountDailyObservation(+ $writer->handle($channel, new AccountDailyObservation(date: $date,followers: $previous->followers_count,provenance: ObservationProvenance::CarriedForward,@@ -95,6 +95,6 @@ class FinalizeAccountDailySnapshot implements ShouldQueuecollectedAt: CarbonImmutable::now('UTC'),metrics: $previous->metrics ?? [],));- $log->record($account, 'followers', $this->observationDate, $this->attempts(), 'carried_forward');+ $log->record($channel, 'followers', $this->observationDate, $this->attempts(), 'carried_forward');}}diff --git a/app/Jobs/Analytics/SyncTryPostPublication.php b/app/Jobs/Analytics/SyncTryPostPublication.phpindex 0578ebbb6..6818a8956 100644--- a/app/Jobs/Analytics/SyncTryPostPublication.php+++ b/app/Jobs/Analytics/SyncTryPostPublication.php@@ -33,6 +33,9 @@ class SyncTryPostPublication implements ShouldQueue}$publication = $sync->fromIdentity($this->identity, $post);- $metrics->queue($publication);++ if ($post->workspace->account->hasAppAccess()) {+ $metrics->queue($publication);+ }}}diff --git a/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.phpindex e8e7caecb..ef7e1bc8b 100644--- a/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/YouTubePublicationMetricsCollector.php@@ -86,7 +86,7 @@ class YouTubePublicationMetricsCollector extends AbstractPublicationMetricsColle->where('platform', Platform::YouTube)->whereKeyNot($publication->id)->where(fn (Builder $query) => $query- ->where('provider_published_at', '>=', $date->subDays(SyncCadence::metricsWindowDays(Platform::YouTube))->startOfDay())+ ->where('provider_published_at', '>=', SyncCadence::metricsWindowStart(Platform::YouTube, $date))->orWhereDoesntHave('dailySnapshots'))->whereDoesntHave('dailySnapshots', fn (Builder $query) => $query->where('date', $date->toDateString()))->latest('provider_published_at')diff --git a/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.phpindex 83ce9ff28..2c6352aaf 100644--- a/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.php@@ -37,7 +37,8 @@ class BlueskyPublicationCollector extends AbstractPublicationHistoryCollectorauthenticated: false,);$records = collect((array) $response->json('records', []));- $hydrated = $this->hydrate($account, $records->pluck('uri')->filter()->values());+ $isReply = fn (mixed $record): bool => filled(data_get($record, 'value.reply'));+ $hydrated = $this->hydrate($account, $records->reject($isReply)->pluck('uri')->filter()->values());$publications = [];$crossedCutoff = false;@@ -54,6 +55,10 @@ class BlueskyPublicationCollector extends AbstractPublicationHistoryCollectorbreak;}+ if ($isReply($record)) {+ continue;+ }+$uri = (string) data_get($record, 'uri');$postId = basename($uri);$view = $hydrated->get($uri);diff --git a/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.phpindex 78a25b970..0eb6292e5 100644--- a/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php@@ -27,6 +27,7 @@ class MastodonPublicationCollector extends AbstractPublicationHistoryCollector['limit' => self::PAGE_SIZE,'exclude_reblogs' => true,+ 'exclude_replies' => true,'max_id' => $cursor,],authenticated: $hasPrivateHistoryScope,@@ -48,6 +49,10 @@ class MastodonPublicationCollector extends AbstractPublicationHistoryCollectorbreak;}+ if (filled(data_get($row, 'in_reply_to_id'))) {+ continue;+ }+$attachments = (array) data_get($row, 'media_attachments', []);$thumbnail = data_get($attachments, '0.preview_url') ?: data_get($attachments, '0.url');diff --git a/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/XPublicationCollector.phpindex 3e24ad46c..186f131b3 100644--- a/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/XPublicationCollector.php@@ -25,9 +25,10 @@ class XPublicationCollector extends AbstractPublicationHistoryCollectorconfig('trypost.platforms.x.api')."/users/{$account->platform_user_id}/tweets",['max_results' => self::PAGE_SIZE,+ 'start_time' => $cutoff->toIso8601ZuluString(),'pagination_token' => $cursor,'exclude' => 'retweets,replies',- 'tweet.fields' => 'created_at,attachments,note_tweet',+ 'tweet.fields' => 'created_at,attachments,note_tweet,referenced_tweets','expansions' => 'attachments.media_keys','media.fields' => 'media_key,type,preview_image_url,url,variants',],@@ -35,21 +36,28 @@ class XPublicationCollector extends AbstractPublicationHistoryCollector$media = collect((array) $response->json('includes.media', []))->keyBy('media_key');$publications = [];$crossedCutoff = false;+ $walkedRows = 0;$providerLimited = false;foreach ((array) $response->json('data', []) as $row) {$publishedAt = $this->publishedAt(data_get($row, 'created_at'));+ if ($publishedAt?->lessThan($cutoff)) {+ $crossedCutoff = true;++ break;+ }++ $walkedRows++;+if (! $publishedAt) {$providerLimited = true;continue;}- if ($publishedAt->lessThan($cutoff)) {- $crossedCutoff = true;-- break;+ if (collect((array) data_get($row, 'referenced_tweets', []))->contains('type', 'replied_to')) {+ continue;}$attachedMedia = collect((array) data_get($row, 'attachments.media_keys', []))@@ -85,7 +93,13 @@ class XPublicationCollector extends AbstractPublicationHistoryCollector$nextCursor = data_get($response->json(), 'meta.next_token');$hasNext = is_string($nextCursor) && $nextCursor !== '' && ! $crossedCutoff;- return new PublicationPage($publications, $hasNext ? $nextCursor : null, ! $hasNext, $providerLimited);+ return new PublicationPage(+ $publications,+ $hasNext ? $nextCursor : null,+ ! $hasNext,+ $providerLimited,+ providerRowCount: $walkedRows,+ );}/** @param list<mixed> $types */diff --git a/app/Support/Analytics/SyncCadence.php b/app/Support/Analytics/SyncCadence.phpindex 4df44b186..90fe5bf5f 100644--- a/app/Support/Analytics/SyncCadence.php+++ b/app/Support/Analytics/SyncCadence.php@@ -5,38 +5,60 @@ declare(strict_types=1);namespace App\Support\Analytics;use App\Enums\SocialAccount\Platform;+use Carbon\CarbonImmutable;/**- * How often Insights data is refreshed, read from the same settings the scheduler uses.+ * How often Insights data is refreshed.*/class SyncCadence{public const int METRICS_WINDOW_DAYS = 30;- public const int X_METRICS_WINDOW_DAYS = 20;+ /**+ * X bills every read, so after the first read a post is read again only at these ages+ * (days since its UTC publish date). The last one closes the window.+ *+ * @var list<int>+ */+ public const array X_METRICS_DAYS = [2, 3, 7, 14, 28];++ /**+ * A post just published has nothing to measure yet, so its first read waits this long.+ */+ public const int FIRST_READ_DELAY_MINUTES = 60;public static function metricsWindowDays(Platform $platform): int{- return $platform === Platform::X ? self::X_METRICS_WINDOW_DAYS : self::METRICS_WINDOW_DAYS;+ return $platform === Platform::X ? max(self::X_METRICS_DAYS) : self::METRICS_WINDOW_DAYS;+ }++ /**+ * The oldest publish time still inside the platform's metrics window on that day.+ */+ public static function metricsWindowStart(Platform $platform, CarbonImmutable $on): CarbonImmutable+ {+ return $on->subDays(self::metricsWindowDays($platform))->startOfDay();+ }++ /**+ * Ages the daily run reads; null means every day of the window.+ *+ * @return list<int>|null+ */+ public static function metricsDays(Platform $platform): ?array+ {+ return $platform === Platform::X ? self::X_METRICS_DAYS : null;}/*** The page reads the last sync time from the report's coverage rows, so a coverage poll keeps it current.*- * @return array{discovery_hours: int, x_discovery_hours: int, metrics_days: int, x_metrics_days: int}+ * @return array{metrics_days: int}*/public static function toArray(): array{return [- 'discovery_hours' => self::hours((int) config('trypost.analytics.discovery_interval_hours')),- 'x_discovery_hours' => self::hours((int) config('trypost.analytics.x_discovery_interval_hours')),'metrics_days' => self::METRICS_WINDOW_DAYS,- 'x_metrics_days' => self::X_METRICS_WINDOW_DAYS,];}-- private static function hours(int $hours): int- {- return max(1, min(24, $hours));- }}diff --git a/lang/ar/analytics.php b/lang/ar/analytics.phpindex f5493c96f..2fab54a97 100644--- a/lang/ar/analytics.php+++ b/lang/ar/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'حالة المزامنة','title' => 'كيف تبقى الإحصاءات محدّثة',- 'new_posts' => 'نجلب المنشورات الجديدة :interval في كل قناة، و:x_interval على X.',- 'every_hours' => '{1} كل ساعة|{2} كل ساعتين|[3,10] كل :count ساعات|[11,*] كل :count ساعة',- 'metrics' => 'تُحدَّث مقاييس المنشورات مرة يوميًا للمنشورات من آخر :days يومًا (:x_days على X).',+ 'new_posts' => 'تُجلب المنشورات الجديدة يوميًا.',+ 'metrics' => 'تُحدَّث مقاييس المنشورات لمدة تصل إلى :days يومًا بعد النشر.','followers' => 'يُحفظ عدد المتابعين مرة يوميًا.','last_sync' => 'آخر مزامنة :time','never' => 'لم تتم المزامنة بعد',diff --git a/lang/de/analytics.php b/lang/de/analytics.phpindex 366d4968c..8ff238bca 100644--- a/lang/de/analytics.php+++ b/lang/de/analytics.php@@ -401,9 +401,8 @@ return ['sync' => ['button' => 'Sync-Status','title' => 'So bleiben Insights aktuell',- 'new_posts' => 'Neue Beiträge werden auf jedem Kanal :interval abgerufen, auf X :x_interval.',- 'every_hours' => '{1} stündlich|[2,*] alle :count Stunden',- 'metrics' => 'Beitragsmetriken werden einmal täglich für Beiträge der letzten :days Tage aktualisiert (:x_days bei X).',+ 'new_posts' => 'Neue Beiträge werden täglich erfasst.',+ 'metrics' => 'Beitragsmetriken werden bis zu :days Tage nach dem Posten aktualisiert.','followers' => 'Follower-Zahlen werden einmal täglich gespeichert.','last_sync' => 'Zuletzt synchronisiert :time','never' => 'Noch nicht synchronisiert',diff --git a/lang/el/analytics.php b/lang/el/analytics.phpindex bdcbe1df5..9b966c3c5 100644--- a/lang/el/analytics.php+++ b/lang/el/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Κατάσταση συγχρονισμού','title' => 'Πώς ενημερώνονται τα Insights',- 'new_posts' => 'Οι νέες αναρτήσεις ανακτώνται :interval σε κάθε κανάλι και :x_interval στο X.',- 'every_hours' => '{1} κάθε ώρα|[2,*] κάθε :count ώρες',- 'metrics' => 'Οι μετρήσεις ανανεώνονται μία φορά την ημέρα για αναρτήσεις των τελευταίων :days ημερών (:x_days στο X).',+ 'new_posts' => 'Οι νέες αναρτήσεις ενημερώνονται καθημερινά.',+ 'metrics' => 'Οι μετρήσεις ανανεώνονται έως :days ημέρες μετά τη δημοσίευση.','followers' => 'Ο αριθμός ακολούθων αποθηκεύεται μία φορά την ημέρα.','last_sync' => 'Τελευταίος συγχρονισμός :time','never' => 'Δεν έχει συγχρονιστεί ακόμα',diff --git a/lang/en/analytics.php b/lang/en/analytics.phpindex b1cd7e207..96a52bb40 100644--- a/lang/en/analytics.php+++ b/lang/en/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Sync status','title' => 'How Insights stay updated',- 'new_posts' => 'New posts are picked up :interval on each channel, and :x_interval on X.',- 'every_hours' => '{1} every hour|[2,*] every :count hours',- 'metrics' => 'Post metrics refresh once a day for posts from the last :days days (:x_days on X).',+ 'new_posts' => 'New posts are picked up daily.',+ 'metrics' => 'Post metrics refresh for up to :days days after publishing.','followers' => 'Follower counts are saved once a day.','last_sync' => 'Last synced :time','never' => 'Not synced yet',diff --git a/lang/es/analytics.php b/lang/es/analytics.phpindex 6736c0ea9..f1314911c 100644--- a/lang/es/analytics.php+++ b/lang/es/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Estado de sincronización','title' => 'Cómo se actualizan los Insights',- 'new_posts' => 'Las publicaciones nuevas se buscan :interval en cada canal, y :x_interval en X.',- 'every_hours' => '{1} cada hora|[2,*] cada :count horas',- 'metrics' => 'Las métricas se actualizan una vez al día para publicaciones de los últimos :days días (:x_days en X).',+ 'new_posts' => 'Las publicaciones nuevas se actualizan a diario.',+ 'metrics' => 'Las métricas se actualizan hasta :days días después de publicar.','followers' => 'El número de seguidores se guarda una vez al día.','last_sync' => 'Última sincronización :time','never' => 'Aún sin sincronizar',diff --git a/lang/fr/analytics.php b/lang/fr/analytics.phpindex 3a42c4557..47a1f9126 100644--- a/lang/fr/analytics.php+++ b/lang/fr/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'État de la synchro','title' => 'Comment les Insights sont mis à jour',- 'new_posts' => 'Les nouveaux posts sont récupérés :interval sur chaque canal, et :x_interval sur X.',- 'every_hours' => '{1} toutes les heures|[2,*] toutes les :count heures',- 'metrics' => 'Les métriques sont actualisées une fois par jour pour les posts des :days derniers jours (:x_days sur X).',+ 'new_posts' => 'Les nouveaux posts sont récupérés chaque jour.',+ 'metrics' => 'Les métriques sont actualisées jusqu\'à :days jours après la publication.','followers' => 'Le nombre d\'abonnés est enregistré une fois par jour.','last_sync' => 'Dernière synchro :time','never' => 'Pas encore synchronisé',diff --git a/lang/it/analytics.php b/lang/it/analytics.phpindex a7c65c5c7..a46c06cfc 100644--- a/lang/it/analytics.php+++ b/lang/it/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Stato sincronizzazione','title' => 'Come si aggiornano gli Insights',- 'new_posts' => 'I nuovi post vengono recuperati :interval su ogni canale, e :x_interval su X.',- 'every_hours' => '{1} ogni ora|[2,*] ogni :count ore',- 'metrics' => 'Le metriche si aggiornano una volta al giorno per i post degli ultimi :days giorni (:x_days su X).',+ 'new_posts' => 'I nuovi post vengono aggiornati ogni giorno.',+ 'metrics' => 'Le metriche si aggiornano fino a :days giorni dopo la pubblicazione.','followers' => 'Il numero di follower viene salvato una volta al giorno.','last_sync' => 'Ultima sincronizzazione :time','never' => 'Non ancora sincronizzato',diff --git a/lang/ja/analytics.php b/lang/ja/analytics.phpindex a4ef8b0f2..dc00a296a 100644--- a/lang/ja/analytics.php+++ b/lang/ja/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => '同期状況','title' => 'Insights の更新タイミング',- 'new_posts' => '新しい投稿は各チャンネルで:interval、X では:x_interval取得します。',- 'every_hours' => '{1} 1時間ごと|[2,*] :count時間ごと',- 'metrics' => '投稿の指標は、過去:days日間(X は:x_days日間)の投稿を対象に1日1回更新されます。',+ 'new_posts' => '新しい投稿は毎日取り込まれます。',+ 'metrics' => '投稿の指標は公開後最大:days日間更新されます。','followers' => 'フォロワー数は1日1回保存されます。','last_sync' => '最終同期 :time','never' => 'まだ同期されていません',diff --git a/lang/ko/analytics.php b/lang/ko/analytics.phpindex 642bcff92..0f3399b0c 100644--- a/lang/ko/analytics.php+++ b/lang/ko/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => '동기화 상태','title' => 'Insights 업데이트 방식',- 'new_posts' => '새 게시물은 채널마다 :interval, X는 :x_interval 가져옵니다.',- 'every_hours' => '{1} 1시간마다|[2,*] :count시간마다',- 'metrics' => '게시물 지표는 최근 :days일 게시물에 대해 하루 한 번 갱신됩니다(X는 :x_days일).',+ 'new_posts' => '새 게시물은 매일 가져옵니다.',+ 'metrics' => '게시물 지표는 게시 후 최대 :days일 동안 갱신됩니다.','followers' => '팔로워 수는 하루 한 번 저장됩니다.','last_sync' => '마지막 동기화 :time','never' => '아직 동기화되지 않음',diff --git a/lang/nl/analytics.php b/lang/nl/analytics.phpindex 17772aaf2..7b604d4db 100644--- a/lang/nl/analytics.php+++ b/lang/nl/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Synchronisatiestatus','title' => 'Zo blijven Insights actueel',- 'new_posts' => 'Nieuwe berichten worden :interval per kanaal opgehaald, en :x_interval op X.',- 'every_hours' => '{1} elk uur|[2,*] elke :count uur',- 'metrics' => 'Statistieken worden dagelijks vernieuwd voor berichten van de afgelopen :days dagen (:x_days op X).',+ 'new_posts' => 'Nieuwe berichten worden dagelijks opgehaald.',+ 'metrics' => 'Statistieken worden tot :days dagen na het plaatsen vernieuwd.','followers' => 'Het aantal volgers wordt eenmaal per dag opgeslagen.','last_sync' => 'Laatst gesynchroniseerd :time','never' => 'Nog niet gesynchroniseerd',diff --git a/lang/pl/analytics.php b/lang/pl/analytics.phpindex d08d0ea16..fdefcc247 100644--- a/lang/pl/analytics.php+++ b/lang/pl/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Stan synchronizacji','title' => 'Jak aktualizują się Insights',- 'new_posts' => 'Nowe posty pobieramy :interval na każdym kanale, a na X :x_interval.',- 'every_hours' => 'co godzinę|co :count godziny|co :count godzin',- 'metrics' => 'Metryki postów odświeżamy raz dziennie dla postów z ostatnich :days dni (:x_days na X).',+ 'new_posts' => 'Nowe posty pobieramy codziennie.',+ 'metrics' => 'Metryki postów odświeżamy do :days dni po publikacji.','followers' => 'Liczba obserwujących jest zapisywana raz dziennie.','last_sync' => 'Ostatnia synchronizacja :time','never' => 'Jeszcze nie zsynchronizowano',diff --git a/lang/pt-BR/analytics.php b/lang/pt-BR/analytics.phpindex 3b259aaa7..833322bba 100644--- a/lang/pt-BR/analytics.php+++ b/lang/pt-BR/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Status da sincronização','title' => 'Como os Insights se atualizam',- 'new_posts' => 'Novos posts são buscados :interval em cada canal, e :x_interval no X.',- 'every_hours' => '{1} a cada hora|[2,*] a cada :count horas',- 'metrics' => 'As métricas dos posts são atualizadas uma vez por dia para posts dos últimos :days dias (:x_days no X).',+ 'new_posts' => 'Os posts novos são atualizados diariamente.',+ 'metrics' => 'As métricas dos posts são atualizadas por até :days dias após a publicação.','followers' => 'O número de seguidores é salvo uma vez por dia.','last_sync' => 'Última sincronização :time','never' => 'Ainda não sincronizado',diff --git a/lang/ru/analytics.php b/lang/ru/analytics.phpindex 5ed1796f1..46725fbb7 100644--- a/lang/ru/analytics.php+++ b/lang/ru/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Статус синхронизации','title' => 'Как обновляются Insights',- 'new_posts' => 'Новые публикации загружаются :interval для каждого канала и :x_interval для X.',- 'every_hours' => 'каждый :count час|каждые :count часа|каждые :count часов|{1} каждый час',- 'metrics' => 'Метрики обновляются раз в день для публикаций за последние :days дней (:x_days для X).',+ 'new_posts' => 'Новые публикации подтягиваются ежедневно.',+ 'metrics' => 'Метрики обновляются в течение :days дней после публикации.','followers' => 'Число подписчиков сохраняется раз в день.','last_sync' => 'Последняя синхронизация :time','never' => 'Ещё не синхронизировано',diff --git a/lang/tr/analytics.php b/lang/tr/analytics.phpindex 47eab735f..c39179bfd 100644--- a/lang/tr/analytics.php+++ b/lang/tr/analytics.php@@ -401,9 +401,8 @@ return ['sync' => ['button' => 'Senkronizasyon durumu','title' => 'Insights nasıl güncel kalır',- 'new_posts' => 'Yeni gönderiler her kanalda :interval, X\'te ise :x_interval alınır.',- 'every_hours' => '{1} her saat|[2,*] her :count saatte bir',- 'metrics' => 'Gönderi metrikleri son :days günün gönderileri için günde bir kez yenilenir (X\'te :x_days).',+ 'new_posts' => 'Yeni gönderiler her gün alınır.',+ 'metrics' => 'Gönderi metrikleri paylaşımdan sonra :days güne kadar yenilenir.','followers' => 'Takipçi sayıları günde bir kez kaydedilir.','last_sync' => 'Son senkronizasyon :time','never' => 'Henüz senkronize edilmedi',diff --git a/lang/uk/analytics.php b/lang/uk/analytics.phpindex ce03629fc..fd38f3266 100644--- a/lang/uk/analytics.php+++ b/lang/uk/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => 'Стан синхронізації','title' => 'Як оновлюються Insights',- 'new_posts' => 'Нові публікації завантажуються :interval для кожного каналу і :x_interval для X.',- 'every_hours' => 'кожну :count годину|кожні :count години|кожні :count годин|{1} щогодини',- 'metrics' => 'Метрики оновлюються раз на день для публікацій за останні :days днів (:x_days для X).',+ 'new_posts' => 'Нові публікації підтягуються щодня.',+ 'metrics' => 'Метрики оновлюються протягом :days днів після публікації.','followers' => 'Кількість підписників зберігається раз на день.','last_sync' => 'Остання синхронізація :time','never' => 'Ще не синхронізовано',diff --git a/lang/zh/analytics.php b/lang/zh/analytics.phpindex 2fdec5952..6563af765 100644--- a/lang/zh/analytics.php+++ b/lang/zh/analytics.php@@ -399,9 +399,8 @@ return ['sync' => ['button' => '同步状态','title' => 'Insights 如何保持更新',- 'new_posts' => '每个频道:interval获取一次新帖子,X 为:x_interval一次。',- 'every_hours' => '{1} 每小时|[2,*] 每 :count 小时',- 'metrics' => '帖子指标每天刷新一次,覆盖最近 :days 天的帖子(X 为 :x_days 天)。',+ 'new_posts' => '新帖子每天同步一次。',+ 'metrics' => '帖子指标在发布后最多 :days 天内持续刷新。','followers' => '粉丝数每天保存一次。','last_sync' => '上次同步 :time','never' => '尚未同步',diff --git a/resources/js/components/analytics/InsightsSyncStatus.vue b/resources/js/components/analytics/InsightsSyncStatus.vueindex 8190ff176..ee43f632f 100644--- a/resources/js/components/analytics/InsightsSyncStatus.vue+++ b/resources/js/components/analytics/InsightsSyncStatus.vue@@ -80,20 +80,7 @@ const lastSyncedAt = computed<string | null>(() =>class="mt-0.5 size-4 shrink-0 text-muted-foreground"aria-hidden="true"/>- <span>{{- $t('analytics.insights.sync.new_posts', {- interval: $tChoice(- 'analytics.insights.sync.every_hours',- cadence.discovery_hours,- { count: String(cadence.discovery_hours) },- ),- x_interval: $tChoice(- 'analytics.insights.sync.every_hours',- cadence.x_discovery_hours,- { count: String(cadence.x_discovery_hours) },- ),- })- }}</span>+ <span>{{ $t('analytics.insights.sync.new_posts') }}</span></li><li class="flex gap-2.5" data-testid="insights-sync-metrics"><IconCalendarStats@@ -103,7 +90,6 @@ const lastSyncedAt = computed<string | null>(() =><span>{{$t('analytics.insights.sync.metrics', {days: String(cadence.metrics_days),- x_days: String(cadence.x_metrics_days),})}}</span></li>diff --git a/resources/js/types/analytics.ts b/resources/js/types/analytics.tsindex 888847061..090f4d74a 100644--- a/resources/js/types/analytics.ts+++ b/resources/js/types/analytics.ts@@ -75,10 +75,7 @@ export type PerformanceRow = AccountIdentityData &Record<PerformanceMetric, Comparison>;export interface InsightsSyncCadence {- discovery_hours: number;- x_discovery_hours: number;metrics_days: number;- x_metrics_days: number;}export interface CoverageRow {diff --git a/tests/Browser/InsightsParityTest.php b/tests/Browser/InsightsParityTest.phpindex cfff52f1e..a0ea9c722 100644--- a/tests/Browser/InsightsParityTest.php+++ b/tests/Browser/InsightsParityTest.php@@ -139,9 +139,8 @@ test('the header offers CSV and Markdown exports of the filtered page and explaiwaitForInsightsParityTestId($page, 'insights-sync-popover');$page->assertSeeIn('@insights-sync-popover', 'How Insights stay updated')- ->assertSeeIn('@insights-sync-new-posts', 'every 3 hours')- ->assertSeeIn('@insights-sync-new-posts', 'every 24 hours on X')- ->assertSeeIn('@insights-sync-metrics', 'last 30 days (20 on X)')+ ->assertSeeIn('@insights-sync-new-posts', 'New posts are picked up daily.')+ ->assertSeeIn('@insights-sync-metrics', 'up to 30 days after publishing')->assertSeeIn('@insights-sync-last', 'Last synced 2 hours ago')->assertNoJavaScriptErrors();});diff --git a/tests/Feature/Analytics/AnalyticsAppAccessTest.php b/tests/Feature/Analytics/AnalyticsAppAccessTest.phpnew file mode 100644index 000000000..8a6060f81--- /dev/null+++ b/tests/Feature/Analytics/AnalyticsAppAccessTest.php@@ -0,0 +1,212 @@+<?php++declare(strict_types=1);++use App\Actions\Analytics\DispatchAccountAnalytics;+use App\Actions\Analytics\ResolveAnalyticsAccountKey;+use App\Dto\Analytics\TryPostPublicationIdentity;+use App\Enums\Analytics\SyncCollector;+use App\Enums\Analytics\SyncStatus;+use App\Enums\PostPlatform\ContentType;+use App\Enums\SocialAccount\Platform;+use App\Jobs\Analytics\BackfillAccountPublications;+use App\Jobs\Analytics\BootstrapAccountAnalytics;+use App\Jobs\Analytics\CollectAccountDailySnapshot;+use App\Jobs\Analytics\CollectPublicationMetrics;+use App\Jobs\Analytics\DiscoverAccountPublications;+use App\Jobs\Analytics\FinalizeAccountDailySnapshot;+use App\Jobs\Analytics\SyncTryPostPublication;+use App\Models\Account;+use App\Models\AnalyticsAccountDailySnapshot;+use App\Models\AnalyticsPublication;+use App\Models\AnalyticsSyncState;+use App\Models\Post;+use App\Models\SocialAccount;+use Carbon\CarbonImmutable;+use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Http;++beforeEach(function () {+ config(['trypost.self_hosted' => false]);+});++function analyticsAccount(bool $subscribed): SocialAccount+{+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);++ if ($subscribed) {+ subscribeAccount($account->workspace->account);+ }++ return $account;+}++test('follower collection skips accounts without app access', function () {+ $paying = analyticsAccount(true);+ analyticsAccount(false);+ Bus::fake([CollectAccountDailySnapshot::class]);++ $this->artisan('analytics:dispatch-account-daily')->assertSuccessful();++ Bus::assertDispatchedTimes(CollectAccountDailySnapshot::class, 1);+ Bus::assertDispatched(CollectAccountDailySnapshot::class, fn (CollectAccountDailySnapshot $job): bool => $job->socialAccountId === $paying->id);+});++test('publication metrics skip accounts without app access', function () {+ CarbonImmutable::setTestNow('2026-10-10 03:00:00 UTC');+ $paying = analyticsAccount(true);+ $lapsed = analyticsAccount(false);++ foreach ([$paying, $lapsed] as $account) {+ AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::X,+ 'network' => Platform::X->network(),+ 'platform_user_id' => $account->platform_user_id,+ 'provider_published_at' => CarbonImmutable::now('UTC')->subDays(2),+ ]);+ }++ Bus::fake([CollectPublicationMetrics::class]);+ $this->artisan('analytics:dispatch-publication-metrics')->assertSuccessful();++ Bus::assertDispatchedTimes(CollectPublicationMetrics::class, 1);+});++test('publication discovery skips accounts without app access', function () {+ foreach ([analyticsAccount(true), analyticsAccount(false)] as $account) {+ foreach ([SyncCollector::PublicationBackfill, SyncCollector::PublicationDiscovery] as $collector) {+ AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'collector' => $collector,+ 'status' => SyncStatus::Complete,+ ]);+ }+ }++ Bus::fake([DiscoverAccountPublications::class, BootstrapAccountAnalytics::class]);+ $this->artisan('analytics:dispatch-publication-discovery')->assertSuccessful();++ Bus::assertDispatchedTimes(DiscoverAccountPublications::class, 1);+});++test('a canceled subscription still in its paid period keeps analytics', function () {+ $account = analyticsAccount(false);+ $account->workspace->account->subscriptions()->create([+ 'type' => Account::SUBSCRIPTION_NAME,+ 'stripe_id' => 'sub_grace',+ 'stripe_status' => 'active',+ 'stripe_price' => 'price_123',+ 'ends_at' => now()->addDays(5),+ ]);+ Bus::fake([CollectAccountDailySnapshot::class]);++ $this->artisan('analytics:dispatch-account-daily')->assertSuccessful();++ Bus::assertDispatched(CollectAccountDailySnapshot::class, fn (CollectAccountDailySnapshot $job): bool => $job->socialAccountId === $account->id);+});++test('self-hosted installs collect analytics without a subscription', function () {+ config(['trypost.self_hosted' => true]);+ $account = analyticsAccount(false);+ Bus::fake([CollectAccountDailySnapshot::class]);++ $this->artisan('analytics:dispatch-account-daily')->assertSuccessful();++ Bus::assertDispatched(CollectAccountDailySnapshot::class, fn (CollectAccountDailySnapshot $job): bool => $job->socialAccountId === $account->id);+});++test('discovery bootstraps a paying channel that was never bootstrapped', function (bool $subscribed, int $bootstraps) {+ $account = analyticsAccount($subscribed);+ AnalyticsSyncState::query()->where('social_account_id', $account->id)->delete();+ Bus::fake([BootstrapAccountAnalytics::class, DiscoverAccountPublications::class]);++ $this->artisan('analytics:dispatch-publication-discovery')->assertSuccessful();++ Bus::assertDispatchedTimes(BootstrapAccountAnalytics::class, $bootstraps);+})->with([+ 'with app access' => [true, 1],+ 'without app access' => [false, 0],+]);++test('a published post is linked to insights but measured only with app access', function (bool $subscribed, int $reads) {+ $account = analyticsAccount($subscribed);+ Bus::fake([SyncTryPostPublication::class, CollectPublicationMetrics::class]);+ $post = Post::factory()+ ->forAccount($account, ContentType::defaultFor(Platform::X))+ ->published()+ ->create(['platform_post_id' => 'tweet-1', 'published_at' => now()]);++ app()->call([new SyncTryPostPublication(+ TryPostPublicationIdentity::fromAccount($account, app(ResolveAnalyticsAccountKey::class)->for($account)),+ $post->id,+ ), 'handle']);++ expect(AnalyticsPublication::query()->where('post_id', $post->id)->exists())->toBeTrue();+ Bus::assertDispatchedTimes(CollectPublicationMetrics::class, $reads);+})->with([+ 'with app access' => [true, 1],+ 'without app access' => [false, 0],+]);++test('a reconnected channel is collected only with app access', function (bool $subscribed, int $jobs) {+ $account = analyticsAccount($subscribed);+ Bus::fake([CollectAccountDailySnapshot::class, BootstrapAccountAnalytics::class]);++ app(DispatchAccountAnalytics::class)->handle($account);++ Bus::assertDispatchedTimes(CollectAccountDailySnapshot::class, $jobs);+ Bus::assertDispatchedTimes(BootstrapAccountAnalytics::class, $jobs);+})->with([+ 'with app access' => [true, 1],+ 'without app access' => [false, 0],+]);++test('queued analytics work stops calling the network once the account loses access', function () {+ CarbonImmutable::setTestNow('2026-10-10 12:00:00 UTC');+ $account = analyticsAccount(false);+ $publication = AnalyticsPublication::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'platform' => Platform::X,+ 'network' => Platform::X->network(),+ 'platform_user_id' => $account->platform_user_id,+ 'provider_published_at' => CarbonImmutable::now('UTC')->subDays(2),+ ]);+ $backfill = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'collector' => SyncCollector::PublicationBackfill,+ 'status' => SyncStatus::Pending,+ 'checkpoint' => ['cursor' => null, 'revision' => 0],+ ]);+ Http::fake();+ Bus::fake();++ app()->call([new CollectPublicationMetrics($publication->id, '2026-10-10'), 'handle']);+ app()->call([new CollectAccountDailySnapshot($account->id, '2026-10-10'), 'handle']);+ app()->call([new BackfillAccountPublications($account->id, $backfill->id), 'handle']);++ Http::assertNothingSent();+ expect($publication->dailySnapshots()->exists())->toBeFalse();+});++test('follower history is not carried forward for an account without access', function () {+ $account = analyticsAccount(false);+ AnalyticsAccountDailySnapshot::factory()->create([+ 'workspace_id' => $account->workspace_id,+ 'social_account_id' => $account->id,+ 'social_account_key' => $account->id,+ 'network' => $account->platform->network(),+ 'platform' => $account->platform,+ 'platform_user_id' => $account->platform_user_id,+ 'date' => '2026-10-09',+ 'followers_count' => 100,+ ]);++ app()->call([new FinalizeAccountDailySnapshot($account->id, '2026-10-10'), 'handle']);++ expect(AnalyticsAccountDailySnapshot::query()->where('social_account_id', $account->id)->whereDate('date', '2026-10-10')->exists())->toBeFalse();+});diff --git a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.phpindex 12714abdc..b233466d1 100644--- a/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php@@ -55,7 +55,7 @@ test('x reads one owned timeline page with only discovery fields', function () {Http::assertSent(fn (Request $request): bool => str_contains($request->url(), "/users/{$account->platform_user_id}/tweets")&& $request['pagination_token'] === 'x-cursor'&& $request['exclude'] === 'retweets,replies'- && $request['tweet.fields'] === 'created_at,attachments,note_tweet'+ && $request['tweet.fields'] === 'created_at,attachments,note_tweet,referenced_tweets'&& $request['media.fields'] === 'media_key,type,preview_image_url,url,variants'&& ! str_contains((string) $request['tweet.fields'], 'public_metrics'));});@@ -382,3 +382,68 @@ test('youtube resolves the uploads playlist once and reuses it on every later diHttp::assertSentCount(4);expect(collect(Http::recorded())->filter(fn (array $pair): bool => str_contains($pair[0]->url(), '/channels'))->count())->toBe(1);});++test('x asks the timeline only for posts since the cutoff', function () {+ Http::fake(['*' => Http::response(['data' => [], 'meta' => []])]);+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);++ app(XPublicationCollector::class)->page(+ $account,+ null,+ CarbonImmutable::parse('2026-10-09 18:00:00', 'UTC'),+ );++ Http::assertSent(fn (Request $request): bool => str_contains($request->url(), "/users/{$account->platform_user_id}/tweets")+ && $request['start_time'] === '2026-10-09T18:00:00Z');+});++test('an x page with nothing since the cutoff ends the sync', function () {+ Http::fake(['*' => Http::response(['meta' => ['result_count' => 0]])]);+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);++ $page = app(XPublicationCollector::class)->page(+ $account,+ null,+ CarbonImmutable::parse('2026-10-09 18:00:00', 'UTC'),+ );++ expect($page->publications)->toBe([])+ ->and($page->nextCursor)->toBeNull()+ ->and($page->providerExhausted)->toBeTrue();+});++test('x tracks a post, never a reply, so a thread is its root', function () {+ Http::fake(['*' => Http::response([+ 'data' => [+ ['id' => 'thread-reply', 'text' => '2/2', 'created_at' => '2026-10-09T12:01:00.000Z', 'referenced_tweets' => [['type' => 'replied_to', 'id' => 'thread-root']]],+ ['id' => 'quote', 'text' => 'quoting', 'created_at' => '2026-10-09T12:00:30.000Z', 'referenced_tweets' => [['type' => 'quoted', 'id' => 'someone']]],+ ['id' => 'thread-root', 'text' => '1/2', 'created_at' => '2026-10-09T12:00:00.000Z'],+ ],+ 'meta' => ['result_count' => 3],+ ])]);+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);++ $page = app(XPublicationCollector::class)->page($account, null, CarbonImmutable::parse('2026-10-01', 'UTC'));++ expect(collect($page->publications)->pluck('providerPostId')->all())->toBe(['quote', 'thread-root'])+ ->and($page->providerRowCount)->toBe(3);+ Http::assertSent(fn (Request $request): bool => str_contains((string) $request['tweet.fields'], 'referenced_tweets'));+});++test('x counts toward the timeline cap only the rows it walked before the cutoff', function () {+ Http::fake(['*' => Http::response([+ 'data' => [+ ['id' => 'inside', 'text' => 'inside', 'created_at' => '2026-10-09T12:00:00.000Z'],+ ['id' => 'outside', 'text' => 'outside', 'created_at' => '2026-09-01T12:00:00.000Z'],+ ['id' => 'older', 'text' => 'older', 'created_at' => '2026-08-01T12:00:00.000Z'],+ ],+ 'meta' => ['result_count' => 3, 'next_token' => 'more'],+ ])]);+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);++ $page = app(XPublicationCollector::class)->page($account, null, CarbonImmutable::parse('2026-10-01', 'UTC'));++ expect(collect($page->publications)->pluck('providerPostId')->all())->toBe(['inside'])+ ->and($page->providerRowCount)->toBe(1)+ ->and($page->nextCursor)->toBeNull();+});diff --git a/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php b/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.phpindex 6304b2e1a..c6879d85f 100644--- a/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php+++ b/tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php@@ -189,6 +189,7 @@ test('mastodon pages account statuses with authenticated private history', functHttp::assertSent(fn (Request $request): bool => str_contains($request->url(), '/api/v1/accounts/42/statuses')&& $request['limit'] === 40&& $request['exclude_reblogs'] === true+ && $request['exclude_replies'] === true&& $request['max_id'] === 'status-3'&& $request->hasHeader('Authorization', 'Bearer '.$account->access_token));});@@ -239,3 +240,76 @@ test('publication collector factory supports open networks', function (Platform[Platform::Bluesky, BlueskyPublicationCollector::class],[Platform::Mastodon, MastodonPublicationCollector::class],]);++test('bluesky tracks a post, never a reply, so a thread is its root', function () {+ $pds = 'https://pds.example';+ $record = fn (string $id, ?array $reply = null): array => [+ 'uri' => "at://did:plc:alice/app.bsky.feed.post/{$id}",+ 'cid' => "cid-{$id}",+ 'value' => array_filter([+ '$type' => 'app.bsky.feed.post',+ 'text' => $id,+ 'createdAt' => '2026-09-22T12:00:00Z',+ 'reply' => $reply,+ ]),+ ];+ $root = ['uri' => 'at://did:plc:alice/app.bsky.feed.post/thread-root', 'cid' => 'cid-thread-root'];+ Http::fake([+ "{$pds}/xrpc/com.atproto.repo.listRecords*" => Http::response([+ 'records' => [$record('thread-reply', ['root' => $root, 'parent' => $root]), $record('thread-root')],+ ]),+ config('trypost.platforms.bluesky.public_appview').'/xrpc/app.bsky.feed.getPosts*' => Http::response(['posts' => []]),+ ]);+ $account = SocialAccount::factory()->bluesky()->create([+ 'platform_user_id' => 'did:plc:alice',+ 'meta' => ['service' => $pds],+ ]);++ $page = app(BlueskyPublicationCollector::class)->page($account, null, CarbonImmutable::parse('2026-09-01', 'UTC'));++ expect(collect($page->publications)->pluck('providerPostId')->all())->toBe(['thread-root']);+ Http::assertNotSent(fn (Request $request): bool => str_contains($request->url(), 'getPosts')+ && str_contains(urldecode($request->url()), 'thread-reply'));+});++test('mastodon tracks a status, never a reply, so a thread is its root', function () {+ Http::fake(['*' => Http::response([+ ['id' => 'thread-reply', 'created_at' => '2026-09-20T12:01:00Z', 'content' => '<p>2/2</p>', 'in_reply_to_id' => 'thread-root', 'media_attachments' => []],+ ['id' => 'thread-root', 'created_at' => '2026-09-20T12:00:00Z', 'content' => '<p>1/2</p>', 'in_reply_to_id' => null, 'media_attachments' => []],+ ])]);+ $account = SocialAccount::factory()->mastodon()->create([+ 'platform_user_id' => '42',+ 'scopes' => ['read:accounts', 'read:statuses', 'write:statuses', 'write:media'],+ 'meta' => ['instance' => 'https://mastodon.example'],+ ]);++ $page = app(MastodonPublicationCollector::class)->page($account, null, CarbonImmutable::parse('2026-01-01', 'UTC'));++ expect(collect($page->publications)->pluck('providerPostId')->all())->toBe(['thread-root']);+});++test('bluesky stops at the cutoff even when the older records are replies', function () {+ $pds = 'https://pds.example';+ $root = ['uri' => 'at://did:plc:alice/app.bsky.feed.post/root', 'cid' => 'cid-root'];+ Http::fake([+ "{$pds}/xrpc/com.atproto.repo.listRecords*" => Http::response([+ 'records' => [[+ 'uri' => 'at://did:plc:alice/app.bsky.feed.post/old-reply',+ 'cid' => 'cid-old-reply',+ 'value' => ['$type' => 'app.bsky.feed.post', 'text' => 'old reply', 'createdAt' => '2025-01-01T12:00:00Z', 'reply' => ['root' => $root, 'parent' => $root]],+ ]],+ 'cursor' => 'repo-next',+ ]),+ config('trypost.platforms.bluesky.public_appview').'/xrpc/app.bsky.feed.getPosts*' => Http::response(['posts' => []]),+ ]);+ $account = SocialAccount::factory()->bluesky()->create([+ 'platform_user_id' => 'did:plc:alice',+ 'meta' => ['service' => $pds],+ ]);++ $page = app(BlueskyPublicationCollector::class)->page($account, null, CarbonImmutable::parse('2026-09-01', 'UTC'));++ expect($page->publications)->toBe([])+ ->and($page->nextCursor)->toBeNull()+ ->and($page->providerExhausted)->toBeTrue();+});diff --git a/tests/Feature/Analytics/InsightsExportTest.php b/tests/Feature/Analytics/InsightsExportTest.phpindex b7c0b8aee..772d364b8 100644--- a/tests/Feature/Analytics/InsightsExportTest.php+++ b/tests/Feature/Analytics/InsightsExportTest.php@@ -246,7 +246,6 @@ test('the insights page shares the sync cadence and the extended performance met->component('insights/Index')->where('sync', SyncCadence::toArray())->where('sync.metrics_days', 30)- ->where('sync.x_metrics_days', 20)->where('report.performance.0.username', 'bravo')->where('report.performance.0.clicks.value', 7)->where('report.performance.0.impressions.value', 200)@@ -255,16 +254,9 @@ test('the insights page shares the sync cadence and the extended performance met->etc());});-test('the sync cadence follows the discovery settings the scheduler uses', function () {- config()->set('trypost.analytics.discovery_interval_hours', 6);- config()->set('trypost.analytics.x_discovery_interval_hours', 48);-- expect(SyncCadence::toArray())->toBe([- 'discovery_hours' => 6,- 'x_discovery_hours' => 24,- 'metrics_days' => 30,- 'x_metrics_days' => 20,- ]);+test('the sync cadence shares the metrics window and x closes it on its last read', function () {+ expect(SyncCadence::toArray())->toBe(['metrics_days' => 30])+ ->and(SyncCadence::metricsWindowDays(Platform::X))->toBe(max(SyncCadence::X_METRICS_DAYS));});test('the export of a workspace without connected channels has no past analytics', function () {diff --git a/tests/Feature/Analytics/PublicationBackfillJobsTest.php b/tests/Feature/Analytics/PublicationBackfillJobsTest.phpindex 6b0ed5424..f8ca5e141 100644--- a/tests/Feature/Analytics/PublicationBackfillJobsTest.php+++ b/tests/Feature/Analytics/PublicationBackfillJobsTest.php@@ -139,7 +139,7 @@ test('daily discovery does not retry a backfill rejected for missing permission'Bus::assertNotDispatched(DiscoverAccountPublications::class);});-test('daily discovery recovers stale bootstraps without starting the manual rollout or interrupting delayed retries', function () {+test('daily discovery recovers stale bootstraps, bootstraps channels never bootstrapped and leaves delayed retries alone', function () {$stalePending = SocialAccount::factory()->instagram()->create();$staleRunning = SocialAccount::factory()->instagram()->create();$recentPending = SocialAccount::factory()->instagram()->create();@@ -176,7 +176,7 @@ test('daily discovery recovers stale bootstraps without starting the manual roll$this->artisan('analytics:dispatch-publication-discovery')->assertSuccessful();expect(Bus::dispatched(BootstrapAccountAnalytics::class)->pluck('socialAccountId')->sort()->values()->all())- ->toBe(collect([$stalePending->id, $staleRunning->id])->sort()->values()->all());+ ->toBe(collect([$stalePending->id, $staleRunning->id, $awaitingRollout->id])->sort()->values()->all());Bus::assertDispatched(DiscoverAccountPublications::class, fn ($job): bool => $job->socialAccountId === $readyForDiscovery->id);Bus::assertDispatchedTimes(DiscoverAccountPublications::class, 1);Bus::assertNotDispatched(BackfillAccountPublications::class);@@ -244,26 +244,60 @@ test('re-authorizing the same account starts incremental discovery without restaBus::assertDispatched(DiscoverAccountPublications::class, fn ($job): bool => $job->syncStateId === $discovery->id);});-test('x backfill reports provider limited when the 3200 post timeline ends before the target', function () {+test('x backfill reports provider limited when the 800 post timeline without replies ends before the target', function () {Bus::fake();$account = SocialAccount::factory()->create(['platform' => Platform::X]);$state = AnalyticsSyncState::factory()->create(['social_account_id' => $account->id,- 'checkpoint' => ['cursor' => 'last-page', 'revision' => 4, 'seen_count' => 3199],+ 'checkpoint' => ['cursor' => 'last-page', 'revision' => 4, 'seen_count' => 799],'target_since' => CarbonImmutable::parse('2025-09-23', 'UTC'),]);bindPublicationPage(new PublicationPage([- new DiscoveredPublication('x-3200', CarbonImmutable::parse('2026-01-01', 'UTC'), PublicationContentType::Text),+ new DiscoveredPublication('x-800', CarbonImmutable::parse('2026-01-01', 'UTC'), PublicationContentType::Text),], null, true));app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);expect($state->fresh()->status)->toBe(SyncStatus::ProviderLimited)- ->and($state->fresh()->last_error_category)->toBe('x_timeline_3200')- ->and($state->fresh()->checkpoint)->toMatchArray(['cursor' => null, 'seen_count' => 3200]);+ ->and($state->fresh()->last_error_category)->toBe('x_timeline_limit')+ ->and($state->fresh()->checkpoint)->toMatchArray(['cursor' => null, 'seen_count' => 800]);Bus::assertNotDispatched(BackfillAccountPublications::class);});+test('x backfill counts the replies the collector skipped toward the timeline cap', function () {+ Bus::fake();+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'last-page', 'revision' => 4, 'seen_count' => 798],+ 'target_since' => CarbonImmutable::parse('2025-09-23', 'UTC'),+ ]);+ bindPublicationPage(new PublicationPage([+ new DiscoveredPublication('x-root', CarbonImmutable::parse('2026-01-01', 'UTC'), PublicationContentType::Text),+ ], null, true, providerRowCount: 2));++ app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);++ expect($state->fresh()->status)->toBe(SyncStatus::ProviderLimited)+ ->and(data_get($state->fresh()->checkpoint, 'seen_count'))->toBe(800);+});++test('x backfill detects the timeline cap on a last page of skipped replies only', function () {+ Bus::fake();+ $account = SocialAccount::factory()->create(['platform' => Platform::X]);+ $state = AnalyticsSyncState::factory()->create([+ 'social_account_id' => $account->id,+ 'checkpoint' => ['cursor' => 'last-page', 'revision' => 4, 'seen_count' => 798],+ 'target_since' => CarbonImmutable::parse('2025-09-23', 'UTC'),+ ]);+ bindPublicationPage(new PublicationPage([], null, true, providerRowCount: 2));++ app()->call([new BackfillAccountPublications($account->id, $state->id), 'handle']);++ expect($state->fresh()->status)->toBe(SyncStatus::ProviderLimited)+ ->and($state->fresh()->last_error_category)->toBe('x_timeline_limit');+});+test('x backfill below the timeline cap completes when the provider exhausts its history', function () {Bus::fake();$account = SocialAccount::factory()->create(['platform' => Platform::X]);@@ -288,7 +322,7 @@ test('restarting a terminal x backfill resets its timeline count', function () {$state = AnalyticsSyncState::factory()->create(['social_account_id' => $account->id,'status' => SyncStatus::ProviderLimited,- 'checkpoint' => ['cursor' => null, 'revision' => 4, 'seen_count' => 3200],+ 'checkpoint' => ['cursor' => null, 'revision' => 4, 'seen_count' => 800],]);$started = app(AdvanceAnalyticsSyncState::class)->begin($state->id, restartTerminal: true);diff --git a/tests/Feature/Analytics/PublicationMetricsJobsTest.php b/tests/Feature/Analytics/PublicationMetricsJobsTest.phpindex 64e897730..9b5529d46 100644--- a/tests/Feature/Analytics/PublicationMetricsJobsTest.php+++ b/tests/Feature/Analytics/PublicationMetricsJobsTest.php@@ -3,6 +3,8 @@declare(strict_types=1);use App\Actions\Analytics\QueuePublicationMetricsForPage;+use App\Dto\Analytics\DiscoveredPublication;+use App\Dto\Analytics\PublicationPage;use App\Enums\Analytics\PublicationAvailability;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\PublicationOrigin;@@ -19,6 +21,7 @@ use App\Models\Post;use App\Models\SocialAccount;use App\Services\Analytics\Collectors\Metrics\MastodonPublicationMetricsCollector;use App\Services\Analytics\Collectors\Metrics\PublicationMetricsCollectorFactory;+use App\Support\Analytics\SyncCadence;use Carbon\CarbonImmutable;use Illuminate\Support\Facades\Bus;use Illuminate\Support\Facades\Http;@@ -43,6 +46,15 @@ function metricJobPublication(Platform $platform, CarbonImmutable $publishedAt):]);}+function discoveredFor(AnalyticsPublication $publication): DiscoveredPublication+{+ return new DiscoveredPublication(+ providerPostId: $publication->remote_id,+ publishedAt: $publication->provider_published_at->toImmutable(),+ contentType: PublicationContentType::Text,+ );+}+test('metric job writes a daily snapshot once and never calls providers for excluded networks', function () {$date = CarbonImmutable::parse('2026-09-23 12:00:00', 'UTC');CarbonImmutable::setTestNow($date);@@ -106,8 +118,8 @@ test('regular collection respects the X and non-X refresh windows', function (Plexpect(AnalyticsPublicationDailySnapshot::query()->where('publication_id', $publication->id)->exists())->toBe($eligible, "{$platform->value} at {$age} days");})->with([- [Platform::X, 20, true],- [Platform::X, 21, false],+ [Platform::X, 28, true],+ [Platform::X, 29, false],[Platform::Mastodon, 30, true],[Platform::Mastodon, 31, false],]);@@ -364,3 +376,116 @@ test('a malformed reading of a recent publication is not counted against it', fuexpect($publication->fresh()->metric_failures)->toBe(0)->and($publication->fresh()->availability)->toBe(PublicationAvailability::Available);});++test('the daily run reads x posts only on the scheduled ages', function () {+ $now = CarbonImmutable::parse('2026-10-10 03:00:00', 'UTC');+ CarbonImmutable::setTestNow($now);+ $read = [];++ foreach ([1, 2, 3, 4, 5, 6, 7, 8, 13, 14, 15, 20, 27, 28, 29] as $age) {+ $publication = metricJobPublication(Platform::X, $now->subDays($age)->setTime(15, 0));+ AnalyticsPublicationDailySnapshot::factory()->create([+ 'publication_id' => $publication->id,+ 'date' => $now->subDays($age)->toDateString(),+ ]);++ if (in_array($age, SyncCadence::X_METRICS_DAYS, true)) {+ $read[] = $publication->id;+ }+ }++ Bus::fake([CollectPublicationMetrics::class]);+ $this->artisan('analytics:dispatch-publication-metrics')->assertSuccessful();++ expect(Bus::dispatched(CollectPublicationMetrics::class)->pluck('publicationId')->sort()->values()->all())+ ->toBe(collect($read)->sort()->values()->all());+});++test('other networks keep the daily thirty day window', function () {+ $now = CarbonImmutable::parse('2026-10-10 03:00:00', 'UTC');+ CarbonImmutable::setTestNow($now);++ foreach ([1, 4, 29, 30] as $age) {+ $publication = metricJobPublication(Platform::Instagram, $now->subDays($age)->setTime(15, 0));+ AnalyticsPublicationDailySnapshot::factory()->create([+ 'publication_id' => $publication->id,+ 'date' => $now->subDays($age)->toDateString(),+ ]);+ }++ Bus::fake([CollectPublicationMetrics::class]);+ $this->artisan('analytics:dispatch-publication-metrics')->assertSuccessful();++ Bus::assertDispatchedTimes(CollectPublicationMetrics::class, 4);+});++test('a published post is first read an hour after publishing on every network', function (Platform $platform) {+ $now = CarbonImmutable::parse('2026-10-10 12:00:00', 'UTC');+ CarbonImmutable::setTestNow($now);+ $publication = metricJobPublication($platform, $now);+ Bus::fake([CollectPublicationMetrics::class]);++ app(QueuePublicationMetricsForPage::class)->queue($publication);++ Bus::assertDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $publication->id+ && $job->observationDate === '2026-10-10'+ && CarbonImmutable::parse($job->delay)->equalTo($now->addHour()));+})->with([Platform::X, Platform::Instagram, Platform::Mastodon]);++test('a late post is first read under the next utc date', function () {+ $now = CarbonImmutable::parse('2026-10-10 23:30:00', 'UTC');+ CarbonImmutable::setTestNow($now);+ $publication = metricJobPublication(Platform::X, $now);+ Bus::fake([CollectPublicationMetrics::class]);++ app(QueuePublicationMetricsForPage::class)->queue($publication);++ Bus::assertDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->observationDate === '2026-10-11');+});++test('a post found more than an hour after publishing is read right away', function () {+ CarbonImmutable::setTestNow('2026-10-10 12:00:00 UTC');+ $publication = metricJobPublication(Platform::Instagram, CarbonImmutable::now('UTC')->subHours(3));+ Bus::fake([CollectPublicationMetrics::class]);++ app(QueuePublicationMetricsForPage::class)->queue($publication);++ Bus::assertDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => CarbonImmutable::parse($job->delay)->equalTo(CarbonImmutable::now('UTC')));+});++test('discovery reads only posts that were never measured', function (Platform $platform) {+ CarbonImmutable::setTestNow('2026-10-10 00:00:00 UTC');+ $measured = metricJobPublication($platform, CarbonImmutable::now('UTC')->subHours(5));+ AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $measured->id, 'date' => '2026-10-09']);+ $native = AnalyticsPublication::factory()->create([+ 'workspace_id' => $measured->workspace_id,+ 'social_account_id' => $measured->social_account_id,+ 'social_account_key' => $measured->social_account_key,+ 'platform' => $platform,+ 'network' => $platform->network(),+ 'platform_user_id' => $measured->platform_user_id,+ 'provider_published_at' => CarbonImmutable::now('UTC')->subHours(3),+ ]);+ Bus::fake([CollectPublicationMetrics::class]);++ app(QueuePublicationMetricsForPage::class)->handle($measured->socialAccount, new PublicationPage([+ discoveredFor($measured),+ discoveredFor($native),+ ], null, true));++ Bus::assertDispatchedTimes(CollectPublicationMetrics::class, 1);+ Bus::assertDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $native->id);+})->with([Platform::X, Platform::Instagram]);++test('the daily run leaves a fresh post to its first read an hour after publishing', function (Platform $platform) {+ $now = CarbonImmutable::parse('2026-10-10 03:00:00', 'UTC');+ CarbonImmutable::setTestNow($now);+ $fresh = metricJobPublication($platform, $now->subMinutes(30));+ $settled = metricJobPublication($platform, $now->subMinutes(90));+ Bus::fake([CollectPublicationMetrics::class]);++ $this->artisan('analytics:dispatch-publication-metrics')->assertSuccessful();++ Bus::assertNotDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $fresh->id);+ Bus::assertDispatched(CollectPublicationMetrics::class, fn (CollectPublicationMetrics $job): bool => $job->publicationId === $settled->id);+})->with([Platform::X, Platform::Instagram]);diff --git a/tests/Feature/LocalizationParityTest.php b/tests/Feature/LocalizationParityTest.phpindex b5d599848..59a627d05 100644--- a/tests/Feature/LocalizationParityTest.php+++ b/tests/Feature/LocalizationParityTest.php@@ -53,7 +53,7 @@ test('every analytics enum value has a display translation', function (string $l}expect(Arr::get($analytics, 'title'))->toBeString()->not->toBeEmpty();- foreach (['insights.export.button', 'insights.sync.title', 'insights.sync.every_hours', 'insights.columns', 'insights.channels_shown'] as $key) {+ foreach (['insights.export.button', 'insights.sync.title', 'insights.sync.new_posts', 'insights.columns', 'insights.channels_shown'] as $key) {expect(Arr::get($analytics, $key))->toBeString()->not->toBeEmpty("{$locale} is missing {$key}");}})->with(Locale::values());