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
Count a Facebook video once in Insights (#493)
Paulo Castellanoee8b3a561961
diff --git a/.ai/rules/analytics.md b/.ai/rules/analytics.mdindex cae4d5d8e..983c1bfb8 100644--- a/.ai/rules/analytics.md+++ b/.ai/rules/analytics.md@@ -7,3 +7,7 @@ paths:## Keep analytics reads in ActionsAnalytics dashboard and post-metric database reads live in app/Actions/Analytics alongside the existing analytics workflows. Do not introduce an app/Queries layer. Keep workspace report orchestration separate from publication and follower aggregation.++## A merged Facebook publication leaves its post on the video id+UpsertAnalyticsPublication::mergeDiscovery() merges the Page post discovery of a Facebook video or photo into the TryPost publication, which takes the Page post id while the post keeps its video or photo id. Never move the post there (reconcileRemoteId does, for TikTok and for the Instagram and TikTok ids claimedBySentPost resolves): repurpose recognises what TryPost published by comparing the source's video ids with posts.platform_post_id (PollRepurposeSource::idsPublishedByTryPost). The merge checks under its lock that the publication is available and still on the post's own id. Same-day snapshots of the two rows go through WritePublicationDailySnapshot::combine(), the same-day rule of every read. A TryPost write that finds a publication carrying its post's media id keeps what discovery reported about the Page post (UpsertAnalyticsPublication::keepsDiscovery()). Which Page post is the TryPost one is decided in ImportExternalPosts (see .ai/rules/post.md).+diff --git a/.ai/rules/post.md b/.ai/rules/post.mdindex 43fc81df7..424809514 100644--- a/.ai/rules/post.md+++ b/.ai/rules/post.md@@ -34,3 +34,6 @@ When a captionless Instagram discovery has an unresolved TryPost candidate in th## Instagram discovery can precede publish completionDiscovery can see a live Instagram post while PublishToSocialPlatform is still Publishing or Retrying after losing media_publish's response. Defer matching discoveries without assigning their IDs during that window too; Retrying requires an Instagram container checkpoint. Keep channel, content type, caption and time-window guards. Published-only matching leaves a duplicate-import race.++## A Facebook video keeps its video id on the post+TryPost saves a Facebook video or reel under its video id; discovery reports it under its Page post id with the video id in provider_metadata.video_id (a single photo can carry photo_id the same way). ImportExternalPosts merges that discovery into the post's publication through UpsertAnalyticsPublication::mergeDiscovery(): the publication takes the Page post id, the post keeps the video id, and same-day snapshots combine through WritePublicationDailySnapshot::combine(), the same-day rule of every read (a measured value wins, a lifetime count never goes down). A Page post matched only through its video_id or photo_id is the TryPost post's own only when it was published within ImportExternalPosts::OWN_PAGE_POST_WINDOW_MINUTES (120) of the post and is the one available publication of the channel carrying that media in that window (every production match was within 227 seconds); any doubt leaves it unlinked. The merge itself is described in .ai/rules/analytics.md. Never move the post to the Page post id (reconcileRemoteId does, for TikTok's video id and the Instagram and TikTok ids claimedBySentPost resolves): repurpose recognises what TryPost published by comparing the source's video ids with posts.platform_post_id (PollRepurposeSource::idsPublishedByTryPost), so a moved post would be repurposed again. analytics:merge-facebook-duplicates merges the duplicates stored before this rule (2026-11-13).diff --git a/app/Actions/Analytics/UpsertAnalyticsPublication.php b/app/Actions/Analytics/UpsertAnalyticsPublication.phpindex 01b61623b..aa5d798f6 100644--- a/app/Actions/Analytics/UpsertAnalyticsPublication.php+++ b/app/Actions/Analytics/UpsertAnalyticsPublication.php@@ -36,7 +36,10 @@ class UpsertAnalyticsPublication*/private const array METRICS_ONLY_PROVIDER_METADATA = ['thread_polls'];- public function __construct(private readonly ResolveAnalyticsAccountKey $accountKeys) {}+ public function __construct(+ private readonly ResolveAnalyticsAccountKey $accountKeys,+ private readonly WritePublicationDailySnapshot $snapshots,+ ) {}public function external(SocialAccount $account,@@ -88,75 +91,133 @@ class UpsertAnalyticsPublication);}+ /**+ * Moves a TryPost publication to the id the network reports, merging the+ * discovery already stored under it, and moves the post to that id too.+ */public function reconcileRemoteId(AnalyticsPublication $publication, string $remoteId): void{DB::transaction(function () use ($publication, $remoteId): void {- $current = AnalyticsPublication::query()->lockForUpdate()->findOrFail($publication->id);+ $current = $this->lockedToMove($publication, $remoteId);- if ($current->remote_id === $remoteId || ! $current->post_id) {+ if (blank($current)) {return;}- $discovered = AnalyticsPublication::query()- ->where('workspace_id', $current->workspace_id)- ->where('social_account_key', $current->social_account_key)- ->where('network', $current->network)- ->where('remote_id', $remoteId)- ->lockForUpdate()- ->first();-- if ($discovered) {- if ($discovered->post_id && $discovered->post_id !== $current->post_id) {- $this->deleteImportedPost($discovered->post_id);- }-- $discovered->dailySnapshots()->lockForUpdate()->reorder()->lazyById(100)->each(function (AnalyticsPublicationDailySnapshot $snapshot) use ($current): void {- $existing = $current->dailySnapshots()- ->where('date', $snapshot->date->toDateString())- ->lockForUpdate()- ->first();-- if (! $existing) {- $snapshot->update(['publication_id' => $current->id]);-- return;- }-- if ($snapshot->collected_at->greaterThan($existing->collected_at)) {- $existing->fill($snapshot->only([- 'collected_at', 'provider_observed_at', 'metrics',- 'reactions_count', 'comments_count', 'shares_count', 'saves_count',- 'views_count', 'impressions_count', 'reach_count',- 'engagement_count', 'exposure_count', 'exposure_kind',- 'watch_time_milliseconds', 'average_watch_time_milliseconds',- ]))->save();- }-- $snapshot->delete();- });-- $current->fill([- 'permalink' => $discovered->permalink ?? $current->permalink,- 'preview_metadata' => $discovered->preview_metadata ?? $current->preview_metadata,- 'provider_metadata' => self::providerMetadataAfterDiscovery($current, $discovered->provider_metadata),- 'provider_synced_at' => $discovered->provider_synced_at ?? $current->provider_synced_at,- 'excerpt' => $discovered->excerpt ?? $current->excerpt,- 'provider_published_at' => $discovered->provider_published_at ?? $current->provider_published_at,- ]);- $discovered->delete();- }-- $current->remote_id = $remoteId;- $current->save();+ transform($this->lockedDiscovery($current, $remoteId), fn (AnalyticsPublication $discovered) => $this->absorb($current, $discovered));+ $this->moveTo($current, $remoteId, $publication);Post::query()->whereKey($current->post_id)->toBase()->update(['platform_post_id' => $remoteId,'platform_url' => $current->permalink,'publication_updated_at' => now(),]);+ });+ }++ /**+ * Merges the discovery stored under `$remoteId` into a TryPost publication+ * that the network reports under another id, while the post keeps the id it+ * was published under: a Facebook video or reel is known by its video id to+ * the post (repurpose skips what TryPost published by that id) and by its+ * Page post id to discovery. Only into a publication still available and+ * on the post's own id, both checked under its lock. False when nothing+ * was merged.+ */+ public function mergeDiscovery(AnalyticsPublication $publication, string $remoteId): bool+ {+ return DB::transaction(function () use ($publication, $remoteId): bool {+ $current = $this->lockedToMove($publication, $remoteId);+ $discovered = filled($current) && $this->sitsOnItsPost($current) ? $this->lockedDiscovery($current, $remoteId) : null;++ if (blank($discovered)) {+ return false;+ }++ $this->absorb($current, $discovered);+ $current->fill([+ 'content_type' => $discovered->content_type === PublicationContentType::Unknown ? $current->content_type : $discovered->content_type,+ 'provider_content_type' => $discovered->provider_content_type ?? $current->provider_content_type,+ ]);+ $this->moveTo($current, $remoteId, $publication);++ return true;+ });+ }++ /**+ * The publication read again under its lock, or null when it already sits+ * on `$remoteId` or belongs to no post.+ */+ private function lockedToMove(AnalyticsPublication $publication, string $remoteId): ?AnalyticsPublication+ {+ $current = AnalyticsPublication::query()->lockForUpdate()->findOrFail($publication->id);++ return $current->remote_id === $remoteId || blank($current->post_id) ? null : $current;+ }++ private function sitsOnItsPost(AnalyticsPublication $current): bool+ {+ return $current->availability === PublicationAvailability::Available+ && Post::query()->whereKey($current->post_id)->value('platform_post_id') === $current->remote_id;+ }++ private function lockedDiscovery(AnalyticsPublication $current, string $remoteId): ?AnalyticsPublication+ {+ return AnalyticsPublication::query()+ ->where('workspace_id', $current->workspace_id)+ ->where('social_account_key', $current->social_account_key)+ ->where('network', $current->network)+ ->where('remote_id', $remoteId)+ ->lockForUpdate()+ ->first();+ }++ /**+ * Folds the discovery into the publication: its daily snapshots (a day both+ * hold is combined by the same-day rule), what it reported about the post,+ * and then removes it, with the post imported from it if any.+ */+ private function absorb(AnalyticsPublication $current, AnalyticsPublication $discovered): void+ {+ if (filled($discovered->post_id) && $discovered->post_id !== $current->post_id) {+ $this->deleteImportedPost($discovered->post_id);+ }++ $discovered->dailySnapshots()->lockForUpdate()->reorder()->lazyById(100)->each(function (AnalyticsPublicationDailySnapshot $snapshot) use ($current): void {+ $existing = $current->dailySnapshots()+ ->where('date', $snapshot->date->toDateString())+ ->lockForUpdate()+ ->first();- $publication->setRawAttributes($current->getAttributes(), true);+ if (blank($existing)) {+ $snapshot->update(['publication_id' => $current->id]);++ return;+ }++ $this->snapshots->combine($existing, $snapshot);+ $snapshot->delete();});++ $current->fill([+ 'permalink' => $discovered->permalink ?? $current->permalink,+ 'preview_metadata' => $discovered->preview_metadata ?? $current->preview_metadata,+ 'provider_metadata' => self::providerMetadataAfterDiscovery($current, $discovered->provider_metadata),+ 'provider_synced_at' => $discovered->provider_synced_at ?? $current->provider_synced_at,+ 'excerpt' => $discovered->excerpt ?? $current->excerpt,+ 'provider_published_at' => $discovered->provider_published_at ?? $current->provider_published_at,+ 'last_seen_at' => collect([$current->last_seen_at, $discovered->last_seen_at])->filter()->max(),+ ]);+ $discovered->delete();+ }++ private function moveTo(AnalyticsPublication $current, string $remoteId, AnalyticsPublication $publication): void+ {+ $current->remote_id = $remoteId;+ $current->save();++ $publication->setRawAttributes($current->getAttributes(), true);}private function deleteImportedPost(string $postId): void@@ -288,6 +349,7 @@ class UpsertAnalyticsPublication...$identityFields,'first_seen_at' => $now,]);+ $keepsDiscovery = self::keepsDiscovery($publication, $origin, $providerPostId);$values = ['social_account_id' => $liveAccount?->id@@ -295,20 +357,20 @@ class UpsertAnalyticsPublication'post_id' => $postId ?? $publication->post_id,'platform_user_id' => $identity->platformUserId,'platform' => $identity->platform,- 'provider_published_at' => $providerPublishedAt,+ 'provider_published_at' => $keepsDiscovery ? $publication->provider_published_at : $providerPublishedAt,'origin' => $origin === PublicationOrigin::TryPost? PublicationOrigin::TryPost: ($publication->origin ?? PublicationOrigin::External),- 'content_type' => $contentTypeReported || ! $publication->exists ? $contentType : $publication->content_type,+ 'content_type' => ($contentTypeReported || ! $publication->exists) && ! $keepsDiscovery ? $contentType : $publication->content_type,'availability' => PublicationAvailability::Available,'last_seen_at' => $now,'provider_synced_at' => $providerSyncedAt ?? $publication->provider_synced_at,];foreach ([- 'provider_content_type' => $providerContentType,- 'permalink' => $permalink,- 'excerpt' => $excerpt,+ 'provider_content_type' => $keepsDiscovery ? null : $providerContentType,+ 'permalink' => $keepsDiscovery ? null : $permalink,+ 'excerpt' => $keepsDiscovery ? null : $excerpt,'preview_metadata' => $previewMetadata,'provider_metadata' => self::providerMetadataAfterDiscovery($publication, $providerMetadata),'account_display_name' => $identity->accountDisplayName,@@ -332,6 +394,19 @@ class UpsertAnalyticsPublication});}+ /**+ * A TryPost write that found its publication under the Page post carrying+ * the post's Facebook video or photo (the post kept on its media id, the+ * publication merged under its Page post id) keeps what discovery reported+ * about that Page post: its link, time, type and text.+ */+ private static function keepsDiscovery(AnalyticsPublication $publication, PublicationOrigin $origin, string $providerPostId): bool+ {+ return $origin === PublicationOrigin::TryPost+ && $publication->remote_id !== $providerPostId+ && in_array($providerPostId, $publication->facebookMediaIds(), true);+ }+/*** The `provider_metadata` after a discovery reported `$discovered`: what it* reports replaces what was stored, so a key it no longer reports goes, whilediff --git a/app/Actions/Analytics/WritePublicationDailySnapshot.php b/app/Actions/Analytics/WritePublicationDailySnapshot.phpindex 35e8ee9c7..52c281b0a 100644--- a/app/Actions/Analytics/WritePublicationDailySnapshot.php+++ b/app/Actions/Analytics/WritePublicationDailySnapshot.php@@ -59,7 +59,9 @@ class WritePublicationDailySnapshot}}- $metrics = $this->mergeMetrics($snapshot->metrics ?? [], $observation->metrics);+ $metrics = $this->mergeMetrics($snapshot->metrics ?? [], collect($observation->metrics)+ ->mapWithKeys(fn (MetricValue $metric): array => [$metric->key->value => $metric->toArray()])+ ->all());$snapshot->fill(['collected_at' => $observation->collectedAt ?? now(),@@ -77,6 +79,35 @@ class WritePublicationDailySnapshot});}+ /**+ * Folds a same-day snapshot of another publication into `$kept` (one post+ * stored twice, being merged) by the rule every same-day read follows: the+ * newer read's metrics merged over the older one's, the columns projected+ * from the result. A snapshot stored without metrics brought nothing to+ * merge, so the other one is kept whole, as a read that brings nothing+ * keeps what is stored.+ */+ public function combine(AnalyticsPublicationDailySnapshot $kept, AnalyticsPublicationDailySnapshot $other): void+ {+ [$older, $newer] = $other->collected_at->greaterThan($kept->collected_at) ? [$kept, $other] : [$other, $kept];++ if (blank($older->metrics) || blank($newer->metrics)) {+ $whole = blank($newer->metrics) && filled($older->metrics) ? $older : $newer;+ $kept->fill($whole->only(['collected_at', 'provider_observed_at', 'metrics', ...array_keys($this->scalarProjections([]))]))->save();++ return;+ }++ $metrics = $this->mergeMetrics($older->metrics, $newer->metrics);++ $kept->fill([+ 'collected_at' => $newer->collected_at,+ 'provider_observed_at' => $newer->provider_observed_at ?? $older->provider_observed_at,+ 'metrics' => $metrics,+ ...$this->scalarProjections($metrics),+ ])->save();+ }+/*** Writes the keys the network reported over the publication's stored* `provider_metadata`, on the row read again under the lock the transaction@@ -99,27 +130,26 @@ class WritePublicationDailySnapshot* value so a partial read (one call refused) cannot undercut a fuller one.** @param array<string, array<string, mixed>> $existing- * @param list<MetricValue> $incoming+ * @param array<string, array<string, mixed>> $incoming Stored metrics (MetricValue::toArray()) keyed by their key* @return array<string, array<string, mixed>>*/private function mergeMetrics(array $existing, array $incoming): array{- foreach ($incoming as $metric) {- $key = $metric->key->value;+ foreach ($incoming as $key => $metric) {$current = data_get($existing, $key);$currentIsMeasured = data_get($current, 'availability') === MetricAvailability::Available->value&& is_numeric(data_get($current, 'value'));- $incomingIsMeasured = $metric->availability === MetricAvailability::Available- && $metric->value !== null;+ $incomingIsMeasured = data_get($metric, 'availability') === MetricAvailability::Available->value+ && is_numeric(data_get($metric, 'value'));$wouldLowerLifetimeCount = $incomingIsMeasured && $currentIsMeasured- && $metric->unit === MetricUnit::Count- && $metric->timeBasis === MetricTimeBasis::Lifetime+ && data_get($metric, 'unit') === MetricUnit::Count->value+ && data_get($metric, 'time_basis') === MetricTimeBasis::Lifetime->value&& data_get($current, 'time_basis', MetricTimeBasis::Lifetime->value) === MetricTimeBasis::Lifetime->value- && $metric->value < data_get($current, 'value');+ && data_get($metric, 'value') < data_get($current, 'value');if (($incomingIsMeasured || ! $currentIsMeasured) && ! $wouldLowerLifetimeCount) {- $existing[$key] = $metric->toArray();+ $existing[$key] = $metric;}}diff --git a/app/Actions/Post/ImportExternalPosts.php b/app/Actions/Post/ImportExternalPosts.phpindex 18a4a337c..562d37bf6 100644--- a/app/Actions/Post/ImportExternalPosts.php+++ b/app/Actions/Post/ImportExternalPosts.php@@ -21,6 +21,7 @@ use App\Support\Social\PublishCheckpoint;use App\Support\Social\ThreadProgress;use App\Support\Social\XPoll;use Carbon\CarbonImmutable;+use Carbon\CarbonInterface;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Collection;use Illuminate\Support\Facades\Cache;@@ -43,6 +44,12 @@ class ImportExternalPostsprivate const int MIN_TRUNCATED_MATCH_LENGTH = 20;+ /**+ * How far from the TryPost post a Facebook Page post carrying its video or+ * photo may be published and still be its own (production: under 4 minutes).+ */+ private const int OWN_PAGE_POST_WINDOW_MINUTES = 120;+/*** @return list<string>*/@@ -119,15 +126,15 @@ class ImportExternalPostsreturn DB::transaction(function () use ($account, $publicationId): ?string {$publication = AnalyticsPublication::query()->lockForUpdate()->find($publicationId);- if (blank($publication) || filled($publication->post_id) || filled($publication->post_dismissed_at)) {+ if (blank($publication) || ! $publication->isLinkable()) {return null;}- $existing = self::tryPostTarget($account, $publication);+ $target = self::tryPostTarget($account, $publication);- if ($existing !== null) {- if (! AnalyticsPublication::query()->where('post_id', $existing->id)->exists()) {- $publication->update(['post_id' => $existing->id]);+ if (filled($target)) {+ if (! self::linkToPost($target, $publication)) {+ self::reportUnlinkedPagePost($target, $publication);}return null;@@ -148,17 +155,136 @@ class ImportExternalPosts});}+ /**+ * Links a publication to the post TryPost published, by the linking rules of+ * the import, whatever its age (the import itself only looks at the newest+ * publications within the history retention). Returns that post, or null+ * when it is not a post TryPost published or it was left as it is.+ */+ public static function linkToTryPost(SocialAccount $account, string $publicationId): ?Post+ {+ return DB::transaction(function () use ($account, $publicationId): ?Post {+ $publication = AnalyticsPublication::query()->lockForUpdate()->find($publicationId);++ if (blank($publication) || ! $publication->isLinkable()) {+ return null;+ }++ $target = self::tryPostTarget($account, $publication);++ return filled($target) && self::linkToPost($target, $publication) ? $target : null;+ });+ }++ /**+ * A Page post carrying a TryPost post's media, published within its window,+ * that was not taken for the post's own (another Page post there shares the+ * media, or the tracked publication could not take the merge): left out of+ * the import, reported once a day. A Page post sharing the media later is+ * expected and not reported.+ */+ private static function reportUnlinkedPagePost(Post $post, AnalyticsPublication $publication): void+ {+ $ambiguous = $post->platform_post_id !== $publication->remote_id+ && $publication->provider_published_at->between(...self::ownPagePostWindow($post));++ if (! $ambiguous || ! Cache::add("import-external-posts:unlinked-page-post:{$publication->id}", true, now()->addDay())) {+ return;+ }++ Log::warning('Facebook Page post carrying a TryPost media was left unlinked.', [+ 'analytics_publication_id' => $publication->id,+ 'post_id' => $post->id,+ ]);+ }++ /**+ * A publication of a post TryPost published is linked to it. One matched+ * only through the Facebook video or photo it carries is linked only when it+ * is that post's own Page post (isOwnPagePost). When a Facebook post is+ * already tracked under its own id, the publication is merged into the+ * tracked one, so Insights counts the post once. Any other network keeps+ * the tracked publication.+ */+ private static function linkToPost(Post $post, AnalyticsPublication $publication): bool+ {+ if ($post->platform_post_id !== $publication->remote_id && ! self::isOwnPagePost($post, $publication)) {+ return false;+ }++ if (blank($post->analyticsPublication)) {+ $publication->update(['post_id' => $post->id]);++ return true;+ }++ return $post->platform === Platform::Facebook+ && app(UpsertAnalyticsPublication::class)->mergeDiscovery($post->analyticsPublication, $publication->remote_id);+ }++ /**+ * The Page post TryPost created when it published a Facebook video or photo:+ * published within OWN_PAGE_POST_WINDOW_MINUTES of the post, and the only+ * available publication of the channel carrying that media in that window+ * (a Page post deleted on the network no longer counts). Any doubt leaves+ * it unlinked; a Page post sharing the media later stays one of its own.+ */+ private static function isOwnPagePost(Post $post, AnalyticsPublication $publication): bool+ {+ $mediaIds = $publication->facebookMediaIds();++ if (blank($mediaIds)) {+ return false;+ }++ $window = self::ownPagePostWindow($post);++ if (! $publication->provider_published_at->between(...$window)) {+ return false;+ }++ return AnalyticsPublication::query()+ ->available()+ ->where('social_account_id', $publication->social_account_id)+ ->whereBetween('provider_published_at', $window)+ ->carryingFacebookMedia($mediaIds)+ ->count() === 1;+ }++ /**+ * The times a TryPost post's own Page post may carry: OWN_PAGE_POST_WINDOW_MINUTES+ * around its publication, placed as tryPost() places it.+ *+ * @return array{0: CarbonInterface, 1: CarbonInterface}+ */+ private static function ownPagePostWindow(Post $post): array+ {+ $publishedAt = $post->published_at ?? $post->publication_updated_at ?? $post->updated_at;++ return [+ $publishedAt->subMinutes(self::OWN_PAGE_POST_WINDOW_MINUTES),+ $publishedAt->addMinutes(self::OWN_PAGE_POST_WINDOW_MINUTES),+ ];+ }++ /**+ * The post TryPost published under the publication's own id, else under the+ * Facebook video or photo it carries.+ */private static function tryPostTarget(SocialAccount $account, AnalyticsPublication $publication): ?Post{- $remoteIds = collect([- $publication->remote_id,- $account->platform === Platform::Facebook ? data_get($publication->provider_metadata, 'video_id') : null,- $account->platform === Platform::Facebook ? data_get($publication->provider_metadata, 'photo_id') : null,- ])->filter(fn (mixed $id): bool => is_string($id) && filled($id))->values()->all();+ return self::postPublishedUnder($account, [$publication->remote_id])+ ?? self::postPublishedUnder($account, $publication->facebookMediaIds());+ }- return Post::query()+ /**+ * @param list<string> $ids+ */+ private static function postPublishedUnder(SocialAccount $account, array $ids): ?Post+ {+ return blank($ids) ? null : Post::query()->where('social_account_id', $account->id)- ->whereIn('platform_post_id', $remoteIds)+ ->whereIn('platform_post_id', $ids)->where('workspace_id', $account->workspace_id)->first();}diff --git a/app/Console/Commands/Scripts/MergeFacebookDuplicatePublicationsCommand.php b/app/Console/Commands/Scripts/MergeFacebookDuplicatePublicationsCommand.phpnew file mode 100644index 000000000..821922ca5--- /dev/null+++ b/app/Console/Commands/Scripts/MergeFacebookDuplicatePublicationsCommand.php@@ -0,0 +1,102 @@+<?php++declare(strict_types=1);++namespace App\Console\Commands\Scripts;++use App\Actions\Post\ImportExternalPosts;+use App\Enums\SocialAccount\Platform;+use App\Models\AnalyticsPublication;+use App\Models\Post;+use App\Models\SocialAccount;+use Closure;+use Illuminate\Console\Attributes\Description;+use Illuminate\Console\Attributes\Signature;+use Illuminate\Console\Command;+use Illuminate\Console\ConfirmableTrait;+use Illuminate\Support\Collection;+use Illuminate\Support\Facades\DB;+use Throwable;++#[Signature('analytics:merge-facebook-duplicates+ {--force : Run without confirmation in production}+ {--dry-run : Count the duplicates without changing anything}')]+#[Description('Link each Facebook Page post carrying a TryPost video or photo to its TryPost post, merging the duplicate, over the whole history')]+class MergeFacebookDuplicatePublicationsCommand extends Command+{+ use ConfirmableTrait;++ public function handle(): int+ {+ $dryRun = (bool) $this->option('dry-run');++ if (! $dryRun && ! $this->confirmToProceed()) {+ return self::FAILURE;+ }++ $linked = new Collection;+ $failed = 0;+ $verb = $dryRun ? 'Would link' : 'Linked';++ AnalyticsPublication::query()+ ->linkable()+ ->where('platform', Platform::Facebook)+ ->carryingAnyFacebookMedia()+ ->with('socialAccount')+ ->lazyById()+ ->each(function (AnalyticsPublication $publication) use ($dryRun, $linked, &$failed): void {+ try {+ $post = $dryRun+ ? $this->withoutWriting(fn (): ?Post => $this->link($publication))+ : $this->link($publication);+ } catch (Throwable $exception) {+ report($exception);+ $failed++;++ return;+ }++ if (filled($post)) {+ $linked->push($post->content_type->value);+ }+ });++ $this->table(+ ['TryPost post type', $verb],+ $linked->countBy()->sortKeys()->map(fn (int $count, string $type): array => [$type, $count])->values()->all(),+ );+ $this->info("{$verb} {$linked->count()} publication(s) to their TryPost post.");++ if ($failed > 0) {+ $this->error("{$failed} publication(s) failed and were reported; run the command again once fixed.");++ return self::FAILURE;+ }++ return self::SUCCESS;+ }++ private function link(AnalyticsPublication $publication): ?Post+ {+ return transform($publication->socialAccount, fn (SocialAccount $account): ?Post => ImportExternalPosts::linkToTryPost($account, $publication->id));+ }++ /**+ * Runs the real link and undoes it, so a dry run counts exactly what a run+ * would link. The link only writes rows of the database: these+ * publications have no post, so no imported post or media is deleted, and+ * nothing is queued.+ *+ * @param Closure(): ?Post $link+ */+ private function withoutWriting(Closure $link): ?Post+ {+ DB::beginTransaction();++ try {+ return $link();+ } finally {+ DB::rollBack();+ }+ }+}diff --git a/app/Enums/Analytics/FacebookMediaKey.php b/app/Enums/Analytics/FacebookMediaKey.phpnew file mode 100644index 000000000..4ab2c1283--- /dev/null+++ b/app/Enums/Analytics/FacebookMediaKey.php@@ -0,0 +1,15 @@+<?php++declare(strict_types=1);++namespace App\Enums\Analytics;++/**+ * The `provider_metadata` keys under which Facebook discovery stores the video+ * or photo a Page post carries, which TryPost may have saved as the post's id.+ */+enum FacebookMediaKey: string+{+ case Video = 'video_id';+ case Photo = 'photo_id';+}diff --git a/app/Models/AnalyticsPublication.php b/app/Models/AnalyticsPublication.phpindex d0ac3b401..688ce2a18 100644--- a/app/Models/AnalyticsPublication.php+++ b/app/Models/AnalyticsPublication.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace App\Models;+use App\Enums\Analytics\FacebookMediaKey;use App\Enums\Analytics\PublicationAvailability;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\PublicationOrigin;@@ -91,4 +92,66 @@ class AnalyticsPublication extends Model{return $query->where('availability', PublicationAvailability::Available);}++ /**+ * Available, linked to no post and not dismissed: what the import may link+ * or turn into a post.+ */+ public function scopeLinkable(Builder $query): Builder+ {+ return $query->available()->whereNull('post_id')->whereNull('post_dismissed_at');+ }++ /**+ * Carrying one of `$mediaIds` as its Facebook video or photo; an empty list+ * matches nothing.+ *+ * @param list<string> $mediaIds+ */+ public function scopeCarryingFacebookMedia(Builder $query, array $mediaIds): Builder+ {+ return $query->where(function (Builder $carrying) use ($mediaIds): void {+ foreach (FacebookMediaKey::cases() as $key) {+ $carrying->orWhereIn("provider_metadata->{$key->value}", $mediaIds);+ }+ });+ }++ /**+ * Carrying a Facebook video or photo, whichever.+ */+ public function scopeCarryingAnyFacebookMedia(Builder $query): Builder+ {+ return $query->where(function (Builder $carrying): void {+ foreach (FacebookMediaKey::cases() as $key) {+ $carrying->orWhereNotNull("provider_metadata->{$key->value}");+ }+ });+ }++ /**+ * The Facebook video or photo this publication carries, which TryPost may+ * have saved as its post's id.+ *+ * @return list<string>+ */+ public function facebookMediaIds(): array+ {+ if ($this->platform !== Platform::Facebook) {+ return [];+ }++ return collect(FacebookMediaKey::cases())+ ->map(fn (FacebookMediaKey $key): mixed => data_get($this->provider_metadata, $key->value))+ ->filter(fn (mixed $id): bool => is_string($id) && filled($id))+ ->values()+ ->all();+ }++ public function isLinkable(): bool+ {+ return $this->availability === PublicationAvailability::Available+ && blank($this->post_id)+ && blank($this->post_dismissed_at);+ }}diff --git a/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php b/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.phpindex c989bd3a4..5bdc37e57 100644--- a/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php+++ b/app/Services/Analytics/Collectors/Metrics/FacebookPublicationMetricsCollector.php@@ -5,6 +5,7 @@ declare(strict_types=1);namespace App\Services\Analytics\Collectors\Metrics;use App\Dto\Analytics\PublicationMetricObservation;+use App\Enums\Analytics\FacebookMediaKey;use App\Enums\Analytics\MetricKey;use App\Enums\Analytics\PublicationContentType;use App\Exceptions\Analytics\AnalyticsCollectionException;@@ -68,7 +69,7 @@ class FacebookPublicationMetricsCollector extends AbstractMetaPublicationMetricsAnalyticsCollectionException::unlessGranted($account, 'pages_read_engagement');$graph = $account->platform->graphApiUrl();$isStory = $publication->content_type === PublicationContentType::Story;- $videoId = data_get($publication->provider_metadata, 'video_id');+ $videoId = data_get($publication->provider_metadata, FacebookMediaKey::Video->value);$isVideo = ! $isStory && (filled($videoId) || $this->isReadByVideoId($publication));$insightsId = $isVideo && filled($videoId) ? $videoId : $publication->remote_id;$edge = $isVideo ? 'video_insights' : 'insights';diff --git a/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.php b/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.phpindex 6c8fa70ef..fab1e6594 100644--- a/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.php+++ b/app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.php@@ -6,6 +6,7 @@ namespace App\Services\Analytics\Collectors\Publications;use App\Dto\Analytics\DiscoveredPublication;use App\Dto\Analytics\PublicationPage;+use App\Enums\Analytics\FacebookMediaKey;use App\Enums\Analytics\PublicationContentType;use App\Models\SocialAccount;use Carbon\CarbonImmutable;@@ -72,8 +73,8 @@ class FacebookPublicationCollector extends AbstractMetaPublicationCollectorexcerpt: data_get($row, 'message'),previewMetadata: $this->preview($previewUrl),providerMetadata: match (true) {- filled($videoId) => ['video_id' => (string) $videoId],- filled($photoId) => ['photo_id' => (string) $photoId],+ filled($videoId) => [FacebookMediaKey::Video->value => (string) $videoId],+ filled($photoId) => [FacebookMediaKey::Photo->value => (string) $photoId],default => null,},);diff --git a/tests/Feature/Analytics/MergeFacebookDuplicatePublicationsTest.php b/tests/Feature/Analytics/MergeFacebookDuplicatePublicationsTest.phpnew file mode 100644index 000000000..6e5f73d6c--- /dev/null+++ b/tests/Feature/Analytics/MergeFacebookDuplicatePublicationsTest.php@@ -0,0 +1,122 @@+<?php++declare(strict_types=1);++use App\Enums\Analytics\PublicationAvailability;+use App\Enums\Analytics\PublicationContentType;+use App\Enums\Analytics\PublicationOrigin;+use App\Models\AnalyticsPublication;+use App\Models\AnalyticsPublicationDailySnapshot;+use App\Models\Post;+use App\Models\SocialAccount;+use Illuminate\Support\Facades\Queue;++function facebookPublication(SocialAccount $account, array $attributes = []): AnalyticsPublication+{+ return 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,+ 'content_type' => PublicationContentType::Reel,+ 'provider_published_at' => now()->subMinute(),+ ...$attributes,+ ]);+}++/**+ * @return array{0: SocialAccount, 1: Post, 2: AnalyticsPublication, 3: AnalyticsPublication}+ */+function facebookReelCountedTwice(string $alias = 'video_id'): array+{+ $account = SocialAccount::factory()->facebook()->create();+ $post = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'media-9']);+ $tracked = facebookPublication($account, ['remote_id' => 'media-9', 'post_id' => $post->id, 'origin' => PublicationOrigin::TryPost]);+ $discovered = facebookPublication($account, [+ 'remote_id' => 'page_post-1',+ 'provider_metadata' => [$alias => 'media-9'],+ 'preview_metadata' => ['thumbnail_url' => 'https://scontent.xx.fbcdn.net/expired.jpg'],+ ]);+ AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $discovered->id, 'comments_count' => 2]);++ return [$account, $post, $tracked, $discovered];+}++test('a dry run counts the duplicates and changes nothing', function () {+ [, $post, $tracked, $discovered] = facebookReelCountedTwice();++ $this->artisan('analytics:merge-facebook-duplicates', ['--dry-run' => true])+ ->expectsOutputToContain('Would link 1 publication(s) to their TryPost post.')+ ->assertSuccessful();++ expect($discovered->fresh())->not->toBeNull()+ ->and($tracked->fresh()->remote_id)->toBe('media-9')+ ->and($post->fresh()->platform_post_id)->toBe('media-9');+});++test('a facebook post counted twice is merged into its trypost publication without queueing anything', function (string $alias) {+ [$account, $post, $tracked, $discovered] = facebookReelCountedTwice($alias);+ Queue::fake();++ $this->artisan('analytics:merge-facebook-duplicates', ['--force' => true])+ ->expectsOutputToContain('Linked 1 publication(s) to their TryPost post.')+ ->assertSuccessful();++ expect($discovered->fresh())->toBeNull()+ ->and(AnalyticsPublication::query()->where('social_account_id', $account->id)->sole()->id)->toBe($tracked->id)+ ->and($tracked->fresh()->remote_id)->toBe('page_post-1')+ ->and($tracked->fresh()->provider_metadata)->toEqual([$alias => 'media-9'])+ ->and($tracked->dailySnapshots()->sole()->comments_count)->toBe(2)+ ->and($post->fresh()->platform_post_id)->toBe('media-9');+ Queue::assertNothingPushed();+})->with(['a video or reel' => 'video_id', 'a single photo' => 'photo_id']);++test('a facebook reel published outside trypost is left alone', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $external = facebookPublication($account, ['remote_id' => 'page_post-2', 'provider_metadata' => ['video_id' => 'video-other']]);++ $this->artisan('analytics:merge-facebook-duplicates', ['--force' => true])+ ->expectsOutputToContain('Linked 0 publication(s) to their TryPost post.')+ ->assertSuccessful();++ expect($external->fresh()->post_id)->toBeNull();+});++test('a dry run counts exactly what a run links', function () {+ [$account, , $tracked] = facebookReelCountedTwice();+ $other = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'media-10']);+ facebookPublication($account, ['remote_id' => 'page_post-2', 'provider_metadata' => ['video_id' => 'media-10']]);+ facebookPublication($account, ['remote_id' => 'page_post-3', 'provider_metadata' => ['video_id' => 'media-10']]);++ $this->artisan('analytics:merge-facebook-duplicates', ['--dry-run' => true])+ ->expectsOutputToContain('Would link 1 publication(s) to their TryPost post.')+ ->assertSuccessful();++ expect($tracked->fresh()->remote_id)->toBe('media-9')+ ->and(AnalyticsPublication::query()->where('social_account_id', $account->id)->count())->toBe(4);++ $this->artisan('analytics:merge-facebook-duplicates', ['--force' => true])+ ->expectsOutputToContain('Linked 1 publication(s) to their TryPost post.')+ ->assertSuccessful();++ expect($tracked->fresh()->remote_id)->toBe('page_post-1')+ ->and(AnalyticsPublication::query()->whereNotNull('post_id')->whereKeyNot($tracked->id)->exists())->toBeFalse()+ ->and($other->fresh()->platform_post_id)->toBe('media-10');+});++test('a dismissed or deleted publication is left alone, as the import leaves it', function (array $state) {+ [, , $tracked, $discovered] = facebookReelCountedTwice();+ $discovered->forceFill($state)->save();++ $this->artisan('analytics:merge-facebook-duplicates', ['--force' => true])+ ->expectsOutputToContain('Linked 0 publication(s) to their TryPost post.')+ ->assertSuccessful();++ expect($discovered->fresh())->not->toBeNull()+ ->and($tracked->fresh()->remote_id)->toBe('media-9');+})->with([+ 'dismissed' => [['post_dismissed_at' => now()]],+ 'deleted on the network' => [['availability' => PublicationAvailability::Deleted]],+]);diff --git a/tests/Feature/Analytics/PublicationReconciliationTest.php b/tests/Feature/Analytics/PublicationReconciliationTest.phpindex 203422f52..573a0df75 100644--- a/tests/Feature/Analytics/PublicationReconciliationTest.php+++ b/tests/Feature/Analytics/PublicationReconciliationTest.php@@ -6,6 +6,14 @@ use App\Actions\Analytics\SyncTryPostPublication;use App\Actions\Analytics\UpsertAnalyticsPublication;use App\Actions\Post\ImportExternalPosts;use App\Dto\Analytics\DiscoveredPublication;+use App\Dto\Analytics\MetricValue;+use App\Enums\Analytics\ExposureKind;+use App\Enums\Analytics\MetricAvailability;+use App\Enums\Analytics\MetricKey;+use App\Enums\Analytics\MetricPrecision;+use App\Enums\Analytics\MetricTimeBasis;+use App\Enums\Analytics\MetricUnit;+use App\Enums\Analytics\PublicationAvailability;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\PublicationOrigin;use App\Enums\Post\PublishStatus as Status;@@ -23,6 +31,7 @@ use Carbon\CarbonImmutable;use Illuminate\Database\QueryException;use Illuminate\Support\Facades\Event;use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Str;beforeEach(function () {Queue::fake();@@ -72,22 +81,25 @@ test('TikTok public video id merges a provisional TryPost post with earlier disc'platform_post_id' => 'v_pub_provisional',]);$provisional = app(SyncTryPostPublication::class)->handle($post);+ $publishedAt = now('UTC')->subDays(2)->startOfHour()->toImmutable();$discovered = app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(providerPostId: '123456789',- publishedAt: CarbonImmutable::parse('2026-09-20 12:00:00', 'UTC'),+ publishedAt: $publishedAt,contentType: PublicationContentType::Video,permalink: 'https://www.tiktok.com/@example/video/123456789',));AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $provisional->id,- 'date' => '2026-09-21',- 'collected_at' => '2026-09-21 10:00:00',+ 'date' => $publishedAt->addDay()->toDateString(),+ 'collected_at' => $publishedAt->addDay()->setTime(10, 0),+ 'metrics' => storedMetrics(['views' => 5]),'views_count' => 5,]);AnalyticsPublicationDailySnapshot::factory()->create(['publication_id' => $discovered->id,- 'date' => '2026-09-21',- 'collected_at' => '2026-09-21 12:00:00',+ 'date' => $publishedAt->addDay()->toDateString(),+ 'collected_at' => $publishedAt->addDay()->setTime(12, 0),+ 'metrics' => storedMetrics(['views' => 12]),'views_count' => 12,]);@@ -102,7 +114,7 @@ test('TikTok public video id merges a provisional TryPost post with earlier discapp(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(providerPostId: '123456789',- publishedAt: CarbonImmutable::parse('2026-09-20 12:00:00', 'UTC'),+ publishedAt: $publishedAt,contentType: PublicationContentType::Video,));expect(AnalyticsPublication::query()->count())->toBe(1);@@ -334,3 +346,195 @@ test('a network that reports the type still corrects the type TryPost published'expect(AnalyticsPublication::sole()->content_type)->toBe(PublicationContentType::Reel);});++/**+ * @param array<string, int|null> $counts+ * @return array<string, array<string, mixed>>+ */+function storedMetrics(array $counts): array+{+ return collect($counts)->mapWithKeys(fn (?int $value, string $key): array => [$key => (new MetricValue(+ key: MetricKey::from($key),+ value: $value,+ unit: MetricUnit::Count,+ timeBasis: MetricTimeBasis::Lifetime,+ precision: MetricPrecision::Exact,+ availability: filled($value) ? MetricAvailability::Available : MetricAvailability::Unavailable,+ ))->toArray()])->all();+}++/**+ * @param array<string, int|null> $trackedCounts+ * @param array<string, int|null> $discoveredCounts+ * @return array{0: AnalyticsPublication, 1: Post}+ */+function facebookVideoReadTwiceOnOneDay(array $trackedCounts, array $discoveredCounts, int $discoveredHoursLater): array+{+ $account = SocialAccount::factory()->facebook()->create();+ $post = Post::factory()->forAccount($account, ContentType::FacebookReel)->published()->create(['platform_post_id' => 'video-9']);+ $tracked = app(SyncTryPostPublication::class)->handle($post);+ $discovered = app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(+ providerPostId: 'page_post-1',+ publishedAt: now()->subDay()->toImmutable(),+ contentType: PublicationContentType::Reel,+ providerMetadata: ['video_id' => 'video-9'],+ ));+ $collectedAt = now()->subHours(3);+ AnalyticsPublicationDailySnapshot::factory()->create([+ 'publication_id' => $tracked->id,+ 'date' => $collectedAt->toDateString(),+ 'collected_at' => $collectedAt->addHour(),+ 'metrics' => storedMetrics($trackedCounts),+ ]);+ AnalyticsPublicationDailySnapshot::factory()->create([+ 'publication_id' => $discovered->id,+ 'date' => $collectedAt->toDateString(),+ 'collected_at' => $collectedAt->addHour()->addHours($discoveredHoursLater),+ 'metrics' => storedMetrics($discoveredCounts),+ ]);++ return [$tracked, $post];+}++test('merging two reads of the same day follows the same-day rule of every read', function (array $tracked, array $discovered, int $discoveredHoursLater, array $expected) {+ [$publication, $post] = facebookVideoReadTwiceOnOneDay($tracked, $discovered, $discoveredHoursLater);++ expect(app(UpsertAnalyticsPublication::class)->mergeDiscovery($publication, 'page_post-1'))->toBeTrue();++ $snapshot = $publication->dailySnapshots()->sole();++ expect($snapshot->only(array_keys($expected)))->toEqual($expected)+ ->and($publication->fresh()->remote_id)->toBe('page_post-1')+ ->and($post->fresh()->platform_post_id)->toBe('video-9');+})->with([+ 'the older read measured comments the newer did not' => [+ ['views' => 52, 'comments' => null], ['views' => 50, 'comments' => 3], -1,+ ['views_count' => 52, 'comments_count' => 3],+ ],+ 'a newer read never lowers a lifetime count' => [+ ['reactions' => 12, 'comments' => 3], ['reactions' => 5, 'comments' => null], 1,+ ['reactions_count' => 12, 'comments_count' => 3],+ ],+ 'a newer read raises a lifetime count' => [+ ['views' => 50], ['views' => 58], 1,+ ['views_count' => 58],+ ],+ 'engagement and exposure come from the merged metrics' => [+ ['views' => 52, 'engagements' => 5], ['reach' => 40, 'engagements' => 16], -1,+ ['engagement_count' => 16, 'exposure_count' => 40, 'exposure_kind' => ExposureKind::Reach],+ ],+]);++test('a stored metric that is not a measured value never replaces one, and is kept where nothing else is', function () {+ [$publication] = facebookVideoReadTwiceOnOneDay(['views' => 52], ['views' => 50], 1);+ $legacy = ['value' => 7, 'unit' => 'count', 'time_basis' => 'lifetime', 'precision' => 'exact', 'availability' => 'available'];+ $discoveredSnapshot = AnalyticsPublicationDailySnapshot::query()->whereNot('publication_id', $publication->id)->sole();+ $discoveredSnapshot->forceFill(['metrics' => [...$discoveredSnapshot->metrics, 'a_retired_metric' => $legacy, 'views' => ['value' => 'many']]])->save();++ expect(app(UpsertAnalyticsPublication::class)->mergeDiscovery($publication, 'page_post-1'))->toBeTrue();++ $metrics = $publication->dailySnapshots()->sole()->metrics;++ expect(data_get($metrics, 'a_retired_metric'))->toEqual($legacy)+ ->and(data_get($metrics, 'views.value'))->toBe(52);+});++test('a merge read from a publication that has moved since does nothing', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $post = Post::factory()->forAccount($account, ContentType::FacebookReel)->published()->create(['platform_post_id' => 'video-9']);+ $stale = app(SyncTryPostPublication::class)->handle($post);+ $discovery = fn (string $id): AnalyticsPublication => app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(+ providerPostId: $id,+ publishedAt: now()->subDay()->toImmutable(),+ contentType: PublicationContentType::Reel,+ providerMetadata: ['video_id' => 'video-9'],+ ));+ $discovery('page_post-1');+ $second = $discovery('page_post-2');++ expect(app(UpsertAnalyticsPublication::class)->mergeDiscovery($stale->replicate()->setRawAttributes($stale->getAttributes()), 'page_post-1'))->toBeTrue()+ ->and(app(UpsertAnalyticsPublication::class)->mergeDiscovery($stale, 'page_post-2'))->toBeFalse()+ ->and($stale->fresh()->remote_id)->toBe('page_post-1')+ ->and($second->fresh())->not->toBeNull();+});++test('a snapshot stored without metrics brings nothing to the merge', function (bool $newerHasMetrics) {+ [$publication] = facebookVideoReadTwiceOnOneDay(['views' => 52, 'comments' => 3], ['views' => 50], 1);+ $withoutMetrics = $newerHasMetrics ? $publication->id : null;+ AnalyticsPublicationDailySnapshot::query()+ ->when($withoutMetrics, fn ($query) => $query->where('publication_id', $withoutMetrics), fn ($query) => $query->whereNot('publication_id', $publication->id))+ ->update(['metrics' => null]);++ app(UpsertAnalyticsPublication::class)->mergeDiscovery($publication, 'page_post-1');++ $snapshot = $publication->dailySnapshots()->sole();++ expect(data_get($snapshot->metrics, 'views.value'))->toBe($newerHasMetrics ? 50 : 52)+ ->and(data_get($snapshot->metrics, 'comments.value'))->toBe($newerHasMetrics ? null : 3);+})->with(['the older one has none' => true, 'the newer one has none' => false]);++test('a merge of two snapshots stored without metrics keeps the newer one', function () {+ [$publication] = facebookVideoReadTwiceOnOneDay(['views' => 52], ['views' => 50], 1);+ AnalyticsPublicationDailySnapshot::query()->update(['metrics' => null]);+ $newer = AnalyticsPublicationDailySnapshot::query()->whereNot('publication_id', $publication->id)->sole()->collected_at;++ app(UpsertAnalyticsPublication::class)->mergeDiscovery($publication, 'page_post-1');++ expect($publication->dailySnapshots()->sole()->collected_at->toIso8601String())->toBe($newer->toIso8601String());+});++test('carrying facebook media matches only the ids given', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $carrying = AnalyticsPublication::factory()->create(['social_account_id' => $account->id, 'platform' => Platform::Facebook, 'provider_metadata' => ['video_id' => 'video-9']]);+ AnalyticsPublication::factory()->create(['social_account_id' => $account->id, 'platform' => Platform::Facebook, 'provider_metadata' => ['photo_id' => 'photo-3']]);++ expect(AnalyticsPublication::query()->carryingFacebookMedia(['video-9'])->pluck('id')->all())->toBe([$carrying->id])+ ->and(AnalyticsPublication::query()->carryingFacebookMedia([])->exists())->toBeFalse()+ ->and(AnalyticsPublication::query()->carryingAnyFacebookMedia()->count())->toBe(2);+});++test('a merged publication keeps the latest time discovery saw the post', function () {+ [$publication] = facebookVideoReadTwiceOnOneDay(['views' => 52], ['views' => 50], 1);+ $seenAt = now()->subMinutes(5)->startOfSecond();+ $publication->forceFill(['last_seen_at' => now()->subDays(3)])->save();+ AnalyticsPublication::query()->whereKeyNot($publication->id)->update(['last_seen_at' => $seenAt]);++ app(UpsertAnalyticsPublication::class)->mergeDiscovery($publication, 'page_post-1');++ expect($publication->fresh()->last_seen_at->toIso8601String())->toBe($seenAt->toIso8601String());+});++test('a merge into a publication marked deleted since it was read does nothing', function () {+ [$publication] = facebookVideoReadTwiceOnOneDay(['views' => 52], ['views' => 50], 1);+ AnalyticsPublication::query()->whereKey($publication->id)->update(['availability' => PublicationAvailability::Deleted]);++ expect(app(UpsertAnalyticsPublication::class)->mergeDiscovery($publication, 'page_post-1'))->toBeFalse()+ ->and($publication->fresh()->remote_id)->toBe('video-9')+ ->and(AnalyticsPublication::query()->where('remote_id', 'page_post-1')->exists())->toBeTrue();+});++test('a discovery under another analytics key is not merged and the publication keeps its id', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $post = Post::factory()->forAccount($account, ContentType::FacebookReel)->published()->create(['platform_post_id' => 'video-9']);+ $tracked = app(SyncTryPostPublication::class)->handle($post);+ $discovered = app(UpsertAnalyticsPublication::class)->external($account, new DiscoveredPublication(+ providerPostId: 'page_post-1',+ publishedAt: now()->subDay()->toImmutable(),+ contentType: PublicationContentType::Reel,+ providerMetadata: ['video_id' => 'video-9'],+ ));+ $discovered->forceFill(['social_account_key' => (string) Str::uuid7()])->save();++ expect(app(UpsertAnalyticsPublication::class)->mergeDiscovery($tracked, 'page_post-1'))->toBeFalse()+ ->and($tracked->fresh()->remote_id)->toBe('video-9')+ ->and($discovered->fresh())->not->toBeNull();++ ImportExternalPosts::execute($account);++ expect(Post::query()->imported()->exists())->toBeFalse()+ ->and($discovered->fresh()->post_id)->toBeNull();++ $this->artisan('analytics:merge-facebook-duplicates', ['--force' => true])+ ->expectsOutputToContain('Linked 0 publication(s) to their TryPost post.')+ ->assertSuccessful();+});diff --git a/tests/Feature/Posts/ImportExternalPostsTest.php b/tests/Feature/Posts/ImportExternalPostsTest.phpindex 18e98ca5b..2cf974f76 100644--- a/tests/Feature/Posts/ImportExternalPostsTest.php+++ b/tests/Feature/Posts/ImportExternalPostsTest.php@@ -2,8 +2,11 @@declare(strict_types=1);+use App\Actions\Analytics\SyncTryPostPublication as SyncTryPostPublicationAction;use App\Actions\Analytics\UpsertAnalyticsPublication;use App\Actions\Post\ImportExternalPosts;+use App\Dto\Analytics\DiscoveredPublication;+use App\Enums\Analytics\PublicationAvailability;use App\Enums\Analytics\PublicationContentType;use App\Enums\Analytics\PublicationOrigin;use App\Enums\Post\Origin;@@ -17,6 +20,7 @@ use App\Jobs\Analytics\BootstrapAccountAnalytics;use App\Jobs\Analytics\CollectAccountDailySnapshot;use App\Jobs\Analytics\SyncTryPostPublication;use App\Models\AnalyticsPublication;+use App\Models\AnalyticsPublicationDailySnapshot;use App\Models\Post;use App\Models\SocialAccount;use App\Services\Analytics\Collectors\Publications\FacebookPublicationCollector;@@ -193,6 +197,7 @@ test('a facebook post links the trypost video it carries by video id', function]);$publication = externalPublication($account, ['remote_id' => 'page_post-1',+ 'provider_published_at' => now()->subMinute(),'provider_metadata' => ['video_id' => 'video-9'],]);@@ -202,21 +207,313 @@ test('a facebook post links the trypost video it carries by video id', function->and($publication->fresh()->post_id)->toBe($tryPost->id);});-test('a facebook video already tracked by its trypost publication is left unlinked', function () {+test('turning text matching off keeps linking a facebook post by the media it carries', function () {+ config()->set('trypost.external_posts.match_window_minutes', 0);+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $publication = externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($publication->fresh()->post_id)->toBe($tryPost->id);+});++test('a facebook video already tracked by its trypost publication is merged into it', function () {$account = SocialAccount::factory()->facebook()->create();$tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9',]);- externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id]);+ $tracked = externalPublication($account, [+ 'remote_id' => 'video-9',+ 'post_id' => $tryPost->id,+ 'origin' => PublicationOrigin::TryPost,+ 'content_type' => PublicationContentType::Video,+ ]);$external = externalPublication($account, ['remote_id' => 'page_post-1',+ 'provider_published_at' => now()->subMinute(),+ 'permalink' => 'https://www.facebook.com/reel/video-9',+ 'content_type' => PublicationContentType::Reel,'provider_metadata' => ['video_id' => 'video-9'],]);+ AnalyticsPublicationDailySnapshot::factory()->create([+ 'publication_id' => $tracked->id,+ 'date' => today()->subDay(),+ 'views_count' => 200,+ ]);+ AnalyticsPublicationDailySnapshot::factory()->create([+ 'publication_id' => $external->id,+ 'date' => today(),+ 'views_count' => 234,+ 'comments_count' => 0,+ ]);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($external->fresh())->toBeNull()+ ->and(AnalyticsPublication::query()->where('social_account_id', $account->id)->count())->toBe(1);++ $merged = $tracked->fresh();++ expect($merged->remote_id)->toBe('page_post-1')+ ->and($merged->content_type)->toBe(PublicationContentType::Reel)+ ->and($merged->post_id)->toBe($tryPost->id)+ ->and($merged->provider_metadata)->toEqual(['video_id' => 'video-9'])+ ->and($merged->dailySnapshots()->orderBy('date')->pluck('views_count')->all())->toBe([200, 234])+ ->and($tryPost->fresh()->platform_post_id)->toBe('video-9');+});++test('a merge keeps the trypost type when discovery could not tell it', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $tracked = externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost, 'content_type' => PublicationContentType::Reel]);+ externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinute(), 'content_type' => PublicationContentType::Unknown, 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($tracked->fresh()->remote_id)->toBe('page_post-1')+ ->and($tracked->fresh()->content_type)->toBe(PublicationContentType::Reel);+});++test('a merged facebook video stays one publication when it syncs and is discovered again', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create([+ 'platform_post_id' => 'video-9',+ 'content' => 'The caption written in TryPost',+ ]);+ $tracked = app(SyncTryPostPublicationAction::class)->handle($tryPost);+ $discovered = new DiscoveredPublication(+ providerPostId: 'page_post-1',+ publishedAt: now()->subHour()->toImmutable(),+ contentType: PublicationContentType::Reel,+ providerContentType: 'video_inline',+ permalink: 'https://www.facebook.com/reel/video-9/',+ excerpt: 'The caption on the Page',+ previewMetadata: null,+ providerMetadata: ['video_id' => 'video-9'],+ );+ app(UpsertAnalyticsPublication::class)->external($account, $discovered);+ ImportExternalPosts::execute($account);+ app(UpsertAnalyticsPublication::class)->external($account, $discovered);+ app(SyncTryPostPublicationAction::class)->handle($tryPost->fresh());ImportExternalPosts::execute($account);- expect(Post::query()->imported()->count())->toBe(0)- ->and($external->fresh()->post_id)->toBeNull();+ $publication = AnalyticsPublication::query()->where('social_account_id', $account->id)->sole();++ expect($publication->id)->toBe($tracked->id)+ ->and($publication->remote_id)->toBe('page_post-1')+ ->and($publication->post_id)->toBe($tryPost->id)+ ->and($publication->origin)->toBe(PublicationOrigin::TryPost)+ ->and($publication->permalink)->toBe('https://www.facebook.com/reel/video-9/')+ ->and($publication->provider_content_type)->toBe('video_inline')+ ->and($publication->excerpt)->toBe('The caption on the Page')+ ->and($publication->content_type)->toBe(PublicationContentType::Reel)+ ->and($publication->provider_published_at->toIso8601String())->toBe($discovered->publishedAt->toIso8601String())+ ->and(Post::query()->imported()->count())->toBe(0)+ ->and($tryPost->fresh()->platform_post_id)->toBe('video-9');+});++test('a facebook video carried by two page posts links neither, tracked or not', function (bool $tracked) {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);++ if ($tracked) {+ externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ }++ $original = externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinutes(2), 'provider_metadata' => ['video_id' => 'video-9']]);+ $share = externalPublication($account, ['remote_id' => 'page_post-2', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);+ ImportExternalPosts::execute($account);++ expect($original->fresh()->post_id)->toBeNull()+ ->and($share->fresh()->post_id)->toBeNull()+ ->and($tryPost->analyticsPublication?->remote_id)->toBe($tracked ? 'video-9' : null)+ ->and(Post::query()->imported()->exists())->toBeFalse();+})->with(['tracked' => true, 'not tracked yet' => false]);++test('a trypost post without a published time is placed by its publication clock', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $tryPost->forceFill(['published_at' => null, 'publication_updated_at' => now()->subMinutes(2)])->saveQuietly();+ $publication = externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($publication->fresh()->post_id)->toBe($tryPost->id);+});++test('a page post deleted on the network no longer shares a facebook video', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $tracked = externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ externalPublication($account, ['remote_id' => 'page_post-2', 'provider_published_at' => now()->subMinute(), 'availability' => PublicationAvailability::Deleted, 'provider_metadata' => ['video_id' => 'video-9']]);+ externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($tracked->fresh()->remote_id)->toBe('page_post-1');+});++test('a page post sharing a facebook video days later does not stop the trypost one from merging', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9', 'published_at' => now()->subDays(3)]);+ $tracked = externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subDays(3)->addMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);+ $share = externalPublication($account, ['remote_id' => 'page_post-2', 'provider_published_at' => now()->subHour(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($tracked->fresh()->remote_id)->toBe('page_post-1')+ ->and($share->fresh()->post_id)->toBeNull()+ ->and(Post::query()->imported()->exists())->toBeFalse();+});++test('an ambiguous page post is reported once a day, and a later share is not', function () {+ Log::spy();+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9', 'published_at' => now()->subDays(2)]);+ externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ $first = externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subDays(2)->addMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);+ $second = externalPublication($account, ['remote_id' => 'page_post-2', 'provider_published_at' => now()->subDays(2)->addMinutes(2), 'provider_metadata' => ['video_id' => 'video-9']]);+ $share = externalPublication($account, ['remote_id' => 'page_post-3', 'provider_published_at' => now()->subHour(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);+ ImportExternalPosts::execute($account);++ $reported = fn (AnalyticsPublication $publication): Closure => fn (array $context): bool => $context['analytics_publication_id'] === $publication->id;+ Log::shouldHaveReceived('warning')->with('Facebook Page post carrying a TryPost media was left unlinked.', Mockery::on($reported($first)))->once();+ Log::shouldHaveReceived('warning')->with('Facebook Page post carrying a TryPost media was left unlinked.', Mockery::on($reported($second)))->once();+ Log::shouldNotHaveReceived('warning', ['Facebook Page post carrying a TryPost media was left unlinked.', Mockery::on($reported($share))]);+});++test('a facebook page post published long after the trypost post is not its own', function (bool $tracked) {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9', 'published_at' => now()->subDays(2)]);++ if ($tracked) {+ externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ }++ $later = externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subHour(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($later->fresh()->post_id)->toBeNull()+ ->and($tryPost->analyticsPublication?->remote_id)->toBe($tracked ? 'video-9' : null)+ ->and(Post::query()->imported()->exists())->toBeFalse();+})->with(['tracked' => true, 'not tracked yet' => false]);++test('a facebook publication tracked as deleted is not merged into', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $tracked = externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost, 'availability' => PublicationAvailability::Deleted]);+ $discovered = externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($tracked->fresh()->remote_id)->toBe('video-9')+ ->and($discovered->fresh())->not->toBeNull()+ ->and(Post::query()->imported()->exists())->toBeFalse();+});++test('a facebook post matched by its own id links whatever else carries its media', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebook()->published()->create(['platform_post_id' => 'page_post-2']);+ externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subHours(3), 'provider_metadata' => ['photo_id' => 'photo-9']]);+ $own = externalPublication($account, ['remote_id' => 'page_post-2', 'provider_published_at' => now()->subHour(), 'provider_metadata' => ['photo_id' => 'photo-9']]);++ ImportExternalPosts::execute($account);++ expect($own->fresh()->post_id)->toBe($tryPost->id);+});++test('a trypost sync rewrites the link of a facebook publication that does not carry its media', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebook()->published()->create(['platform_post_id' => 'page_post-2', 'platform_url' => 'https://www.facebook.com/page_post-2']);+ $tracked = externalPublication($account, ['remote_id' => 'page_post-1', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost, 'permalink' => 'https://www.facebook.com/page_post-1']);++ app(SyncTryPostPublicationAction::class)->handle($tryPost);++ expect($tracked->fresh()->permalink)->toBe('https://www.facebook.com/page_post-2');+});++test('a facebook publication links the post published under its own id before one sharing its media', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $byMedia = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $byId = Post::factory()->forAccount($account)->facebook()->published()->create(['platform_post_id' => 'page_post-1']);+ $publication = externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($publication->fresh()->post_id)->toBe($byId->id)+ ->and($byMedia->fresh()->analyticsPublication)->toBeNull();+});++test('a trypost sync rewrites the link of another network\'s publication found by its post', function () {+ $account = SocialAccount::factory()->instagram()->create();+ $tryPost = Post::factory()->forAccount($account)->instagram()->published()->create(['platform_post_id' => 'media-9', 'platform_url' => 'https://www.instagram.com/p/media-9/']);+ $tracked = externalPublication($account, ['remote_id' => 'container-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost, 'permalink' => 'https://example.com/old']);++ app(SyncTryPostPublicationAction::class)->handle($tryPost);++ expect($tracked->fresh()->permalink)->toBe('https://www.instagram.com/p/media-9/');+});++test('two page posts carrying a facebook video in the same second link neither', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $tracked = externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ $publishedAt = now()->subHour();+ externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => $publishedAt, 'provider_metadata' => ['video_id' => 'video-9']]);+ externalPublication($account, ['remote_id' => 'page_post-2', 'provider_published_at' => $publishedAt, 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);++ expect($tracked->fresh()->remote_id)->toBe('video-9')+ ->and(Post::query()->imported()->exists())->toBeFalse();+});++test('another page post sharing a merged facebook video stays a publication of its own', function () {+ $account = SocialAccount::factory()->facebook()->create();+ $tryPost = Post::factory()->forAccount($account)->facebookReel()->published()->create(['platform_post_id' => 'video-9']);+ $tracked = externalPublication($account, ['remote_id' => 'video-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ externalPublication($account, ['remote_id' => 'page_post-1', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);+ ImportExternalPosts::execute($account);+ $repost = externalPublication($account, ['remote_id' => 'page_post-2', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'video-9']]);++ ImportExternalPosts::execute($account);+ ImportExternalPosts::execute($account);++ expect($tracked->fresh()->remote_id)->toBe('page_post-1')+ ->and($repost->fresh())->not->toBeNull()+ ->and($repost->fresh()->post_id)->toBeNull()+ ->and(Post::query()->imported()->exists())->toBeFalse()+ ->and($tryPost->fresh()->platform_post_id)->toBe('video-9');+});++test('another network never links a post by a media id in its metadata', function () {+ $account = SocialAccount::factory()->instagram()->create();+ $tryPost = Post::factory()->forAccount($account)->instagram()->published()->create(['platform_post_id' => 'media-9']);+ $publication = externalPublication($account, ['remote_id' => 'ig-1', 'provider_published_at' => now()->subMinute(), 'provider_metadata' => ['video_id' => 'media-9']]);++ ImportExternalPosts::execute($account);++ expect($publication->fresh()->post_id)->not->toBe($tryPost->id);+});++test('a publication of another network tracked under another id is left to that publication', function () {+ $account = SocialAccount::factory()->instagram()->create();+ $tryPost = Post::factory()->forAccount($account)->instagram()->published()->create(['platform_post_id' => 'media-9']);+ $tracked = externalPublication($account, ['remote_id' => 'container-9', 'post_id' => $tryPost->id, 'origin' => PublicationOrigin::TryPost]);+ $discovered = externalPublication($account, ['remote_id' => 'media-9']);++ expect(ImportExternalPosts::execute($account))->toBe([])+ ->and(Post::query()->imported()->exists())->toBeFalse()+ ->and($tracked->fresh()->remote_id)->toBe('container-9')+ ->and($discovered->fresh()->post_id)->toBeNull();});test('a facebook photo discovered under its feed post id does not duplicate the original', function (bool $tracked) {@@ -251,7 +548,12 @@ test('a facebook photo discovered under its feed post id does not duplicate theexpect(ImportExternalPosts::execute($account))->toBe([])->and(ImportExternalPosts::execute($account))->toBe([])->and(Post::query()->imported()->count())->toBe(0)- ->and($publication->fresh()->post_id)->toBe($tracked ? null : $original->id);+ ->and(AnalyticsPublication::query()->where('social_account_id', $account->id)->sole()->post_id)->toBe($original->id);++ if ($tracked) {+ expect($publication->fresh())->toBeNull()+ ->and($original->fresh()->platform_post_id)->toBe('photo-9');+ }Http::assertSentCount(1);})->with(['untracked original' => false, 'tracked original' => true]);