feat: MCP tools for events (list/get/create/update/delete/done/ack); EventRules shared by /api and manual
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01BCrwHHnGCB5XH968Nxokqw
This commit is contained in:
@@ -2,7 +2,6 @@
|
|||||||
|
|
||||||
namespace App\Http\Controllers\Api;
|
namespace App\Http\Controllers\Api;
|
||||||
|
|
||||||
use App\Enums\EventState;
|
|
||||||
use App\Http\Controllers\Controller;
|
use App\Http\Controllers\Controller;
|
||||||
use App\Http\Requests\UpsertEventsRequest;
|
use App\Http\Requests\UpsertEventsRequest;
|
||||||
use App\Ingest\EventUpserter;
|
use App\Ingest\EventUpserter;
|
||||||
@@ -34,8 +33,7 @@ class EventsController extends Controller
|
|||||||
|
|
||||||
public function destroy(Request $request): Response
|
public function destroy(Request $request): Response
|
||||||
{
|
{
|
||||||
$event = $this->lookup($request);
|
$this->upserter->withdraw($this->lookup($request));
|
||||||
$event->update(['state' => EventState::Withdrawn]);
|
|
||||||
|
|
||||||
return response()->noContent();
|
return response()->noContent();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,9 +28,7 @@ class EventsController extends Controller
|
|||||||
? [$request->query('state')]
|
? [$request->query('state')]
|
||||||
: EventState::nonTerminalValues();
|
: EventState::nonTerminalValues();
|
||||||
|
|
||||||
$events = $user->events()->with('source')->whereIn('state', $states)->orderBy('due_date')->orderBy('due_instant')->get();
|
return response()->json(['events' => $user->liveEvents($states)->get()->map(EventPresenter::forUser(...))->values()]);
|
||||||
|
|
||||||
return response()->json(['events' => $events->map(EventPresenter::forUser(...))->values()]);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function ack(Request $request, int $event): JsonResponse
|
public function ack(Request $request, int $event): JsonResponse
|
||||||
|
|||||||
@@ -2,10 +2,9 @@
|
|||||||
|
|
||||||
namespace App\Http\Requests;
|
namespace App\Http\Requests;
|
||||||
|
|
||||||
use App\Ingest\DueAtParser;
|
use App\Ingest\EventRules;
|
||||||
use Illuminate\Foundation\Http\FormRequest;
|
use Illuminate\Foundation\Http\FormRequest;
|
||||||
use Illuminate\Validation\Validator;
|
use Illuminate\Validation\Validator;
|
||||||
use InvalidArgumentException;
|
|
||||||
|
|
||||||
class UpsertEventsRequest extends FormRequest
|
class UpsertEventsRequest extends FormRequest
|
||||||
{
|
{
|
||||||
@@ -21,42 +20,25 @@ class UpsertEventsRequest extends FormRequest
|
|||||||
'events.*.user' => ['required', 'string', 'max:255'],
|
'events.*.user' => ['required', 'string', 'max:255'],
|
||||||
'events.*.source_ref' => ['required', 'string', 'max:255'],
|
'events.*.source_ref' => ['required', 'string', 'max:255'],
|
||||||
'events.*.topic' => ['sometimes', 'nullable', 'string', 'max:255'],
|
'events.*.topic' => ['sometimes', 'nullable', 'string', 'max:255'],
|
||||||
'events.*.due_at' => ['required', 'string'],
|
] + EventRules::itemPrefixed('events.*.');
|
||||||
'events.*.fire_at' => ['required', 'date_format:Y-m-d'],
|
|
||||||
'events.*.after_due' => ['required', 'in:keep,expire'],
|
|
||||||
'events.*.payload' => ['required', 'array'],
|
|
||||||
'events.*.payload.title' => ['required', 'string'],
|
|
||||||
'events.*.payload.subtitle' => ['sometimes', 'nullable', 'string'],
|
|
||||||
'events.*.payload.deep_link' => ['sometimes', 'nullable', 'string', 'max:2048', 'regex:#^(/(?![/\\\\])|https?://)#i'],
|
|
||||||
'events.*.payload.done_label' => ['sometimes', 'nullable', 'string', 'max:64'],
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function messages(): array
|
public function messages(): array
|
||||||
{
|
{
|
||||||
return [
|
return EventRules::messages('events.*.');
|
||||||
'events.*.payload.deep_link.regex' => 'deep_link должен быть относительным путём или http(s)-ссылкой',
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function after(): array
|
public function after(): array
|
||||||
{
|
{
|
||||||
return [function (Validator $v) {
|
return [function (Validator $v) {
|
||||||
foreach ((array) $this->input('events', []) as $i => $item) {
|
foreach ((array) $this->input('events', []) as $i => $item) {
|
||||||
if (! is_array($item) || ! isset($item['due_at'], $item['fire_at']) || ! is_string($item['due_at'])) {
|
if (! is_array($item)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
try {
|
foreach (EventRules::check($item) as $field => $error) {
|
||||||
$due = DueAtParser::parse($item['due_at']);
|
if ($v->errors()->missing("events.$i.$field")) {
|
||||||
} catch (InvalidArgumentException $e) {
|
$v->errors()->add("events.$i.$field", $error);
|
||||||
$v->errors()->add("events.$i.due_at", $e->getMessage());
|
}
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
// Проверка fire_at <= день срока — по поясу по умолчанию; для fixed это
|
|
||||||
// приближение, точный день пользователя известен только при upsert.
|
|
||||||
if ($v->errors()->missing("events.$i.fire_at") && $item['fire_at'] > $due->dayFor(config('hado.default_tz'))) {
|
|
||||||
$v->errors()->add("events.$i.fire_at", 'fire_at не может быть позже дня срока');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}];
|
}];
|
||||||
|
|||||||
97
core/app/Ingest/EventRules.php
Normal file
97
core/app/Ingest/EventRules.php
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Ingest;
|
||||||
|
|
||||||
|
use Illuminate\Support\Facades\Validator as ValidatorFactory;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use Illuminate\Validation\Validator;
|
||||||
|
use InvalidArgumentException;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Правила одного события в форме upsert-элемента (§5 спеки). Один источник правды
|
||||||
|
* для клиентов (/api, пачкой) и для manual-событий из инбокса и от агента.
|
||||||
|
*/
|
||||||
|
final class EventRules
|
||||||
|
{
|
||||||
|
/** @return array<string,list<string>> */
|
||||||
|
public static function item(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'due_at' => ['required', 'string'],
|
||||||
|
'fire_at' => ['required', 'date_format:Y-m-d'],
|
||||||
|
'after_due' => ['required', 'in:keep,expire'],
|
||||||
|
'payload' => ['required', 'array'],
|
||||||
|
'payload.title' => ['required', 'string'],
|
||||||
|
'payload.subtitle' => ['sometimes', 'nullable', 'string'],
|
||||||
|
'payload.deep_link' => ['sometimes', 'nullable', 'string', 'max:2048', 'regex:#^(/(?![/\\\\])|https?://)#i'],
|
||||||
|
'payload.done_label' => ['sometimes', 'nullable', 'string', 'max:64'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Те же правила с префиксом ключа — для пачки `events.*.`.
|
||||||
|
*
|
||||||
|
* @return array<string,list<string>>
|
||||||
|
*/
|
||||||
|
public static function itemPrefixed(string $prefix): array
|
||||||
|
{
|
||||||
|
$rules = [];
|
||||||
|
foreach (self::item() as $key => $rule) {
|
||||||
|
$rules[$prefix.$key] = $rule;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $rules;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @return array<string,string> */
|
||||||
|
public static function messages(string $prefix = ''): array
|
||||||
|
{
|
||||||
|
return [$prefix.'payload.deep_link.regex' => 'deep_link должен быть относительным путём или http(s)-ссылкой'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Проверки после правил: due_at разбирается, fire_at не позже дня срока.
|
||||||
|
* Возвращает ошибки как поле => текст; пусто — всё хорошо.
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $item
|
||||||
|
* @return array<string,string>
|
||||||
|
*/
|
||||||
|
public static function check(array $item): array
|
||||||
|
{
|
||||||
|
if (! isset($item['due_at'], $item['fire_at']) || ! is_string($item['due_at'])) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$due = DueAtParser::parse($item['due_at']);
|
||||||
|
} catch (InvalidArgumentException $e) {
|
||||||
|
return ['due_at' => $e->getMessage()];
|
||||||
|
}
|
||||||
|
// Проверка fire_at <= день срока — по поясу по умолчанию; для fixed это
|
||||||
|
// приближение, точный день пользователя известен только при upsert.
|
||||||
|
if ($item['fire_at'] > $due->dayFor(config('hado.default_tz'))) {
|
||||||
|
return ['fire_at' => 'fire_at не может быть позже дня срока'];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Проверить один элемент целиком.
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $item
|
||||||
|
*
|
||||||
|
* @throws ValidationException
|
||||||
|
*/
|
||||||
|
public static function validate(array $item): void
|
||||||
|
{
|
||||||
|
ValidatorFactory::make($item, self::item(), self::messages())
|
||||||
|
->after(function (Validator $v) use ($item) {
|
||||||
|
foreach (self::check($item) as $field => $error) {
|
||||||
|
if ($v->errors()->missing($field)) {
|
||||||
|
$v->errors()->add($field, $error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
->validate();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,15 +38,10 @@ final class EventUpserter
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public function withdraw(Source $source, string $sourceRef, string $topic): bool
|
/** Снять событие: withdrawn — терминальное, ядро больше не напоминает. */
|
||||||
|
public function withdraw(Event $event): void
|
||||||
{
|
{
|
||||||
$event = $this->find($source, $sourceRef, $topic);
|
|
||||||
if ($event === null) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
$event->update(['state' => EventState::Withdrawn]);
|
$event->update(['state' => EventState::Withdrawn]);
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function find(Source $source, string $sourceRef, string $topic): ?Event
|
public function find(Source $source, string $sourceRef, string $topic): ?Event
|
||||||
|
|||||||
@@ -5,8 +5,10 @@ namespace App\Ingest;
|
|||||||
use App\Models\Event;
|
use App\Models\Event;
|
||||||
use App\Models\Source;
|
use App\Models\Source;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Presenters\EventPresenter;
|
||||||
use Carbon\CarbonImmutable;
|
use Carbon\CarbonImmutable;
|
||||||
use Illuminate\Support\Str;
|
use Illuminate\Support\Str;
|
||||||
|
use LogicException;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* События, которые пользователь заводит сам — кнопкой в инбоксе или через агента.
|
* События, которые пользователь заводит сам — кнопкой в инбоксе или через агента.
|
||||||
@@ -32,25 +34,76 @@ final class ManualEvents
|
|||||||
*/
|
*/
|
||||||
public function create(User $user, array $fields): Event
|
public function create(User $user, array $fields): Event
|
||||||
{
|
{
|
||||||
return $this->upsert($user, 'manual:'.Str::ulid(), $fields);
|
return $this->upsert($user, 'manual:'.Str::ulid(), self::item($fields));
|
||||||
}
|
}
|
||||||
|
|
||||||
private function upsert(User $user, string $sourceRef, array $fields): Event
|
/**
|
||||||
|
* Частичная правка своего события: не переданные поля берутся из него. Новый `due_at` —
|
||||||
|
* это перенос (§5): состояние пересчитывается даже из терминального, а `fire_at`,
|
||||||
|
* если не задан явно, считается заново от нового срока.
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $fields
|
||||||
|
*/
|
||||||
|
public function update(Event $event, array $fields): Event
|
||||||
{
|
{
|
||||||
[$result] = $this->upserter->upsert($this->source(), [[
|
if (! self::owns($event)) {
|
||||||
'user' => $user->login,
|
throw new LogicException("Событие источника «{$event->source->name}» правит только его источник");
|
||||||
'source_ref' => $sourceRef,
|
}
|
||||||
'topic' => '',
|
$current = EventPresenter::forClient($event);
|
||||||
'due_at' => $fields['due_at'],
|
$merged = [
|
||||||
'fire_at' => $fields['fire_at'] ?? self::defaultFireAt($fields['due_at']),
|
'title' => $current['payload']['title'],
|
||||||
|
'subtitle' => $current['payload']['subtitle'] ?? null,
|
||||||
|
'done_label' => $current['payload']['done_label'] ?? null,
|
||||||
|
'deep_link' => $current['payload']['deep_link'] ?? null,
|
||||||
|
'due_at' => $current['due_at'],
|
||||||
|
'fire_at' => isset($fields['due_at']) ? null : $current['fire_at'],
|
||||||
|
'after_due' => $current['after_due'],
|
||||||
|
];
|
||||||
|
foreach ($fields as $key => $value) {
|
||||||
|
$merged[$key] = $value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->upsert($event->user, $event->source_ref, self::item($merged));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function withdraw(Event $event): void
|
||||||
|
{
|
||||||
|
if (! self::owns($event)) {
|
||||||
|
throw new LogicException("Событие источника «{$event->source->name}» снимает только его источник");
|
||||||
|
}
|
||||||
|
$this->upserter->withdraw($event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Плоские поля → upsert-элемент с дефолтами кнопки инбокса. Проверяется теми же
|
||||||
|
* правилами, что и события клиентов.
|
||||||
|
*
|
||||||
|
* @param array<string,mixed> $fields
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
private static function item(array $fields): array
|
||||||
|
{
|
||||||
|
$dueAt = (string) ($fields['due_at'] ?? '');
|
||||||
|
$item = [
|
||||||
|
'due_at' => $dueAt,
|
||||||
|
'fire_at' => $fields['fire_at'] ?? self::defaultFireAt($dueAt),
|
||||||
'after_due' => $fields['after_due'] ?? 'keep',
|
'after_due' => $fields['after_due'] ?? 'keep',
|
||||||
'payload' => array_filter([
|
'payload' => array_filter([
|
||||||
'title' => $fields['title'],
|
'title' => $fields['title'] ?? null,
|
||||||
'subtitle' => $fields['subtitle'] ?? null,
|
'subtitle' => $fields['subtitle'] ?? null,
|
||||||
'done_label' => $fields['done_label'] ?? 'Сделано',
|
'done_label' => $fields['done_label'] ?? 'Сделано',
|
||||||
'deep_link' => $fields['deep_link'] ?? null,
|
'deep_link' => $fields['deep_link'] ?? null,
|
||||||
], fn ($v) => $v !== null && $v !== ''),
|
], fn ($v) => $v !== null && $v !== ''),
|
||||||
]]);
|
];
|
||||||
|
EventRules::validate($item);
|
||||||
|
|
||||||
|
return $item;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $item */
|
||||||
|
private function upsert(User $user, string $sourceRef, array $item): Event
|
||||||
|
{
|
||||||
|
[$result] = $this->upserter->upsert($this->source(), [['user' => $user->login, 'source_ref' => $sourceRef, 'topic' => ''] + $item]);
|
||||||
|
|
||||||
return Event::with('source')->findOrFail($result['id']);
|
return Event::with('source')->findOrFail($result['id']);
|
||||||
}
|
}
|
||||||
@@ -60,9 +113,11 @@ final class ManualEvents
|
|||||||
return Source::firstOrCreate(['name' => self::SOURCE], ['token_hash' => hash('sha256', Str::random(64))]);
|
return Source::firstOrCreate(['name' => self::SOURCE], ['token_hash' => hash('sha256', Str::random(64))]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** День срока минус DEFAULT_LEAD_DAYS; из due_at берётся только дата. */
|
/** День срока минус DEFAULT_LEAD_DAYS; из due_at берётся только дата. Кривой due_at отдаём правилам как есть. */
|
||||||
private static function defaultFireAt(string $dueAt): string
|
private static function defaultFireAt(string $dueAt): ?string
|
||||||
{
|
{
|
||||||
return CarbonImmutable::createFromFormat('Y-m-d', substr($dueAt, 0, 10))->subDays(self::DEFAULT_LEAD_DAYS)->format('Y-m-d');
|
$day = CarbonImmutable::createFromFormat('Y-m-d', substr($dueAt, 0, 10));
|
||||||
|
|
||||||
|
return $day === false ? null : $day->subDays(self::DEFAULT_LEAD_DAYS)->format('Y-m-d');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,5 +28,13 @@ class HadoServer extends Server
|
|||||||
Повторяющееся — отдельные события на каждое вхождение, не одно с переносом даты.
|
Повторяющееся — отдельные события на каждое вхождение, не одно с переносом даты.
|
||||||
MD;
|
MD;
|
||||||
|
|
||||||
protected array $tools = [];
|
protected array $tools = [
|
||||||
|
Tools\ListEvents::class,
|
||||||
|
Tools\GetEvent::class,
|
||||||
|
Tools\CreateEvent::class,
|
||||||
|
Tools\UpdateEvent::class,
|
||||||
|
Tools\DeleteEvent::class,
|
||||||
|
Tools\MarkDone::class,
|
||||||
|
Tools\MarkAck::class,
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
50
core/app/Mcp/Tools/AgentTool.php
Normal file
50
core/app/Mcp/Tools/AgentTool.php
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Ingest\ManualEvents;
|
||||||
|
use App\Models\Event;
|
||||||
|
use App\Models\User;
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\Response;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
use Laravel\Mcp\Server\Tool;
|
||||||
|
|
||||||
|
/** Общее для тулов агента: пользователь токена и его события. */
|
||||||
|
abstract class AgentTool extends Tool
|
||||||
|
{
|
||||||
|
/** Пользователь, которого положил AuthenticateAgent — тот же атрибут, что у RemoteUser. */
|
||||||
|
protected function user(): User
|
||||||
|
{
|
||||||
|
return request()->attributes->get('user');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Событие по `id` из аргументов; чужое или несуществующее — ошибка для модели, а не 500. */
|
||||||
|
protected function withEvent(Request $request, Closure $then): Response|ResponseFactory
|
||||||
|
{
|
||||||
|
$id = (int) $request->validate(['id' => ['required', 'integer']])['id'];
|
||||||
|
try {
|
||||||
|
$event = $this->user()->ownEvent($id);
|
||||||
|
} catch (ModelNotFoundException) {
|
||||||
|
return Response::error('Событие не найдено');
|
||||||
|
}
|
||||||
|
|
||||||
|
return $then($event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** То же, но только своё (manual) событие — для правки и снятия. */
|
||||||
|
protected function withOwnEvent(Request $request, Closure $then): Response|ResponseFactory
|
||||||
|
{
|
||||||
|
return $this->withEvent($request, fn (Event $event) => ManualEvents::owns($event)
|
||||||
|
? $then($event)
|
||||||
|
: Response::error("Это событие источника {$event->source->name}: правит и снимает его только источник. Можно закрыть через mark_done."));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string,mixed> $data */
|
||||||
|
protected function respond(array $data): ResponseFactory
|
||||||
|
{
|
||||||
|
return Response::structured($data);
|
||||||
|
}
|
||||||
|
}
|
||||||
72
core/app/Mcp/Tools/CreateEvent.php
Normal file
72
core/app/Mcp/Tools/CreateEvent.php
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Ingest\ManualEvents;
|
||||||
|
use App\Presenters\EventPresenter;
|
||||||
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
|
||||||
|
class CreateEvent extends AgentTool
|
||||||
|
{
|
||||||
|
protected string $name = 'create_event';
|
||||||
|
|
||||||
|
protected string $description = 'Поставить пользователю напоминание (источник manual — как кнопка «Добавить» в инбоксе). `due_at`: `YYYY-MM-DD` (весь день), `YYYY-MM-DDTHH:MM` (по поясу пользователя) или со смещением `+02:00` — только если событие привязано к месту. `fire_at` — день, с которого начинать напоминать; по умолчанию за 30 дней до срока. `after_due`: `keep` — после срока долбить, пока не закроют (по умолчанию), `expire` — тихо истечь. Повторяющееся — отдельное событие на каждое вхождение.';
|
||||||
|
|
||||||
|
public function __construct(private readonly ManualEvents $manual) {}
|
||||||
|
|
||||||
|
public function schema(JsonSchema $schema): array
|
||||||
|
{
|
||||||
|
return self::fields($schema, required: true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(Request $request): ResponseFactory
|
||||||
|
{
|
||||||
|
$fields = $request->validate(self::shape(required: true));
|
||||||
|
|
||||||
|
return $this->respond(EventPresenter::forUser($this->manual->create($this->user(), $fields)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Поля события — общие для create_event и update_event. Форматы и смысл
|
||||||
|
* (fire_at не позже срока, deep_link — путь или ссылка) проверяет ManualEvents.
|
||||||
|
*
|
||||||
|
* @return array<string,mixed>
|
||||||
|
*/
|
||||||
|
public static function fields(JsonSchema $schema, bool $required): array
|
||||||
|
{
|
||||||
|
$title = $schema->string()->max(200)->description('Заголовок напоминания');
|
||||||
|
$dueAt = $schema->string()->description('Срок: YYYY-MM-DD, YYYY-MM-DDTHH:MM или со смещением');
|
||||||
|
|
||||||
|
return [
|
||||||
|
'title' => $required ? $title->required() : $title,
|
||||||
|
'due_at' => $required ? $dueAt->required() : $dueAt,
|
||||||
|
'subtitle' => $schema->string()->max(200)->description('Подзаголовок'),
|
||||||
|
'fire_at' => $schema->string()->description('YYYY-MM-DD, день начала подготовки; не позже дня срока'),
|
||||||
|
'after_due' => $schema->string()->enum(['keep', 'expire'])->description('Что после срока: keep (по умолчанию) или expire'),
|
||||||
|
'done_label' => $schema->string()->max(64)->description('Подпись кнопки закрытия, по умолчанию «Сделано»'),
|
||||||
|
'deep_link' => $schema->string()->description('Куда вести из напоминания: относительный путь или http(s)-ссылка'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Форма аргументов: что передано и какого типа. Остальное — EventRules через ManualEvents.
|
||||||
|
*
|
||||||
|
* @return array<string,list<string>>
|
||||||
|
*/
|
||||||
|
public static function shape(bool $required): array
|
||||||
|
{
|
||||||
|
$presence = $required ? 'required' : 'sometimes';
|
||||||
|
|
||||||
|
return [
|
||||||
|
'title' => [$presence, 'string', 'max:200'],
|
||||||
|
'due_at' => [$presence, 'string'],
|
||||||
|
'subtitle' => ['sometimes', 'nullable', 'string', 'max:200'],
|
||||||
|
'fire_at' => ['sometimes', 'nullable', 'string'],
|
||||||
|
'after_due' => ['sometimes', 'string'],
|
||||||
|
'done_label' => ['sometimes', 'nullable', 'string'],
|
||||||
|
'deep_link' => ['sometimes', 'nullable', 'string'],
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
35
core/app/Mcp/Tools/DeleteEvent.php
Normal file
35
core/app/Mcp/Tools/DeleteEvent.php
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Ingest\ManualEvents;
|
||||||
|
use App\Models\Event;
|
||||||
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\Response;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;
|
||||||
|
|
||||||
|
#[IsDestructive]
|
||||||
|
class DeleteEvent extends AgentTool
|
||||||
|
{
|
||||||
|
protected string $name = 'delete_event';
|
||||||
|
|
||||||
|
protected string $description = 'Снять своё событие (editable: true): оно уходит в withdrawn и больше не напоминает. Это не «Сделано» — для закрытия любого события есть mark_done.';
|
||||||
|
|
||||||
|
public function __construct(private readonly ManualEvents $manual) {}
|
||||||
|
|
||||||
|
public function schema(JsonSchema $schema): array
|
||||||
|
{
|
||||||
|
return ['id' => $schema->integer()->required()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(Request $request): Response|ResponseFactory
|
||||||
|
{
|
||||||
|
return $this->withOwnEvent($request, function (Event $event) {
|
||||||
|
$this->manual->withdraw($event);
|
||||||
|
|
||||||
|
return $this->respond(['id' => $event->id, 'state' => $event->fresh()->state->value]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
29
core/app/Mcp/Tools/GetEvent.php
Normal file
29
core/app/Mcp/Tools/GetEvent.php
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Models\Event;
|
||||||
|
use App\Presenters\EventPresenter;
|
||||||
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\Response;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
|
||||||
|
|
||||||
|
#[IsReadOnly]
|
||||||
|
class GetEvent extends AgentTool
|
||||||
|
{
|
||||||
|
protected string $name = 'get_event';
|
||||||
|
|
||||||
|
protected string $description = 'Одно событие пользователя целиком по id.';
|
||||||
|
|
||||||
|
public function schema(JsonSchema $schema): array
|
||||||
|
{
|
||||||
|
return ['id' => $schema->integer()->required()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(Request $request): Response|ResponseFactory
|
||||||
|
{
|
||||||
|
return $this->withEvent($request, fn (Event $event) => $this->respond(EventPresenter::forUser($event)));
|
||||||
|
}
|
||||||
|
}
|
||||||
46
core/app/Mcp/Tools/ListEvents.php
Normal file
46
core/app/Mcp/Tools/ListEvents.php
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Enums\EventState;
|
||||||
|
use App\Models\Event;
|
||||||
|
use App\Presenters\EventPresenter;
|
||||||
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||||
|
use Illuminate\Validation\Rule;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
|
||||||
|
|
||||||
|
#[IsReadOnly]
|
||||||
|
class ListEvents extends AgentTool
|
||||||
|
{
|
||||||
|
protected string $name = 'list_events';
|
||||||
|
|
||||||
|
protected string $description = 'Инбокс пользователя: активные события всех источников по сроку. `state` — фильтр по одному состоянию, `archive: true` — вместо активных закрытые (done, expired), последние 100. У каждого события `editable` говорит, можно ли его править и снимать (только свои, источник manual).';
|
||||||
|
|
||||||
|
public function schema(JsonSchema $schema): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'state' => $schema->string()->enum(EventState::nonTerminalValues())->description('Только события в этом состоянии'),
|
||||||
|
'archive' => $schema->boolean()->description('Закрытые события вместо активных'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(Request $request): ResponseFactory
|
||||||
|
{
|
||||||
|
$args = $request->validate([
|
||||||
|
'state' => ['sometimes', Rule::in(EventState::nonTerminalValues())],
|
||||||
|
'archive' => ['sometimes', 'boolean'],
|
||||||
|
]);
|
||||||
|
$user = $this->user();
|
||||||
|
|
||||||
|
if ($args['archive'] ?? false) {
|
||||||
|
return $this->respond(['events' => $user->archive()->get()
|
||||||
|
->map(fn (Event $e) => EventPresenter::forUser($e) + ['closed_as' => EventPresenter::closedAs($e)])->values()->all()]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$states = isset($args['state']) ? [$args['state']] : EventState::nonTerminalValues();
|
||||||
|
|
||||||
|
return $this->respond(['events' => $user->liveEvents($states)->get()->map(EventPresenter::forUser(...))->values()->all()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
34
core/app/Mcp/Tools/MarkAck.php
Normal file
34
core/app/Mcp/Tools/MarkAck.php
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Delivery\EventActions;
|
||||||
|
use App\Models\Event;
|
||||||
|
use App\Presenters\EventPresenter;
|
||||||
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\Response;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
|
||||||
|
class MarkAck extends AgentTool
|
||||||
|
{
|
||||||
|
protected string $name = 'mark_ack';
|
||||||
|
|
||||||
|
protected string $description = '«Помню»: заглушить текущее напоминание до следующей контрольной точки, событие остаётся открытым. Работает для события любого источника; на закрытом ничего не делает.';
|
||||||
|
|
||||||
|
public function __construct(private readonly EventActions $actions) {}
|
||||||
|
|
||||||
|
public function schema(JsonSchema $schema): array
|
||||||
|
{
|
||||||
|
return ['id' => $schema->integer()->required()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(Request $request): Response|ResponseFactory
|
||||||
|
{
|
||||||
|
return $this->withEvent($request, function (Event $event) {
|
||||||
|
$this->actions->ack($event);
|
||||||
|
|
||||||
|
return $this->respond(EventPresenter::forUser($event->fresh('source')));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
34
core/app/Mcp/Tools/MarkDone.php
Normal file
34
core/app/Mcp/Tools/MarkDone.php
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Delivery\EventActions;
|
||||||
|
use App\Models\Event;
|
||||||
|
use App\Presenters\EventPresenter;
|
||||||
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\Response;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
|
||||||
|
class MarkDone extends AgentTool
|
||||||
|
{
|
||||||
|
protected string $name = 'mark_done';
|
||||||
|
|
||||||
|
protected string $description = '«Сделано»: закрыть событие любого источника — как кнопка в инбоксе. Уже закрытое не трогается.';
|
||||||
|
|
||||||
|
public function __construct(private readonly EventActions $actions) {}
|
||||||
|
|
||||||
|
public function schema(JsonSchema $schema): array
|
||||||
|
{
|
||||||
|
return ['id' => $schema->integer()->required()];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(Request $request): Response|ResponseFactory
|
||||||
|
{
|
||||||
|
return $this->withEvent($request, function (Event $event) {
|
||||||
|
$this->actions->done($event);
|
||||||
|
|
||||||
|
return $this->respond(EventPresenter::forUser($event->fresh('source')));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
32
core/app/Mcp/Tools/UpdateEvent.php
Normal file
32
core/app/Mcp/Tools/UpdateEvent.php
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Mcp\Tools;
|
||||||
|
|
||||||
|
use App\Ingest\ManualEvents;
|
||||||
|
use App\Models\Event;
|
||||||
|
use App\Presenters\EventPresenter;
|
||||||
|
use Illuminate\Contracts\JsonSchema\JsonSchema;
|
||||||
|
use Laravel\Mcp\Request;
|
||||||
|
use Laravel\Mcp\Response;
|
||||||
|
use Laravel\Mcp\ResponseFactory;
|
||||||
|
|
||||||
|
class UpdateEvent extends AgentTool
|
||||||
|
{
|
||||||
|
protected string $name = 'update_event';
|
||||||
|
|
||||||
|
protected string $description = 'Поправить своё событие (editable: true) — любое подмножество полей create_event, остальное не меняется. Новый `due_at` — это перенос: состояние пересчитывается от новой даты даже у закрытого события, «Помню» сбрасывается, `fire_at` без явного значения считается заново (за 30 дней до нового срока). События других источников не правятся — их закрывают через mark_done.';
|
||||||
|
|
||||||
|
public function __construct(private readonly ManualEvents $manual) {}
|
||||||
|
|
||||||
|
public function schema(JsonSchema $schema): array
|
||||||
|
{
|
||||||
|
return ['id' => $schema->integer()->required()] + CreateEvent::fields($schema, required: false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function handle(Request $request): Response|ResponseFactory
|
||||||
|
{
|
||||||
|
$fields = $request->validate(CreateEvent::shape(required: false));
|
||||||
|
|
||||||
|
return $this->withOwnEvent($request, fn (Event $event) => $this->respond(EventPresenter::forUser($this->manual->update($event, $fields))));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -27,6 +27,16 @@ class User extends Model
|
|||||||
return $this->events()->with('source')->whereKey($id)->firstOrFail();
|
return $this->events()->with('source')->whereKey($id)->firstOrFail();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Живые события в этих состояниях, по сроку.
|
||||||
|
*
|
||||||
|
* @param list<string> $states
|
||||||
|
*/
|
||||||
|
public function liveEvents(array $states): HasMany
|
||||||
|
{
|
||||||
|
return $this->events()->with('source')->whereIn('state', $states)->orderBy('due_date')->orderBy('due_instant');
|
||||||
|
}
|
||||||
|
|
||||||
/** Закрытые события для архива: done и expired, свежие первыми, не больше 100. */
|
/** Закрытые события для архива: done и expired, свежие первыми, не больше 100. */
|
||||||
public function archive(): HasMany
|
public function archive(): HasMany
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -126,12 +126,13 @@ class EventUpserterTest extends TestCase
|
|||||||
$this->assertNull($event->due_date);
|
$this->assertNull($event->due_date);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function test_withdraw_marks_withdrawn_and_reports_missing(): void
|
public function test_withdraw_marks_withdrawn(): void
|
||||||
{
|
{
|
||||||
$this->upserter->upsert($this->source, [$this->item()]);
|
$this->upserter->upsert($this->source, [$this->item()]);
|
||||||
|
|
||||||
$this->assertTrue($this->upserter->withdraw($this->source, 'document:918', 'expiry'));
|
$this->upserter->withdraw($this->upserter->find($this->source, 'document:918', 'expiry'));
|
||||||
|
|
||||||
$this->assertSame(EventState::Withdrawn, Event::sole()->state);
|
$this->assertSame(EventState::Withdrawn, Event::sole()->state);
|
||||||
$this->assertFalse($this->upserter->withdraw($this->source, 'document:918', 'other'));
|
$this->assertNull($this->upserter->find($this->source, 'document:918', 'other'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
179
core/tests/Feature/McpToolsTest.php
Normal file
179
core/tests/Feature/McpToolsTest.php
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature;
|
||||||
|
|
||||||
|
use App\Enums\AfterDue;
|
||||||
|
use App\Enums\DueMode;
|
||||||
|
use App\Enums\EventState;
|
||||||
|
use App\Mcp\HadoServer;
|
||||||
|
use App\Mcp\Tools\CreateEvent;
|
||||||
|
use App\Mcp\Tools\DeleteEvent;
|
||||||
|
use App\Mcp\Tools\GetEvent;
|
||||||
|
use App\Mcp\Tools\GetProfile;
|
||||||
|
use App\Mcp\Tools\ListEvents;
|
||||||
|
use App\Mcp\Tools\MarkAck;
|
||||||
|
use App\Mcp\Tools\MarkDone;
|
||||||
|
use App\Mcp\Tools\UpdateEvent;
|
||||||
|
use App\Mcp\Tools\UpdateProfile;
|
||||||
|
use App\Models\Event;
|
||||||
|
use App\Models\Source;
|
||||||
|
use App\Models\User;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Illuminate\Testing\Fluent\AssertableJson;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class McpToolsTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
private User $user;
|
||||||
|
|
||||||
|
private Source $docs;
|
||||||
|
|
||||||
|
protected function setUp(): void
|
||||||
|
{
|
||||||
|
parent::setUp();
|
||||||
|
config(['hado.default_tz' => 'UTC']);
|
||||||
|
CarbonImmutable::setTestNow('2026-09-05T12:00:00Z');
|
||||||
|
$this->user = User::create(['login' => 'nikita', 'tz' => 'UTC']);
|
||||||
|
$this->docs = Source::create(['name' => 'docs', 'token_hash' => hash('sha256', 'x')]);
|
||||||
|
// Как AuthenticateAgent: пользователь токена лежит в атрибутах текущего запроса
|
||||||
|
$this->app['request']->attributes->set('user', $this->user);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function tearDown(): void
|
||||||
|
{
|
||||||
|
CarbonImmutable::setTestNow();
|
||||||
|
parent::tearDown();
|
||||||
|
}
|
||||||
|
|
||||||
|
private function docsEvent(User $user, EventState $state = EventState::Today, string $topic = 't', string $due = '2026-09-05'): Event
|
||||||
|
{
|
||||||
|
return Event::create([
|
||||||
|
'source_id' => $this->docs->id, 'user_id' => $user->id, 'source_ref' => 'r', 'topic' => $topic,
|
||||||
|
'due_mode' => DueMode::Local, 'due_date' => $due, 'due_time' => '24:00:00', 'fire_on' => $due,
|
||||||
|
'after_due' => AfterDue::Keep, 'payload' => ['title' => "Docs $topic", 'done_label' => 'Поздравил'], 'state' => $state,
|
||||||
|
'quiet_until' => CarbonImmutable::now()->subDay(),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Своё событие через тул; id — из базы, TestResponse его наружу не отдаёт. */
|
||||||
|
private function createOwn(string $title = 'Виза', string $due = '2026-10-05'): int
|
||||||
|
{
|
||||||
|
HadoServer::tool(CreateEvent::class, ['title' => $title, 'due_at' => $due])->assertOk();
|
||||||
|
|
||||||
|
return Event::orderByDesc('id')->firstOrFail()->id;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- чтение ---
|
||||||
|
|
||||||
|
public function test_list_events_shows_active_events_of_all_sources_with_editable_flag(): void
|
||||||
|
{
|
||||||
|
$this->docsEvent($this->user, EventState::Today, 'a');
|
||||||
|
$this->docsEvent($this->user, EventState::Done, 'closed');
|
||||||
|
$other = User::create(['login' => 'other', 'tz' => 'UTC']);
|
||||||
|
$this->docsEvent($other, EventState::Today, 'foreign');
|
||||||
|
HadoServer::tool(CreateEvent::class, ['title' => 'Своё', 'due_at' => '2026-10-01'])->assertOk();
|
||||||
|
|
||||||
|
HadoServer::tool(ListEvents::class)->assertOk()->assertStructuredContent(fn (AssertableJson $j) => $j
|
||||||
|
->count('events', 2)
|
||||||
|
->where('events.0.source', 'docs')->where('events.0.editable', false)
|
||||||
|
->where('events.1.source', 'manual')->where('events.1.editable', true)
|
||||||
|
->etc());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_list_events_filters_by_state_and_archive(): void
|
||||||
|
{
|
||||||
|
$this->docsEvent($this->user, EventState::Today, 'a');
|
||||||
|
$this->docsEvent($this->user, EventState::Scheduled, 'b', '2026-12-01');
|
||||||
|
$this->docsEvent($this->user, EventState::Expired, 'c', '2026-08-01');
|
||||||
|
|
||||||
|
HadoServer::tool(ListEvents::class, ['state' => 'scheduled'])->assertOk()
|
||||||
|
->assertStructuredContent(fn (AssertableJson $j) => $j->count('events', 1)->where('events.0.topic', 'b')->etc());
|
||||||
|
HadoServer::tool(ListEvents::class, ['archive' => true])->assertOk()
|
||||||
|
->assertStructuredContent(fn (AssertableJson $j) => $j->count('events', 1)->where('events.0.topic', 'c')->where('events.0.closed_as', 'Истекло')->etc());
|
||||||
|
HadoServer::tool(ListEvents::class, ['state' => 'garbage'])->assertHasErrors();
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_get_event_returns_own_and_hides_foreign(): void
|
||||||
|
{
|
||||||
|
$mine = $this->docsEvent($this->user);
|
||||||
|
$other = User::create(['login' => 'other', 'tz' => 'UTC']);
|
||||||
|
$foreign = $this->docsEvent($other, EventState::Today, 'f');
|
||||||
|
|
||||||
|
HadoServer::tool(GetEvent::class, ['id' => $mine->id])->assertOk()
|
||||||
|
->assertStructuredContent(fn (AssertableJson $j) => $j->where('id', $mine->id)->where('state', 'today')->where('editable', false)->etc());
|
||||||
|
HadoServer::tool(GetEvent::class, ['id' => $foreign->id])->assertHasErrors(['не найдено']);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- свои события (manual) ---
|
||||||
|
|
||||||
|
public function test_create_event_uses_inbox_defaults(): void
|
||||||
|
{
|
||||||
|
HadoServer::tool(CreateEvent::class, ['title' => 'Виза', 'due_at' => '2026-10-05'])->assertOk()
|
||||||
|
->assertStructuredContent(fn (AssertableJson $j) => $j
|
||||||
|
->where('source', 'manual')->where('editable', true)->where('state', 'preparing')
|
||||||
|
->where('fire_at', '2026-09-05')->where('after_due', 'keep')->where('due_at', '2026-10-05')
|
||||||
|
->where('payload.title', 'Виза')->where('payload.done_label', 'Сделано')
|
||||||
|
->etc());
|
||||||
|
$this->assertSame($this->user->id, Event::sole()->user_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_create_event_honours_explicit_fields(): void
|
||||||
|
{
|
||||||
|
HadoServer::tool(CreateEvent::class, [
|
||||||
|
'title' => 'Вылет', 'subtitle' => 'SU 123', 'due_at' => '2026-09-10T08:15+02:00', 'fire_at' => '2026-09-10',
|
||||||
|
'after_due' => 'expire', 'done_label' => 'Улетел', 'deep_link' => '/trips/1',
|
||||||
|
])->assertOk()->assertStructuredContent(fn (AssertableJson $j) => $j
|
||||||
|
->where('due_at', '2026-09-10T06:15:00+00:00')->where('fire_at', '2026-09-10')->where('after_due', 'expire')
|
||||||
|
->where('payload.subtitle', 'SU 123')->where('payload.done_label', 'Улетел')->where('payload.deep_link', '/trips/1')
|
||||||
|
->etc());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_create_event_rejects_fire_after_due(): void
|
||||||
|
{
|
||||||
|
HadoServer::tool(CreateEvent::class, ['title' => 'x', 'due_at' => '2026-10-05', 'fire_at' => '2026-10-06'])->assertHasErrors();
|
||||||
|
HadoServer::tool(CreateEvent::class, ['due_at' => '2026-10-05'])->assertHasErrors(['title']);
|
||||||
|
$this->assertSame(0, Event::count());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_update_event_edits_own_event_in_place(): void
|
||||||
|
{
|
||||||
|
$id = $this->createOwn();
|
||||||
|
|
||||||
|
HadoServer::tool(UpdateEvent::class, ['id' => $id, 'title' => 'Виза в Японию', 'subtitle' => 'посольство'])->assertOk()
|
||||||
|
->assertStructuredContent(fn (AssertableJson $j) => $j->where('id', $id)->where('payload.title', 'Виза в Японию')
|
||||||
|
->where('payload.subtitle', 'посольство')->where('due_at', '2026-10-05')->where('state', 'preparing')->etc());
|
||||||
|
$this->assertSame(1, Event::count());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_update_event_with_new_due_is_a_reschedule(): void
|
||||||
|
{
|
||||||
|
$id = $this->createOwn(due: '2026-09-01');
|
||||||
|
HadoServer::tool(MarkDone::class, ['id' => $id])->assertOk();
|
||||||
|
|
||||||
|
// Перенос: состояние пересчитывается даже из терминального, fire_at — заново от нового срока
|
||||||
|
HadoServer::tool(UpdateEvent::class, ['id' => $id, 'due_at' => '2026-12-01'])->assertOk()
|
||||||
|
->assertStructuredContent(fn (AssertableJson $j) => $j->where('state', 'scheduled')->where('fire_at', '2026-11-01')->etc());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_update_and_delete_refuse_foreign_source_events(): void
|
||||||
|
{
|
||||||
|
$docs = $this->docsEvent($this->user);
|
||||||
|
|
||||||
|
HadoServer::tool(UpdateEvent::class, ['id' => $docs->id, 'title' => 'Хак'])->assertHasErrors(['источника docs']);
|
||||||
|
HadoServer::tool(DeleteEvent::class, ['id' => $docs->id])->assertHasErrors(['источника docs']);
|
||||||
|
$this->assertSame('Docs t', $docs->fresh()->payload['title']);
|
||||||
|
$this->assertSame(EventState::Today, $docs->fresh()->state);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_delete_event_withdraws_own_event(): void
|
||||||
|
{
|
||||||
|
$id = $this->createOwn();
|
||||||
|
|
||||||
|
HadoServer::tool(DeleteEvent::class, ['id' => $id])->assertOk()
|
||||||
|
->assertStructuredContent(['id' => $id, 'state' => 'withdrawn']);
|
||||||
|
$this->assertSame(EventState::Withdrawn, Event::findOrFail($id)->state);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user