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:
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]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function find(Source $source, string $sourceRef, string $topic): ?Event
|
||||
|
||||
@@ -5,8 +5,10 @@ namespace App\Ingest;
|
||||
use App\Models\Event;
|
||||
use App\Models\Source;
|
||||
use App\Models\User;
|
||||
use App\Presenters\EventPresenter;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Str;
|
||||
use LogicException;
|
||||
|
||||
/**
|
||||
* События, которые пользователь заводит сам — кнопкой в инбоксе или через агента.
|
||||
@@ -32,25 +34,76 @@ final class ManualEvents
|
||||
*/
|
||||
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(), [[
|
||||
'user' => $user->login,
|
||||
'source_ref' => $sourceRef,
|
||||
'topic' => '',
|
||||
'due_at' => $fields['due_at'],
|
||||
'fire_at' => $fields['fire_at'] ?? self::defaultFireAt($fields['due_at']),
|
||||
if (! self::owns($event)) {
|
||||
throw new LogicException("Событие источника «{$event->source->name}» правит только его источник");
|
||||
}
|
||||
$current = EventPresenter::forClient($event);
|
||||
$merged = [
|
||||
'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',
|
||||
'payload' => array_filter([
|
||||
'title' => $fields['title'],
|
||||
'title' => $fields['title'] ?? null,
|
||||
'subtitle' => $fields['subtitle'] ?? null,
|
||||
'done_label' => $fields['done_label'] ?? 'Сделано',
|
||||
'deep_link' => $fields['deep_link'] ?? null,
|
||||
], 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']);
|
||||
}
|
||||
@@ -60,9 +113,11 @@ final class ManualEvents
|
||||
return Source::firstOrCreate(['name' => self::SOURCE], ['token_hash' => hash('sha256', Str::random(64))]);
|
||||
}
|
||||
|
||||
/** День срока минус DEFAULT_LEAD_DAYS; из due_at берётся только дата. */
|
||||
private static function defaultFireAt(string $dueAt): string
|
||||
/** День срока минус DEFAULT_LEAD_DAYS; из due_at берётся только дата. Кривой due_at отдаём правилам как есть. */
|
||||
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');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user