Комментарии к записям — на примере заметок
This commit is contained in:
1 parent
5d01831ebd
commit
f5da740bc8
8 files changed
+344
No files matched your search
@@ -8,6 +8,7 @@ use App\Models\Note;
|
|||||||
use Rsgrinko\Proton\Access\Policy;
|
use Rsgrinko\Proton\Access\Policy;
|
||||||
use Rsgrinko\Proton\Access\Scope;
|
use Rsgrinko\Proton\Access\Scope;
|
||||||
use Rsgrinko\Proton\Access\Viewer;
|
use Rsgrinko\Proton\Access\Viewer;
|
||||||
|
use Rsgrinko\Proton\Comments\Comment;
|
||||||
use Rsgrinko\Proton\Database\Model\Query;
|
use Rsgrinko\Proton\Database\Model\Query;
|
||||||
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
use Rsgrinko\Proton\Database\Model\RecordNotFound;
|
||||||
use Rsgrinko\Proton\Events\Events;
|
use Rsgrinko\Proton\Events\Events;
|
||||||
@@ -313,6 +314,7 @@ final class NotesController extends Controller
|
|||||||
'note' => $note,
|
'note' => $note,
|
||||||
'author' => $note->author,
|
'author' => $note->author,
|
||||||
'attachments' => Attachment::of('note', $note->id()),
|
'attachments' => Attachment::of('note', $note->id()),
|
||||||
|
'comments' => Comment::of('note', $note->id()),
|
||||||
], (string) $note->title);
|
], (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()]);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Убрать вложение заметки.
|
* Убрать вложение заметки.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -0,0 +1,97 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace Rsgrinko\Proton\Comments;
|
||||||
|
|
||||||
|
use Rsgrinko\Proton\Database\Connection;
|
||||||
|
use Rsgrinko\Proton\Database\Model\Model;
|
||||||
|
use Rsgrinko\Proton\Database\Model\Relations\BelongsTo;
|
||||||
|
use Rsgrinko\Proton\Models\User;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Комментарий, оставленный к записи любого раздела.
|
||||||
|
*
|
||||||
|
* Comment::add('note', $note->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<int, self>
|
||||||
|
*/
|
||||||
|
public static function of(string $entity, int|string $entityId): array
|
||||||
|
{
|
||||||
|
/** @var array<int, self> $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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
.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; }
|
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; }
|
.bulk-bar { margin-bottom: 10px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 8px; }
|
||||||
|
|
||||||
/* Панель отладки: видна только при APP_DEBUG и не мешает содержимому */
|
/* Панель отладки: видна только при APP_DEBUG и не мешает содержимому */
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Migrations;
|
||||||
|
|
||||||
|
use Rsgrinko\Proton\Database\Migration;
|
||||||
|
use Rsgrinko\Proton\Database\Schema\Blueprint;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Комментарии: обсуждение к любой записи, не только к заметкам.
|
||||||
|
*
|
||||||
|
* Та же идея, что у вложений (`attachments`) — запись не привязана внешним
|
||||||
|
* ключом к конкретной таблице, а несёт раздел и номер записи сама. Так
|
||||||
|
* комментарии заводятся под любой раздел без миграции: достаточно вызвать
|
||||||
|
* `Comment::add()` из своего контроллера.
|
||||||
|
*/
|
||||||
|
final class CreateComments extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
$this->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');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ declare(strict_types=1);
|
|||||||
* @var \App\Models\Note $note
|
* @var \App\Models\Note $note
|
||||||
* @var \Rsgrinko\Proton\Models\User|null $author
|
* @var \Rsgrinko\Proton\Models\User|null $author
|
||||||
* @var array<int, \Rsgrinko\Proton\Files\Attachment> $attachments
|
* @var array<int, \Rsgrinko\Proton\Files\Attachment> $attachments
|
||||||
|
* @var array<int, \Rsgrinko\Proton\Comments\Comment> $comments
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use Rsgrinko\Proton\Support\SignedUrl;
|
use Rsgrinko\Proton\Support\SignedUrl;
|
||||||
@@ -108,6 +109,43 @@ use Rsgrinko\Proton\View\View;
|
|||||||
</div>
|
</div>
|
||||||
<?php } ?>
|
<?php } ?>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>Комментарии (<?= count($comments) ?>)</h2>
|
||||||
|
|
||||||
|
<?php if ($comments === []) { ?>
|
||||||
|
<p class="muted small">Пока никто не написал.</p>
|
||||||
|
<?php } else { ?>
|
||||||
|
<?php $viewerId = View::viewer()->id(); ?>
|
||||||
|
<div class="comments">
|
||||||
|
<?php foreach ($comments as $comment) { ?>
|
||||||
|
<?php $author = $comment->author; ?>
|
||||||
|
<div class="comment">
|
||||||
|
<div class="row">
|
||||||
|
<strong class="small"><?= View::e($author === null ? 'удалённый пользователь' : (string) $author->login) ?></strong>
|
||||||
|
<span class="muted small"><?= View::e(View::ago((string) $comment->raw('created_at'))) ?></span>
|
||||||
|
<span class="spacer"></span>
|
||||||
|
|
||||||
|
<?php if ((int) $comment->raw('user_id') === $viewerId || View::can('notes.manage')) { ?>
|
||||||
|
<form method="post" action="<?= View::e(View::route('notes.comment.delete', ['id' => $note->id()])) ?>">
|
||||||
|
<?= View::csrf() ?>
|
||||||
|
<input type="hidden" name="comment" value="<?= $comment->id() ?>">
|
||||||
|
<button type="submit" class="small danger">Убрать</button>
|
||||||
|
</form>
|
||||||
|
<?php } ?>
|
||||||
|
</div>
|
||||||
|
<p class="break small"><?= View::e((string) $comment->raw('body')) ?></p>
|
||||||
|
</div>
|
||||||
|
<?php } ?>
|
||||||
|
</div>
|
||||||
|
<?php } ?>
|
||||||
|
|
||||||
|
<form method="post" action="<?= View::e(View::route('notes.comment', ['id' => $note->id()])) ?>" style="margin-top: 12px;">
|
||||||
|
<?= View::csrf() ?>
|
||||||
|
<textarea name="body" rows="3" placeholder="Написать комментарий…" required></textarea>
|
||||||
|
<button type="submit" class="primary" style="margin-top: 8px;">Отправить</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
<?= View::partial('history', ['entity' => 'note', 'id' => $note->id()]) ?>
|
<?= View::partial('history', ['entity' => 'note', 'id' => $note->id()]) ?>
|
||||||
|
|
||||||
<p><a href="<?= View::e(View::route('notes.index')) ?>">← ко всем заметкам</a></p>
|
<p><a href="<?= View::e(View::route('notes.index')) ?>">← ко всем заметкам</a></p>
|
||||||
@@ -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->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->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->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');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Комментарии: обсуждение к любой записи.
|
||||||
|
*/
|
||||||
|
|
||||||
|
use App\Models\Note;
|
||||||
|
use Rsgrinko\Proton\Comments\Comment;
|
||||||
|
use Rsgrinko\Proton\Database\Model\Factory;
|
||||||
|
use Rsgrinko\Proton\Models\User;
|
||||||
|
|
||||||
|
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()]);
|
||||||
|
|
||||||
|
$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()));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -13,6 +13,7 @@ use App\Models\Note;
|
|||||||
use Rsgrinko\Proton\Access\Permission;
|
use Rsgrinko\Proton\Access\Permission;
|
||||||
use Rsgrinko\Proton\Auth\Auth;
|
use Rsgrinko\Proton\Auth\Auth;
|
||||||
use Rsgrinko\Proton\Auth\Csrf;
|
use Rsgrinko\Proton\Auth\Csrf;
|
||||||
|
use Rsgrinko\Proton\Comments\Comment;
|
||||||
use Rsgrinko\Proton\Http\Kernel;
|
use Rsgrinko\Proton\Http\Kernel;
|
||||||
use Rsgrinko\Proton\Http\Request;
|
use Rsgrinko\Proton\Http\Request;
|
||||||
use Rsgrinko\Proton\Http\Response;
|
use Rsgrinko\Proton\Http\Response;
|
||||||
@@ -217,6 +218,46 @@ test('http: чужая запись для обычного пользовате
|
|||||||
assertNotContains('Чужая заметка', $list->body());
|
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 {
|
test('http: форма без токена ничего не меняет', function (): void {
|
||||||
$before = Note::query()->where('user_id', httpAdmin()->id())->count();
|
$before = Note::query()->where('user_id', httpAdmin()->id())->count();
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user