From f5da740bc8ab06be727cb77ffac19ba55a63d821 Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Wed, 16 Sep 2026 11:12:00 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9A=D0=BE=D0=BC=D0=BC=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0=D1=80=D0=B8=D0=B8=20=D0=BA=20=D0=B7=D0=B0=D0=BF=D0=B8?= =?UTF-8?q?=D1=81=D1=8F=D0=BC=20=E2=80=94=20=D0=BD=D0=B0=20=D0=BF=D1=80?= =?UTF-8?q?=D0=B8=D0=BC=D0=B5=D1=80=D0=B5=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=82?= =?UTF-8?q?=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/Controllers/Web/NotesController.php | 59 +++++++++++ framework/Comments/Comment.php | 97 +++++++++++++++++++ framework/View/views/layouts/main.php | 5 + migrations/20260916040000_create_comments.php | 39 ++++++++ resources/views/notes/show.php | 38 ++++++++ routes/web.php | 2 + tests/CommentsTest.php | 63 ++++++++++++ tests/HttpTest.php | 41 ++++++++ 8 files changed, 344 insertions(+) create mode 100644 framework/Comments/Comment.php create mode 100644 migrations/20260916040000_create_comments.php create mode 100644 tests/CommentsTest.php diff --git a/app/Controllers/Web/NotesController.php b/app/Controllers/Web/NotesController.php index b89c6ed..6793778 100644 --- a/app/Controllers/Web/NotesController.php +++ b/app/Controllers/Web/NotesController.php @@ -8,6 +8,7 @@ use App\Models\Note; use Rsgrinko\Proton\Access\Policy; use Rsgrinko\Proton\Access\Scope; use Rsgrinko\Proton\Access\Viewer; +use Rsgrinko\Proton\Comments\Comment; use Rsgrinko\Proton\Database\Model\Query; use Rsgrinko\Proton\Database\Model\RecordNotFound; use Rsgrinko\Proton\Events\Events; @@ -313,6 +314,7 @@ final class NotesController extends Controller 'note' => $note, 'author' => $note->author, 'attachments' => Attachment::of('note', $note->id()), + 'comments' => Comment::of('note', $note->id()), ], (string) $note->title); } @@ -491,6 +493,63 @@ final class NotesController extends Controller ); } + /** + * Оставить комментарий. Доступно всем, кто видит заметку, — обсуждение, + * а не правка: право смотреть уже проверено прослойкой notes.view. + */ + public function comment(Request $request, int $id, Scope $scope, Viewer $viewer): Response + { + $note = $this->find($id, $scope); + + $data = $this->validate($request, [ + 'body' => 'required|max:2000', + ], ['body' => 'Комментарий']); + + Comment::add('note', $note->id(), $viewer->id(), (string) $data['body']); + + Audit::action('note', $note->id(), 'оставлен комментарий'); + + $this->flash('Комментарий добавлен'); + + return $this->redirect('notes.show', ['id' => $note->id()]); + } + + /** + * Убрать комментарий: свой — сам автор, чужой — только у кого есть + * notes.manage. Одно и то же действие, а не два разных маршрута. + */ + public function commentDelete(Request $request, int $id, Scope $scope, Viewer $viewer): Response + { + $note = $this->find($id, $scope); + + /** @var Comment|null $comment */ + $comment = Comment::query() + ->where('entity', 'note') + ->where('entity_id', (string) $note->id()) + ->where('id', (int) $request->input('comment', 0)) + ->first(); + + if ($comment === null) { + $this->flash('Комментария нет', 'error'); + + return $this->redirect('notes.show', ['id' => $note->id()]); + } + + if ((int) $comment->raw('user_id') !== $viewer->id() && !$viewer->can('notes.manage')) { + $this->flash('Убрать можно только свой комментарий', 'error'); + + return $this->redirect('notes.show', ['id' => $note->id()]); + } + + $comment->delete(); + + Audit::action('note', $note->id(), 'убран комментарий'); + + $this->flash('Комментарий убран'); + + return $this->redirect('notes.show', ['id' => $note->id()]); + } + /** * Убрать вложение заметки. */ diff --git a/framework/Comments/Comment.php b/framework/Comments/Comment.php new file mode 100644 index 0000000..dd1f893 --- /dev/null +++ b/framework/Comments/Comment.php @@ -0,0 +1,97 @@ +id(), $viewer->id(), 'Текст'); + * Comment::of('note', $note->id()); // все комментарии записи, старые сверху + * Comment::removeAll('note', $note->id()); // запись удалили — комментарии не нужны + * + * Та же идея, что у вложений (`Files\Attachment`): раздел и номер записи — + * обычные колонки, а не внешний ключ, поэтому комментарии заводятся под новый + * раздел без миграции. Само добавление и удаление конкретных строк — забота + * контроллера раздела: чужому право писать или стирать здесь не проверяется. + */ +final class Comment extends Model +{ + protected static string $table = 'comments'; + + /** Только created_at — комментарий не правят, только пишут и стирают */ + protected bool $timestamps = false; + + protected array $casts = ['user_id' => 'int']; + + /** + * Оставить комментарий. + */ + public static function add(string $entity, int|string $entityId, int $userId, string $body): self + { + $comment = new self(); + + $comment->forceFill([ + 'entity' => $entity, + 'entity_id' => (string) $entityId, + 'user_id' => $userId > 0 ? $userId : null, + 'body' => trim($body), + 'created_at' => Connection::now(), + ]); + + $comment->save(); + + return $comment; + } + + /** + * Комментарии записи, старые сверху — обсуждение читается по порядку. + * + * @return array + */ + public static function of(string $entity, int|string $entityId): array + { + /** @var array $found */ + $found = self::query() + ->where('entity', $entity) + ->where('entity_id', (string) $entityId) + ->orderBy('id', 'asc') + ->get(); + + return $found; + } + + /** + * Сколько комментариев у записи — для счётчика в списке и заголовка. + */ + public static function countOf(string $entity, int|string $entityId): int + { + return self::query() + ->where('entity', $entity) + ->where('entity_id', (string) $entityId) + ->count(); + } + + /** + * Убрать все комментарии записи: саму запись удалили насовсем — держать + * обсуждение того, чего больше нет, незачем. + */ + public static function removeAll(string $entity, int|string $entityId): int + { + return self::query() + ->where('entity', $entity) + ->where('entity_id', (string) $entityId) + ->delete(); + } + + public function author(): BelongsTo + { + return $this->belongsTo(User::class, 'user_id'); + } +} diff --git a/framework/View/views/layouts/main.php b/framework/View/views/layouts/main.php index bc117aa..59347b9 100644 --- a/framework/View/views/layouts/main.php +++ b/framework/View/views/layouts/main.php @@ -237,6 +237,11 @@ $unread = $viewer->isGuest() ? 0 : UserNotification::unreadFor($viewer->id()); .attachments .file-icon { display: flex; align-items: center; justify-content: center; width: 140px; height: 100px; border: 1px solid var(--border); border-radius: 6px; color: var(--muted); font-size: 12px; } + .comments .comment { padding: 10px 0; border-bottom: 1px solid var(--border); } + .comments .comment:last-child { border-bottom: none; } + .comments .comment p { margin: 6px 0 0; } + .comments textarea { min-height: 70px; font-family: inherit; font-size: 14px; } + .bulk-bar { margin-bottom: 10px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 8px; } /* Панель отладки: видна только при APP_DEBUG и не мешает содержимому */ diff --git a/migrations/20260916040000_create_comments.php b/migrations/20260916040000_create_comments.php new file mode 100644 index 0000000..9de525f --- /dev/null +++ b/migrations/20260916040000_create_comments.php @@ -0,0 +1,39 @@ +create('comments', function (Blueprint $table): void { + $table->id(); + // К чему относится: раздел и запись + $table->string('entity', 64); + $table->string('entity_id', 64); + $table->foreignId('user_id')->nullable(); + $table->text('body'); + $table->dateTime('created_at')->nullable(); + + $table->index('idx_comments_owner', ['entity', 'entity_id']); + }); + } + + public function down(): void + { + $this->drop('comments'); + } +} diff --git a/resources/views/notes/show.php b/resources/views/notes/show.php index b28a301..ffa64a8 100644 --- a/resources/views/notes/show.php +++ b/resources/views/notes/show.php @@ -8,6 +8,7 @@ declare(strict_types=1); * @var \App\Models\Note $note * @var \Rsgrinko\Proton\Models\User|null $author * @var array $attachments + * @var array $comments */ use Rsgrinko\Proton\Support\SignedUrl; @@ -108,6 +109,43 @@ use Rsgrinko\Proton\View\View; +
+

Комментарии ()

+ + +

Пока никто не написал.

+ + id(); ?> +
+ + author; ?> +
+
+ login) ?> + raw('created_at'))) ?> + + + raw('user_id') === $viewerId || View::can('notes.manage')) { ?> +
+ + + +
+ +
+

raw('body')) ?>

+
+ +
+ + +
+ + + +
+
+ 'note', 'id' => $note->id()]) ?>

← ко всем заметкам

diff --git a/routes/web.php b/routes/web.php index 15bf1ea..df70472 100644 --- a/routes/web.php +++ b/routes/web.php @@ -103,6 +103,8 @@ return static function (Router $router): void { $router->get('/{id:\d+}/file', [NotesController::class, 'file'])->middleware('can:notes.view')->name('notes.file'); $router->post('/{id:\d+}/detach', [NotesController::class, 'detach'])->middleware('can:notes.manage')->name('notes.detach'); $router->get('/{id:\d+}/attachment/{attachment:\d+}', [NotesController::class, 'attachment'])->middleware('can:notes.view')->name('notes.attachment'); + $router->post('/{id:\d+}/comments', [NotesController::class, 'comment'])->middleware('can:notes.view')->name('notes.comment'); + $router->post('/{id:\d+}/comments/delete', [NotesController::class, 'commentDelete'])->middleware('can:notes.view')->name('notes.comment.delete'); }); }); }); diff --git a/tests/CommentsTest.php b/tests/CommentsTest.php new file mode 100644 index 0000000..f4b60f1 --- /dev/null +++ b/tests/CommentsTest.php @@ -0,0 +1,63 @@ +create(); + /** @var Note $note */ + $note = Factory::of(Note::class)->create(['user_id' => $author->id()]); + + $first = Comment::add('note', $note->id(), $author->id(), 'Первый'); + $second = Comment::add('note', $note->id(), $author->id(), ' Второй '); + + assertSame('Второй', $second->body, 'пробелы по краям обрезаются'); + + $found = Comment::of('note', $note->id()); + + assertCount(2, $found); + assertSame($first->id(), $found[0]->id(), 'старые сверху'); + assertSame($second->id(), $found[1]->id()); + + assertSame(2, Comment::countOf('note', $note->id())); + assertSame(0, Comment::countOf('note', $note->id() + 1), 'у чужой записи комментариев нет'); + }); +}); + +test('комментарии: знают своего автора', function (): void { + withOwnDatabase(static function (): void { + /** @var User $author */ + $author = Factory::of(User::class)->create(); + /** @var Note $note */ + $note = Factory::of(Note::class)->create(['user_id' => $author->id()]); + + $comment = Comment::add('note', $note->id(), $author->id(), 'Текст'); + + assertSame($author->id(), $comment->author?->id()); + }); +}); + +test('комментарии: удаление записи разом убирает все её комментарии', function (): void { + withOwnDatabase(static function (): void { + /** @var User $author */ + $author = Factory::of(User::class)->create(); + /** @var Note $note */ + $note = Factory::of(Note::class)->create(['user_id' => $author->id()]); + + Comment::add('note', $note->id(), $author->id(), 'Раз'); + Comment::add('note', $note->id(), $author->id(), 'Два'); + + assertSame(2, Comment::removeAll('note', $note->id())); + assertSame(0, Comment::countOf('note', $note->id())); + }); +}); diff --git a/tests/HttpTest.php b/tests/HttpTest.php index 51bb236..4846ac7 100644 --- a/tests/HttpTest.php +++ b/tests/HttpTest.php @@ -13,6 +13,7 @@ use App\Models\Note; use Rsgrinko\Proton\Access\Permission; use Rsgrinko\Proton\Auth\Auth; use Rsgrinko\Proton\Auth\Csrf; +use Rsgrinko\Proton\Comments\Comment; use Rsgrinko\Proton\Http\Kernel; use Rsgrinko\Proton\Http\Request; use Rsgrinko\Proton\Http\Response; @@ -217,6 +218,46 @@ test('http: чужая запись для обычного пользовате assertNotContains('Чужая заметка', $list->body()); }); +test('http: комментарий к заметке пишет и стирает свой, чужой — только с notes.manage', function (): void { + $note = Note::create(['title' => 'Заметка для обсуждения']); + + $note->forceFill(['user_id' => httpAdmin()->id()])->save(); + + $response = httpRequest('POST', '/notes/' . $note->id() . '/comments', httpAdmin(), ['body' => 'Первый комментарий']); + + assertStatus(302, $response); + + $shown = httpRequest('GET', '/notes/' . $note->id(), httpAdmin()); + + assertSee('Первый комментарий', $shown); + + $comment = assertNotNull(Comment::query()->where('entity', 'note')->where('entity_id', (string) $note->id())->first()); + + // Читатель без notes.manage чужой комментарий не уберёт + $role = Role::create(['name' => 'Только смотрит ' . bin2hex(random_bytes(3)), 'permissions' => ['notes.view']]); + + $viewer = User::register('http_comment_viewer_' . bin2hex(random_bytes(3)), 'секрет123', [ + 'email' => 'commentviewer' . bin2hex(random_bytes(3)) . '@example.com', + 'role_id' => $role->id(), + ]); + + afterTests(static function () use ($viewer, $role): void { + $viewer->forceDelete(); + $role->forceDelete(); + }); + + $denied = httpRequest('POST', '/notes/' . $note->id() . '/comments/delete', $viewer, ['comment' => $comment->id()]); + + assertStatus(302, $denied); + assertNotNull(Comment::find($comment->id()), 'чужой комментарий остался цел'); + + // Сам автор свой комментарий убирает + $removed = httpRequest('POST', '/notes/' . $note->id() . '/comments/delete', httpAdmin(), ['comment' => $comment->id()]); + + assertStatus(302, $removed); + assertNull(Comment::find($comment->id())); +}); + test('http: форма без токена ничего не меняет', function (): void { $before = Note::query()->where('user_id', httpAdmin()->id())->count();