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.

42.4 KB
Raw Blame
<?php

declare(strict_types=1);

use App\Actions\Post\CreatePosts;
use App\Actions\Post\Queue\ReflowChannelQueue;
use App\Enums\Post\PublishStatus;
use App\Enums\Post\QueuePosition;
use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Enums\PostPlatform\ContentType;
use App\Enums\User\TimeFormat;
use App\Exceptions\Social\ErrorCategory;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Models\WorkspaceLabel;
use App\Support\PostingSchedule;
use Carbon\CarbonInterface;

function waitForPublishQueueOrder(mixed $page, Post $first, Post $second): void
{
    waitForDatabase($page, fn () => $first->refresh()->scheduled_at->lessThan($second->refresh()->scheduled_at));
}

/**
 * @return array{0: User, 1: Workspace, 2: SocialAccount}
 */
function publishQueueSetup(): array
{
    $user = User::factory()->create(['timezone' => 'UTC']);
    $workspace = Workspace::factory()->create([
        'user_id' => $user->id,
        'account_id' => $user->account_id,
    ]);
    $workspace->members()->attach($user->id, membershipPivot('admin'));
    $user->update(['current_workspace_id' => $workspace->id]);
    subscribeAccount($user->account);

    $schedule = PostingSchedule::empty();

    foreach (range(0, 6) as $day) {
        $schedule = $schedule->withTime($day, '09:00')->withTime($day, '12:00')->withTime($day, '18:00');
    }

    $channel = SocialAccount::factory()->linkedin()->create([
        'workspace_id' => $workspace->id,
        'timezone' => 'UTC',
        'posting_schedule' => $schedule,
    ]);

    return [$user, $workspace, $channel];
}

function publishQueuePost(User $user, SocialAccount $channel, QueuePosition $position = QueuePosition::Next): Post
{
    $post = Post::factory()->forAccount($channel)->create([
        'user_id' => $user->id,
        'status' => PostStatus::Scheduled,
        'schedule_mode' => ScheduleMode::Queue,
        'scheduled_at' => null,
    ]);

    ReflowChannelQueue::handle($channel, $post, $position);

    return $post->refresh();
}

function publishQueueSlotKey(SocialAccount $channel, CarbonInterface $slot): string
{
    return "{$channel->id}-{$slot->getTimestamp()}";
}

function publishQueueVisitWithCleanStorage(string $url): mixed
{
    $page = visit($url);
    $page->script('window.localStorage.clear()');

    return $page->refresh();
}

test('a slot opens the composer at that slot and saving places the post there as a queue post', function () {
    [$user, , $channel] = publishQueueSetup();
    $user->update(['time_format' => TimeFormat::TwentyFourHour]);
    $slot = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2)[1];
    $slotKey = publishQueueSlotKey($channel, $slot);
    $this->actingAs($user);

    $page = visit(route('app.posts.index'));
    waitFor($page, "@queue-slot-{$slotKey}");

    $page->assertVisible("@queue-day-{$slot->utc()->format('Y-m-d')}")
        ->assertVisible("@queue-slot-{$slotKey}")
        ->click("@queue-slot-new-{$slotKey}");

    waitFor($page, "@composer-caption-{$channel->id}");
    $page->fill("@composer-caption-{$channel->id}", 'From an empty slot');
    waitFor($page, '@composer-submit');
    $label = $slot->format($slot->year === now('UTC')->year ? 'M j' : 'M j, Y').", {$slot->format('H:i')}";

    expect($page->script('document.querySelector(\'[data-testid="composer-submit"]\').dataset.scheduleMode'))->toBe('custom')
        ->and(trim((string) $page->script('document.querySelector("[data-testid=composer-schedule-trigger]").textContent')))->toBe($label);

    $page->click('@composer-submit');
    waitForGone($page, '@post-composer-dialog');

    $post = Post::query()->where('workspace_id', $channel->workspace_id)->sole();

    expect($post->scheduled_at->equalTo($slot))->toBeTrue()
        ->and($post->schedule_mode)->toBe(ScheduleMode::Queue)
        ->and($post->status)->toBe(PostStatus::Scheduled);
    $page->assertNoJavaScriptErrors();
});

test('a member whose posts need approval can still open the composer from an empty slot', function () {
    [, $workspace, $channel] = publishQueueSetup();
    $requester = workspaceMember($workspace, 'approval', ['timezone' => 'UTC']);
    $slot = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 1)[0];
    $slotKey = publishQueueSlotKey($channel, $slot);
    $this->actingAs($requester);

    $page = visit(route('app.posts.index'));
    waitFor($page, "@queue-slot-new-{$slotKey}");

    expect($page->script("(() => { const slot = document.querySelector('[data-testid=\"queue-slot-new-{$slotKey}\"]'); const icon = slot.querySelector('svg[data-testid=\"queue-slot-icon-{$slotKey}\"]'); return [icon !== null, slot.querySelector('img') === null, icon && getComputedStyle(icon).color]; })()"))
        ->toBe([true, true, 'rgb(10, 102, 194)']);

    $page->assertSeeIn("@queue-slot-new-{$slotKey}", 'New')
        ->click("@queue-slot-new-{$slotKey}");

    waitFor($page, "@composer-caption-{$channel->id}");
    $page->assertVisible("@composer-caption-{$channel->id}")
        ->assertNoJavaScriptErrors();
});

test('scheduled posts replace the slots with a list of only those posts', function () {
    [$user, , $channel] = publishQueueSetup();
    $queued = publishQueuePost($user, $channel);
    $custom = Post::factory()->forAccount($channel)->create([
        'user_id' => $user->id,
        'status' => PostStatus::Scheduled,
        'schedule_mode' => ScheduleMode::Custom,
        'scheduled_at' => now()->utc()->addDays(120)->setTime(15, 30),
    ]);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
    waitFor($page, "@post-card-{$custom->id}");

    $page->assertVisible("@post-card-{$queued->id}")
        ->assertPresent("@queue-day-{$custom->scheduled_at->format('Y-m-d')}")
        ->assertAttribute("@post-schedule-mode-{$custom->id}", 'data-mode', 'custom')
        ->assertAttribute("@post-schedule-mode-{$queued->id}", 'data-mode', 'queue')
        ->assertMissing('@queue-more-times');

    expect($page->script('document.querySelectorAll(\'[data-testid^="queue-slot-"]\').length'))->toBe(0);
    $page->assertNoJavaScriptErrors();
});

test('move down from the card menu swaps a queued post with the next one', function () {
    [$user, , $channel] = publishQueueSetup();
    $a = publishQueuePost($user, $channel);
    $b = publishQueuePost($user, $channel);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', $channel));
    waitFor($page, "@post-card-menu-{$a->id}");
    $page->click("@post-card-menu-{$a->id}");
    waitFor($page, "@post-move-down-{$a->id}");
    $page->click("@post-move-down-{$a->id}");
    waitForPublishQueueOrder($page, $b, $a);

    expect($b->refresh()->scheduled_at->lessThan($a->refresh()->scheduled_at))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('move down from the card menu moves a queued post into the free posting time after it', function () {
    [$user, , $channel] = publishQueueSetup();
    $post = publishQueuePost($user, $channel);
    $post->update(['content' => 'Queued post']);
    [, $nextFree] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $nextFree));
    $page->click("@post-card-menu-{$post->id}");
    waitForState($page, "@post-move-down-{$post->id}", "element.getAttribute('data-disabled') === null");
    $page->click("@post-move-down-{$post->id}");
    waitForDatabase($page, fn () => $post->refresh()->scheduled_at->equalTo($nextFree));

    expect($post->refresh()->scheduled_at->equalTo($nextFree))->toBeTrue()
        ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);
    $page->assertNoJavaScriptErrors();
});

test('move up from the card menu moves a queued post into the free posting time before it', function () {
    [$user, , $channel] = publishQueueSetup();
    $first = publishQueuePost($user, $channel);
    $post = publishQueuePost($user, $channel);
    $post->update(['content' => 'Queued post']);
    $freed = $first->scheduled_at;
    $first->delete();
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $freed));
    $page->click("@post-card-menu-{$post->id}");
    waitForState($page, "@post-move-up-{$post->id}", "element.getAttribute('data-disabled') === null");
    $page->click("@post-move-up-{$post->id}");
    waitForDatabase($page, fn () => $post->refresh()->scheduled_at->equalTo($freed));

    expect($post->refresh()->scheduled_at->equalTo($freed))->toBeTrue()
        ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);
    $page->assertNoJavaScriptErrors();
});

test('move to top is disabled for the first post of the queue and enabled below it', function () {
    [$user, , $channel] = publishQueueSetup();
    $first = publishQueuePost($user, $channel);
    $second = publishQueuePost($user, $channel);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    $page->click("@post-card-menu-{$first->id}");
    waitForState($page, "@post-move-top-{$first->id}", "element.getAttribute('data-disabled') !== null");
    $page->assertAttribute("@post-move-top-{$first->id}", 'data-disabled', '')
        ->keys("@post-move-top-{$first->id}", 'Escape');
    waitForGone($page, "@post-move-top-{$first->id}");

    $page->click("@post-card-menu-{$second->id}");
    waitFor($page, "@post-move-top-{$second->id}");
    $page->assertAttributeMissing("@post-move-top-{$second->id}", 'data-disabled')
        ->assertNoJavaScriptErrors();
});

test('move to top is enabled when a free posting time comes before the post', function () {
    [$user, , $channel] = publishQueueSetup();
    $first = publishQueuePost($user, $channel);
    $post = publishQueuePost($user, $channel);
    $freed = $first->scheduled_at;
    $first->delete();
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $freed));
    $page->click("@post-card-menu-{$post->id}");
    waitFor($page, "@post-move-top-{$post->id}");

    $page->assertAttributeMissing("@post-move-top-{$post->id}", 'data-disabled')
        ->assertNoJavaScriptErrors();
});

test('dragging a queued post above another reorders the queue', function () {
    [$user, , $channel] = publishQueueSetup();
    $a = publishQueuePost($user, $channel);
    $b = publishQueuePost($user, $channel);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', $channel));
    waitFor($page, "@post-drag-handle-{$b->id}");
    $page->drag("@post-card-{$b->id}", "@post-card-{$a->id}");
    waitForPublishQueueOrder($page, $b, $a);

    expect($b->refresh()->scheduled_at->lessThan($a->refresh()->scheduled_at))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('a stale reorder is rolled back and reported', function () {
    [$user, , $channel] = publishQueueSetup();
    $a = publishQueuePost($user, $channel);
    $b = publishQueuePost($user, $channel);
    $this->actingAs($user);

    $page = visit(route('app.channels.publish', $channel));
    waitFor($page, "@post-card-menu-{$a->id}");
    $top = publishQueuePost($user, $channel, QueuePosition::Top);
    $page->click("@post-card-menu-{$a->id}");
    waitFor($page, "@post-move-down-{$a->id}");
    $page->click("@post-move-down-{$a->id}");
    waitFor($page, '@queue-reorder-error-toast');

    $page->assertSeeIn('@queue-reorder-error-toast', __('posts.errors.queue_order_stale'));
    waitFor($page, "@post-card-{$top->id}");
    $page->assertVisible("@post-card-{$top->id}");
    expect($page->script("document.querySelector('[data-post-id=\"{$a->id}\"]').compareDocumentPosition(document.querySelector('[data-post-id=\"{$b->id}\"]')) & Node.DOCUMENT_POSITION_FOLLOWING"))->toBeGreaterThan(0)
        ->and($a->refresh()->scheduled_at->lessThan($b->refresh()->scheduled_at))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('the posting times toggle hides every slot and survives a reload', function () {
    [$user, , $channel] = publishQueueSetup();
    $queued = publishQueuePost($user, $channel);
    $slot = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2)[1];
    $slotKey = publishQueueSlotKey($channel, $slot);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@queue-slot-{$slotKey}");
    $page->click('@publish-menu');
    waitFor($page, '@publish-toggle-slots');
    $page->click('@publish-toggle-slots');
    waitForGone($page, '[data-testid^="queue-slot-"]');

    expect($page->script('document.querySelectorAll(\'[data-testid^="queue-slot-"]\').length'))->toBe(0);
    $page->assertVisible("@post-card-{$queued->id}");

    $page->refresh();
    waitFor($page, "@post-card-{$queued->id}");

    expect($page->script('document.querySelectorAll(\'[data-testid^="queue-slot-"]\').length'))->toBe(0);
    $page->assertVisible("@post-card-{$queued->id}")
        ->assertNoJavaScriptErrors();
});

test('a far display time zone regroups slots under its own calendar day', function () {
    [$user, , $channel] = publishQueueSetup();
    $slot = now()->utc()->addDay()->setTime(18, 0);
    $slotKey = publishQueueSlotKey($channel, $slot);
    $utcDay = $slot->format('Y-m-d');
    $aucklandDay = $slot->setTimezone('Pacific/Auckland')->format('Y-m-d');
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
    waitFor($page, "@queue-slot-{$slotKey}");

    expect($page->script("!!document.querySelector('[data-testid=\"queue-day-{$utcDay}\"] [data-testid=\"queue-slot-{$slotKey}\"]')"))->toBeTrue();

    $page->click('@publish-timezone-trigger');
    waitFor($page, '@publish-timezone-search');
    $page->type('@publish-timezone-search', 'Auckland');
    waitFor($page, '@publish-timezone-option-Pacific-Auckland');
    $page->click('@publish-timezone-option-Pacific-Auckland');
    waitForState($page, "@queue-day-{$aucklandDay} @queue-slot-{$slotKey}", 'true');

    expect($page->script('new URLSearchParams(location.search).get("tz")'))->toBe('Pacific/Auckland')
        ->and($page->script("!!document.querySelector('[data-testid=\"queue-day-{$aucklandDay}\"] [data-testid=\"queue-slot-{$slotKey}\"]')"))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('the time zone picked for the list is kept in the browser and shown again on the next load', function () {
    [$user] = publishQueueSetup();
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
    waitFor($page, '@publish-timezone-trigger');
    $page->click('@publish-timezone-trigger');
    waitFor($page, '@publish-timezone-search');
    $page->type('@publish-timezone-search', 'Auckland');
    waitFor($page, '@publish-timezone-option-Pacific-Auckland');
    $page->click('@publish-timezone-option-Pacific-Auckland');
    waitForQueryParameter($page, 'tz', 'Pacific/Auckland');

    expect(browserStorageItem($page, $user, 'publish.tz'))->toBe('Pacific/Auckland');

    $fresh = publishQueueVisitWithCleanStorage(route('app.posts.index'));
    waitFor($fresh, '@publish-timezone-trigger');
    setBrowserStorageItem($fresh, $user, 'publish.tz', 'Asia/Tokyo');
    $fresh->refresh();
    waitForText($fresh, '@publish-timezone-trigger', 'Tokyo');

    $fresh->assertSeeIn('@publish-timezone-trigger', 'Tokyo')
        ->assertNoJavaScriptErrors();
});

test('changing the time zone keeps a tab that came from a notes link', function () {
    [$user, , $channel] = publishQueueSetup();
    $draft = Post::factory()->forAccount($channel)->create([
        'user_id' => $user->id,
        'status' => PostStatus::Draft,
        'scheduled_at' => null,
    ]);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.posts.index', ['notes' => $draft->id]));
    waitFor($page, "@post-card-{$draft->id}");
    $page->script("document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))");

    $page->click('@publish-timezone-trigger');
    waitFor($page, '@publish-timezone-search');
    $page->type('@publish-timezone-search', 'Auckland');
    waitFor($page, '@publish-timezone-option-Pacific-Auckland');
    $page->click('@publish-timezone-option-Pacific-Auckland');
    waitForQueryParameter($page, 'tz', 'Pacific/Auckland');
    waitFor($page, "@post-card-{$draft->id}");

    expect($page->script('new URLSearchParams(location.search).get("tab")'))->toBe('drafts')
        ->and($page->script('new URLSearchParams(location.search).has("notes")'))->toBeFalse();
    $page->assertVisible("@post-card-{$draft->id}")->assertNoJavaScriptErrors();
});

test('more times extends the queue range', function () {
    [$user] = publishQueueSetup();
    $farDay = now()->utc()->addDays(20)->format('Y-m-d');
    $this->actingAs($user);

    $page = visit(route('app.posts.index'));
    waitFor($page, '@queue-more-times');
    $page->assertMissing("@queue-day-{$farDay}")
        ->click('@queue-more-times');
    waitFor($page, "@queue-day-{$farDay}");

    $page->assertPresent("@queue-day-{$farDay}")
        ->assertNoJavaScriptErrors();
});

test('a failed post is listed in sent with its failed badge and actions', function () {
    [$user, $workspace, $channel] = publishQueueSetup();
    $failed = Post::factory()->forAccount($channel)->failed()->create([
        'error_message' => 'Video duration exceeds the 90 second limit.',
        'error_context' => ['category' => ErrorCategory::MediaFormat->value],
        'user_id' => $user->id,
        'scheduled_at' => now()->subDays(21),
    ]);
    $this->actingAs($user);

    $page = visit(route('app.posts.index', ['tab' => 'sent']));
    waitFor($page, "@post-card-{$failed->id}");

    $page->assertSeeIn("@post-status-{$failed->id}", __('posts.status.failed'))
        ->assertSeeIn("@post-created-by-{$failed->id}", $user->name)
        ->assertMissing("@post-published-via-{$failed->id}")
        ->assertMissing("@post-edit-{$failed->id}");

    expect($page->script("document.querySelector('[data-testid=\"post-time-{$failed->id}\"]').getAttribute('datetime')"))
        ->toStartWith($failed->scheduled_at->toDateString());

    $page->click("@post-status-{$failed->id}");
    waitFor($page, "@post-failure-{$failed->id}");

    $page->assertSeeIn("@post-failure-reason-{$failed->id}", __('posts.publish.failure.categories.media_format'))
        ->assertSeeIn("@post-failure-details-{$failed->id}", 'Video duration exceeds the 90 second limit.');

    $page->script("document.dispatchEvent(new KeyboardEvent('keydown', {key: 'Escape', bubbles: true}))");
    waitForGone($page, "@post-failure-{$failed->id}");

    $page->click("@post-card-menu-{$failed->id}");
    waitFor($page, "@post-duplicate-{$failed->id}");

    $page->assertPresent("@post-duplicate-{$failed->id}")
        ->assertPresent("@post-details-open-{$failed->id}")
        ->assertMissing("@post-delete-{$failed->id}")
        ->assertNoJavaScriptErrors();
});

function publishQueueCustomPost(User $user, SocialAccount $channel, CarbonInterface $at): Post
{
    $post = Post::factory()->forAccount($channel)->create([
        'user_id' => $user->id,
        'content' => 'A post with its own time',
        'status' => PostStatus::Scheduled,
        'schedule_mode' => ScheduleMode::Custom,
        'scheduled_at' => $at,
    ]);

    return $post;
}

test('move up from the card menu moves a custom-time post into the free posting time before it', function () {
    [$user, , $channel] = publishQueueSetup();
    [$freeAbove, $slot] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2);
    $custom = publishQueueCustomPost($user, $channel, $slot);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $freeAbove));
    $page->click("@post-card-menu-{$custom->id}");
    waitFor($page, "@post-move-top-{$custom->id}");
    $page->assertAttributeMissing("@post-move-top-{$custom->id}", 'data-disabled')
        ->assertAttributeMissing("@post-move-down-{$custom->id}", 'data-disabled')
        ->click("@post-move-up-{$custom->id}");
    waitForDatabase($page, fn () => $custom->refresh()->scheduled_at->equalTo($freeAbove));

    expect($custom->refresh()->scheduled_at->equalTo($freeAbove))->toBeTrue()
        ->and($custom->schedule_mode)->toBe(ScheduleMode::Queue);
    $page->assertNoJavaScriptErrors();
});

/**
 * @return array{top: string, up: string, down: string}
 */
function publishQueueMoveActions(mixed $page, Post $post): array
{
    $page->click("@post-card-menu-{$post->id}");
    waitForOpen($page, "@post-card-menu-content-{$post->id}");

    $states = $page->script("['top', 'up', 'down'].map((action) => { const item = document.querySelector('[data-testid=\"post-move-' + action + '-{$post->id}\"]'); return item === null ? 'missing' : (item.hasAttribute('data-disabled') ? 'disabled' : 'enabled'); })");

    $page->keys("@post-card-menu-content-{$post->id}", 'Escape');
    waitForGone($page, "@post-card-menu-content-{$post->id}");

    return array_combine(['top', 'up', 'down'], $states);
}

test('move down from the card menu skips a custom-time post on the way to a free posting time', function () {
    [$user, , $channel] = publishQueueSetup();
    [, $customAt, $nextFree] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 3);
    $queued = publishQueuePost($user, $channel);
    $queued->update(['content' => 'Queued post']);
    $custom = publishQueueCustomPost($user, $channel, $customAt);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $nextFree));
    $page->click("@post-card-menu-{$queued->id}");
    waitForState($page, "@post-move-down-{$queued->id}", "element.getAttribute('data-disabled') === null");
    $page->click("@post-move-down-{$queued->id}");
    waitForDatabase($page, fn () => $queued->refresh()->scheduled_at->equalTo($nextFree));

    expect($queued->refresh()->scheduled_at->equalTo($nextFree))->toBeTrue()
        ->and($custom->refresh()->scheduled_at->equalTo($customAt))->toBeTrue()
        ->and($custom->schedule_mode)->toBe(ScheduleMode::Custom);
    $page->assertNoJavaScriptErrors();
});

test('with the posting times hidden, the ends of the queue cannot move past them', function () {
    [$user, , $channel] = publishQueueSetup();
    $first = publishQueuePost($user, $channel);
    $last = publishQueuePost($user, $channel);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@post-card-{$last->id}");
    $page->click('@publish-menu');
    waitFor($page, '@publish-toggle-slots');
    $page->click('@publish-toggle-slots');
    waitForGone($page, '[data-testid^="queue-slot-"]');

    expect(publishQueueMoveActions($page, $first))->toBe(['top' => 'disabled', 'up' => 'disabled', 'down' => 'enabled'])
        ->and(publishQueueMoveActions($page, $last))->toBe(['top' => 'enabled', 'up' => 'enabled', 'down' => 'disabled']);
    $page->assertNoJavaScriptErrors();
});

test('on the list of all channels, the ends of the queue cannot move further and a custom-time post has no move actions', function () {
    [$user, , $channel] = publishQueueSetup();
    [, , $customAt] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 3);
    $first = publishQueuePost($user, $channel);
    $last = publishQueuePost($user, $channel);
    $custom = publishQueueCustomPost($user, $channel, $customAt->addDay());
    connectAiTo($user);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
    waitFor($page, "@post-card-{$custom->id}");

    expect(publishQueueMoveActions($page, $first))->toBe(['top' => 'disabled', 'up' => 'disabled', 'down' => 'enabled'])
        ->and(publishQueueMoveActions($page, $last))->toBe(['top' => 'enabled', 'up' => 'enabled', 'down' => 'disabled'])
        ->and(publishQueueMoveActions($page, $custom))->toBe(['top' => 'missing', 'up' => 'missing', 'down' => 'missing']);
    $page->assertNoJavaScriptErrors();
});

test('move down from the card menu moves a custom-time post into the free posting time after it', function () {
    [$user, , $channel] = publishQueueSetup();
    [$slot, $freeBelow] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2);
    $custom = publishQueueCustomPost($user, $channel, $slot);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $freeBelow));

    expect(publishQueueMoveActions($page, $custom))->toBe(['top' => 'disabled', 'up' => 'disabled', 'down' => 'enabled']);

    $page->click("@post-card-menu-{$custom->id}");
    waitFor($page, "@post-move-down-{$custom->id}");
    $page->click("@post-move-down-{$custom->id}");
    waitForDatabase($page, fn () => $custom->refresh()->scheduled_at->equalTo($freeBelow));

    expect($custom->refresh()->scheduled_at->equalTo($freeBelow))->toBeTrue()
        ->and($custom->schedule_mode)->toBe(ScheduleMode::Queue);
    $page->assertNoJavaScriptErrors();
});

test('move to top from the card menu puts a custom-time post first in the queue', function () {
    [$user, , $channel] = publishQueueSetup();
    [$freeAbove, $slot] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2);
    $custom = publishQueueCustomPost($user, $channel, $slot);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $freeAbove));
    $page->click("@post-card-menu-{$custom->id}");
    waitForState($page, "@post-move-top-{$custom->id}", "element.getAttribute('data-disabled') === null");
    $page->click("@post-move-top-{$custom->id}");
    waitForDatabase($page, fn () => $custom->refresh()->scheduled_at->equalTo($freeAbove));

    expect($custom->refresh()->scheduled_at->equalTo($freeAbove))->toBeTrue()
        ->and($custom->schedule_mode)->toBe(ScheduleMode::Queue);
    $page->assertNoJavaScriptErrors();
});

test('with a label filter, move to top stays available on the first post shown', function () {
    [$user, $workspace, $channel] = publishQueueSetup();
    $label = WorkspaceLabel::factory()->create(['workspace_id' => $workspace->id]);
    publishQueuePost($user, $channel);
    $labelled = publishQueuePost($user, $channel);
    $labelled->labels()->attach($label);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', ['account' => $channel, 'labels' => [$label->id]]));
    waitFor($page, "@post-card-{$labelled->id}");

    expect(publishQueueMoveActions($page, $labelled))->toBe(['top' => 'enabled', 'up' => 'disabled', 'down' => 'disabled']);
    $page->assertNoJavaScriptErrors();
});

function publishQueueFollows(mixed $page, string $firstTestId, string $secondTestId): bool
{
    return (bool) $page->script("(document.querySelector('[data-testid=\"{$firstTestId}\"]').compareDocumentPosition(document.querySelector('[data-testid=\"{$secondTestId}\"]')) & Node.DOCUMENT_POSITION_FOLLOWING) > 0");
}

function waitForPublishQueueMode(mixed $page, Post $post, ScheduleMode $mode): void
{
    waitForDatabase($page, fn () => $post->refresh()->schedule_mode === $mode);
}

test('a scheduled post sits between the free posting times and its drag handle shows in the gutter on hover', function () {
    [$user, , $channel] = publishQueueSetup();
    $queued = publishQueuePost($user, $channel);
    [, $nextFree] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2);
    $nextFreeKey = publishQueueSlotKey($channel, $nextFree);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@post-time-{$queued->id}");
    waitFor($page, "@queue-slot-{$nextFreeKey}");

    $page->assertVisible("@post-card-{$queued->id}")
        ->assertVisible("@queue-slot-{$nextFreeKey}")
        ->assertMissing('@queue-slot-'.publishQueueSlotKey($channel, $queued->scheduled_at));

    expect(publishQueueFollows($page, "post-card-{$queued->id}", "queue-slot-{$nextFreeKey}"))->toBeTrue();

    $handle = "document.querySelector('[data-testid=\"post-drag-handle-{$queued->id}\"]')";
    $time = "document.querySelector('[data-testid=\"post-time-{$queued->id}\"]')";
    $card = "document.querySelector('[data-testid=\"post-open-{$queued->id}\"]').closest('article')";

    expect($page->script("getComputedStyle({$handle}).opacity"))->toBe('0');

    $page->hover("@post-time-{$queued->id}");
    waitForState($page, "@post-drag-handle-{$queued->id}", "getComputedStyle(element).opacity === '1'");

    expect($page->script("getComputedStyle({$handle}).opacity"))->toBe('1')
        ->and($page->script("{$handle}.getBoundingClientRect().left >= {$time}.getBoundingClientRect().right"))->toBeTrue()
        ->and($page->script("{$handle}.getBoundingClientRect().right <= {$card}.getBoundingClientRect().left"))->toBeTrue()
        ->and($page->script("Math.abs(({$handle}.getBoundingClientRect().top + {$handle}.getBoundingClientRect().bottom) / 2 - ({$time}.getBoundingClientRect().top + {$time}.getBoundingClientRect().bottom) / 2) <= 3"))->toBeTrue()
        ->and($page->script("getComputedStyle({$handle}).cursor"))->toBe('grab');
    $page->assertNoJavaScriptErrors();
});

test('dragging a post with its own time onto a free slot queues it at that slot', function () {
    [$user, , $channel] = publishQueueSetup();
    publishQueuePost($user, $channel);
    $slots = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 3);
    $custom = publishQueueCustomPost($user, $channel, $slots[2]->addMinutes(90));
    $targetKey = publishQueueSlotKey($channel, $slots[2]);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@post-drag-handle-{$custom->id}");
    waitFor($page, "@queue-slot-{$targetKey}");
    $page->drag("@post-card-{$custom->id}", "@queue-slot-{$targetKey}");
    waitForPublishQueueMode($page, $custom, ScheduleMode::Queue);

    expect($custom->refresh()->schedule_mode)->toBe(ScheduleMode::Queue)
        ->and($custom->scheduled_at->equalTo($slots[2]))->toBeTrue();
    waitForGone($page, "@queue-slot-{$targetKey}");
    $page->assertMissing("@queue-slot-{$targetKey}")
        ->assertNoJavaScriptErrors();
});

test('dropping a post on a slot taken meanwhile is rolled back and reported', function () {
    [$user, , $channel] = publishQueueSetup();
    publishQueuePost($user, $channel);
    $slots = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2);
    $custom = publishQueueCustomPost($user, $channel, $slots[1]->addMinutes(90));
    $targetKey = publishQueueSlotKey($channel, $slots[1]);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@queue-slot-{$targetKey}");
    waitFor($page, "@post-drag-handle-{$custom->id}");
    publishQueuePost($user, $channel);
    $page->drag("@post-card-{$custom->id}", "@queue-slot-{$targetKey}");
    waitFor($page, '@queue-reorder-error-toast');

    $page->assertSeeIn('@queue-reorder-error-toast', __('posts.errors.queue_order_stale'));
    expect($custom->refresh()->schedule_mode)->toBe(ScheduleMode::Custom)
        ->and($custom->scheduled_at->equalTo($slots[1]->addMinutes(90)))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('dragging a queued post onto a later free slot keeps it there and leaves the others in place', function () {
    [$user, , $channel] = publishQueueSetup();
    $first = publishQueuePost($user, $channel);
    $first->update(['content' => 'First queued post']);
    $second = publishQueuePost($user, $channel);
    $secondAt = $second->scheduled_at;
    $slots = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 4);
    $targetKey = publishQueueSlotKey($channel, $slots[3]);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@queue-slot-{$targetKey}");
    waitFor($page, "@post-card-{$first->id}");
    $page->drag("@post-card-{$first->id}", "@queue-slot-{$targetKey}");

    waitForDatabase($page, fn () => $first->refresh()->scheduled_at->equalTo($slots[3]));

    expect($first->refresh()->scheduled_at->equalTo($slots[3]))->toBeTrue()
        ->and($first->schedule_mode)->toBe(ScheduleMode::Queue)
        ->and($second->refresh()->scheduled_at->equalTo($secondAt))->toBeTrue();
    waitFor($page, '@queue-slot-'.publishQueueSlotKey($channel, $slots[0]));
    $page->assertPresent('@queue-slot-'.publishQueueSlotKey($channel, $slots[0]))
        ->assertNoJavaScriptErrors();
});

test('free slots follow the loaded posts beyond the default range', function () {
    config()->set('app.pagination.default', 2);
    [$user, , $channel] = publishQueueSetup();
    publishQueuePost($user, $channel);
    $far = publishQueueCustomPost($user, $channel, now()->utc()->addDays(20)->setTime(15, 30));
    publishQueueCustomPost($user, $channel, now()->utc()->addDays(40)->setTime(15, 30));
    $beyondDefault = now()->utc()->addDays(18)->setTime(9, 0);
    $slotKey = publishQueueSlotKey($channel, $beyondDefault);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@post-card-{$far->id}");
    waitForState($page, "@queue-slot-{$slotKey}", 'true');

    $page->assertPresent("@queue-slot-{$slotKey}");
    expect(publishQueueFollows($page, "queue-slot-{$slotKey}", "post-card-{$far->id}"))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('the all channels queue keeps its drag handle inline before the time', function () {
    [$user, , $channel] = publishQueueSetup();
    $first = publishQueuePost($user, $channel);
    publishQueuePost($user, $channel);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.posts.index'));
    waitFor($page, "@post-drag-handle-{$first->id}");

    $handle = "document.querySelector('[data-testid=\"post-drag-handle-{$first->id}\"]')";
    $time = "document.querySelector('[data-testid=\"post-time-{$first->id}\"]')";

    expect($page->script("getComputedStyle({$handle}).opacity"))->toBe('1')
        ->and($page->script("getComputedStyle({$handle}).position"))->toBe('static')
        ->and($page->script("{$handle}.getBoundingClientRect().right <= {$time}.getBoundingClientRect().left"))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('a pending queue request shows at its reserved slot and approving it keeps it there as a queued post', function () {
    [$user, $workspace, $channel] = publishQueueSetup();
    $requester = workspaceMember($workspace, 'approval');
    [$first, $reserved] = $channel->posting_schedule->nextSlots(now()->addMinute(), $channel->timezone, 2);

    $pending = CreatePosts::execute($workspace, $requester, [
        'status' => 'scheduled',
        'content' => 'Waiting in its slot',
        'scheduled_at' => $reserved->toIso8601String(),
        'queue_slot' => $reserved->toIso8601String(),
        'media' => [],
        'label_ids' => [],
        'destinations' => [[
            'social_account_id' => $channel->id,
            'content_type' => ContentType::LinkedInPost->value,
            'meta' => [],
        ]],
    ])->sole();

    expect($pending->status)->toBe(PostStatus::PendingApproval)
        ->and($pending->schedule_mode)->toBe(ScheduleMode::Queue);

    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    waitFor($page, "@post-card-{$pending->id}");

    $page->assertVisible("@post-approval-badge-{$pending->id}")
        ->assertVisible("@post-approve-{$pending->id}")
        ->assertVisible("@post-reject-{$pending->id}")
        ->assertMissing("@post-drag-handle-{$pending->id}")
        ->assertMissing('@queue-slot-'.publishQueueSlotKey($channel, $reserved))
        ->assertVisible('@queue-slot-'.publishQueueSlotKey($channel, $first));

    expect($page->script("new Date(document.querySelector('[data-testid=\"post-time-{$pending->id}\"]').getAttribute('datetime')).getTime()"))
        ->toBe($reserved->getTimestamp() * 1000)
        ->and(publishQueueFollows($page, 'queue-slot-'.publishQueueSlotKey($channel, $first), "post-card-{$pending->id}"))->toBeTrue();

    $page->click("@post-approve-{$pending->id}");
    waitForGone($page, "@post-approval-badge-{$pending->id}");

    expect($pending->refresh()->status)->toBe(PostStatus::Scheduled)
        ->and($pending->scheduled_at->equalTo($reserved))->toBeTrue();

    waitFor($page, "@post-card-{$pending->id}");
    $page->assertVisible("@post-card-{$pending->id}")
        ->assertMissing("@post-approval-badge-{$pending->id}")
        ->assertPresent("@post-drag-handle-{$pending->id}")
        ->assertNoJavaScriptErrors();
});

test('a publishing post waiting for a network limit shows when it retries', function () {
    [$user, $workspace, $channel] = publishQueueSetup();
    $user->update(['time_format' => TimeFormat::TwentyFourHour]);
    $retryAt = now()->addHours(2)->startOfMinute();
    $waiting = Post::factory()->forAccount($channel)->create([
        'publish_status' => PublishStatus::Retrying,
        'retry_at' => $retryAt,
        'error_message' => 'LinkedIn rate limit reached. Please try again later.',
        'error_context' => ['category' => ErrorCategory::RateLimit->value, 'limit_retries' => 1],
        'user_id' => $user->id,
        'status' => PostStatus::Publishing,
        'schedule_mode' => ScheduleMode::Custom,
        'scheduled_at' => now()->subMinute(),
        'content' => 'Waiting for the limit',
    ]);
    $this->actingAs($user);

    $page = visit(route('app.posts.index'));
    waitFor($page, "@post-limit-retry-{$waiting->id}");

    $page->assertVisible("@post-publishing-{$waiting->id}")
        ->assertSeeIn("@post-limit-retry-{$waiting->id}", __('posts.publish.retrying_at', ['time' => $retryAt->utc()->format('H:i')]))
        ->assertDontSeeIn("@post-publishing-{$waiting->id}", __('posts.publish.publishing_on', ['network' => $channel->platform->label()]))
        ->assertNoJavaScriptErrors();
});

test('a google business post waiting for review says google is reviewing it', function () {
    [$user, $workspace] = publishQueueSetup();
    $channel = SocialAccount::factory()->googleBusiness()->create(['workspace_id' => $workspace->id]);
    $inReview = Post::factory()->forAccount($channel)->pendingReview()->create([
        'user_id' => $user->id,
        'schedule_mode' => ScheduleMode::Custom,
        'scheduled_at' => now()->subMinute(),
        'content' => 'Waiting for Google',
    ]);
    $this->actingAs($user);

    $page = visit(route('app.posts.index'));
    waitFor($page, "@post-google-review-{$inReview->id}");

    $page->assertSeeIn("@post-google-review-{$inReview->id}", __('posts.publish.in_google_review'))
        ->assertNotPresent("@post-publishing-progress-{$inReview->id}")
        ->assertDontSeeIn("@post-publishing-{$inReview->id}", __('posts.publish.publishing_on', ['network' => $channel->platform->label()]))
        ->assertNoJavaScriptErrors();
});

test('a publishing post sits in its own queue group and moves to sent once it settles', function () {
    [$user, $workspace, $channel] = publishQueueSetup();
    $scheduled = publishQueuePost($user, $channel);
    $publishing = Post::factory()->forAccount($channel)->create([
        'user_id' => $user->id,
        'status' => PostStatus::Publishing,
        'schedule_mode' => ScheduleMode::Custom,
        'scheduled_at' => now()->subMinute(),
        'content' => 'Going out right now',
    ]);
    $this->actingAs($user);

    $page = visit(route('app.posts.index'));
    waitFor($page, "@post-publishing-{$publishing->id}");

    $page->assertVisible('@queue-publishing')
        ->assertVisible("@post-publishing-{$publishing->id}")
        ->assertPresent("@post-publishing-progress-{$publishing->id}")
        ->assertSeeIn('@queue-publishing', 'Publishing now')
        ->assertSeeIn("@post-publishing-{$publishing->id}", __('posts.publish.publishing_on', ['network' => $channel->platform->label()]))
        ->assertVisible("@post-time-{$publishing->id}")
        ->assertMissing("@post-drag-handle-{$publishing->id}")
        ->assertMissing("@post-edit-{$publishing->id}")
        ->assertMissing("@post-card-menu-{$publishing->id}")
        ->assertVisible("@post-card-{$scheduled->id}")
        ->assertSeeIn('@publish-tab-count-queue', '2');

    expect($page->script(<<<'JS'
        (() => {
            const group = document.querySelector('[data-testid="queue-publishing"]');
            const firstDay = document.querySelector('[data-testid^="queue-day-"]');
            return Boolean(group.compareDocumentPosition(firstDay) & Node.DOCUMENT_POSITION_FOLLOWING);
        })()
    JS))->toBeTrue();

    $publishing->markAsPublished();

    $page->script(<<<JS
        window.Pusher.instances[0].channels.channels['private-workspace.{$workspace->id}']
            .emit('post.platform.status.updated', { post_id: '{$publishing->id}' });
    JS);
    waitForGone($page, '@queue-publishing');

    $page->assertMissing('@queue-publishing')
        ->assertMissing("@post-card-{$publishing->id}")
        ->assertVisible("@post-card-{$scheduled->id}")
        ->assertSeeIn('@publish-tab-count-queue', '1');

    $page->click('@publish-tab-sent');
    waitFor($page, "@post-card-{$publishing->id}");

    $page->assertVisible("@post-card-{$publishing->id}")
        ->assertNoJavaScriptErrors();
});

test('moving a post to the top toasts with a link to its details, through the partial reload', function () {
    [$user, , $channel] = publishQueueSetup();
    $first = publishQueuePost($user, $channel);
    $post = publishQueuePost($user, $channel);
    $first->update(['content' => 'First in the queue']);
    $post->update(['content' => 'Moved to the top']);
    $this->actingAs($user);

    $page = publishQueueVisitWithCleanStorage(route('app.channels.publish', $channel));
    $page->click("@post-card-menu-{$post->id}");
    waitFor($page, "@post-move-top-{$post->id}");
    $page->click("@post-move-top-{$post->id}");
    waitFor($page, '@flash-success-toast [data-button]');

    $page->assertSeeIn('[data-testid="flash-success-toast"] [data-button]', 'View post')
        ->assertNoJavaScriptErrors();
});