89 lines
2.9 KiB
PHP
89 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Actions;
|
|
|
|
use App\Engine\Quests;
|
|
use App\Game\GameRuleViolation;
|
|
use App\Models\Player;
|
|
use App\Models\Report;
|
|
use App\Models\User;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
|
|
/** A player's reports on one world: list, read, delete. */
|
|
final class Reports
|
|
{
|
|
public const PER_PAGE = 25;
|
|
|
|
/**
|
|
* A page of reports, newest first; `type` keeps one kind (attack, defense, support).
|
|
* The unread count is over every kind.
|
|
*
|
|
* @return array{reports: list<array<string, mixed>>, page: int, pages: int, unread: int}
|
|
*/
|
|
public function list(User $user, int $worldId, int $page = 1, ?string $type = null): array
|
|
{
|
|
$query = $this->of($user, $worldId)->orderByDesc('happened_at')->orderByDesc('id');
|
|
if (in_array($type, [Report::ATTACK, Report::DEFENSE, Report::SUPPORT], true)) {
|
|
$query->where('type', $type);
|
|
}
|
|
$pages = max(1, (int) ceil($query->count() / self::PER_PAGE));
|
|
$page = max(1, min($pages, $page));
|
|
|
|
return [
|
|
'reports' => $query->forPage($page, self::PER_PAGE)->get()->map(fn (Report $r) => self::present($r))->all(),
|
|
'page' => $page,
|
|
'pages' => $pages,
|
|
'unread' => $this->of($user, $worldId)->whereNull('read_at')->count(),
|
|
];
|
|
}
|
|
|
|
/** One report in full; opening it marks it read. */
|
|
public function show(User $user, int $reportId): array
|
|
{
|
|
$report = Report::whereKey($reportId)->whereIn('player_id', Player::where('user_id', $user->id)->select('id'))->first()
|
|
?? throw new GameRuleViolation('not_found', 'Report not found.');
|
|
if (! $report->read_at) {
|
|
Quests::bump($report->player_id, 'reports.read');
|
|
}
|
|
$report->read_at ??= now();
|
|
$report->save();
|
|
|
|
return self::present($report);
|
|
}
|
|
|
|
/** @param list<int> $ids */
|
|
public function delete(User $user, int $worldId, array $ids): array
|
|
{
|
|
$this->of($user, $worldId)->whereIn('id', $ids)->delete();
|
|
|
|
return $this->list($user, $worldId);
|
|
}
|
|
|
|
public function readAll(User $user, int $worldId): array
|
|
{
|
|
$this->of($user, $worldId)->whereNull('read_at')->update(['read_at' => now()]);
|
|
|
|
return $this->list($user, $worldId);
|
|
}
|
|
|
|
public static function present(Report $report): array
|
|
{
|
|
return [
|
|
'id' => $report->id,
|
|
'type' => $report->type,
|
|
'happened_at' => $report->happened_at->utc()->format('Y-m-d\TH:i:s.v\Z'),
|
|
'read' => $report->read_at !== null,
|
|
'payload' => $report->payload,
|
|
];
|
|
}
|
|
|
|
/** @return Builder<Report> */
|
|
private function of(User $user, int $worldId): Builder
|
|
{
|
|
$player = Player::where('user_id', $user->id)->where('world_id', $worldId)->first()
|
|
?? throw new GameRuleViolation('not_found', 'Not on this world.');
|
|
|
|
return Report::where('player_id', $player->id);
|
|
}
|
|
}
|