Files
portal/app/tests/Feature/ClientTg/PollModerationTest.php
T

173 lines
8.0 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
use App\Jobs\ClientTg\PollTelegramModerationJob;
use App\Models\AdWallet;
use App\Models\AdWalletHold;
use App\Models\ClientTg\Campaign;
use App\Models\Tenant;
use App\Services\Advertising\AdWalletService;
use App\Services\ClientTg\RobotResult;
use App\Services\ClientTg\TelegramRobotRunner;
use App\Services\NotificationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery\MockInterface;
use Tests\Concerns\SharesSupplierPdo;
// Опросчик перечисляет moderating-кампании через pgsql_supplier (BYPASSRLS).
// Шарим PDO, иначе данные транзакции RefreshDatabase не видны supplier-соединению.
uses(RefreshDatabase::class, SharesSupplierPdo::class);
/**
* Задача 3.4 — PollTelegramModerationJob: опросчик вердикта модерации МТС.
*
* Живая отправка робота ставит `moderating` (задача 3.2). Опросчик раз в цикл
* читает кабинет роботом-читалкой (в тестах — мок) по `mts_campaign_id` и применяет
* вердикт:
* — `rejected` → статус `rejected` + причина; возврат брони (в бою); уведомление
* «отклонена»;
* — `approved` → `launched`; уведомление «одобрена»;
* — `moderating` (ещё не проверено) / робот не смог прочитать → НЕ трогаем, ждём
* следующего цикла (деньги/статус без изменений).
*/
/** Кампания в заданном статусе (self-contained). */
function pollCampaign(int $tenantId, string $status, ?string $mtsId = null): Campaign
{
return Campaign::query()->create([
'tenant_id' => $tenantId,
'status' => $status,
'mts_campaign_id' => $mtsId,
'ad_text' => 'Опрос-тест',
'ord_category' => 'Размещение рекламы',
'budget_cap_rub' => '1000.00',
'audience_kind' => Campaign::AUDIENCE_LIST,
'planned_count' => 0,
'estimated_cost_rub' => '0.00',
'created_by' => 1,
]);
}
/** Кошелёк тенанта + активная бронь под кампанию (как в SweepStuckTest). */
function pollWalletWithHold(int $tenantId, int $campaignId, string $balance, string $freeze): void
{
AdWallet::query()->create([
'tenant_id' => $tenantId,
'balance_rub' => $balance,
'frozen_rub' => '0.00',
]);
app(AdWalletService::class)->freeze($tenantId, 'telegram', 'campaign', $campaignId, $freeze);
}
/** Подменяет робота-читалку мок-результатом. */
function pollMockRobot(RobotResult $result): void
{
$mock = Mockery::mock(TelegramRobotRunner::class);
$mock->shouldReceive('readModeration')->andReturn($result);
app()->instance(TelegramRobotRunner::class, $mock);
}
/** Мок NotificationService для проверки, какое уведомление ушло. */
function pollMockNotifications(): MockInterface
{
$mock = Mockery::mock(NotificationService::class);
app()->instance(NotificationService::class, $mock);
return $mock;
}
it('RobotResult знает moderationStatus и разбирает его из JSON робота', function () {
$r = RobotResult::fromRobotJson(['ok' => true, 'moderationStatus' => 'rejected', 'reason' => 'нельзя']);
expect($r->moderationStatus)->toBe('rejected')
->and($r->reason)->toBe('нельзя');
// Отсутствие поля → null (робот его пока не прислал).
expect(RobotResult::fromRobotJson(['ok' => true])->moderationStatus)->toBeNull();
});
it('вердикт «отклонена» → rejected + причина, бронь возвращена, уведомление «отклонена»', function () {
config()->set('client_tg.sandbox', false);
$t = Tenant::factory()->create();
$c = pollCampaign($t->id, Campaign::STATUS_MODERATING, '2231134');
pollWalletWithHold($t->id, $c->id, '5000.00', '1000.00');
pollMockRobot(new RobotResult(ok: true, moderationStatus: 'rejected', reason: 'Ссылка недоступна'));
$notify = pollMockNotifications();
$notify->shouldReceive('notifyTelegramCampaignRejected')->once();
$notify->shouldReceive('notifyTelegramCampaignApproved')->never();
PollTelegramModerationJob::dispatchSync();
$fresh = Campaign::find($c->id);
expect($fresh->status)->toBe(Campaign::STATUS_REJECTED)
->and($fresh->status_reason)->toBe('Ссылка недоступна')
->and((string) AdWallet::where('tenant_id', $t->id)->value('frozen_rub'))->toBe('0.00')
->and(AdWalletHold::where('source_id', $c->id)->value('status'))->toBe(AdWalletHold::STATUS_RELEASED);
});
it('вердикт «одобрена» → launched, уведомление «одобрена», деньги не тронуты', function () {
config()->set('client_tg.sandbox', false);
$t = Tenant::factory()->create();
$c = pollCampaign($t->id, Campaign::STATUS_MODERATING, '2231140');
pollWalletWithHold($t->id, $c->id, '5000.00', '1000.00');
pollMockRobot(new RobotResult(ok: true, moderationStatus: 'approved'));
$notify = pollMockNotifications();
$notify->shouldReceive('notifyTelegramCampaignApproved')->once();
$notify->shouldReceive('notifyTelegramCampaignRejected')->never();
PollTelegramModerationJob::dispatchSync();
expect(Campaign::find($c->id)->status)->toBe(Campaign::STATUS_LAUNCHED)
->and((string) AdWallet::where('tenant_id', $t->id)->value('frozen_rub'))->toBe('1000.00')
->and(AdWalletHold::where('source_id', $c->id)->value('status'))->toBe(AdWalletHold::STATUS_ACTIVE);
});
it('вердикт «ещё на модерации» → остаётся moderating, без уведомлений и без денег', function () {
config()->set('client_tg.sandbox', false);
$t = Tenant::factory()->create();
$c = pollCampaign($t->id, Campaign::STATUS_MODERATING, '2231150');
pollWalletWithHold($t->id, $c->id, '5000.00', '1000.00');
pollMockRobot(new RobotResult(ok: true, moderationStatus: 'moderating'));
$notify = pollMockNotifications();
$notify->shouldReceive('notifyTelegramCampaignRejected')->never();
$notify->shouldReceive('notifyTelegramCampaignApproved')->never();
PollTelegramModerationJob::dispatchSync();
expect(Campaign::find($c->id)->status)->toBe(Campaign::STATUS_MODERATING)
->and((string) AdWallet::where('tenant_id', $t->id)->value('frozen_rub'))->toBe('1000.00');
});
it('робот не смог прочитать вердикт (moderationStatus=null) → moderating без изменений', function () {
config()->set('client_tg.sandbox', false);
$t = Tenant::factory()->create();
$c = pollCampaign($t->id, Campaign::STATUS_MODERATING, '2231160');
pollMockRobot(new RobotResult(ok: false, reason: 'кабинет не открылся'));
$notify = pollMockNotifications();
$notify->shouldReceive('notifyTelegramCampaignRejected')->never();
$notify->shouldReceive('notifyTelegramCampaignApproved')->never();
PollTelegramModerationJob::dispatchSync();
expect(Campaign::find($c->id)->status)->toBe(Campaign::STATUS_MODERATING);
});
it('moderating без mts_campaign_id не опрашивается (робот не зовётся)', function () {
config()->set('client_tg.sandbox', false);
$t = Tenant::factory()->create();
$c = pollCampaign($t->id, Campaign::STATUS_MODERATING, null);
// Робот-мок вернул бы approved, но кампанию без id опросчик даже не берёт.
pollMockRobot(new RobotResult(ok: true, moderationStatus: 'approved'));
$notify = pollMockNotifications();
$notify->shouldReceive('notifyTelegramCampaignApproved')->never();
PollTelegramModerationJob::dispatchSync();
expect(Campaign::find($c->id)->status)->toBe(Campaign::STATUS_MODERATING);
});