Implemented the authenticated admin contact system.

This commit is contained in:
2026-05-16 22:02:32 +03:30
parent 04e7931ccc
commit e633805ed3
28 changed files with 2200 additions and 14 deletions

View File

@@ -0,0 +1,152 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreSupportMessageRequest;
use App\Http\Requests\UpdateSupportConversationStatusRequest;
use App\Models\SupportAttachment;
use App\Models\SupportConversation;
use App\Models\SupportMessage;
use App\Services\Support\SupportMessageCreator;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;
class AdminSupportConversationController extends Controller
{
public function index(): Response
{
return Inertia::render('admin/support/index', [
'stats' => [
'open' => SupportConversation::query()->where('status', SupportConversation::STATUS_OPEN)->count(),
'closed' => SupportConversation::query()->where('status', SupportConversation::STATUS_CLOSED)->count(),
],
'conversations' => SupportConversation::query()
->with(['latestMessage.user', 'user'])
->withCount('messages')
->latest('last_message_at')
->latest()
->limit(75)
->get()
->map(fn (SupportConversation $conversation) => $this->conversationSummary($conversation)),
]);
}
public function show(SupportConversation $conversation): Response
{
$conversation->load([
'messages' => fn ($query) => $query->oldest()->with(['attachments', 'user']),
'user.channel',
]);
return Inertia::render('admin/support/show', [
'conversation' => $this->conversationPayload($conversation),
]);
}
public function reply(StoreSupportMessageRequest $request, SupportConversation $conversation, SupportMessageCreator $messages): RedirectResponse
{
abort_unless($conversation->isOpen(), 422, 'Reopen this conversation before replying.');
$validated = $request->validated();
$messages->create(
$conversation,
$request->user(),
$validated['body'],
$request->file('attachments', []) ?: [],
);
return back()->with('success', 'Reply sent.');
}
public function update(UpdateSupportConversationStatusRequest $request, SupportConversation $conversation): RedirectResponse
{
$conversation->forceFill([
'status' => $request->validated('status'),
])->save();
return back()->with(
'success',
$conversation->isOpen() ? 'Conversation reopened.' : 'Conversation closed.',
);
}
/**
* @return array<string, mixed>
*/
private function conversationPayload(SupportConversation $conversation): array
{
return [
...$this->conversationSummary($conversation),
'user' => [
'id' => $conversation->user->id,
'name' => $conversation->user->name,
'email' => $conversation->user->email,
'can_create_channel' => $conversation->user->can_create_channel,
'suspended_at' => $conversation->user->suspended_at?->toIso8601String(),
'channel' => $conversation->user->channel ? [
'id' => $conversation->user->channel->id,
'slug' => $conversation->user->channel->slug,
'display_name' => $conversation->user->channel->display_name,
] : null,
],
'messages' => $conversation->messages->map(fn (SupportMessage $message) => $this->messagePayload($message)),
];
}
/**
* @return array<string, mixed>
*/
private function conversationSummary(SupportConversation $conversation): array
{
return [
'id' => $conversation->id,
'category' => $conversation->category,
'category_label' => SupportConversation::categoryLabels()[$conversation->category] ?? 'Other',
'subject' => $conversation->subject,
'status' => $conversation->status,
'last_message_at' => $conversation->last_message_at?->toIso8601String(),
'messages_count' => $conversation->messages_count ?? $conversation->messages()->count(),
'user' => [
'id' => $conversation->user->id,
'name' => $conversation->user->name,
'email' => $conversation->user->email,
],
'latest_message' => $conversation->latestMessage ? $this->messagePreviewPayload($conversation->latestMessage) : null,
];
}
/**
* @return array<string, mixed>
*/
private function messagePayload(SupportMessage $message): array
{
return [
...$this->messagePreviewPayload($message),
'attachments' => $message->attachments->map(fn (SupportAttachment $attachment) => [
'id' => $attachment->id,
'original_name' => $attachment->original_name,
'mime_type' => $attachment->mime_type,
'size' => $attachment->size,
]),
];
}
/**
* @return array<string, mixed>
*/
private function messagePreviewPayload(SupportMessage $message): array
{
return [
'id' => $message->id,
'body' => $message->body,
'created_at' => $message->created_at?->toIso8601String(),
'author' => [
'id' => $message->user?->id,
'name' => $message->user?->name ?? 'Deleted user',
'is_admin' => (bool) $message->user?->is_admin,
],
];
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Http\Controllers;
use App\Models\SupportAttachment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
class SupportAttachmentController extends Controller
{
public function __invoke(Request $request, SupportAttachment $attachment): StreamedResponse
{
$attachment->loadMissing('message.conversation');
abort_unless(
$request->user()?->is_admin || $attachment->message->conversation->user_id === $request->user()?->id,
403,
);
return Storage::disk($attachment->disk)->download($attachment->path, $attachment->original_name);
}
}

View File

@@ -0,0 +1,161 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreSupportConversationRequest;
use App\Http\Requests\StoreSupportMessageRequest;
use App\Models\SupportAttachment;
use App\Models\SupportConversation;
use App\Models\SupportMessage;
use App\Services\Support\SupportMessageCreator;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;
class SupportConversationController extends Controller
{
public function index(Request $request): Response
{
return Inertia::render('support/index', [
'categories' => $this->categories(),
'conversations' => $request->user()
->supportConversations()
->with(['latestMessage.user'])
->withCount('messages')
->latest('last_message_at')
->latest()
->limit(50)
->get()
->map(fn (SupportConversation $conversation) => $this->conversationSummary($conversation)),
]);
}
public function store(StoreSupportConversationRequest $request, SupportMessageCreator $messages): RedirectResponse
{
$validated = $request->validated();
$conversation = $messages->createConversation(
$request->user(),
$validated['category'],
$validated['subject'],
$validated['body'],
$request->file('attachments', []) ?: [],
);
return redirect()
->route('support.show', $conversation)
->with('success', 'Message sent to admin.');
}
public function show(Request $request, SupportConversation $conversation): Response
{
$this->authorizeUserConversation($request, $conversation);
$conversation->load([
'messages' => fn ($query) => $query->oldest()->with(['attachments', 'user']),
'user',
]);
return Inertia::render('support/show', [
'conversation' => $this->conversationPayload($conversation),
]);
}
public function reply(StoreSupportMessageRequest $request, SupportConversation $conversation, SupportMessageCreator $messages): RedirectResponse
{
$this->authorizeUserConversation($request, $conversation);
abort_unless($conversation->isOpen(), 422, 'This conversation is closed.');
$validated = $request->validated();
$messages->create(
$conversation,
$request->user(),
$validated['body'],
$request->file('attachments', []) ?: [],
);
return back()->with('success', 'Reply sent.');
}
private function authorizeUserConversation(Request $request, SupportConversation $conversation): void
{
abort_unless($conversation->user_id === $request->user()->id, 403);
}
/**
* @return array<int, array{value: string, label: string}>
*/
private function categories(): array
{
return collect(SupportConversation::categoryLabels())
->map(fn (string $label, string $value): array => [
'value' => $value,
'label' => $label,
])
->values()
->all();
}
/**
* @return array<string, mixed>
*/
private function conversationPayload(SupportConversation $conversation): array
{
return [
...$this->conversationSummary($conversation),
'messages' => $conversation->messages->map(fn (SupportMessage $message) => $this->messagePayload($message)),
];
}
/**
* @return array<string, mixed>
*/
private function conversationSummary(SupportConversation $conversation): array
{
return [
'id' => $conversation->id,
'category' => $conversation->category,
'category_label' => SupportConversation::categoryLabels()[$conversation->category] ?? 'Other',
'subject' => $conversation->subject,
'status' => $conversation->status,
'last_message_at' => $conversation->last_message_at?->toIso8601String(),
'messages_count' => $conversation->messages_count ?? $conversation->messages()->count(),
'latest_message' => $conversation->latestMessage ? $this->messagePreviewPayload($conversation->latestMessage) : null,
];
}
/**
* @return array<string, mixed>
*/
private function messagePayload(SupportMessage $message): array
{
return [
...$this->messagePreviewPayload($message),
'attachments' => $message->attachments->map(fn (SupportAttachment $attachment) => [
'id' => $attachment->id,
'original_name' => $attachment->original_name,
'mime_type' => $attachment->mime_type,
'size' => $attachment->size,
]),
];
}
/**
* @return array<string, mixed>
*/
private function messagePreviewPayload(SupportMessage $message): array
{
return [
'id' => $message->id,
'body' => $message->body,
'created_at' => $message->created_at?->toIso8601String(),
'author' => [
'id' => $message->user?->id,
'name' => $message->user?->name ?? 'Deleted user',
'is_admin' => (bool) $message->user?->is_admin,
],
];
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace App\Http\Requests;
use App\Models\SupportConversation;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreSupportConversationRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, array<int, mixed>>
*/
public function rules(): array
{
return [
'category' => ['required', 'string', Rule::in(SupportConversation::categories())],
'subject' => ['required', 'string', 'max:120'],
'body' => ['required', 'string', 'max:2000'],
'attachments' => ['nullable', 'array', 'max:3'],
'attachments.*' => ['file', 'max:10240', 'mimes:jpg,jpeg,png,webp,gif,pdf,txt,log,json,zip'],
];
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreSupportMessageRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
/**
* @return array<string, array<int, string>>
*/
public function rules(): array
{
return [
'body' => ['required', 'string', 'max:2000'],
'attachments' => ['nullable', 'array', 'max:3'],
'attachments.*' => ['file', 'max:10240', 'mimes:jpg,jpeg,png,webp,gif,pdf,txt,log,json,zip'],
];
}
}

View File

@@ -0,0 +1,25 @@
<?php
namespace App\Http\Requests;
use App\Models\SupportConversation;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateSupportConversationStatusRequest extends FormRequest
{
public function authorize(): bool
{
return (bool) $this->user()?->is_admin;
}
/**
* @return array<string, array<int, mixed>>
*/
public function rules(): array
{
return [
'status' => ['required', 'string', Rule::in(SupportConversation::statuses())],
];
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace App\Models;
use Database\Factories\SupportAttachmentFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable(['support_message_id', 'disk', 'path', 'original_name', 'mime_type', 'size'])]
class SupportAttachment extends Model
{
/** @use HasFactory<SupportAttachmentFactory> */
use HasFactory;
public function message(): BelongsTo
{
return $this->belongsTo(SupportMessage::class, 'support_message_id');
}
}

View File

@@ -0,0 +1,92 @@
<?php
namespace App\Models;
use Database\Factories\SupportConversationFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
#[Fillable(['user_id', 'category', 'subject', 'status', 'last_message_at'])]
class SupportConversation extends Model
{
/** @use HasFactory<SupportConversationFactory> */
use HasFactory;
public const CATEGORY_BUG = 'bug';
public const CATEGORY_SUGGESTION = 'suggestion';
public const CATEGORY_CHANNEL_REQUEST = 'channel_request';
public const CATEGORY_OTHER = 'other';
public const STATUS_OPEN = 'open';
public const STATUS_CLOSED = 'closed';
/**
* @return array<string, string>
*/
public static function categoryLabels(): array
{
return [
self::CATEGORY_BUG => 'Bug report',
self::CATEGORY_SUGGESTION => 'Suggestion',
self::CATEGORY_CHANNEL_REQUEST => 'Channel request',
self::CATEGORY_OTHER => 'Other',
];
}
/**
* @return array<int, string>
*/
public static function categories(): array
{
return array_keys(self::categoryLabels());
}
/**
* @return array<int, string>
*/
public static function statuses(): array
{
return [
self::STATUS_OPEN,
self::STATUS_CLOSED,
];
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'last_message_at' => 'datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function messages(): HasMany
{
return $this->hasMany(SupportMessage::class);
}
public function latestMessage(): HasOne
{
return $this->hasOne(SupportMessage::class)->latestOfMany();
}
public function isOpen(): bool
{
return $this->status === self::STATUS_OPEN;
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace App\Models;
use Database\Factories\SupportMessageFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['support_conversation_id', 'user_id', 'body'])]
class SupportMessage extends Model
{
/** @use HasFactory<SupportMessageFactory> */
use HasFactory;
public function conversation(): BelongsTo
{
return $this->belongsTo(SupportConversation::class, 'support_conversation_id');
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function attachments(): HasMany
{
return $this->hasMany(SupportAttachment::class);
}
}

View File

@@ -57,6 +57,16 @@ class User extends Authenticatable
return $this->hasMany(Follow::class);
}
public function supportConversations(): HasMany
{
return $this->hasMany(SupportConversation::class);
}
public function supportMessages(): HasMany
{
return $this->hasMany(SupportMessage::class);
}
public function isSuspended(): bool
{
return $this->suspended_at !== null;

View File

@@ -0,0 +1,62 @@
<?php
namespace App\Services\Support;
use App\Models\SupportConversation;
use App\Models\SupportMessage;
use App\Models\User;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SupportMessageCreator
{
/**
* @param array<int, UploadedFile> $attachments
*/
public function createConversation(User $author, string $category, string $subject, string $body, array $attachments = []): SupportConversation
{
return DB::transaction(function () use ($attachments, $author, $body, $category, $subject): SupportConversation {
$conversation = $author->supportConversations()->create([
'category' => $category,
'subject' => trim($subject),
'status' => SupportConversation::STATUS_OPEN,
]);
$this->create($conversation, $author, $body, $attachments);
return $conversation;
});
}
/**
* @param array<int, UploadedFile> $attachments
*/
public function create(SupportConversation $conversation, User $author, string $body, array $attachments = []): SupportMessage
{
return DB::transaction(function () use ($attachments, $author, $body, $conversation): SupportMessage {
$message = $conversation->messages()->create([
'user_id' => $author->id,
'body' => trim($body),
]);
foreach ($attachments as $attachment) {
$path = $attachment->store("support/{$conversation->id}/{$message->id}", 'local');
$message->attachments()->create([
'disk' => 'local',
'path' => $path,
'original_name' => Str::limit($attachment->getClientOriginalName(), 255, ''),
'mime_type' => $attachment->getMimeType() ?: 'application/octet-stream',
'size' => $attachment->getSize() ?: 0,
]);
}
$conversation->forceFill([
'last_message_at' => now(),
])->save();
return $message;
});
}
}