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.

8.5 KB
Raw Blame
<?php

declare(strict_types=1);

use App\Enums\Notification\Type;
use App\Enums\SocialAccount\Platform;
use App\Enums\SocialAccount\Status;
use App\Jobs\Analytics\BootstrapAccountAnalytics;
use App\Jobs\Analytics\CollectAccountDailySnapshot;
use App\Jobs\SendNotification;
use App\Mail\AccountDisconnected;
use App\Models\SocialAccount;
use App\Models\User;
use App\Models\Workspace;
use App\Support\PostingSchedule;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Queue;

beforeEach(function () {
    Queue::fake([BootstrapAccountAnalytics::class, CollectAccountDailySnapshot::class]);

    $this->owner = User::factory()->create();
    $this->workspace = Workspace::factory()->create(['user_id' => $this->owner->id]);
});

// ---- needsProactiveTokenRefresh ----

test('needsProactiveTokenRefresh: rotating platforms refresh only when expired, extension platforms while still valid', function () {
    // Rotating (X): a still-valid token that is merely expiring soon is NOT refreshed.
    $xValid = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'token_expires_at' => now()->addMinutes(10),
    ]);
    expect($xValid->needsProactiveTokenRefresh())->toBeFalse();

    // Rotating (X): once actually expired, it is refreshed.
    $xExpired = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'token_expires_at' => now()->subMinute(),
    ]);
    expect($xExpired->needsProactiveTokenRefresh())->toBeTrue();

    // Extension-model (Instagram): a still-valid token that is expiring soon MUST
    // be refreshed while valid — its token can't be extended once expired.
    $igValid = SocialAccount::factory()->create([
        'workspace_id' => $this->workspace->id,
        'platform' => Platform::Instagram,
        'token_expires_at' => now()->addMinutes(10),
    ]);
    expect($igValid->needsProactiveTokenRefresh())->toBeTrue();
});

// ---- markAsTokenExpired ----

test('markAsTokenExpired updates status and dispatches notification when transitioning from connected', function () {
    Queue::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Connected,
        'username' => 'testuser',
    ]);

    $account->markAsTokenExpired('refresh_token rejected');

    expect($account->fresh()->status)->toBe(Status::TokenExpired);
    expect($account->fresh()->error_message)->toBe('refresh_token rejected');

    Queue::assertPushed(SendNotification::class, function ($job) {
        return $job->user->id === $this->owner->id
            && $job->type === Type::AccountDisconnected
            && $job->mailable instanceof AccountDisconnected;
    });
});

test('markAsTokenExpired does not dispatch notification when already token expired', function () {
    Queue::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::TokenExpired,
        'disconnected_at' => now()->subDay(),
    ]);

    $account->markAsTokenExpired('another failure');

    Queue::assertNotPushed(SendNotification::class);
});

test('markAsTokenExpired does not dispatch notification when account is disconnected', function () {
    Queue::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Disconnected,
        'disconnected_at' => now()->subDay(),
    ]);

    $account->markAsTokenExpired('refresh_token rejected after disconnect');

    Queue::assertNotPushed(SendNotification::class);
});

test('markAsTokenExpired respects notify=false flag', function () {
    Queue::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Connected,
        'username' => 'testuser',
    ]);

    $account->markAsTokenExpired('refresh_token rejected', notify: false);

    expect($account->fresh()->status)->toBe(Status::TokenExpired);
    Queue::assertNotPushed(SendNotification::class);
});

test('markAsTokenExpired preserves existing disconnected_at value', function () {
    Queue::fake();

    $earlier = now()->subDays(3);
    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Connected,
        'disconnected_at' => $earlier,
    ]);

    $account->markAsTokenExpired('refresh_token rejected');

    expect($account->fresh()->disconnected_at->toIso8601String())
        ->toBe($earlier->toIso8601String());
});

test('markAsTokenExpired emails the workspace owner', function () {
    Mail::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Connected,
        'username' => 'testuser',
    ]);

    $account->markAsTokenExpired('refresh_token rejected');

    Mail::assertQueued(AccountDisconnected::class, fn (AccountDisconnected $mail) => $mail->hasTo($this->owner->email)
        && $mail->account->is($account));
});

// ---- markAsDisconnected ----

test('markAsDisconnected updates status and dispatches notification when transitioning from connected', function () {
    Queue::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Connected,
        'username' => 'testuser',
    ]);

    $account->markAsDisconnected('manual disconnect');

    expect($account->fresh()->status)->toBe(Status::Disconnected);
    expect($account->fresh()->error_message)->toBe('manual disconnect');
    expect($account->fresh()->disconnected_at)->not->toBeNull();

    Queue::assertPushed(SendNotification::class, function ($job) {
        return $job->user->id === $this->owner->id
            && $job->type === Type::AccountDisconnected;
    });
});

test('markAsDisconnected does not dispatch notification when already disconnected', function () {
    Queue::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Disconnected,
        'disconnected_at' => now()->subDay(),
    ]);

    $account->markAsDisconnected('another disconnect');

    Queue::assertNotPushed(SendNotification::class);
});

test('markAsDisconnected emails the workspace owner', function () {
    Mail::fake();

    $account = SocialAccount::factory()->x()->create([
        'workspace_id' => $this->workspace->id,
        'status' => Status::Connected,
        'username' => 'testuser',
    ]);

    $account->markAsDisconnected('manual disconnect');

    Mail::assertQueued(AccountDisconnected::class, fn (AccountDisconnected $mail) => $mail->hasTo($this->owner->email)
        && $mail->account->is($account));
});

// ---- profile_url ----

test('profile_url for google business prefers the Maps listing when stored', function () {
    $account = SocialAccount::factory()->googleBusiness()->create([
        'workspace_id' => $this->workspace->id,
        'meta' => [
            'location_id' => 'accounts/123456789/locations/987654321',
            'maps_uri' => 'https://maps.google.com/?cid=123',
        ],
    ]);

    expect($account->profile_url)->toBe('https://maps.google.com/?cid=123');
});

test('profile_url for google business falls back to the location dashboard', function () {
    $account = SocialAccount::factory()->googleBusiness()->create([
        'workspace_id' => $this->workspace->id,
    ]);

    expect($account->profile_url)->toBe('https://business.google.com/dashboard/l/u987654321');
});

test('profile_url for google business is null without a stored location', function () {
    $account = SocialAccount::factory()->googleBusiness()->create([
        'workspace_id' => $this->workspace->id,
        'meta' => ['google_user_id' => 'google-user-123'],
    ]);

    expect($account->profile_url)->toBeNull();
});

test('hasPostingSchedule is true only when the schedule yields an upcoming slot', function (?PostingSchedule $schedule, bool $expected) {
    $account = SocialAccount::factory()->create([
        'workspace_id' => $this->workspace->id,
        'timezone' => 'America/Sao_Paulo',
        'posting_schedule' => $schedule,
    ]);

    expect($account->hasPostingSchedule())->toBe($expected);
})->with([
    'no schedule' => [null, false],
    'no times' => [fn () => PostingSchedule::empty(), false],
    'times only on switched-off days' => [fn () => PostingSchedule::empty()->withTime(2, '09:00')->withDayEnabled(2, false), false],
    'an enabled time' => [fn () => PostingSchedule::empty()->withTime(2, '09:00'), true],
]);