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.

40.7 KB
Raw Blame
<?php

declare(strict_types=1);

use App\Enums\Post\ScheduleMode;
use App\Enums\Post\Status as PostStatus;
use App\Enums\SocialAccount\Platform;
use App\Enums\User\Locale;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Models\AnalyticsPublication;
use App\Models\AnalyticsPublicationDailySnapshot;
use App\Models\Post;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Support\PostingSchedule;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Queue;

/**
 * @return array{0: User, 1: SocialAccount, 2: SocialAccount}
 */
function calendarPageSetup(): 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);

    return [
        $user,
        SocialAccount::factory()->linkedin()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']),
        SocialAccount::factory()->x()->create(['workspace_id' => $workspace->id, 'timezone' => 'UTC']),
    ];
}

function calendarPagePost(SocialAccount $account, ?CarbonInterface $at, PostStatus $status = PostStatus::Scheduled): Post
{
    return Post::factory()->forAccount($account)->create([
        'user_id' => $account->workspace->user_id,
        'status' => $status,
        'scheduled_at' => $at,
    ]);
}

/**
 * How many items a month day shows before "+N more", and whether the last one
 * stays above the "+N more" button inside the cell.
 */
function calendarMonthDayFits(string $dayKey): string
{
    return <<<JS
        (() => {
            const cell = document.querySelector('[data-testid="calendar-day-{$dayKey}"]').getBoundingClientRect();
            const items = [...document.querySelector('[data-testid="calendar-items-{$dayKey}"]').children];
            const last = items.at(-1).getBoundingClientRect();
            const more = document.querySelector('[data-testid="calendar-more-{$dayKey}"]').getBoundingClientRect();

            return { shown: items.length, fits: last.bottom <= more.top + 0.5 && more.bottom <= cell.bottom + 0.5 };
        })()
    JS;
}

function calendarChipSlot(mixed $page, Post $post): ?string
{
    return $page->script("document.querySelector('[data-testid=\"calendar-post-{$post->id}\"]')?.closest('[data-testid^=\"calendar-slot-\"]')?.dataset.testid ?? null");
}

test('the week grid places posts in their hour row, stacked as compact rows when they share it', function () {
    [$user, $linkedin, $x] = calendarPageSetup();
    $weekStart = now('UTC')->startOfWeek()->addWeek();
    $day = $weekStart->copy()->addDays(2);
    $dayKey = $day->format('Y-m-d');

    $first = calendarPagePost($linkedin, $day->copy()->setTime(14, 10));
    $second = calendarPagePost($x, $day->copy()->setTime(14, 30));
    $morning = calendarPagePost($x, $day->copy()->setTime(9, 0));

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]));
    waitFor($page, "@calendar-post-{$first->id}");

    expect(calendarChipSlot($page, $first))->toBe("calendar-slot-{$dayKey}-14")
        ->and(calendarChipSlot($page, $second))->toBe("calendar-slot-{$dayKey}-14")
        ->and(calendarChipSlot($page, $morning))->toBe("calendar-slot-{$dayKey}-09");

    $layout = $page->script(<<<JS
        (() => {
            const box = (id) => document.querySelector('[data-testid="calendar-post-' + id + '"]').getBoundingClientRect();
            const slot = document.querySelector('[data-testid="calendar-slot-{$dayKey}-14"]').getBoundingClientRect();
            const midnight = document.querySelector('[data-testid="calendar-slot-{$dayKey}-00"]').getBoundingClientRect();
            const first = box('{$first->id}');
            const second = box('{$second->id}');

            return {
                stacked: second.top >= first.bottom && Math.abs(first.left - second.left) < 1,
                sameWidth: Math.abs(first.width - second.width) < 1,
                hourOffset: Math.round(slot.top - midnight.top),
                inSlot: first.top >= slot.top && second.bottom <= slot.bottom,
            };
        })()
    JS);

    expect($layout)->toBe([
        'stacked' => true,
        'sameWidth' => true,
        'hourOffset' => 14 * 106,
        'inSlot' => true,
    ]);

    $page->assertNoJavaScriptErrors();
});

test('the week grid has no now line and scrolls to the current hour', function () {
    [$user] = calendarPageSetup();
    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week']));
    waitFor($page, '@calendar-time-grid');

    $page->assertMissing('@calendar-now-line')
        ->assertScript(
            '(() => { const grid = document.querySelector(\'[data-testid="calendar-time-grid"]\'); return grid.scrollTop === Math.min('.(now('UTC')->hour * 106).', grid.scrollHeight - grid.clientHeight); })()',
            true,
        )
        ->assertNoJavaScriptErrors();
});

test('the calendar honours the channels filter and the display time zone', function () {
    [$user, $linkedin, $x] = calendarPageSetup();
    $weekStart = now('UTC')->startOfWeek()->addWeek();
    $day = $weekStart->copy()->addDays(2);

    $linkedinPost = calendarPagePost($linkedin, $day->copy()->setTime(14, 30));
    $xPost = calendarPagePost($x, $day->copy()->setTime(14, 30));

    $this->actingAs($user);

    $page = visit(route('app.calendar', [
        'view' => 'week',
        'week' => $weekStart->format('Y-m-d'),
        'channels' => [$x->id],
        'tz' => 'Asia/Tokyo',
    ]))->resize(1600, 900);
    waitFor($page, "@calendar-post-{$xPost->id}");

    $page->assertMissing("@calendar-post-{$linkedinPost->id}")
        ->assertSeeIn('@publish-timezone-select', 'Tokyo');

    expect(calendarChipSlot($page, $xPost))->toBe("calendar-slot-{$day->format('Y-m-d')}-23");

    $listHref = $page->script('decodeURIComponent(document.querySelector(\'[data-testid="schedule-view-list"]\').getAttribute("href"))');

    expect($listHref)->toContain("channels[]={$x->id}")
        ->toContain('tz=Asia/Tokyo');

    $page->assertNoJavaScriptErrors();
});

test('an overflowing week hour expands in place', function () {
    [$user, $linkedin, $x] = calendarPageSetup();
    $weekStart = now('UTC')->startOfWeek()->addWeek();
    $day = $weekStart->copy()->addDays(2);
    $dayKey = $day->format('Y-m-d');

    $posts = collect(range(0, 3))->map(fn (int $minute): Post => calendarPagePost($minute % 2 ? $x : $linkedin, $day->copy()->setTime(11, $minute * 10)));

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]));
    waitFor($page, "@calendar-more-{$dayKey}-11");

    $page->assertSeeIn("@calendar-more-{$dayKey}-11", '+2')
        ->assertMissing("@calendar-post-{$posts[3]->id}")
        ->click("@calendar-more-{$dayKey}-11");
    waitFor($page, "@calendar-post-{$posts[3]->id}");

    $page->assertVisible("@calendar-post-{$posts[2]->id}")
        ->assertVisible("@calendar-post-{$posts[3]->id}")
        ->assertMissing("@calendar-more-{$dayKey}-11")
        ->assertScript('location.pathname', route('app.calendar', ['view' => 'week'], absolute: false))
        ->assertNoJavaScriptErrors();
});

test('the status filter narrows the calendar to one kind of post', function () {
    [$user, $linkedin] = calendarPageSetup();
    $weekStart = now('UTC')->startOfWeek()->addWeek();
    $day = $weekStart->copy()->addDays(2);

    $scheduled = calendarPagePost($linkedin, $day->copy()->setTime(10, 0));
    $draft = calendarPagePost($linkedin, $day->copy()->setTime(12, 0), PostStatus::Draft);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]))->resize(1600, 900);
    waitFor($page, "@calendar-post-{$scheduled->id}");
    $page->assertSeeIn('@calendar-status-filter', 'All posts')
        ->click('@calendar-status-filter');
    waitFor($page, '@calendar-status-drafts');
    $page->click('@calendar-status-drafts');
    waitForGone($page, "@calendar-post-{$scheduled->id}");

    $page->assertMissing("@calendar-post-{$scheduled->id}")
        ->assertVisible("@calendar-post-{$draft->id}")
        ->assertSeeIn('@calendar-status-filter', 'Drafts')
        ->assertScript('new URLSearchParams(location.search).get("status")', 'drafts')
        ->assertNoJavaScriptErrors();
});

test('the no date panel slides open and closed, pushing the calendar aside gradually', function () {
    [$user, $linkedin] = calendarPageSetup();
    calendarPagePost($linkedin, null, PostStatus::Draft);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month']))->resize(1280, 900);
    waitFor($page, '@calendar-no-date');

    $sample = fn (int $settled): string => <<<JS
        (async () => {
            const widths = [];
            document.querySelector('[data-testid="calendar-no-date"]').click();
            const started = performance.now();
            while (performance.now() - started < 3000 && (performance.now() - started < 500 || widths.at(-1) !== {$settled})) {
                await new Promise((resolve) => requestAnimationFrame(resolve));
                widths.push(Math.round(document.querySelector('[data-testid="calendar-undated-slide"]')?.getBoundingClientRect().width ?? 0));
            }
            return widths;
        })()
    JS;

    $opening = $page->script($sample(360));
    expect(collect($opening)->contains(fn (int $width) => $width > 0 && $width < 360))->toBeTrue()
        ->and(end($opening))->toBe(360);

    $closing = $page->script($sample(0));
    expect(collect($closing)->contains(fn (int $width) => $width > 0 && $width < 360))->toBeTrue()
        ->and(end($closing))->toBe(0);

    $page->assertMissing('@calendar-undated-panel')->assertNoJavaScriptErrors();
});

test('an undated draft without a channel says so in the language of the user and has no drag hint', function () {
    [$user, $linkedin] = calendarPageSetup();
    $user->update(['locale' => Locale::PortugueseBrazil]);
    $draft = Post::factory()->draft()->create([
        'workspace_id' => $linkedin->workspace_id,
        'user_id' => $user->id,
        'scheduled_at' => null,
    ]);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'undated' => 1]));
    waitFor($page, "@calendar-undated-{$draft->id}");

    $page->assertSeeIn("@calendar-undated-{$draft->id}", 'Sem canal')
        ->assertMissing("@calendar-drag-hint-{$draft->id}")
        ->assertNoJavaScriptErrors();
});

test('the no date panel lists undated drafts and a card opens the composer', function () {
    [$user, $linkedin, $x] = calendarPageSetup();
    $undated = calendarPagePost($linkedin, null, PostStatus::Draft);
    $dated = calendarPagePost($x, now('UTC')->addDays(3), PostStatus::Draft);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month']));
    waitFor($page, '@calendar-no-date');
    $page->assertMissing('@calendar-undated-panel')
        ->assertPresent('@calendar-no-date-icon-closed')
        ->assertMissing('@calendar-no-date-icon-open')
        ->click('@calendar-no-date');
    waitFor($page, "@calendar-undated-{$undated->id}");

    $page->assertVisible('@calendar-undated-panel')
        ->assertPresent('@calendar-no-date-icon-open')
        ->assertMissing('@calendar-no-date-icon-closed')
        ->assertSeeIn('@calendar-undated-panel', 'Undated drafts')
        ->assertMissing("@calendar-undated-{$dated->id}")
        ->assertAttribute('@calendar-no-date', 'aria-pressed', 'true')
        ->assertScript('new URLSearchParams(location.search).get("undated")', '1')
        ->click('@calendar-undated-close');
    waitForGone($page, '@calendar-undated-panel');

    $page->assertMissing('@calendar-undated-panel')
        ->click('@calendar-no-date');
    waitFor($page, "@calendar-undated-{$undated->id}");
    $page->click("@calendar-undated-{$undated->id}");
    waitFor($page, '@post-composer-dialog');

    $page->assertVisible('@post-composer-dialog')
        ->assertNoJavaScriptErrors();
});

test('show posting times renders empty slots in the week and month views', function () {
    [$user, $linkedin] = calendarPageSetup();
    $schedule = PostingSchedule::empty();

    foreach (range(0, 6) as $weekday) {
        $schedule = $schedule->withTime($weekday, '15:00');
    }

    $linkedin->update(['posting_schedule' => $schedule]);

    $weekStart = now('UTC')->startOfWeek()->addWeek();
    $day = $weekStart->copy()->addDays(2);
    $slotKey = "{$linkedin->id}-{$day->copy()->setTime(15, 0)->getTimestamp()}";

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]));
    $page->script('window.localStorage.clear()');
    $page->refresh();
    waitFor($page, "@calendar-posting-slot-{$slotKey}");

    expect($page->script("(() => { const chip = document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]'); return [chip.querySelector('svg[data-testid=\"calendar-posting-slot-icon-{$slotKey}\"]') !== null, chip.querySelector('img') === null]; })()"))
        ->toBe([true, true]);

    $page->hover("@calendar-posting-slot-{$slotKey}");
    $page->assertSeeIn("@calendar-posting-slot-{$slotKey}", __('posts.publish.add_post_in_slot'));
    expect($page->script("document.querySelector('[data-testid=\"calendar-add-{$day->format('Y-m-d')}-15\"]').getBoundingClientRect().height"))
        ->toBe($page->script("document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]').getBoundingClientRect().height"));

    expect($page->script("document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]').closest('[data-testid^=\"calendar-slot-\"]').dataset.testid"))
        ->toBe("calendar-slot-{$day->format('Y-m-d')}-15");

    $page->script(<<<'JS'
        (() => {
            window.__partialData = [];
            const setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
            XMLHttpRequest.prototype.setRequestHeader = function (name, value) {
                if (name.toLowerCase() === 'x-inertia-partial-data') {
                    window.__partialData.push(String(value));
                }

                return setRequestHeader.call(this, name, value);
            };
        })()
    JS);
    $page->click('@calendar-menu');
    waitFor($page, '@calendar-toggle-slots');
    $page->click('@calendar-toggle-slots');
    waitForGone($page, '[data-testid^="calendar-posting-slot-"]');
    waitForCondition($page, "!new URLSearchParams(location.search).has('slots')");

    expect(browserStorageItem($page, $user, 'publish.showSlots'))->toBeFalse();
    $page->assertMissing("@calendar-posting-slot-{$slotKey}")
        ->assertScript("new URLSearchParams(location.search).has('slots')", false)
        ->assertScript("window.__partialData.every((only) => !only.split(',').includes('slots'))", true);

    $page->refresh();
    waitFor($page, "@calendar-slot-{$day->format('Y-m-d')}-15");
    $page->assertMissing("@calendar-posting-slot-{$slotKey}");

    $month = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]));
    waitFor($month, "@calendar-posting-slot-{$slotKey}");

    expect($month->script("document.querySelector('[data-testid=\"calendar-posting-slot-{$slotKey}\"]').closest('[data-testid^=\"calendar-day-\"]').dataset.testid"))
        ->toBe("calendar-day-{$day->format('Y-m-d')}");

    $month->hover("@calendar-posting-slot-{$slotKey}");
    $month->assertSeeIn("@calendar-posting-slot-{$slotKey}", __('posts.publish.add_post_in_slot'))
        ->click("@calendar-posting-slot-{$slotKey}");
    waitFor($month, "@composer-caption-{$linkedin->id}");
    $month->fill("@composer-caption-{$linkedin->id}", 'From a calendar slot');
    waitFor($month, '@composer-submit');

    expect($month->script('document.querySelector(\'[data-testid="composer-submit"]\').dataset.scheduleMode'))->toBe('custom');

    $month->click('@composer-submit');
    waitForGone($month, '@post-composer-dialog');
    $post = Post::query()->where('workspace_id', $linkedin->workspace_id)->sole();

    expect($post->scheduled_at->equalTo($day->copy()->setTime(15, 0)))->toBeTrue()
        ->and($post->schedule_mode)->toBe(ScheduleMode::Queue);
    $month->assertNoJavaScriptErrors();
});

test('a calendar opened by its link asks for its posting times only once its page is in the browser history, so Back still returns to it', function () {
    [$user, $linkedin] = calendarPageSetup();
    $post = calendarPagePost($linkedin, now('UTC')->startOfWeek()->addWeek()->addDays(2)->setTime(10, 0));
    $this->actingAs($user);

    $page = visit(route('app.settings.preferences'));
    $page->page()->context()->addInitScript(<<<'JS'
        window.__slotsAskedWith = [];
        const setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
        XMLHttpRequest.prototype.setRequestHeader = function (name, value) {
            if (name.toLowerCase() === 'x-inertia-partial-data' && String(value).split(',').includes('slots')) {
                window.__slotsAskedWith.push(window.history.state?.page ? 'page' : 'nothing');
            }

            return setRequestHeader.call(this, name, value);
        };
    JS);
    $page->navigate(route('app.calendar', ['view' => 'week']));
    waitForCondition($page, 'window.__slotsAskedWith.length === 1');

    expect($page->script('window.__slotsAskedWith'))->toBe(['page']);

    $page->click('@calendar-next');
    waitFor($page, "@calendar-post-{$post->id}");
    $page->back();
    waitForGone($page, "@calendar-post-{$post->id}");

    $page->assertPathIs(route('app.calendar', ['view' => 'week'], false))
        ->assertScript("new URLSearchParams(location.search).has('week')", false)
        ->assertNoJavaScriptErrors();
});

test('in the month a post the network deleted shows the deleted mark instead of the published one', function () {
    [$user, $linkedin] = calendarPageSetup();
    $day = now('UTC')->subMonthNoOverflow()->startOfMonth()->addDays(14);
    $published = Post::factory()->forAccount($linkedin)->published()->create([
        'user_id' => $user->id,
        'scheduled_at' => $day->setTime(10, 0),
        'published_at' => $day->setTime(10, 0),
    ]);
    $deleted = Post::factory()->forAccount($linkedin)->deletedOnNetwork()->create([
        'user_id' => $user->id,
        'scheduled_at' => $day->setTime(12, 0),
        'published_at' => $day->setTime(12, 0),
    ]);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]))->resize(1440, 900);
    waitFor($page, "@calendar-post-{$deleted->id}");

    $page->assertPresent("@calendar-post-deleted-{$deleted->id}")
        ->assertMissing("@calendar-post-published-{$deleted->id}")
        ->assertAttribute("@calendar-post-deleted-{$deleted->id}", 'aria-label', __('calendar.post_status.deleted'))
        ->assertPresent("@calendar-post-published-{$published->id}")
        ->assertMissing("@calendar-post-deleted-{$published->id}")
        ->assertNoJavaScriptErrors();
});

test('in the month a post shows its network in color and a status icon with a tooltip, and a free posting time reads as a hatched empty slot', function () {
    [$user, $linkedin] = calendarPageSetup();
    $schedule = PostingSchedule::empty();

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

    $linkedin->update(['posting_schedule' => $schedule]);

    $day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(9);
    $scheduled = calendarPagePost($linkedin, $day->copy()->setTime(15, 0));
    $scheduled->update(['content' => '<p>Launch recap</p>']);
    $draft = calendarPagePost($linkedin, $day->copy()->setTime(10, 0), PostStatus::Draft);
    $pending = calendarPagePost($linkedin, $day->copy()->addDay()->setTime(12, 0), PostStatus::PendingApproval);
    $failed = calendarPagePost($linkedin, $day->copy()->addDays(2)->setTime(13, 0), PostStatus::Failed);
    $slotKey = "{$linkedin->id}-{$day->copy()->setTime(18, 0)->getTimestamp()}";

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d'), 'slots' => 1]))->resize(1440, 900);
    waitFor($page, "@calendar-posting-slot-{$slotKey}");
    waitFor($page, "@calendar-post-{$scheduled->id}");

    $page->assertDontSeeIn("@calendar-post-{$scheduled->id}", 'Launch recap')
        ->assertPresent("@calendar-post-draft-{$draft->id}")
        ->assertPresent("@calendar-post-pending-{$pending->id}")
        ->assertPresent("@calendar-post-failed-{$failed->id}")
        ->assertMissing("@calendar-post-pending-{$scheduled->id}")
        ->assertMissing("@calendar-post-failed-{$scheduled->id}");

    $styles = $page->script(<<<JS
        (() => {
            const chip = (id) => document.querySelector('[data-testid="' + id + '"]');
            const style = (id) => getComputedStyle(chip(id));

            return {
                postIcon: getComputedStyle(chip('calendar-post-platform-{$scheduled->id}')).color,
                draftIcon: getComputedStyle(chip('calendar-post-platform-{$draft->id}')).color,
                draftBorder: style('calendar-post-{$draft->id}').borderStyle,
                slotBorder: style('calendar-posting-slot-{$slotKey}').borderStyle,
                slotHatched: style('calendar-posting-slot-{$slotKey}').backgroundImage.startsWith('linear-gradient'),
                slotIcons: chip('calendar-posting-slot-{$slotKey}').querySelectorAll('svg').length,
                failedChipLooksScheduled: ['borderColor', 'backgroundColor'].every((key) => style('calendar-post-{$failed->id}')[key] === style('calendar-post-{$scheduled->id}')[key]),
                failedIconColored: style('calendar-post-failed-{$failed->id}').color !== style('post-schedule-mode-{$scheduled->id}').color,
                pendingIconMuted: style('calendar-post-pending-{$pending->id}').color === style('post-schedule-mode-{$scheduled->id}').color,
            };
        })()
    JS);

    expect($styles)->toMatchArray([
        'postIcon' => 'rgb(10, 102, 194)',
        'draftBorder' => 'solid',
        'slotBorder' => 'dashed',
        'slotHatched' => true,
        'slotIcons' => 1,
        'draftIcon' => 'rgb(10, 102, 194)',
        'failedChipLooksScheduled' => true,
        'failedIconColored' => true,
        'pendingIconMuted' => true,
    ]);

    $page->hover("@calendar-post-pending-{$pending->id}");
    waitForText($page, '[data-slot="tooltip-content"]', __('calendar.post_status.pending_approval'));
    $page->assertSee(__('calendar.post_status.pending_approval'));

    $page->assertNoJavaScriptErrors();
});

test('clicking a scheduled post chip in the month view opens its details', function () {
    [$user, $linkedin] = calendarPageSetup();
    $at = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10)->setTime(10, 0);
    $post = calendarPagePost($linkedin, $at);
    $post->update(['content' => '<p>Details caption</p>']);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $at->format('Y-m-d')]));
    waitFor($page, "@calendar-post-{$post->id}");

    $page->assertAttribute("@calendar-post-{$post->id}", 'type', 'button')
        ->assertPresent("@calendar-post-platform-{$post->id}")
        ->assertMissing("@calendar-post-thumbnail-{$post->id}")
        ->assertMissing("@post-card-{$post->id}");

    $page->click("@calendar-post-{$post->id}");
    waitFor($page, "@post-details-{$post->id}");

    $page->assertVisible("@post-details-{$post->id}")
        ->assertSeeIn("@post-details-{$post->id}", 'Details caption')
        ->assertPresent("@post-details-edit-{$post->id}")
        ->assertPresent("@post-details-publish-now-{$post->id}");

    $page->keys("@post-details-{$post->id}", 'Escape');
    waitForGone($page, "@post-details-{$post->id}");
    expect($page->script('document.activeElement?.dataset.testid'))->toBe("calendar-post-{$post->id}");

    $page->click("@calendar-post-{$post->id}");
    waitFor($page, "@post-details-{$post->id}");
    $page->assertVisible("@post-details-{$post->id}")
        ->assertNoJavaScriptErrors();
});

test('a published post opens details with its metrics, go to post and the sent menu', function () {
    Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);
    [$user] = calendarPageSetup();
    $instagram = SocialAccount::factory()->instagram()->create(['workspace_id' => $user->current_workspace_id, 'timezone' => 'UTC']);

    $post = Post::factory()->forAccount($instagram)->published()->create([
        'user_id' => $user->id,
        'content' => 'Already live',
        'platform_url' => 'https://www.instagram.com/p/abc/',
        'published_at' => now()->subHour(),
    ]);
    $publication = AnalyticsPublication::factory()->create([
        'workspace_id' => $instagram->workspace_id,
        'social_account_id' => $instagram->id,
        'social_account_key' => $instagram->id,
        'post_id' => $post->id,
        'platform' => Platform::Instagram,
        'network' => Platform::Instagram->network(),
        'remote_id' => $post->platform_post_id,
    ]);
    AnalyticsPublicationDailySnapshot::factory()->create([
        'publication_id' => $publication->id,
        'metrics' => [
            'reactions' => ['value' => 12, 'unit' => 'count', 'availability' => 'available'],
        ],
    ]);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month']));
    waitFor($page, "@calendar-post-{$post->id}");
    $page->click("@calendar-post-{$post->id}");
    waitFor($page, "@post-details-{$post->id}");

    $page->assertPresent("@post-details-metrics-{$post->id}")
        ->assertPresent("@post-details-view-{$post->id}")
        ->assertMissing("@post-details-edit-{$post->id}");

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

    expect($page->script("Array.from(document.querySelectorAll('[data-testid=\"post-card-menu-content-details-{$post->id}\"] [role=\"menuitem\"]')).map((element) => element.dataset.testid)"))
        ->toBe(["post-duplicate-details-{$post->id}", "post-share-link-details-{$post->id}", "post-copy-link-details-{$post->id}"]);
    $page->assertNoJavaScriptErrors();
});

test('an overflowing month day expands and collapses back, scrolling inside its cell', function () {
    [$user, $linkedin] = calendarPageSetup();
    $day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(12);
    $dayKey = $day->format('Y-m-d');
    $posts = collect(range(0, 9))->map(fn (int $index) => calendarPagePost($linkedin, $day->copy()->setTime(9 + $index, 0)));
    $last = $posts->last();

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $dayKey]))->resize(1440, 900);
    waitFor($page, "@calendar-more-{$dayKey}");

    $cellHeight = "document.querySelector('[data-testid=\"calendar-day-{$dayKey}\"]').getBoundingClientRect().height";
    $heightBefore = $page->script($cellHeight);
    expect($page->script(calendarMonthDayFits($dayKey)))->toBe(['shown' => 4, 'fits' => true]);

    $page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 6]))
        ->assertMissing("@calendar-post-{$last->id}")
        ->click("@calendar-more-{$dayKey}");
    waitFor($page, "@calendar-post-{$last->id}");

    $layout = $page->script(<<<JS
        (() => {
            const cell = document.querySelector('[data-testid="calendar-day-{$dayKey}"]').getBoundingClientRect();
            const items = document.querySelector('[data-testid="calendar-items-{$dayKey}"]');
            const more = document.querySelector('[data-testid="calendar-more-{$dayKey}"]').getBoundingClientRect();

            return {
                scrolls: items.scrollHeight > items.clientHeight,
                moreInCell: more.bottom <= cell.bottom + 0.5,
            };
        })()
    JS);

    expect($layout)->toBe(['scrolls' => true, 'moreInCell' => true])
        ->and(abs($page->script($cellHeight) - $heightBefore))->toBeLessThan(1);

    $page->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.less'))
        ->click("@calendar-more-{$dayKey}");
    waitForGone($page, "@calendar-post-{$last->id}");

    $page->assertMissing("@calendar-post-{$last->id}")
        ->assertSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 6]))
        ->assertNoJavaScriptErrors();
});

test('a details action reloads the calendar and the details show the new status', function () {
    [$user, $linkedin] = calendarPageSetup();
    $at = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10)->setTime(10, 0);
    $post = calendarPagePost($linkedin, $at);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $at->format('Y-m-d')]));
    waitFor($page, "@calendar-post-{$post->id}");
    $page->click("@calendar-post-{$post->id}");
    waitFor($page, "@post-card-menu-details-{$post->id}");
    $page->click("@post-card-menu-details-{$post->id}");
    waitFor($page, "@post-move-drafts-details-{$post->id}");
    $page->click("@post-move-drafts-details-{$post->id}");
    waitForText($page, "@post-details-status-{$post->id}", __('posts.status.draft'));
    waitFor($page, "@calendar-post-draft-{$post->id}");

    expect($post->refresh()->status)->toBe(PostStatus::Draft);

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

test('on a phone the week shows its seven days in columns with their posts', function () {
    [$user, $linkedin, $x] = calendarPageSetup();
    $weekStart = now('UTC')->startOfWeek()->addWeek();
    $first = calendarPagePost($linkedin, $weekStart->copy()->addDays(2)->setTime(9, 0));
    $second = calendarPagePost($x, $weekStart->copy()->addDays(4)->setTime(16, 0));

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week', 'week' => $weekStart->format('Y-m-d')]))->resize(390, 844);
    waitFor($page, '@calendar-time-grid');

    expect($page->script('document.querySelectorAll(\'[data-testid^="calendar-column-"]\').length'))->toBe(7);
    expect($page->script('[...document.querySelectorAll(\'[data-testid^="calendar-add-"]\')].every((button) => button.getBoundingClientRect().width === 0)'))->toBeTrue();

    $page->assertPresent("@calendar-post-{$first->id}")
        ->assertPresent("@calendar-post-{$second->id}")
        ->assertScript("(() => { const box = document.querySelector('[data-testid=\"calendar-post-{$first->id}\"]').getBoundingClientRect(); return box.height === 28 && box.width >= box.height; })()", true)
        ->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)
        ->assertNoJavaScriptErrors();
});

test('the three days view shows three columns, and only the phone picker offers it', function () {
    [$user, $linkedin] = calendarPageSetup();
    $day = now('UTC')->addDays(10)->startOfDay();
    $post = calendarPagePost($linkedin, $day->copy()->addDay()->setTime(9, 0));

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'days', 'day' => $day->format('Y-m-d')]))->resize(390, 844);
    waitFor($page, '@calendar-time-grid');

    expect($page->script('[...document.querySelectorAll(\'[data-testid^="calendar-column-"]\')].map((el) => el.dataset.testid)'))
        ->toBe(collect(range(0, 2))->map(fn (int $offset): string => "calendar-column-{$day->copy()->addDays($offset)->format('Y-m-d')}")->all());

    $page->assertPresent("@calendar-post-{$post->id}")
        ->assertSeeIn("@calendar-post-{$post->id}", '9:00')
        ->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true);

    $page->resize(1280, 900);
    waitFor($page, '@calendar-view-trigger');
    $page->assertSeeIn('@calendar-view-trigger', __('calendar.days'))
        ->click('@calendar-view-trigger');
    waitFor($page, '@calendar-view-week');
    $page->assertPresent('@calendar-view-month')
        ->assertMissing('@calendar-view-days')
        ->keys('@calendar-view-week', 'Escape');
    waitForGone($page, '@calendar-view-week');
    $page->click('@calendar-next');
    waitForCondition($page, "new URLSearchParams(location.search).get('day') === '{$day->copy()->addDays(3)->format('Y-m-d')}'");

    $page->assertMissing("@calendar-post-{$post->id}")->assertNoJavaScriptErrors();
});

test('on a phone the calendar tab of the view switch keeps the three days view, on a desktop it opens the month', function () {
    [$user] = calendarPageSetup();

    $this->actingAs($user);

    $calendarTabPath = 'new URL(document.querySelector(\'[data-testid="schedule-view-calendar"]\').href).pathname';

    $page = visit(route('app.calendar', ['view' => 'days']))->resize(390, 844);
    waitFor($page, '@schedule-view-trigger');
    $page->click('@schedule-view-trigger');
    waitForOpen($page, '@schedule-view-menu');
    $page->assertScript($calendarTabPath, route('app.calendar', ['view' => 'days'], false))
        ->click('@schedule-view-calendar');
    waitFor($page, '@calendar-time-grid');
    $page->assertPathIs(route('app.calendar', ['view' => 'days'], false));

    $page->resize(1280, 900);
    waitForState($page, '@schedule-view-calendar', 'new URL(element.href).pathname.endsWith("/month")');
    $page->assertScript($calendarTabPath, route('app.calendar', ['view' => 'month'], false))
        ->assertNoJavaScriptErrors();
});

test('on a phone the month shows its weeks in columns with the posts of each day as icon tiles', function () {
    [$user, $linkedin, $x] = calendarPageSetup();
    $day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(12);
    $dayKey = $day->format('Y-m-d');
    $posts = collect(range(0, 4))->map(fn (int $index): Post => calendarPagePost($index % 2 ? $x : $linkedin, $day->copy()->setTime(9 + $index, 0)));

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $dayKey]))->resize(390, 844);
    waitFor($page, '@calendar-month-grid');

    $page->assertPresent("@calendar-day-{$dayKey}")
        ->assertPresent("@calendar-post-{$posts[0]->id}")
        ->assertSeeIn("@calendar-more-{$dayKey}", '+2')
        ->assertDontSeeIn("@calendar-more-{$dayKey}", __('calendar.more', ['count' => 2]))
        ->assertScript(calendarMonthDayFits($dayKey), ['shown' => 3, 'fits' => true])
        ->assertScript("(() => { const chip = document.querySelector('[data-testid=\"calendar-post-{$posts[0]->id}\"]'); const box = chip.getBoundingClientRect(); return box.height === 28 && box.width >= box.height && chip.innerText.trim() === '' && !chip.querySelector('img, video'); })()", true)
        ->assertScript('document.documentElement.scrollWidth <= window.innerWidth', true)
        ->assertNoJavaScriptErrors();

    $page->click("@calendar-more-{$dayKey}");
    waitFor($page, "@calendar-post-{$posts[4]->id}");
    $page->assertAttribute("@calendar-more-{$dayKey}", 'aria-label', __('calendar.less'));
});

test('on a phone, tapping a post in the month opens its details directly', function () {
    [$user, $linkedin] = calendarPageSetup();
    $at = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10)->setTime(12, 0);
    $post = calendarPagePost($linkedin, $at);

    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $at->format('Y-m-d')]))->resize(390, 844);
    waitFor($page, "@calendar-post-{$post->id}");
    $page->click("@calendar-post-{$post->id}");
    waitFor($page, "@post-details-{$post->id}");

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

test('in Portuguese the week columns show one-word weekday names', function () {
    [$user] = calendarPageSetup();
    $user->update(['locale' => Locale::PortugueseBrazil]);
    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week']))->resize(1280, 900);
    waitFor($page, '@calendar-time-grid');

    $names = $page->script('[...document.querySelectorAll(\'[data-testid^="calendar-column-"] span:first-child\')].map((el) => el.textContent.trim().toLowerCase())');

    expect($names)->toHaveCount(7)
        ->and(collect($names)->sort()->values()->all())->toBe(['domingo', 'quarta', 'quinta', 'segunda', 'sexta', 'sábado', 'terça']);

    $page->assertNoJavaScriptErrors();
});

test('on a phone the period picker opens from the bottom, switches the view in place and jumps to a picked day', function () {
    [$user] = calendarPageSetup();
    $this->actingAs($user);

    $shownWeek = now()->addYear()->setDate(now()->addYear()->year, 3, 1)->toDateString();
    $pickedDay = now()->addYear()->setDate(now()->addYear()->year, 3, 17);
    $page = visit(route('app.calendar', ['view' => 'week', 'week' => $shownWeek]))->resize(390, 844);
    waitFor($page, '@calendar-period-trigger');

    expect($page->script('Boolean(document.querySelector(\'[data-testid="calendar-previous"]\'))'))->toBeFalse();

    $page->click('@calendar-period-trigger');
    waitFor($page, '@calendar-period-calendar');
    waitForState($page, '@calendar-period-picker', 'Math.abs(window.innerHeight - element.getBoundingClientRect().bottom) <= 1');

    $page->assertVisible('@calendar-view-days')
        ->click("[data-testid=\"calendar-period-calendar\"] [data-testid=\"calendar-date-{$pickedDay->toDateString()}\"]");
    waitForCondition($page, "new URLSearchParams(location.search).get(\"week\") !== \"{$shownWeek}\"");

    $week = $page->script('new URLSearchParams(location.search).get("week")');
    expect($week >= $pickedDay->subDays(6)->toDateString() && $week <= $pickedDay->toDateString())->toBeTrue();
    waitForGone($page, '@calendar-period-picker');
    $page->assertMissing('@calendar-period-picker');

    $page->click('@calendar-period-trigger');
    waitFor($page, '@calendar-view-month');
    $page->click('@calendar-view-month');
    waitForCondition($page, 'location.pathname.endsWith("/month")');

    expect($page->script('location.pathname.endsWith("/month")'))->toBeTrue();
    $page->assertVisible('@calendar-period-calendar')
        ->assertAttribute('@calendar-view-month', 'aria-pressed', 'true')
        ->click('@calendar-today');
    waitForGone($page, '@calendar-period-picker');

    $page->assertMissing('@calendar-period-picker')->assertNoJavaScriptErrors();

    $page->resize(1280, 900);
    waitFor($page, '@calendar-previous');
    $page->assertVisible('@calendar-next')->assertVisible('@calendar-view-trigger');
});

test('the previous period arrow starts on the same line as the calendar', function () {
    [$user] = calendarPageSetup();
    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week']))->resize(1440, 900);
    waitFor($page, '@calendar-time-grid');

    expect($page->script("Math.round(document.querySelector('[data-testid=\"calendar-previous\"]').getBoundingClientRect().left)"))
        ->toBe($page->script("Math.round(document.querySelector('[data-testid=\"calendar-grid\"]').getBoundingClientRect().left)"));
    $page->assertNoJavaScriptErrors();
});

test('on a phone the month chips show each post\'s status icon and fit their day', function () {
    [$user, $linkedin] = calendarPageSetup();
    $day = now('UTC')->addMonthNoOverflow()->startOfMonth()->addDays(10);
    $draft = calendarPagePost($linkedin, $day->setTime(9, 0), PostStatus::Draft);
    $failed = calendarPagePost($linkedin, $day->setTime(11, 0), PostStatus::Failed);
    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'month', 'month' => $day->format('Y-m-d')]))->resize(390, 844);
    waitFor($page, "@calendar-post-{$draft->id}");

    $page->assertPresent("@calendar-post-draft-{$draft->id}")
        ->assertPresent("@calendar-post-failed-{$failed->id}");
    expect($page->script("(() => { const chip = document.querySelector('[data-testid=\"calendar-post-{$draft->id}\"]'); const day = document.querySelector('[data-testid=\"calendar-day-{$day->format('Y-m-d')}\"]'); return chip.getBoundingClientRect().right <= day.getBoundingClientRect().right; })()"))->toBeTrue();
    $page->assertNoJavaScriptErrors();
});

test('hiding posting times keeps the page address in the form the server answers with', function () {
    [$user] = calendarPageSetup();
    $week = now('UTC')->addWeek()->startOfWeek()->format('Y-m-d');
    $this->actingAs($user);

    $page = visit(route('app.calendar', ['view' => 'week', 'week' => $week, 'undated' => 1, 'slots' => 1]));
    $page->click('@calendar-menu');
    waitFor($page, '@calendar-toggle-slots');
    $page->click('@calendar-toggle-slots');
    waitForCondition($page, "!new URLSearchParams(location.search).has('slots')");

    $page->assertScript('location.search', "?undated=1&week={$week}")
        ->assertNoJavaScriptErrors();
});