Skip to content

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.

Remove the one-off Facebook duplicates command (#495)

Paulo Castellano1de3858d8663
diff --git a/.ai/rules/post.md b/.ai/rules/post.md
index 424809514..d2ee1ddb5 100644
--- a/.ai/rules/post.md
+++ b/.ai/rules/post.md
@@ -36,4 +36,4 @@ When a captionless Instagram discovery has an unresolved TryPost candidate in th
Discovery 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).
+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.
diff --git a/app/Actions/Post/ImportExternalPosts.php b/app/Actions/Post/ImportExternalPosts.php
index 562d37bf6..6d813d9f5 100644
--- a/app/Actions/Post/ImportExternalPosts.php
+++ b/app/Actions/Post/ImportExternalPosts.php
@@ -155,27 +155,6 @@ 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
diff --git a/app/Console/Commands/Scripts/MergeFacebookDuplicatePublicationsCommand.php b/app/Console/Commands/Scripts/MergeFacebookDuplicatePublicationsCommand.php
deleted file mode 100644
index 821922ca5..000000000
--- a/app/Console/Commands/Scripts/MergeFacebookDuplicatePublicationsCommand.php
+++ /dev/null
@@ -1,102 +0,0 @@
-<?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/Models/AnalyticsPublication.php b/app/Models/AnalyticsPublication.php
index 688ce2a18..73cbb53b4 100644
--- a/app/Models/AnalyticsPublication.php
+++ b/app/Models/AnalyticsPublication.php
@@ -93,15 +93,6 @@ 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.
@@ -117,18 +108,6 @@ class AnalyticsPublication extends Model
});
}
- /**
- * 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.
diff --git a/tests/Feature/Analytics/MergeFacebookDuplicatePublicationsTest.php b/tests/Feature/Analytics/MergeFacebookDuplicatePublicationsTest.php
deleted file mode 100644
index 6e5f73d6c..000000000
--- a/tests/Feature/Analytics/MergeFacebookDuplicatePublicationsTest.php
+++ /dev/null
@@ -1,122 +0,0 @@
-<?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.php
index 573a0df75..257841789 100644
--- a/tests/Feature/Analytics/PublicationReconciliationTest.php
+++ b/tests/Feature/Analytics/PublicationReconciliationTest.php
@@ -489,8 +489,7 @@ test('carrying facebook media matches only the ids given', function () {
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);
+ ->and(AnalyticsPublication::query()->carryingFacebookMedia([])->exists())->toBeFalse();
});
test('a merged publication keeps the latest time discovery saw the post', function () {
@@ -533,8 +532,4 @@ test('a discovery under another analytics key is not merged and the publication
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();
});