v7.0.0-beta.1 release
This commit is contained in:
commit
6595fd0eb5
3967 files changed
+1875383
No files matched your search
@@ -0,0 +1,189 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\ReorderAttachmentsRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UploadAttachmentRequest;
|
||||
use Modules\Sirsoft\Board\Services\AttachmentService;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
/**
|
||||
* 관리자용 게시판 첨부파일 컨트롤러
|
||||
*
|
||||
* 게시판별 동적 테이블을 사용하는 첨부파일 업로드, 삭제, 순서 변경 등을 처리합니다.
|
||||
*/
|
||||
class AttachmentController extends AdminBaseController
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* AttachmentController 생성자
|
||||
*
|
||||
* @param AttachmentService $attachmentService 첨부파일 서비스
|
||||
* @param BoardService $boardService 게시판 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private AttachmentService $attachmentService,
|
||||
private BoardService $boardService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 파일 업로드
|
||||
*
|
||||
* @param UploadAttachmentRequest $request 업로드 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
*/
|
||||
public function upload(UploadAttachmentRequest $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug);
|
||||
|
||||
$validated = $request->validated();
|
||||
|
||||
// post_id가 없으면 임시 업로드 (temp_key 필수)
|
||||
$postId = $validated['post_id'] ?? null;
|
||||
$tempKey = $validated['temp_key'] ?? null;
|
||||
|
||||
$attachment = $this->attachmentService->upload(
|
||||
slug: $slug,
|
||||
file: $request->file('file'),
|
||||
postId: $postId,
|
||||
collection: $validated['collection'] ?? 'attachments',
|
||||
tempKey: $tempKey
|
||||
);
|
||||
|
||||
// FileUploader 컴포넌트가 response.data?.data 형식을 기대하므로
|
||||
// data 키 안에 한 번 더 감싸서 반환
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.attachment.upload_success',
|
||||
[
|
||||
'data' => [
|
||||
'id' => $attachment->id,
|
||||
'hash' => $attachment->hash,
|
||||
'original_filename' => $attachment->original_filename,
|
||||
'stored_filename' => $attachment->stored_filename,
|
||||
'mime_type' => $attachment->mime_type,
|
||||
'size' => $attachment->size,
|
||||
'url' => $this->attachmentService->getUrl($slug, $attachment->id),
|
||||
'order' => $attachment->order,
|
||||
'created_at' => $attachment->created_at,
|
||||
],
|
||||
],
|
||||
201
|
||||
);
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->error('sirsoft-board::messages.board.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.attachment.upload_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부파일 삭제
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param int $id 첨부파일 ID
|
||||
*/
|
||||
public function destroy(string $slug, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug);
|
||||
|
||||
// 첨부파일 조회 (Service를 통해)
|
||||
$attachment = $this->attachmentService->getById($slug, $id);
|
||||
|
||||
if (! $attachment) {
|
||||
return $this->error('sirsoft-board::messages.attachment.not_found', 404);
|
||||
}
|
||||
|
||||
// 삭제 (Service에서 처리)
|
||||
$result = $this->attachmentService->delete($slug, $id);
|
||||
|
||||
if (! $result) {
|
||||
return $this->error('sirsoft-board::messages.attachment.delete_failed', 500);
|
||||
}
|
||||
|
||||
return $this->success('sirsoft-board::messages.attachment.delete_success');
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->error('sirsoft-board::messages.board.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.attachment.delete_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부파일 순서 변경
|
||||
*
|
||||
* @param ReorderAttachmentsRequest $request 순서 변경 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
*/
|
||||
public function reorder(ReorderAttachmentsRequest $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug);
|
||||
|
||||
$validated = $request->validated();
|
||||
|
||||
// FileUploader가 [{id, order}] 형태로 전송 → [ID => order] 매핑으로 변환
|
||||
$orders = collect($validated['order'])->pluck('order', 'id')->all();
|
||||
$result = $this->attachmentService->reorder($slug, $orders);
|
||||
|
||||
if (! $result) {
|
||||
return $this->error('sirsoft-board::messages.attachment.reorder_failed', 500);
|
||||
}
|
||||
|
||||
return $this->success('sirsoft-board::messages.attachment.reorder_success');
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->error('sirsoft-board::messages.board.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.attachment.reorder_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부파일 다운로드 (해시 기반)
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string $hash 첨부파일 해시
|
||||
*/
|
||||
public function download(string $slug, string $hash): StreamedResponse|JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug);
|
||||
|
||||
// 해시로 첨부파일 조회
|
||||
$attachment = $this->attachmentService->getByHash($slug, $hash);
|
||||
|
||||
if (! $attachment) {
|
||||
return $this->error('sirsoft-board::messages.attachment.not_found', 404);
|
||||
}
|
||||
|
||||
// 다운로드 응답 생성
|
||||
$response = $this->attachmentService->download($slug, $attachment->id);
|
||||
|
||||
if (! $response) {
|
||||
return $this->error('sirsoft-board::messages.attachment.file_not_found', 404);
|
||||
}
|
||||
|
||||
return $response;
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->error('sirsoft-board::messages.board.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.attachment.download_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\Sirsoft\Board\Exceptions\MenuAlreadyExistsException;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\StoreBoardRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UpdateBoardRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardCollection;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\PostResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardTypeResource;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
use Modules\Sirsoft\Board\Services\BoardTypeService;
|
||||
use Modules\Sirsoft\Board\Services\PostService;
|
||||
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* 관리자용 게시판 관리 컨트롤러
|
||||
*
|
||||
* 게시판의 생성, 수정, 삭제, 조회 등 관리자 전용 기능을 제공합니다.
|
||||
*/
|
||||
class BoardController extends AdminBaseController
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
/**
|
||||
* BoardController 생성자
|
||||
*
|
||||
* @param BoardService $boardService 게시판 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private BoardService $boardService,
|
||||
private BoardTypeService $boardTypeService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 게시판 목록 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$boards = $this->boardService->getBoards($request->all());
|
||||
|
||||
// BoardCollection의 withPermissions 사용
|
||||
$collection = new BoardCollection($boards);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.boards.fetch_success',
|
||||
$collection->withPermissions()
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판 상세 정보를 조회합니다.
|
||||
*
|
||||
* @param int $id 게시판 ID
|
||||
* @return JsonResponse 게시판 상세 정보 응답
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = $this->boardService->getBoard($id);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.boards.fetch_success',
|
||||
new BoardResource($board)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 슬러그로 게시판 상세 정보를 조회합니다.
|
||||
*
|
||||
* parent_id 쿼리 파라미터가 있으면 원글 정보도 함께 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param PostService $postService 게시글 서비스 (DI)
|
||||
* @return JsonResponse 게시판 상세 정보 응답
|
||||
*/
|
||||
public function showBySlug(Request $request, string $slug, PostService $postService): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = $this->boardService->getBoardBySlug($slug);
|
||||
|
||||
if (! $board) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
}
|
||||
|
||||
// 관리자 라우트에서는 항상 사용자 권한 정보 포함
|
||||
$request->merge(['include_user_abilities' => true]);
|
||||
|
||||
$responseData = (new BoardResource($board))->toArray($request);
|
||||
|
||||
// parent_id가 있으면 원글 정보도 함께 반환
|
||||
$parentId = $request->query('parent_id');
|
||||
if ($parentId) {
|
||||
try {
|
||||
$parentPost = $postService->getPost($slug, (int) $parentId);
|
||||
$parentPostData = (new PostResource($parentPost))->toArray($request);
|
||||
// 답변글 기본 제목 추가
|
||||
$parentPostData['reply_title'] = 'RE: '.$parentPost->title;
|
||||
$responseData['parent_post'] = $parentPostData;
|
||||
} catch (ModelNotFoundException $e) {
|
||||
// 원글이 없으면 null로 설정
|
||||
$responseData['parent_post'] = null;
|
||||
}
|
||||
}
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.boards.fetch_success',
|
||||
$responseData
|
||||
);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 새로운 게시판을 생성합니다.
|
||||
*
|
||||
* @param StoreBoardRequest $request 게시판 생성 요청
|
||||
* @return JsonResponse 생성된 게시판 정보 응답
|
||||
*/
|
||||
public function store(StoreBoardRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = $this->boardService->createBoard($request->validated());
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.boards.create_success',
|
||||
new BoardResource($board),
|
||||
201
|
||||
);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->validationError($e->errors(), 'sirsoft-board::messages.boards.validation_failed');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.create_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판 정보를 수정합니다.
|
||||
*
|
||||
* @param UpdateBoardRequest $request 게시판 수정 요청
|
||||
* @param int $id 게시판 ID
|
||||
* @return JsonResponse 수정된 게시판 정보 응답
|
||||
*/
|
||||
public function update(UpdateBoardRequest $request, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = $this->boardService->updateBoard($id, $request->validated());
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.boards.update_success',
|
||||
new BoardResource($board)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->validationError($e->errors(), 'sirsoft-board::messages.boards.validation_failed');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.update_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판을 영구 삭제합니다.
|
||||
*
|
||||
* @param int $id 게시판 ID
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 삭제 성공 응답
|
||||
*/
|
||||
public function destroy(int $id, Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$forceDelete = (bool) $request->input('force_delete', false);
|
||||
$this->boardService->deleteBoard($id, $forceDelete);
|
||||
|
||||
return $this->success('sirsoft-board::messages.boards.delete_success');
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.delete_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판 폼에 필요한 데이터를 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 폼 데이터 응답
|
||||
*/
|
||||
public function getFormData(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$basicDefaults = g7_module_settings('sirsoft-board', 'basic_defaults', []);
|
||||
|
||||
// 수정 모드
|
||||
if ($request->filled('board_id')) {
|
||||
$request->merge(['include_permissions' => true]);
|
||||
|
||||
$board = $this->boardService->getBoard($request->board_id);
|
||||
$data = (new BoardResource($board))->toArray($request);
|
||||
}
|
||||
// 복사 모드
|
||||
elseif ($request->filled('copy_id')) {
|
||||
$copyData = $this->boardService->copyBoard($request->copy_id);
|
||||
|
||||
$copyData['permissions'] = BoardResource::formatPermissionsForFrontend(
|
||||
$copyData['permissions'] ?? []
|
||||
);
|
||||
|
||||
$data = $copyData;
|
||||
}
|
||||
// 생성 모드
|
||||
else {
|
||||
$defaults = collect($basicDefaults);
|
||||
|
||||
$data = $defaults->reject(fn ($value) => is_array($value))->toArray();
|
||||
|
||||
// 수정 모드 전용 필드 명시적 null/빈값 설정 (수정→생성 이동 시 이전 값 제거)
|
||||
$data['id'] = null;
|
||||
$data['slug'] = null;
|
||||
$data['is_active'] = true;
|
||||
|
||||
// 로그인한 관리자를 게시판 관리자 기본값으로 지정
|
||||
$currentUser = Auth::user();
|
||||
$data['board_managers'] = $currentUser ? [[
|
||||
'uuid' => $currentUser->uuid,
|
||||
'name' => $currentUser->name,
|
||||
'email' => $currentUser->email,
|
||||
]] : [];
|
||||
$data['board_steps'] = [];
|
||||
$data['board_manager_ids'] = $currentUser ? [$currentUser->uuid] : [];
|
||||
$data['board_step_ids'] = [];
|
||||
$data['created_at'] = null;
|
||||
$data['updated_at'] = null;
|
||||
|
||||
// 다국어 필드 기본값 초기화 (기본 언어 배열로)
|
||||
$fallbackLocale = config('app.fallback_locale', 'ko');
|
||||
$data['name'] = [$fallbackLocale => ''];
|
||||
$data['description'] = [$fallbackLocale => ''];
|
||||
|
||||
$data['categories'] = [];
|
||||
$data['notify_author_channels'] = $basicDefaults['notify_author_channels'] ?? [];
|
||||
$data['notify_admin_on_post_channels'] = $basicDefaults['notify_admin_on_post_channels'] ?? [];
|
||||
$spamSecurity = g7_module_settings('sirsoft-board', 'spam_security', []);
|
||||
$data['blocked_keywords'] = collect($spamSecurity['blocked_keywords'] ?? [])->join(',');
|
||||
$data['allowed_extensions'] = collect($basicDefaults['allowed_extensions'] ?? [])->join(',');
|
||||
|
||||
$data['permissions'] = BoardResource::formatPermissionsForFrontend(
|
||||
$basicDefaults['default_board_permissions'] ?? []
|
||||
);
|
||||
}
|
||||
|
||||
$data['board_types'] = BoardTypeResource::collection(
|
||||
$this->boardTypeService->getBoardTypes()
|
||||
);
|
||||
|
||||
$data['_meta'] = [
|
||||
'limits' => config('sirsoft-board.limits', []),
|
||||
];
|
||||
|
||||
return $this->success('sirsoft-board::messages.boards.form_data_retrieved', $data);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.form_data_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판을 관리자 메뉴에 추가합니다.
|
||||
*
|
||||
* @param int $id 게시판 ID
|
||||
* @return JsonResponse 메뉴 추가 결과 응답
|
||||
*/
|
||||
public function addToAdminMenu(int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
// Service 계층에 위임
|
||||
$menu = $this->boardService->addToAdminMenu($id);
|
||||
|
||||
return $this->success('sirsoft-board::messages.boards.menu_added_success', ['menu' => $menu]);
|
||||
} catch (MenuAlreadyExistsException $e) {
|
||||
return $this->error($e->getMessage(), $e->getCode());
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (ValidationException $e) {
|
||||
return $this->validationError($e->errors(), 'sirsoft-board::messages.boards.menu_add_failed');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.boards.menu_add_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use App\Http\Requests\MailTemplate\MailTemplateIndexRequest;
|
||||
use App\Http\Requests\MailTemplate\MailTemplatePreviewRequest;
|
||||
use App\Http\Requests\MailTemplate\UpdateMailTemplateRequest;
|
||||
use App\Http\Resources\MailTemplateCollection;
|
||||
use App\Http\Resources\MailTemplateResource;
|
||||
use Modules\Sirsoft\Board\Models\BoardMailTemplate;
|
||||
use Modules\Sirsoft\Board\Services\BoardMailTemplateService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
/**
|
||||
* 게시판 메일 템플릿 관리 컨트롤러
|
||||
*/
|
||||
class BoardMailTemplateController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* BoardMailTemplateController 생성자.
|
||||
*
|
||||
* @param BoardMailTemplateService $service 메일 템플릿 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private BoardMailTemplateService $service
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 템플릿 목록을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param MailTemplateIndexRequest $request 검증된 목록 조회 요청
|
||||
* @return JsonResponse 페이지네이션된 템플릿 목록
|
||||
*/
|
||||
public function index(MailTemplateIndexRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$filters = array_filter($request->validated(), fn ($value) => $value !== null);
|
||||
$perPage = (int) ($request->validated('per_page') ?? 20);
|
||||
$templates = $this->service->getTemplates($filters, $perPage);
|
||||
|
||||
$collection = new MailTemplateCollection($templates);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_fetch_success',
|
||||
$collection->toArray($request)
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_fetch_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 템플릿을 수정합니다.
|
||||
*
|
||||
* @param UpdateMailTemplateRequest $request 수정 요청
|
||||
* @param BoardMailTemplate $boardMailTemplate 수정 대상
|
||||
* @return JsonResponse 수정 결과
|
||||
*/
|
||||
public function update(UpdateMailTemplateRequest $request, BoardMailTemplate $boardMailTemplate): JsonResponse
|
||||
{
|
||||
try {
|
||||
$userId = $request->user()?->id;
|
||||
$template = $this->service->updateTemplate(
|
||||
$boardMailTemplate,
|
||||
$request->validated(),
|
||||
$userId
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_save_success',
|
||||
new MailTemplateResource($template)
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_save_error',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 템플릿의 활성 상태를 토글합니다.
|
||||
*
|
||||
* @param BoardMailTemplate $boardMailTemplate 토글 대상
|
||||
* @return JsonResponse 토글 결과
|
||||
*/
|
||||
public function toggleActive(BoardMailTemplate $boardMailTemplate): JsonResponse
|
||||
{
|
||||
try {
|
||||
$template = $this->service->toggleActive($boardMailTemplate);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_toggle_success',
|
||||
new MailTemplateResource($template)
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_toggle_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 템플릿 미리보기를 반환합니다.
|
||||
*
|
||||
* @param MailTemplatePreviewRequest $request 검증된 미리보기 요청
|
||||
* @return JsonResponse 미리보기 결과
|
||||
*/
|
||||
public function preview(MailTemplatePreviewRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$result = $this->service->getPreview($request->validated());
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_preview_success',
|
||||
$result
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_preview_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 메일 템플릿을 시더 기본값으로 복원합니다.
|
||||
*
|
||||
* @param BoardMailTemplate $boardMailTemplate 복원 대상
|
||||
* @return JsonResponse 복원 결과
|
||||
*/
|
||||
public function reset(BoardMailTemplate $boardMailTemplate): JsonResponse
|
||||
{
|
||||
try {
|
||||
$defaultData = $this->service->getDefaultTemplateData($boardMailTemplate->type);
|
||||
|
||||
if (! $defaultData) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_reset_no_default',
|
||||
404
|
||||
);
|
||||
}
|
||||
|
||||
$template = $this->service->resetToDefault($boardMailTemplate, $defaultData);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_reset_success',
|
||||
new MailTemplateResource($template)
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.mail_template_reset_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Extension\HookManager;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\Sirsoft\Board\Http\Requests\Admin\BulkApplySettingsRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\Admin\StoreBoardSettingsRequest;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
use Modules\Sirsoft\Board\Services\BoardSettingsService;
|
||||
|
||||
/**
|
||||
* 게시판 모듈 환경설정 컨트롤러
|
||||
*
|
||||
* 게시판 모듈의 환경설정을 관리하는 API를 제공합니다.
|
||||
*/
|
||||
class BoardSettingsController extends AdminBaseController
|
||||
{
|
||||
/**
|
||||
* BoardSettingsController 생성자
|
||||
*
|
||||
* @param BoardSettingsService $settingsService 환경설정 서비스
|
||||
* @param BoardService $boardService 게시판 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private BoardSettingsService $settingsService,
|
||||
private BoardService $boardService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 모든 게시판 설정을 조회합니다.
|
||||
*
|
||||
* @return JsonResponse 설정 목록을 포함한 JSON 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$settings = $this->settingsService->getAllSettings();
|
||||
$settings['report_permissions'] = $this->settingsService->getReportPermissionRoles();
|
||||
|
||||
$settings['abilities'] = [
|
||||
'can_update' => PermissionHelper::check('sirsoft-board.settings.update', $request->user()),
|
||||
];
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.settings.fetch_success',
|
||||
$settings
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.settings.fetch_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리별 설정을 조회합니다.
|
||||
*
|
||||
* @param string $category 카테고리명
|
||||
* @return JsonResponse 카테고리 설정을 포함한 JSON 응답
|
||||
*/
|
||||
public function show(Request $request, string $category): JsonResponse
|
||||
{
|
||||
try {
|
||||
$settings = $this->settingsService->getSettings($category);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.settings.fetch_success',
|
||||
[
|
||||
'category' => $category,
|
||||
'settings' => $settings,
|
||||
'abilities' => [
|
||||
'can_update' => PermissionHelper::check('sirsoft-board.settings.update', $request->user()),
|
||||
],
|
||||
]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.settings.fetch_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판 설정을 저장합니다.
|
||||
*
|
||||
* @param StoreBoardSettingsRequest $request 저장 요청 데이터
|
||||
* @return JsonResponse 저장 결과 JSON 응답
|
||||
*/
|
||||
public function store(StoreBoardSettingsRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$settings = $request->validatedSettings();
|
||||
|
||||
$result = $this->settingsService->saveSettings($settings);
|
||||
|
||||
if ($result) {
|
||||
if ($request->has('report_permissions')) {
|
||||
$this->settingsService->syncReportPermissionRoles($request->input('report_permissions'));
|
||||
}
|
||||
|
||||
$updatedSettings = $this->settingsService->getAllSettings();
|
||||
$updatedSettings['report_permissions'] = $this->settingsService->getReportPermissionRoles();
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.settings.save_success',
|
||||
$updatedSettings
|
||||
);
|
||||
} else {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.settings.save_failed',
|
||||
400
|
||||
);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.settings.save_error',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 환경설정 기본값을 기존 게시판에 일괄 적용합니다.
|
||||
*
|
||||
* @param BulkApplySettingsRequest $request 일괄 적용 요청 데이터
|
||||
* @return JsonResponse 일괄 적용 결과 JSON 응답
|
||||
*/
|
||||
public function bulkApply(BulkApplySettingsRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$fields = $request->validated('fields');
|
||||
$applyAll = $request->validated('apply_all');
|
||||
$boardIds = $request->validated('board_ids', []);
|
||||
$overrideValues = $request->validated('override_values', []);
|
||||
|
||||
$updatedCount = $this->boardService->bulkApplySettings(
|
||||
$fields,
|
||||
$applyAll,
|
||||
$boardIds,
|
||||
$overrideValues
|
||||
);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.settings.bulk_apply_success',
|
||||
['updated_count' => $updatedCount],
|
||||
200,
|
||||
['count' => $updatedCount]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.settings.bulk_apply_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용 가능한 알림 채널 목록을 반환합니다.
|
||||
*
|
||||
* 기본 채널(mail, database)을 제공하며, 플러그인이
|
||||
* 'sirsoft-board.notification.available_channels' Filter 훅으로 채널을 추가할 수 있습니다.
|
||||
* 추후 코어에 공통 API가 생기면 이 메서드만 교체하면 됩니다.
|
||||
*
|
||||
* @return JsonResponse 채널 목록 JSON 응답
|
||||
*/
|
||||
public function notificationChannels(): JsonResponse
|
||||
{
|
||||
$defaultChannels = [
|
||||
['value' => 'mail', 'label' => __('sirsoft-board::admin.settings.notification_channels.channel_mail')],
|
||||
];
|
||||
|
||||
$channels = HookManager::applyFilters(
|
||||
'sirsoft-board.notification.available_channels',
|
||||
$defaultChannels
|
||||
);
|
||||
|
||||
return ResponseHelper::success('messages.fetch_success', $channels);
|
||||
}
|
||||
|
||||
/**
|
||||
* 설정 캐시를 초기화합니다.
|
||||
*
|
||||
* ModuleSettings 캐시와 게시판 캐시를 모두 초기화합니다.
|
||||
*
|
||||
* @return JsonResponse 초기화 결과 JSON 응답
|
||||
*/
|
||||
public function clearCache(): JsonResponse
|
||||
{
|
||||
try {
|
||||
// ModuleSettings 캐시 초기화
|
||||
$this->settingsService->clearCache();
|
||||
|
||||
// 게시판 캐시 초기화 (boards:list)
|
||||
Cache::forget('boards:list');
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-board',
|
||||
'messages.settings.clear_cache_success',
|
||||
['cleared' => true]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-board',
|
||||
'messages.settings.clear_cache_error',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Board\Http\Requests\StoreBoardTypeRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UpdateBoardTypeRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardTypeResource;
|
||||
use Modules\Sirsoft\Board\Services\BoardTypeService;
|
||||
|
||||
class BoardTypeController extends AdminBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private BoardTypeService $boardTypeService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
{
|
||||
$boardTypes = $this->boardTypeService->getBoardTypes();
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.board_type.list',
|
||||
BoardTypeResource::collection($boardTypes)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param StoreBoardTypeRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function store(StoreBoardTypeRequest $request): JsonResponse
|
||||
{
|
||||
$boardType = $this->boardTypeService->createBoardType($request->validated());
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.board_type.created',
|
||||
new BoardTypeResource($boardType),
|
||||
201
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param UpdateBoardTypeRequest $request
|
||||
* @param int $id
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function update(UpdateBoardTypeRequest $request, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$boardType = $this->boardTypeService->updateBoardType($id, $request->validated());
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.board_type.updated',
|
||||
new BoardTypeResource($boardType)
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('sirsoft-board::messages.board_type.not_found');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $id
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->boardTypeService->deleteBoardType($id);
|
||||
|
||||
return $this->success('sirsoft-board::messages.board_type.deleted');
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('sirsoft-board::messages.board_type.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error($e->getMessage(), 422);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Board\Http\Requests\BlindCommentRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\StoreCommentRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UpdateCommentRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\CommentResource;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Services\CommentService;
|
||||
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* 관리자용 댓글 컨트롤러
|
||||
*
|
||||
* 댓글 생성, 수정, 삭제, 블라인드, 복원 기능을 제공합니다.
|
||||
*/
|
||||
class CommentController extends AdminBaseController
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* CommentController 생성자
|
||||
*
|
||||
* @param CommentService $commentService 댓글 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private CommentService $commentService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글 수정/삭제 권한을 확인합니다.
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param int|null $commentUserId 댓글 작성자 ID
|
||||
* @return JsonResponse|null 권한이 없으면 JsonResponse, 있으면 null
|
||||
*/
|
||||
protected function authorizeCommentModification(string $slug, ?int $commentUserId): ?JsonResponse
|
||||
{
|
||||
// admin.manage 권한이 있으면 모든 댓글 수정/삭제 가능
|
||||
if ($this->checkBoardPermission($slug, 'admin.manage')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 비회원 댓글은 admin.manage 권한 필요
|
||||
if ($commentUserId === null) {
|
||||
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
|
||||
}
|
||||
|
||||
// admin.write 권한이 있고 본인 댓글이면 수정/삭제 가능
|
||||
if ($this->checkBoardPermission($slug, 'admin.write') && $this->isCommentOwner($commentUserId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 사용자가 댓글 작성자인지 확인합니다.
|
||||
*
|
||||
* @param int|null $commentUserId 댓글 작성자 ID
|
||||
* @return bool 댓글 작성자이면 true, 아니면 false
|
||||
*/
|
||||
protected function isCommentOwner(?int $commentUserId): bool
|
||||
{
|
||||
return Auth::id() === $commentUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 생성합니다.
|
||||
*
|
||||
* @param StoreCommentRequest $request 댓글 생성 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @return JsonResponse 댓글 생성 결과 응답
|
||||
*/
|
||||
public function store(StoreCommentRequest $request, string $slug, int $postId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$data = $request->validated();
|
||||
$data['post_id'] = $postId;
|
||||
$data['user_id'] = Auth::id();
|
||||
$data['ip_address'] = $request->ip();
|
||||
|
||||
$comment = $this->commentService->createComment($slug, $data);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.comment.create_success',
|
||||
new CommentResource($comment),
|
||||
201
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.create_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 수정합니다.
|
||||
*
|
||||
* @param UpdateCommentRequest $request 댓글 수정 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @param int $id 댓글 ID
|
||||
* @return JsonResponse 댓글 수정 결과 응답
|
||||
*/
|
||||
public function update(UpdateCommentRequest $request, string $slug, int $postId, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 댓글 조회
|
||||
$comment = $this->commentService->getComment($slug, $id);
|
||||
|
||||
// 권한 체크: 본인 댓글 또는 admin.manage
|
||||
if ($response = $this->authorizeCommentModification($slug, $comment->user_id)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$data = $request->validated();
|
||||
$updatedComment = $this->commentService->updateComment($slug, $id, $data);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.comment.update_success',
|
||||
new CommentResource($updatedComment)
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('sirsoft-board::messages.comment.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.update_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 삭제합니다.
|
||||
*
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @param int $id 댓글 ID
|
||||
* @return JsonResponse 댓글 삭제 결과 응답
|
||||
*/
|
||||
public function destroy(string $slug, int $postId, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 댓글 조회
|
||||
$comment = $this->commentService->getComment($slug, $id);
|
||||
|
||||
// 권한 체크: 본인 댓글 또는 admin.manage
|
||||
if ($response = $this->authorizeCommentModification($slug, $comment->user_id)) {
|
||||
return $response;
|
||||
}
|
||||
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$this->commentService->deleteComment($slug, $id, 'admin');
|
||||
|
||||
return $this->success('sirsoft-board::messages.comment.delete_success');
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('sirsoft-board::messages.comment.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.delete_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 블라인드 처리합니다.
|
||||
*
|
||||
* @param BlindCommentRequest $request 블라인드 처리 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @param int $id 댓글 ID
|
||||
* @return JsonResponse 댓글 블라인드 결과 응답
|
||||
*/
|
||||
public function blind(BlindCommentRequest $request, string $slug, int $postId, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$validated = $request->validated();
|
||||
$reason = $validated['reason'] ?? '';
|
||||
|
||||
$comment = $this->commentService->blindComment($slug, $id, $reason);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.comment.blind_success',
|
||||
new CommentResource($comment)
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('sirsoft-board::messages.comment.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.blind_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 블라인드된 댓글을 복원합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 객체
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @param int $id 댓글 ID
|
||||
* @return JsonResponse 댓글 복원 결과 응답
|
||||
*/
|
||||
public function restore(Request $request, string $slug, int $postId, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$reason = $request->input('reason');
|
||||
$comment = $this->commentService->restoreComment($slug, $id, $reason);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.comment.restore_success',
|
||||
new CommentResource($comment)
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('sirsoft-board::messages.comment.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.restore_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,570 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
|
||||
use Modules\Sirsoft\Board\Exceptions\PostNotFoundException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\BlindPostRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\RestorePostRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\StorePostRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UpdatePostRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\PostCollection;
|
||||
use Modules\Sirsoft\Board\Http\Resources\PostResource;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
use Modules\Sirsoft\Board\Services\PostService;
|
||||
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
/**
|
||||
* 관리자용 게시글 관리 컨트롤러
|
||||
*
|
||||
* 게시판 게시글의 조회, 생성, 수정, 삭제, 블라인드 처리 등 관리자 전용 기능을 제공합니다.
|
||||
*/
|
||||
class PostController extends AdminBaseController
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* PostController 생성자
|
||||
*
|
||||
* @param PostService $postService 게시글 서비스
|
||||
* @param BoardService $boardService 게시판 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private PostService $postService,
|
||||
private BoardService $boardService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 게시글 목록 응답
|
||||
*/
|
||||
public function index(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.read)
|
||||
try {
|
||||
// 게시판 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug);
|
||||
if (! $board) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 목록 조회 파라미터 빌드 (필터 + perPage, 게시판 설정 적용)
|
||||
$listParams = $this->postService->buildListParams($request->all(), [
|
||||
'context' => 'admin',
|
||||
'board' => $board,
|
||||
]);
|
||||
|
||||
// 삭제된 게시글 포함 여부 (admin.manage 또는 admin.control 권한)
|
||||
$canViewDeleted = $this->checkBoardPermission($slug, 'admin.manage');
|
||||
|
||||
// 게시글 목록 조회
|
||||
$posts = $this->postService->getPosts($slug, $listParams['filters'], $listParams['perPage'], withTrashed: $canViewDeleted);
|
||||
$totalNormalPosts = $this->postService->getTotalNormalPosts($slug, $listParams['filters'], $canViewDeleted);
|
||||
|
||||
// PostCollection 구성
|
||||
$collection = new PostCollection($posts);
|
||||
$collection->setTotalNormalPosts($totalNormalPosts);
|
||||
$collection->setOrderDirection($listParams['filters']['order_direction']);
|
||||
|
||||
// BoardResource로 boardInfo 생성
|
||||
$boardResource = new BoardResource($board);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.posts.fetch_success',
|
||||
$collection->withBoardInfo($boardResource->toBoardInfoForAdmin())
|
||||
);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 상세 정보를 조회합니다.
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 게시글 상세 정보 응답
|
||||
*/
|
||||
public function show(string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.read)
|
||||
// 문자열로 전달된 ID를 정수로 변환
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
// 게시글 조회 (상태 확인을 위해 먼저 조회)
|
||||
$post = $this->postService->getPost($slug, $id);
|
||||
|
||||
// 삭제된 게시글은 admin.manage 권한 필요
|
||||
if ($post->deleted_at !== null) {
|
||||
if (! $this->checkBoardPermission($slug, 'admin.manage')) {
|
||||
return $this->error('sirsoft-board::messages.posts.deleted_post_access_denied', 403);
|
||||
}
|
||||
}
|
||||
|
||||
// 삭제된 게시글 포함 여부 판단
|
||||
$canViewDeleted = $this->checkBoardPermission($slug, 'admin.manage')
|
||||
|| $this->checkBoardPermission($slug, 'admin.control');
|
||||
|
||||
// 상세 정보 로드 (조회수 증가, 댓글 로드, 이전/다음 게시글 조회)
|
||||
$post = $this->postService->loadPostDetail($slug, $id, $canViewDeleted);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.fetch_success',
|
||||
new PostResource($post)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
// 404 예외는 그대로 던짐
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 생성합니다.
|
||||
*
|
||||
* @param StorePostRequest $request 게시글 생성 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 생성된 게시글 정보 응답
|
||||
*/
|
||||
public function store(StorePostRequest $request, string $slug): JsonResponse
|
||||
{
|
||||
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.write)
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
|
||||
// 작성자 정보 및 IP 주소 자동 설정
|
||||
$validated['user_id'] = Auth::id();
|
||||
$validated['ip_address'] = $request->ip();
|
||||
|
||||
// 파일은 별도로 전달 (validated에서 제외)
|
||||
$files = $request->file('files', []);
|
||||
unset($validated['files']);
|
||||
|
||||
// 첨부파일 ID 배열 추출
|
||||
$attachmentIds = $validated['attachment_ids'] ?? [];
|
||||
unset($validated['attachment_ids']);
|
||||
|
||||
$post = $this->postService->createPost($slug, $validated, $files, $attachmentIds);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.create_success',
|
||||
new PostResource($post),
|
||||
201
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.create_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 수정합니다.
|
||||
*
|
||||
* @param UpdatePostRequest $request 게시글 수정 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 수정된 게시글 정보 응답
|
||||
*/
|
||||
public function update(UpdatePostRequest $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
// 문자열로 전달된 ID를 정수로 변환
|
||||
$id = (int) $id;
|
||||
|
||||
// 게시글 조회 (권한 체크를 위해)
|
||||
try {
|
||||
$post = $this->postService->getPost($slug, $id);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
}
|
||||
|
||||
// 삭제된 게시글은 admin.manage 권한 필요
|
||||
if ($post->deleted_at !== null) {
|
||||
if ($response = $this->authorizeOrFail($slug, 'admin.manage')) {
|
||||
return $response;
|
||||
}
|
||||
} else {
|
||||
// 일반 게시글: admin.manage (타인 글) 또는 admin.write (본인 글)
|
||||
if ($response = $this->authorizePostModification($slug, $post->user_id)) {
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
|
||||
// 첨부파일 ID 배열 추출
|
||||
$attachmentIds = $validated['attachment_ids'] ?? [];
|
||||
unset($validated['attachment_ids']);
|
||||
|
||||
$post = $this->postService->updatePost($slug, $id, $validated, $attachmentIds);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.update_success',
|
||||
new PostResource($post)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
// 404 예외는 그대로 던짐
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.update_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 삭제합니다 (소프트 삭제).
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 삭제 결과 응답
|
||||
*/
|
||||
public function destroy(string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
// 문자열로 전달된 ID를 정수로 변환
|
||||
$id = (int) $id;
|
||||
|
||||
// 게시글 조회 (권한 체크를 위해)
|
||||
try {
|
||||
$post = $this->postService->getPost($slug, $id);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
}
|
||||
|
||||
// 이미 삭제된 게시글은 admin.manage 권한 필요
|
||||
if ($post->deleted_at !== null) {
|
||||
if ($response = $this->authorizeOrFail($slug, 'admin.manage')) {
|
||||
return $response;
|
||||
}
|
||||
} else {
|
||||
// 일반 게시글: admin.manage (타인 글) 또는 admin.write (본인 글)
|
||||
if ($response = $this->authorizePostModification($slug, $post->user_id)) {
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
$deletedPost = $this->postService->deletePost($slug, $id, 'admin');
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.delete_success',
|
||||
new PostResource($deletedPost)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
// 404 예외는 그대로 던짐
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.delete_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 블라인드 처리합니다.
|
||||
*
|
||||
* @param BlindPostRequest $request 블라인드 처리 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 블라인드 처리된 게시글 정보 응답
|
||||
*/
|
||||
public function blind(BlindPostRequest $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.manage)
|
||||
// 문자열로 전달된 ID를 정수로 변환
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
$reason = $validated['reason'] ?? '';
|
||||
|
||||
$post = $this->postService->blindPost($slug, $id, $reason);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.blind_success',
|
||||
new PostResource($post)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
// 404 예외는 그대로 던짐
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.blind_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 블라인드 처리된 게시글을 복원합니다.
|
||||
*
|
||||
* @param RestorePostRequest $request 복원 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 복원된 게시글 정보 응답
|
||||
*/
|
||||
public function restore(RestorePostRequest $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.manage)
|
||||
// 문자열로 전달된 ID를 정수로 변환
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
$reason = $validated['reason'] ?? null;
|
||||
|
||||
$post = $this->postService->restorePost($slug, $id, $reason);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.restore_success',
|
||||
new PostResource($post)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
// 404 예외는 그대로 던짐
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.restore_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 폼 입력용 데이터를 반환합니다. (API 전송용)
|
||||
*
|
||||
* 생성/수정/답변글 작성 모드에 따라 적절한 폼 데이터를 반환합니다.
|
||||
* - 생성 모드: 빈 폼 데이터
|
||||
* - 수정 모드: 기존 게시글 데이터
|
||||
* - 답변글 모드: 기본값이 설정된 폼 데이터
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 폼 입력 데이터 응답
|
||||
*/
|
||||
public function getFormData(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.write)
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug);
|
||||
if (! $board) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
$formData = [];
|
||||
|
||||
// 수정 모드: post_id가 있으면 기존 게시글 데이터 로드
|
||||
if ($request->filled('post_id')) {
|
||||
$postId = (int) $request->get('post_id');
|
||||
$post = $this->postService->getPost($slug, $postId);
|
||||
|
||||
$postResource = new PostResource($post);
|
||||
$postData = $postResource->toArray($request);
|
||||
|
||||
// form에 필요한 필드만 추출 (API 전송용)
|
||||
$formData = [
|
||||
'id' => $postData['id'] ?? null,
|
||||
'title' => $postData['title'] ?? '',
|
||||
'content' => $postData['content'] ?? '',
|
||||
'content_mode' => $postData['content_mode'] ?? 'text',
|
||||
'category' => $postData['category'] ?? null,
|
||||
'is_notice' => $postData['is_notice'] ?? false,
|
||||
'is_secret' => $postData['is_secret'] ?? false,
|
||||
'parent_id' => $postData['parent_id'] ?? null,
|
||||
];
|
||||
}
|
||||
// 답변글 모드: parent_id가 있으면 기본값 설정
|
||||
elseif ($request->filled('parent_id')) {
|
||||
// 답글 기능이 비활성화된 경우 접근 차단
|
||||
if (! $board->use_reply) {
|
||||
return $this->error('sirsoft-board::validation.post.reply_not_allowed', 404);
|
||||
}
|
||||
|
||||
$parentId = (int) $request->get('parent_id');
|
||||
$parentPost = $this->postService->getPost($slug, $parentId);
|
||||
|
||||
// 답변글 기본값 설정
|
||||
$formData = [
|
||||
'title' => 'Re: '.$parentPost->title,
|
||||
'content' => '',
|
||||
'content_mode' => 'text',
|
||||
'category' => $parentPost->category ?? null,
|
||||
'is_notice' => false,
|
||||
'is_secret' => $parentPost->is_secret ?? false,
|
||||
'parent_id' => $parentId,
|
||||
];
|
||||
}
|
||||
// 생성 모드: 빈 폼 데이터
|
||||
else {
|
||||
$formData = [
|
||||
'title' => '',
|
||||
'content' => '',
|
||||
'content_mode' => 'text',
|
||||
'category' => null,
|
||||
'is_notice' => false,
|
||||
'is_secret' => $board->secret_mode->value === 'always',
|
||||
'parent_id' => null,
|
||||
];
|
||||
}
|
||||
|
||||
return $this->success('sirsoft-board::messages.posts.form_data_retrieved', $formData);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException((int) ($request->get('post_id') ?? $request->get('parent_id') ?? 0));
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.form_data_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 폼 화면 표시용 메타 데이터를 반환합니다. (읽기 전용)
|
||||
*
|
||||
* 게시판 정보, 원글 정보, 작성자 정보 등 화면 표시에 필요한 데이터를 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 폼 메타 데이터 응답
|
||||
*/
|
||||
public function getFormMeta(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
// 권한은 라우트 미들웨어에서 체크됨 (sirsoft-board.{slug}.admin.posts.write)
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug);
|
||||
if (! $board) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 관리자 라우트에서는 항상 사용자 권한 정보 포함
|
||||
$request->merge(['include_user_abilities' => true]);
|
||||
|
||||
$boardResource = new \Modules\Sirsoft\Board\Http\Resources\BoardResource($board);
|
||||
$boardData = $boardResource->toArray($request);
|
||||
|
||||
// 게시글 폼에서는 게시판 이름을 로컬라이즈된 문자열로 반환
|
||||
$boardData['name'] = $board->getLocalizedName();
|
||||
|
||||
$metaData = [
|
||||
'board' => $boardData,
|
||||
];
|
||||
|
||||
// 수정 모드: 작성자 정보, 작성일, 첨부파일 정보 포함
|
||||
if ($request->filled('post_id')) {
|
||||
$postId = (int) $request->get('post_id');
|
||||
$post = $this->postService->getPost($slug, $postId);
|
||||
|
||||
// 첨부파일 및 원글 관계 로드
|
||||
$post->load(['attachments', 'parent']);
|
||||
|
||||
$postResource = new PostResource($post);
|
||||
$postData = $postResource->toArray($request);
|
||||
|
||||
$metaData['author'] = $postData['author'] ?? null;
|
||||
$metaData['created_at'] = $postData['created_at'] ?? null;
|
||||
$metaData['attachments'] = $postData['attachments'] ?? [];
|
||||
|
||||
// 수정 시 원글 정보가 있으면 포함
|
||||
if (! empty($postData['parent'])) {
|
||||
$metaData['parent_post'] = $postData['parent'];
|
||||
}
|
||||
}
|
||||
// 답변글 모드: 원글 정보 포함
|
||||
elseif ($request->filled('parent_id')) {
|
||||
$parentId = (int) $request->get('parent_id');
|
||||
$parentPost = $this->postService->getPost($slug, $parentId);
|
||||
|
||||
// 블라인드 또는 삭제된 게시글에는 답글 작성 불가
|
||||
if ($parentPost->status === \Modules\Sirsoft\Board\Enums\PostStatus::Blinded) {
|
||||
return $this->error('sirsoft-board::validation.post.parent_id.blinded', 403);
|
||||
}
|
||||
if ($parentPost->status === \Modules\Sirsoft\Board\Enums\PostStatus::Deleted) {
|
||||
return $this->error('sirsoft-board::validation.post.parent_id.deleted', 403);
|
||||
}
|
||||
|
||||
$parentPostResource = new PostResource($parentPost);
|
||||
$metaData['parent_post'] = $parentPostResource->toArray($request);
|
||||
}
|
||||
|
||||
return $this->success('sirsoft-board::messages.posts.form_meta_retrieved', $metaData);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException((int) ($request->get('post_id') ?? $request->get('parent_id') ?? 0));
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.form_meta_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 현재 사용자가 게시글의 작성자인지 확인합니다.
|
||||
*
|
||||
* @param int $postUserId 게시글 작성자 ID
|
||||
* @return bool 본인 여부
|
||||
*/
|
||||
private function isPostOwner(int $postUserId): bool
|
||||
{
|
||||
return Auth::check() && Auth::id() === $postUserId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 수정/삭제 권한을 확인합니다.
|
||||
*
|
||||
* - admin.manage 권한: 모든 글 수정/삭제 가능 (비회원 글 포함)
|
||||
* - admin.write 권한: 본인 글만 수정/삭제 가능
|
||||
* - 비회원 게시글: admin.manage 권한 필요
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param int|null $postUserId 게시글 작성자 ID (비회원은 null)
|
||||
* @return JsonResponse|null 권한이 없으면 JsonResponse, 있으면 null
|
||||
*/
|
||||
private function authorizePostModification(string $slug, ?int $postUserId): ?JsonResponse
|
||||
{
|
||||
// admin.manage 권한이 있으면 모든 글 수정/삭제 가능
|
||||
if ($this->checkBoardPermission($slug, 'admin.manage')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 비회원 게시글은 admin.manage 권한 필요 (위에서 통과 안 됨)
|
||||
if ($postUserId === null) {
|
||||
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
|
||||
}
|
||||
|
||||
// admin.posts.write 권한이 있고 본인 글이면 수정/삭제 가능
|
||||
if ($this->checkBoardPermission($slug, 'admin.posts.write') && $this->isPostOwner($postUserId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Board\Http\Requests\BulkUpdateStatusRequest;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UpdateStatusRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportCollection;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportDetailResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportLogResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportResource;
|
||||
use Modules\Sirsoft\Board\Services\ReportService;
|
||||
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* 관리자용 신고 관리 컨트롤러
|
||||
*
|
||||
* 게시판 신고의 조회, 상태 변경, 삭제 등 관리자 전용 기능을 제공합니다.
|
||||
*/
|
||||
class ReportController extends AdminBaseController
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
/**
|
||||
* ReportController 생성자
|
||||
*
|
||||
* @param ReportService $reportService 신고 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private ReportService $reportService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고 목록을 조회합니다.
|
||||
*
|
||||
* 동일 대상(게시글/댓글)에 대한 신고는 그룹화하여 최초 신고만 목록에 표시합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 신고 목록 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 조회 권한 체크
|
||||
if (! $this->checkModulePermission('reports', 'view')) {
|
||||
return $this->forbidden('sirsoft-board::messages.reports.permission_denied');
|
||||
}
|
||||
|
||||
// filters 배열에서 검색 조건 추출 (admin_user_list.json과 동일한 구조)
|
||||
$filtersParam = $request->input('filters', []);
|
||||
$searchField = $filtersParam[0]['field'] ?? 'all';
|
||||
$searchValue = $filtersParam[0]['value'] ?? null;
|
||||
|
||||
$filters = [
|
||||
'search' => $searchValue,
|
||||
'search_field' => $searchField,
|
||||
'status' => $request->input('status', []),
|
||||
'target_type' => $request->input('target_type', []),
|
||||
'target_status' => $request->input('target_status', []),
|
||||
'board_id' => $request->input('board_id'),
|
||||
'reported_at_from' => $request->input('reported_at_from'),
|
||||
'reported_at_to' => $request->input('reported_at_to'),
|
||||
'sort_by' => $request->input('sort_by'),
|
||||
'sort_order' => $request->input('sort_order'),
|
||||
];
|
||||
|
||||
// perPage 제한 (10~20)
|
||||
$perPage = min(max((int) $request->input('per_page', 15), 10), 20);
|
||||
|
||||
// 그룹화된 신고 목록 조회
|
||||
$reports = $this->reportService->getGroupedReports($filters, $perPage);
|
||||
$statistics = $this->reportService->getStatistics($filters);
|
||||
|
||||
// ReportCollection의 withStatisticsAndPermissions 사용
|
||||
$collection = new ReportCollection($reports);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.reports.fetch_success',
|
||||
$collection->withStatisticsAndPermissions($statistics)
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고 상세 정보를 조회합니다.
|
||||
*
|
||||
* 동일 대상에 대한 모든 신고와 함께 그룹화된 정보를 반환합니다.
|
||||
*
|
||||
* @param int $id 신고 ID
|
||||
* @return JsonResponse 신고 상세 정보 응답
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 조회 권한 체크
|
||||
if (! $this->checkModulePermission('reports', 'view')) {
|
||||
return $this->forbidden('sirsoft-board::messages.reports.permission_denied');
|
||||
}
|
||||
|
||||
// 그룹화된 상세 정보 조회
|
||||
$groupedDetail = $this->reportService->getGroupedReportDetail($id);
|
||||
$groupedDetail['reportable'] = $this->reportService->buildReportableData($groupedDetail['report']);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.reports.fetch_success',
|
||||
new ReportDetailResource($groupedDetail)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.reports.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고 케이스의 신고자 목록을 페이지네이션으로 반환합니다.
|
||||
*
|
||||
* @param int $id 신고 케이스 ID
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 신고자 목록 응답
|
||||
*/
|
||||
public function reporters(int $id, Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
if (! $this->checkModulePermission('reports', 'view')) {
|
||||
return $this->forbidden('sirsoft-board::messages.reports.permission_denied');
|
||||
}
|
||||
|
||||
$perPage = min((int) $request->query('per_page', 10), 50);
|
||||
$page = max((int) $request->query('page', 1), 1);
|
||||
|
||||
$paginator = $this->reportService->paginateReporters($id, $perPage, $page);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.reports.fetch_success',
|
||||
[
|
||||
'data' => ReportLogResource::collection($paginator->items())->resolve(),
|
||||
'pagination' => [
|
||||
'total' => $paginator->total(),
|
||||
'from' => $paginator->firstItem() ?? 0,
|
||||
'to' => $paginator->lastItem() ?? 0,
|
||||
'per_page' => $paginator->perPage(),
|
||||
'current_page' => $paginator->currentPage(),
|
||||
'last_page' => $paginator->lastPage(),
|
||||
],
|
||||
]
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.reports.error_404');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고 상태를 변경합니다 (그룹 변경 포함).
|
||||
*
|
||||
* @param UpdateStatusRequest $request 상태 변경 요청
|
||||
* @param int $id 신고 ID
|
||||
* @return JsonResponse 변경된 신고 정보 응답
|
||||
*/
|
||||
public function updateStatus(UpdateStatusRequest $request, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
|
||||
// 1케이스 구조: 케이스 ID 직접 사용 (expandGroupedReportIds 불필요)
|
||||
$result = $this->reportService->bulkUpdateStatus(
|
||||
[$id],
|
||||
[
|
||||
'status' => $validated['status'],
|
||||
'process_note' => $validated['process_note'] ?? null,
|
||||
]
|
||||
);
|
||||
|
||||
// 케이스 재조회 (응답용)
|
||||
$report = $this->reportService->getReport($id);
|
||||
$report->reportableData = $this->reportService->buildReportableData($report);
|
||||
|
||||
// 수동 블라인드 복구 안내 메시지
|
||||
$messageKey = 'sirsoft-board::messages.reports.status_updated';
|
||||
if ($result['manual_blind_restored'] > 0) {
|
||||
$messageKey = 'sirsoft-board::messages.reports.status_updated';
|
||||
}
|
||||
|
||||
return $this->successWithResource(
|
||||
$messageKey,
|
||||
new ReportResource($report)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.reports.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.status_update_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 선택된 신고들의 상태별 건수를 조회합니다.
|
||||
* 일괄 처리 전 사용자에게 선택한 신고의 상태 분포를 보여주기 위한 API입니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청 (ids 배열 필요)
|
||||
* @return JsonResponse 상태별 건수 응답
|
||||
*/
|
||||
public function getStatusCounts(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$ids = $request->input('ids', []);
|
||||
$targetStatus = $request->input('target_status');
|
||||
|
||||
if (empty($ids)) {
|
||||
return $this->error('sirsoft-board::messages.reports.no_reports_selected', 422);
|
||||
}
|
||||
|
||||
// 상태별 건수 집계
|
||||
$statusCounts = $this->reportService->getStatusCountsByIds($ids, $targetStatus);
|
||||
|
||||
// 요약 데이터 계산
|
||||
$summary = $this->reportService->getStatusCountsSummary($statusCounts, $ids, $targetStatus);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.reports.status_counts_success',
|
||||
$summary
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.status_counts_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 여러 신고의 상태를 일괄 변경합니다.
|
||||
*
|
||||
* @param BulkUpdateStatusRequest $request 대량 상태 변경 요청
|
||||
* @return JsonResponse 변경 결과 응답
|
||||
*/
|
||||
public function bulkUpdateStatus(BulkUpdateStatusRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$validated = $request->validated();
|
||||
$targetStatus = $validated['status'];
|
||||
|
||||
// 선택한 신고만 처리 (그룹 확장 제거)
|
||||
// 일괄 변경 실행
|
||||
$result = $this->reportService->bulkUpdateStatus(
|
||||
$validated['ids'],
|
||||
[
|
||||
'status' => $targetStatus,
|
||||
'process_note' => $validated['process_note'] ?? null,
|
||||
]
|
||||
);
|
||||
|
||||
$affectedCount = $result['affected_count'];
|
||||
|
||||
// 상태명 다국어 키 가져오기
|
||||
$statusEnum = \Modules\Sirsoft\Board\Enums\ReportStatus::from($targetStatus);
|
||||
$statusLabel = $statusEnum->label();
|
||||
|
||||
// 성공 메시지 생성
|
||||
$successMessage = __('sirsoft-board::messages.reports.bulk_status_updated_with_count', [
|
||||
'count' => $affectedCount,
|
||||
'status' => $statusLabel,
|
||||
]);
|
||||
|
||||
// 수동 블라인드 복구 안내 메시지 추가
|
||||
if ($result['manual_blind_restored'] > 0) {
|
||||
$successMessage .= ' '.__('sirsoft-board::messages.reports.manual_blind_restored_notice', [
|
||||
'count' => $result['manual_blind_restored'],
|
||||
]);
|
||||
}
|
||||
|
||||
return $this->success(
|
||||
$successMessage,
|
||||
[
|
||||
'affected_count' => $affectedCount,
|
||||
'restored_count' => $result['restored_count'],
|
||||
'manual_blind_restored' => $result['manual_blind_restored'],
|
||||
'status_label' => $statusLabel,
|
||||
'message' => $successMessage,
|
||||
],
|
||||
200,
|
||||
['count' => $affectedCount, 'status' => $statusLabel]
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.bulk_status_update_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고를 삭제합니다 (소프트 삭제).
|
||||
*
|
||||
* @param int $id 신고 ID
|
||||
* @return JsonResponse 삭제 성공 응답
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->reportService->deleteReport($id);
|
||||
|
||||
return $this->success('sirsoft-board::messages.reports.delete_success');
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.reports.error_404');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.delete_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\ReorderAttachmentsRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UploadAttachmentRequest;
|
||||
use Modules\Sirsoft\Board\Services\AttachmentService;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
use Symfony\Component\HttpFoundation\BinaryFileResponse;
|
||||
use Symfony\Component\HttpFoundation\StreamedResponse;
|
||||
|
||||
/**
|
||||
* 사용자용 첨부파일 컨트롤러
|
||||
*
|
||||
* 게시판 첨부파일 업로드, 다운로드, 삭제 기능을 제공합니다.
|
||||
* hash 기반 첨부파일 서빙 API도 제공합니다.
|
||||
*/
|
||||
class AttachmentController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* AttachmentController 생성자
|
||||
*
|
||||
* @param AttachmentService $attachmentService 첨부파일 서비스
|
||||
* @param BoardService $boardService 게시판 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private AttachmentService $attachmentService,
|
||||
private BoardService $boardService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부파일 다운로드 (서빙)
|
||||
*
|
||||
* 모든 파일(이미지 포함)을 다운로드 방식(Content-Disposition: attachment)으로 제공합니다.
|
||||
* 이미지 미리보기는 별도의 preview() 메서드를 사용합니다.
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string $hash 첨부파일 해시 (12자)
|
||||
* @return StreamedResponse|JsonResponse 파일 응답 또는 에러 응답
|
||||
*/
|
||||
public function download(string $slug, string $hash): StreamedResponse|JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
|
||||
// 해시로 첨부파일 조회
|
||||
$attachment = $this->attachmentService->getByHash($slug, $hash);
|
||||
|
||||
if (! $attachment) {
|
||||
return $this->notFound(__('sirsoft-board::messages.attachment.not_found'));
|
||||
}
|
||||
|
||||
// 모든 파일(이미지 포함) 다운로드 방식으로 제공
|
||||
$response = $this->attachmentService->download($slug, $attachment->id, context: 'user');
|
||||
|
||||
if (! $response) {
|
||||
return $this->notFound(__('sirsoft-board::messages.attachment.not_found'));
|
||||
}
|
||||
|
||||
return $response;
|
||||
} catch (\Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->notFound(__('sirsoft-board::messages.boards.not_found'));
|
||||
} catch (\Exception $e) {
|
||||
return $this->error(__('sirsoft-board::messages.attachment.download_failed'), 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 이미지 미리보기 (권한 체크 없이, 캐싱 헤더 포함)
|
||||
*
|
||||
* 이미지 파일만 미리보기를 제공합니다.
|
||||
* 비회원도 이미지를 볼 수 있습니다.
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string $hash 첨부파일 해시 (12자)
|
||||
* @return BinaryFileResponse|Response|JsonResponse 이미지 응답 또는 에러 응답
|
||||
*/
|
||||
public function preview(string $slug, string $hash): BinaryFileResponse|Response|JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
|
||||
// 해시로 첨부파일 조회
|
||||
$attachment = $this->attachmentService->getByHash($slug, $hash);
|
||||
|
||||
if (! $attachment) {
|
||||
return $this->notFound(__('sirsoft-board::messages.attachment.not_found'));
|
||||
}
|
||||
|
||||
// 이미지가 아닌 경우
|
||||
if (! $attachment->is_image) {
|
||||
return $this->badRequest(__('sirsoft-board::messages.attachment.not_image'));
|
||||
}
|
||||
|
||||
// 파일 정보 조회
|
||||
$fileInfo = $this->attachmentService->getFileInfo($slug, $attachment->id);
|
||||
|
||||
if (! $fileInfo) {
|
||||
return $this->notFound(__('sirsoft-board::messages.attachment.not_found'));
|
||||
}
|
||||
|
||||
// 캐싱 헤더와 함께 응답 (환경설정 레이아웃 캐시 TTL 사용, 기본 24시간)
|
||||
return $this->fileResponse(
|
||||
$fileInfo['path'],
|
||||
$fileInfo['mime_type'],
|
||||
(int) g7_core_settings('cache.layout_ttl', 86400)
|
||||
);
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->notFound(__('sirsoft-board::messages.boards.not_found'));
|
||||
} catch (\Exception $e) {
|
||||
return $this->error(__('sirsoft-board::messages.attachment.preview_failed'), 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 단일 파일 업로드
|
||||
*
|
||||
* @param UploadAttachmentRequest $request 업로드 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 업로드 결과 응답
|
||||
*/
|
||||
public function upload(UploadAttachmentRequest $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 및 설정 확인
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
|
||||
// 첨부파일 사용 설정 확인
|
||||
if (! $board->use_file_upload) {
|
||||
return $this->forbidden(__('sirsoft-board::messages.attachment.upload_disabled'));
|
||||
}
|
||||
|
||||
$validated = $request->validated();
|
||||
|
||||
// 첨부파일 업로드 (Service에서 처리)
|
||||
$attachment = $this->attachmentService->upload(
|
||||
slug: $slug,
|
||||
file: $request->file('file'),
|
||||
postId: $validated['post_id'] ?? null,
|
||||
collection: $validated['collection'] ?? 'attachments',
|
||||
tempKey: $validated['temp_key'] ?? null
|
||||
);
|
||||
|
||||
// FileUploader 컴포넌트가 response.data?.data 형식을 기대하므로
|
||||
// data 키 안에 한 번 더 감싸서 반환
|
||||
return $this->success(
|
||||
__('sirsoft-board::messages.attachment.upload_success'),
|
||||
[
|
||||
'data' => [
|
||||
'id' => $attachment->id,
|
||||
'hash' => $attachment->hash,
|
||||
'original_filename' => $attachment->original_filename,
|
||||
'stored_filename' => $attachment->stored_filename,
|
||||
'mime_type' => $attachment->mime_type,
|
||||
'size' => $attachment->size,
|
||||
'url' => $this->attachmentService->getUrl($slug, $attachment->id),
|
||||
'order' => $attachment->order,
|
||||
'created_at' => $attachment->created_at,
|
||||
],
|
||||
],
|
||||
201
|
||||
);
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->notFound(__('sirsoft-board::messages.board.not_found'));
|
||||
} catch (\Exception $e) {
|
||||
return $this->error(__('sirsoft-board::messages.attachment.upload_failed'), 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부파일 순서 변경
|
||||
*
|
||||
* @param ReorderAttachmentsRequest $request 순서 변경 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 순서 변경 결과 응답
|
||||
*/
|
||||
public function reorder(ReorderAttachmentsRequest $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
|
||||
$validated = $request->validated();
|
||||
|
||||
// FileUploader가 [{id, order}] 형태로 전송 → [ID => order] 매핑으로 변환
|
||||
$orders = collect($validated['order'])->pluck('order', 'id')->all();
|
||||
$result = $this->attachmentService->reorder($slug, $orders);
|
||||
|
||||
if (! $result) {
|
||||
return $this->error(__('sirsoft-board::messages.attachment.reorder_failed'), 500);
|
||||
}
|
||||
|
||||
return $this->success(__('sirsoft-board::messages.attachment.reorder_success'));
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->notFound(__('sirsoft-board::messages.board.not_found'));
|
||||
} catch (\Exception $e) {
|
||||
return $this->error(__('sirsoft-board::messages.attachment.reorder_failed'), 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 첨부파일 삭제
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param int $id 첨부파일 ID
|
||||
* @return JsonResponse 삭제 결과 응답
|
||||
*/
|
||||
public function destroy(string $slug, int $id): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 존재 여부 확인
|
||||
$this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
|
||||
// 첨부파일 조회 (Service를 통해)
|
||||
$attachment = $this->attachmentService->getById($slug, $id);
|
||||
|
||||
if (! $attachment) {
|
||||
return $this->notFound(__('sirsoft-board::messages.attachment.not_found'));
|
||||
}
|
||||
|
||||
// 권한 확인 (Service에서 처리)
|
||||
if (! $this->attachmentService->canDelete($attachment, Auth::id())) {
|
||||
return $this->forbidden(__('sirsoft-board::messages.attachment.delete_forbidden'));
|
||||
}
|
||||
|
||||
// 삭제 (Service에서 처리)
|
||||
$result = $this->attachmentService->delete($slug, $id);
|
||||
|
||||
if (! $result) {
|
||||
return $this->error(__('sirsoft-board::messages.attachment.delete_failed'), 500);
|
||||
}
|
||||
|
||||
return $this->success(__('sirsoft-board::messages.attachment.delete_success'));
|
||||
} catch (BoardNotFoundException $e) {
|
||||
return $this->notFound(__('sirsoft-board::messages.board.not_found'));
|
||||
} catch (\Exception $e) {
|
||||
return $this->error(__('sirsoft-board::messages.attachment.delete_failed'), 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Models\User;
|
||||
use App\Services\CacheService;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardMenuResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardResource;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
|
||||
/**
|
||||
* 사용자용 게시판 컨트롤러
|
||||
*
|
||||
* - 비로그인 사용자도 접근 가능한 공개 API
|
||||
* - 활성화된 게시판 목록 조회
|
||||
* - 게시판 상세 정보 조회 (권한 체크 포함)
|
||||
*/
|
||||
class BoardController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* BoardController 생성자
|
||||
*
|
||||
* @param BoardService $boardService 게시판 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
protected BoardService $boardService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 활성화된 게시판 목록 조회 (경량)
|
||||
*
|
||||
* 전체 게시판 목록 페이지에서 사용하는 경량 API입니다.
|
||||
* - id, name, slug, description, posts_count만 반환
|
||||
* - 각 게시판별 최신글 N개 포함 (답변글, 삭제, 블라인드 제외)
|
||||
* - limit 파라미터로 게시글 개수 조절 가능 (기본: 0, 최대: 10)
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
// 활성화된 게시판만 조회
|
||||
$boards = $this->boardService->getActiveBoards();
|
||||
|
||||
// limit 파라미터 (0이면 최신글 미포함, 최대 10개)
|
||||
$recentPostsLimit = min(max((int) $request->input('limit', 0), 0), 10);
|
||||
|
||||
// toListArray() 메서드를 사용하여 경량 데이터 반환
|
||||
$data = $boards->map(function ($board) use ($recentPostsLimit) {
|
||||
$boardData = (new BoardResource($board))->toListArray();
|
||||
|
||||
// limit가 0보다 크면 최신글 조회
|
||||
if ($recentPostsLimit > 0) {
|
||||
$boardData['recent_posts'] = $this->boardService->getBoardRecentPosts($board->slug, $recentPostsLimit);
|
||||
}
|
||||
|
||||
return $boardData;
|
||||
});
|
||||
|
||||
return $this->success(
|
||||
'common.success',
|
||||
$data
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 게시판 상세 정보 조회
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function show(string $slug): JsonResponse
|
||||
{
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
|
||||
// 게시판이 없거나 비활성화된 경우 404 (보안: 존재 여부 숨김)
|
||||
if (! $board || ! $board->is_active) {
|
||||
return $this->notFound();
|
||||
}
|
||||
|
||||
return $this->success(
|
||||
'common.success',
|
||||
BoardResource::make($board)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 네비게이션 메뉴용 게시판 목록 조회 (경량)
|
||||
*
|
||||
* 헤더 메뉴 등에서 사용할 최소한의 게시판 정보만 반환합니다.
|
||||
* - id, name, slug만 포함
|
||||
* - 활성화된 게시판만 조회
|
||||
* - 오래된 순으로 정렬 (created_at ASC)
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function boardMenu(): JsonResponse
|
||||
{
|
||||
// 활성화된 게시판을 오래된 순으로 조회
|
||||
$boards = $this->boardService->getActiveBoards(orderBy: 'created_at', orderDirection: 'asc');
|
||||
|
||||
// 경량 리소스로 변환하여 반환
|
||||
return $this->success(
|
||||
'common.success',
|
||||
BoardMenuResource::collection($boards)->resolve()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판 관련 통계 조회
|
||||
*
|
||||
* 홈 페이지 등에서 표시할 게시판 관련 통계 정보를 반환합니다.
|
||||
* - 활성화된 게시판 수
|
||||
* - 전체 게시글 수
|
||||
* - 전체 댓글 수
|
||||
*
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function stats(): JsonResponse
|
||||
{
|
||||
$stats = CacheService::remember(
|
||||
'sirsoft-board',
|
||||
'stats',
|
||||
fn () => $this->calculateStats(),
|
||||
config('sirsoft-board.cache.ttl', 60)
|
||||
);
|
||||
|
||||
return $this->success('common.success', $stats);
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 게시글 조회
|
||||
*
|
||||
* 모든 게시판의 최근 게시글을 통합하여 반환합니다.
|
||||
* - 기본 5개, 최대 20개까지 조회 가능
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function recentPosts(Request $request): JsonResponse
|
||||
{
|
||||
$limit = min((int) $request->input('limit', 5), 20);
|
||||
|
||||
$posts = CacheService::remember(
|
||||
'sirsoft-board',
|
||||
"recent_posts_{$limit}",
|
||||
fn () => $this->boardService->getRecentPosts($limit),
|
||||
config('sirsoft-board.cache.ttl', 60)
|
||||
);
|
||||
|
||||
return $this->success('common.success', $posts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인기 게시글 조회 (조회수 기준)
|
||||
*
|
||||
* 조회수가 많은 순으로 게시글 목록을 반환합니다.
|
||||
* - 기본 20개, 최대 50개까지 조회 가능
|
||||
* - 기간별 필터링: today, week, month, all (기본: week)
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function popular(Request $request): JsonResponse
|
||||
{
|
||||
$period = $request->input('period', 'week'); // today, week, month, all
|
||||
$limit = min((int) $request->input('limit', 20), 50);
|
||||
$locale = app()->getLocale();
|
||||
|
||||
// 캐시 키에 period, locale 포함
|
||||
$posts = CacheService::remember(
|
||||
'sirsoft-board',
|
||||
"popular_posts_{$locale}_{$period}_{$limit}",
|
||||
fn () => $this->boardService->getPopularPosts($period, $limit),
|
||||
config('sirsoft-board.cache.ttl', 60)
|
||||
);
|
||||
|
||||
return $this->success('common.success', $posts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 인기 게시판 조회 (게시글 수 기준)
|
||||
*
|
||||
* 게시글 수가 많은 순으로 게시판 목록을 반환합니다.
|
||||
* - 기본 4개, 최대 20개까지 조회 가능
|
||||
*
|
||||
* @param Request $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function popularBoards(Request $request): JsonResponse
|
||||
{
|
||||
$limit = min((int) $request->input('limit', 4), 20);
|
||||
$locale = app()->getLocale();
|
||||
|
||||
$boards = CacheService::remember(
|
||||
'sirsoft-board',
|
||||
"popular_boards_{$locale}_{$limit}",
|
||||
fn () => $this->boardService->getPopularBoards($limit),
|
||||
config('sirsoft-board.cache.ttl', 60)
|
||||
);
|
||||
|
||||
return $this->success('common.success', $boards);
|
||||
}
|
||||
|
||||
/**
|
||||
* 통계 계산 (홈페이지용)
|
||||
*
|
||||
* @return array{users: int, boards: int, posts: int, comments: int}
|
||||
*/
|
||||
private function calculateStats(): array
|
||||
{
|
||||
return [
|
||||
'users' => User::count(),
|
||||
'boards' => Board::where('is_active', true)->count(),
|
||||
'posts' => $this->boardService->getTotalPostsCount(),
|
||||
'comments' => $this->boardService->getTotalCommentsCount(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Sirsoft\Board\Http\Requests\StoreCommentRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UpdateCommentRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\CommentResource;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Services\CommentService;
|
||||
|
||||
/**
|
||||
* 사용자용 댓글 컨트롤러
|
||||
*
|
||||
* 회원/비회원 모두 댓글 생성, 수정, 삭제 기능을 제공합니다.
|
||||
*/
|
||||
class CommentController extends PublicBaseController
|
||||
{
|
||||
/**
|
||||
* CommentController 생성자
|
||||
*
|
||||
* @param CommentService $commentService 댓글 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private CommentService $commentService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글의 댓글 목록을 조회합니다.
|
||||
*
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @return JsonResponse 댓글 목록 응답
|
||||
*/
|
||||
public function index(string $slug, int $postId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$comments = $this->commentService->getCommentsByPostId($slug, $postId);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.comments.index_success',
|
||||
CommentResource::collection($comments)
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->error('sirsoft-board::messages.boards.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comments.index_failed', 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 생성합니다.
|
||||
*
|
||||
* @param StoreCommentRequest $request 댓글 생성 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @return JsonResponse 댓글 생성 결과 응답
|
||||
*/
|
||||
public function store(StoreCommentRequest $request, string $slug, int $postId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$data = $request->validated();
|
||||
$data['ip_address'] = $request->ip();
|
||||
|
||||
// user_id 설정 (인증 필수)
|
||||
$data['user_id'] = Auth::id();
|
||||
|
||||
$comment = $this->commentService->createComment($slug, $data);
|
||||
|
||||
// 쿨다운 캐시 기록 (댓글 생성 성공 후)
|
||||
$spamSecurity = g7_module_settings('sirsoft-board', 'spam_security', []);
|
||||
$cooldown = (int) ($spamSecurity['comment_cooldown_seconds'] ?? 0);
|
||||
if ($cooldown > 0) {
|
||||
$identifier = Auth::id() ?? $request->ip();
|
||||
Cache::put("comment_cooldown_{$slug}_{$identifier}", true, $cooldown);
|
||||
}
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.comment.create_success',
|
||||
new CommentResource($comment),
|
||||
201
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->error('sirsoft-board::messages.boards.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.create_failed', 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 수정합니다.
|
||||
*
|
||||
* @param UpdateCommentRequest $request 댓글 수정 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @param int $commentId 댓글 ID
|
||||
* @return JsonResponse 댓글 수정 결과 응답
|
||||
*/
|
||||
public function update(UpdateCommentRequest $request, string $slug, int $postId, int $commentId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$comment = $this->commentService->getComment($slug, $commentId);
|
||||
|
||||
// 권한 확인 (Service에서 처리)
|
||||
$canUpdate = $this->commentService->canUpdate(
|
||||
$comment,
|
||||
Auth::id(),
|
||||
$request->input('password'),
|
||||
$slug
|
||||
);
|
||||
|
||||
if (! $canUpdate) {
|
||||
return $this->forbidden('sirsoft-board::messages.comment.update_forbidden');
|
||||
}
|
||||
|
||||
// password는 검증용이므로 제거
|
||||
$data = $request->except('password');
|
||||
$updatedComment = $this->commentService->updateComment($slug, $commentId, $data);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.comment.update_success',
|
||||
new CommentResource($updatedComment)
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->error('sirsoft-board::messages.comment.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.update_failed', 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 삭제합니다.
|
||||
*
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @param int $commentId 댓글 ID
|
||||
* @return JsonResponse 댓글 삭제 결과 응답
|
||||
*/
|
||||
public function destroy(string $slug, int $postId, int $commentId): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_comment) {
|
||||
return $this->error('sirsoft-board::messages.comments.comments_disabled', 403);
|
||||
}
|
||||
|
||||
$comment = $this->commentService->getComment($slug, $commentId);
|
||||
|
||||
// 비회원인 경우 password 파라미터 필요
|
||||
$password = request()->input('password');
|
||||
|
||||
// 권한 확인 (Service에서 처리)
|
||||
$canDelete = $this->commentService->canDelete(
|
||||
$comment,
|
||||
Auth::id(),
|
||||
$password,
|
||||
$slug
|
||||
);
|
||||
|
||||
if (! $canDelete) {
|
||||
return $this->forbidden('sirsoft-board::messages.comment.delete_forbidden');
|
||||
}
|
||||
|
||||
$this->commentService->deleteComment($slug, $commentId, 'user');
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.comment.delete_success'
|
||||
);
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->error('sirsoft-board::messages.comment.not_found', 404);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.delete_failed', 500);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비회원 댓글 비밀번호를 검증합니다.
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $commentId 댓글 ID
|
||||
* @return JsonResponse 비밀번호 검증 결과 응답
|
||||
*/
|
||||
public function verifyPassword(Request $request, string $slug, int $commentId): JsonResponse
|
||||
{
|
||||
$request->validate([
|
||||
'password' => ['required', 'string'],
|
||||
]);
|
||||
|
||||
try {
|
||||
$comment = $this->commentService->getComment($slug, $commentId);
|
||||
|
||||
if (! $comment) {
|
||||
return $this->error('sirsoft-board::messages.comment.not_found', 404);
|
||||
}
|
||||
|
||||
// 비회원 댓글 확인
|
||||
if ($comment->user_id !== null) {
|
||||
return $this->error('sirsoft-board::messages.comment.not_guest_comment', 400);
|
||||
}
|
||||
|
||||
$result = Hash::check($request->password, $comment->password);
|
||||
|
||||
// 비밀번호 검증
|
||||
if (! $result) {
|
||||
return $this->error('sirsoft-board::messages.comment.invalid_password', 401);
|
||||
}
|
||||
|
||||
// 검증 성공 시 임시 토큰 생성 (프론트엔드에서 로컬 스토리지에 저장)
|
||||
$verificationToken = Str::random(32);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.comment.password_verified',
|
||||
[
|
||||
'verified' => true,
|
||||
'comment_id' => $commentId,
|
||||
'verification_token' => $verificationToken,
|
||||
'expires_at' => now()->addHours(1)->toIso8601String(), // 1시간 유효
|
||||
]
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.comment.verify_password_failed', 500);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use App\Models\User;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Str;
|
||||
use App\Enums\PermissionType;
|
||||
use Modules\Sirsoft\Board\Enums\SecretMode;
|
||||
use Modules\Sirsoft\Board\Exceptions\BoardNotFoundException;
|
||||
use Modules\Sirsoft\Board\Exceptions\PostNotFoundException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\User\StorePostRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\User\UpdatePostRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\User\VerifyGuestPasswordRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\PostCollection;
|
||||
use Modules\Sirsoft\Board\Http\Resources\PostResource;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
use Modules\Sirsoft\Board\Services\CommentService;
|
||||
use Modules\Sirsoft\Board\Services\PostService;
|
||||
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
/**
|
||||
* 사용자용 게시글 컨트롤러
|
||||
*
|
||||
* 게시판 게시글의 CRUD 기능을 제공합니다.
|
||||
* - 비로그인 사용자도 목록/상세 조회 가능 (게시판 설정에 따름)
|
||||
* - 비밀글은 권한 체크 후 조회
|
||||
* - 회원/비회원 모두 게시글 작성 가능 (게시판 설정에 따름)
|
||||
* - 수정/삭제는 작성자 본인 또는 비회원 비밀번호 확인 필요
|
||||
*/
|
||||
class PostController extends PublicBaseController
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* PostController 생성자
|
||||
*
|
||||
* @param PostService $postService 게시글 서비스
|
||||
* @param BoardService $boardService 게시판 서비스
|
||||
* @param CommentService $commentService 댓글 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private PostService $postService,
|
||||
private BoardService $boardService,
|
||||
private CommentService $commentService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 게시글 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 게시글 목록 응답
|
||||
*/
|
||||
public function index(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 조회 및 활성화 확인
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 목록 조회 파라미터 빌드 (필터 + perPage)
|
||||
$listParams = $this->postService->buildListParams($request->all(), [
|
||||
'context' => 'user',
|
||||
'board' => $board,
|
||||
'userAgent' => $request->header('User-Agent'),
|
||||
]);
|
||||
|
||||
// 삭제된 게시글 포함 여부 (manager 권한 + 토글 ON 시에만 포함)
|
||||
$canViewDeleted = $this->checkBoardPermission($slug, 'manager', PermissionType::User);
|
||||
$withTrashed = $canViewDeleted && $request->boolean('del');
|
||||
|
||||
// 게시글 목록 조회
|
||||
$posts = $this->postService->getPosts($slug, $listParams['filters'], $listParams['perPage'], withTrashed: $withTrashed, context: 'user');
|
||||
$totalNormalPosts = $this->postService->getTotalNormalPosts($slug, $listParams['filters'], $withTrashed, context: 'user');
|
||||
|
||||
// PostCollection 구성
|
||||
$collection = new PostCollection($posts);
|
||||
$collection->setTotalNormalPosts($totalNormalPosts);
|
||||
$collection->setOrderDirection($listParams['filters']['order_direction']);
|
||||
|
||||
// BoardResource로 boardInfo 생성
|
||||
$boardResource = new BoardResource($board);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.posts.fetch_success',
|
||||
$collection->withBoardInfo($boardResource->toBoardInfoForUser())
|
||||
);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 상세 정보를 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 게시글 상세 정보 응답
|
||||
*/
|
||||
public function show(Request $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 게시글 조회
|
||||
$post = $this->postService->getPost($slug, $id, context: 'user');
|
||||
|
||||
// 삭제된 게시글은 manager 권한 필요
|
||||
if ($post->trashed()) {
|
||||
if (! $this->checkBoardPermission($slug, 'manager', PermissionType::User)) {
|
||||
throw new PostNotFoundException($id);
|
||||
}
|
||||
}
|
||||
|
||||
// 조회수 증가 (캐시 기반 중복 방지)
|
||||
$this->postService->incrementViewCountOnce($slug, $id);
|
||||
|
||||
// 댓글/첨부파일 카운트 포함하여 게시글 조회
|
||||
$post = $this->postService->getPostWithCounts($slug, $id);
|
||||
|
||||
// board 관계 수동 설정
|
||||
$post->setRelation('board', $board);
|
||||
|
||||
// manager 권한 체크 (삭제 게시글/댓글 포함 여부 결정)
|
||||
$canViewDeleted = $this->checkBoardPermission($slug, 'manager', PermissionType::User);
|
||||
|
||||
// 댓글 로드 (게시판 comment_order 설정 적용, manager 권한 + 토글 ON 시 삭제 댓글 포함)
|
||||
$withTrashedComments = $canViewDeleted && $request->boolean('del_cmt');
|
||||
$comments = $this->commentService->getCommentsByPostId($slug, $id, context: 'user', withTrashed: $withTrashedComments);
|
||||
|
||||
// 댓글의 post에 board 관계 수동 설정 (CommentResource의 권한 체크에 필요)
|
||||
foreach ($comments as $comment) {
|
||||
$comment->setRelation('post', $post);
|
||||
}
|
||||
|
||||
// 정렬된 댓글을 post에 설정
|
||||
$post->setRelation('comments', $comments);
|
||||
|
||||
// 이전/다음 게시글 조회 (manager 권한 + del=1 시 삭제된 게시글 포함)
|
||||
$withTrashedNav = $canViewDeleted && $request->boolean('del');
|
||||
$post->navigation = $this->postService->getAdjacentPosts($slug, $id, filters: [], withTrashed: $withTrashedNav);
|
||||
|
||||
// 비밀글 권한 체크 및 content 필터링은 PostResource에서 처리
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.fetch_success',
|
||||
new PostResource($post)
|
||||
);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 생성합니다.
|
||||
*
|
||||
* @param StorePostRequest $request 게시글 생성 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 생성된 게시글 응답
|
||||
*/
|
||||
public function store(StorePostRequest $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 파일 업로드 허용 여부 확인
|
||||
if ($request->hasFile('files')) {
|
||||
// 게시판에서 파일 업로드를 비활성화한 경우
|
||||
if (! $board->use_file_upload) {
|
||||
return $this->error('sirsoft-board::messages.posts.file_upload_not_allowed', 403);
|
||||
}
|
||||
|
||||
// 파일 업로드 권한 확인
|
||||
if (! $this->checkBoardPermission($slug, 'attachments.upload', PermissionType::User)) {
|
||||
return $this->forbidden('sirsoft-board::messages.permissions.access_denied');
|
||||
}
|
||||
}
|
||||
|
||||
// 요청 데이터 준비
|
||||
$data = $request->validated();
|
||||
|
||||
// user_id 설정 (인증 필수)
|
||||
$data['user_id'] = Auth::id();
|
||||
|
||||
// IP 주소 설정
|
||||
$data['ip_address'] = $request->ip();
|
||||
|
||||
// secret_mode에 따른 비밀글 설정 검증
|
||||
if ($board->secret_mode === SecretMode::Disabled) {
|
||||
// 비밀글 기능 비활성화된 경우 is_secret=true 요청 거부
|
||||
if (! empty($data['is_secret'])) {
|
||||
return $this->error('sirsoft-board::messages.posts.secret_post_not_allowed', 403);
|
||||
}
|
||||
} elseif ($board->secret_mode === SecretMode::Always) {
|
||||
// 비밀글 필수인 경우 자동으로 is_secret=true 설정
|
||||
$data['is_secret'] = true;
|
||||
}
|
||||
// secret_mode='enabled'인 경우 사용자 선택에 따름 (별도 처리 불필요)
|
||||
|
||||
// 게시글 생성
|
||||
$post = $this->postService->createPost($slug, $data);
|
||||
|
||||
// 쿨다운 캐시 기록 (게시글 생성 성공 후)
|
||||
$spamSecurity = g7_module_settings('sirsoft-board', 'spam_security', []);
|
||||
$cooldown = (int) ($spamSecurity['post_cooldown_seconds'] ?? 0);
|
||||
if ($cooldown > 0) {
|
||||
$identifier = Auth::id() ?? $request->ip();
|
||||
Cache::put("post_cooldown_{$slug}_{$identifier}", true, $cooldown);
|
||||
}
|
||||
|
||||
// board 관계 수동 설정
|
||||
$post->setRelation('board', $board);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.create_success',
|
||||
new PostResource($post),
|
||||
201
|
||||
);
|
||||
} catch (BoardNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.create_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 수정합니다.
|
||||
*
|
||||
* @param UpdatePostRequest $request 게시글 수정 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 수정된 게시글 응답
|
||||
*/
|
||||
public function update(UpdatePostRequest $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 게시글 조회
|
||||
$post = $this->postService->getPost($slug, $id, context: 'user');
|
||||
|
||||
// 수정 권한 확인
|
||||
if (! $this->canModifyPost($post, $request)) {
|
||||
return $this->error('sirsoft-board::messages.posts.modify_permission_denied', 403);
|
||||
}
|
||||
|
||||
// 게시글 수정
|
||||
$data = $request->validated();
|
||||
$post = $this->postService->updatePost($slug, $id, $data);
|
||||
|
||||
// board 관계 수동 설정
|
||||
$post->setRelation('board', $board);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.update_success',
|
||||
new PostResource($post)
|
||||
);
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.update_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 삭제합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 삭제 결과 응답
|
||||
*/
|
||||
public function destroy(Request $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 게시글 조회
|
||||
$post = $this->postService->getPost($slug, $id, context: 'user');
|
||||
|
||||
// 삭제 권한 확인
|
||||
if (! $this->canModifyPost($post, $request)) {
|
||||
return $this->error('sirsoft-board::messages.posts.delete_permission_denied', 403);
|
||||
}
|
||||
|
||||
// 게시글 삭제 (소프트 삭제)
|
||||
$this->postService->deletePost($slug, $id, 'user');
|
||||
|
||||
return $this->success('sirsoft-board::messages.posts.delete_success');
|
||||
} catch (AccessDeniedHttpException $e) {
|
||||
return $this->error('auth.scope_denied', 403);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.delete_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 비밀글 조회를 위한 비밀번호를 검증합니다.
|
||||
*
|
||||
* 비밀글의 내용을 조회할 때 사용합니다. (posts.read 권한 필요)
|
||||
* 검증 성공 시 게시글 내용과 첨부파일을 포함하여 반환합니다.
|
||||
*
|
||||
* @param VerifyGuestPasswordRequest $request 비밀번호 검증 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 검증 결과 응답 (content, attachments 포함)
|
||||
*/
|
||||
public function verifyPassword(VerifyGuestPasswordRequest $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 게시글 조회 (첨부파일 포함)
|
||||
$post = $this->postService->getPostWithCounts($slug, $id);
|
||||
$post->setRelation('board', $board);
|
||||
|
||||
// 비밀번호 검증 (Service 사용)
|
||||
$password = $request->validated('password');
|
||||
$verifyResult = $this->postService->verifyPassword($post, $password);
|
||||
|
||||
if (! $verifyResult['success']) {
|
||||
return $this->error($verifyResult['error_key'], $verifyResult['error_code']);
|
||||
}
|
||||
|
||||
// 검증 성공 - password_verified 플래그 설정하여 PostResource에서 content 포함
|
||||
$post->password_verified = true;
|
||||
|
||||
// successWithResource 사용: $this->when() 조건부 필드가 올바르게 직렬화됨
|
||||
// (toArray 직접 호출 시 MissingValue 객체가 반환되는 문제 방지)
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.posts.password_verified',
|
||||
new PostResource($post)
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.password_verify_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 수정/삭제를 위한 비밀번호를 검증합니다.
|
||||
*
|
||||
* 게시글 수정 또는 삭제 전 권한 확인용입니다. (posts.write 권한 필요)
|
||||
* 검증 성공 시 임시 토큰을 반환합니다.
|
||||
*
|
||||
* @param VerifyGuestPasswordRequest $request 비밀번호 검증 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param string|int $id 게시글 ID
|
||||
* @return JsonResponse 검증 결과 응답 (verification_token 포함)
|
||||
*/
|
||||
public function verifyPasswordForModify(VerifyGuestPasswordRequest $request, string $slug, string|int $id): JsonResponse
|
||||
{
|
||||
$id = (int) $id;
|
||||
|
||||
try {
|
||||
// 게시판 정보 조회
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// 게시글 조회
|
||||
$post = $this->postService->getPost($slug, $id, context: 'user');
|
||||
|
||||
// 비밀번호 검증 (Service 사용)
|
||||
$password = $request->validated('password');
|
||||
$verifyResult = $this->postService->verifyPassword($post, $password);
|
||||
|
||||
if (! $verifyResult['success']) {
|
||||
return $this->error($verifyResult['error_key'], $verifyResult['error_code']);
|
||||
}
|
||||
|
||||
// 검증 성공 시 임시 토큰 생성 및 캐시 저장 (1시간 유효)
|
||||
$verificationToken = Str::random(32);
|
||||
$expiresAt = now()->addHours(1);
|
||||
Cache::put("board_post_verify_{$slug}_{$id}_{$verificationToken}", true, $expiresAt);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.posts.password_verified',
|
||||
[
|
||||
'verified' => true,
|
||||
'post_id' => $id,
|
||||
'verification_token' => $verificationToken,
|
||||
'expires_at' => $expiresAt->toIso8601String(),
|
||||
]
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException($id);
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.password_verify_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 폼 메타 데이터를 반환합니다.
|
||||
*
|
||||
* 게시판 설정 정보, 파일 업로드 설정, 카테고리 목록 등 폼 렌더링에 필요한 메타 정보를 반환합니다.
|
||||
* 수정 모드 시 기존 첨부파일 정보, 답글 모드 시 원글 정보를 포함합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 폼 메타 데이터 응답
|
||||
*/
|
||||
public function getFormMeta(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
// Admin과 동일하게 BoardResource 사용
|
||||
// user_abilities 포함을 위해 include_user_abilities 파라미터 설정
|
||||
$request->merge(['include_user_abilities' => true]);
|
||||
$boardResource = new BoardResource($board);
|
||||
$boardData = $boardResource->toArray($request);
|
||||
|
||||
// 게시글 폼에서는 게시판 이름을 로컬라이즈된 문자열로 반환
|
||||
$boardData['name'] = $board->getLocalizedName();
|
||||
|
||||
$metaData = [
|
||||
'board' => $boardData,
|
||||
];
|
||||
|
||||
// 수정 모드: 작성자 정보, 작성일, 첨부파일 정보 포함
|
||||
if ($request->filled('post_id') && $request->get('post_id') !== 'undefined' && $request->get('post_id') !== '') {
|
||||
$postId = (int) $request->get('post_id');
|
||||
$post = $this->postService->getPost($slug, $postId, context: 'user');
|
||||
|
||||
// 회원 게시글이고 본인이 아닌 경우 권한 에러
|
||||
if ($post->user_id && Auth::id() !== $post->user_id) {
|
||||
if (! $this->checkBoardPermission($slug, 'admin.manage')) {
|
||||
return $this->error('sirsoft-board::messages.posts.no_permission', 403);
|
||||
}
|
||||
}
|
||||
|
||||
// 비회원 게시글인 경우 비밀번호 확인 필요
|
||||
$requiresPassword = ! $post->user_id && $post->password;
|
||||
|
||||
// verification_token이 유효하면 비밀번호 확인 불필요
|
||||
if ($requiresPassword && $request->filled('verification_token')) {
|
||||
$token = $request->get('verification_token');
|
||||
if ($this->isVerificationTokenValid($slug, $postId, $token)) {
|
||||
$requiresPassword = false;
|
||||
}
|
||||
}
|
||||
|
||||
$metaData['requires_password'] = $requiresPassword;
|
||||
$metaData['is_guest_post'] = ! $post->user_id;
|
||||
|
||||
// 첨부파일 관계 로드
|
||||
$post->load('attachments');
|
||||
|
||||
$postResource = new PostResource($post);
|
||||
$postData = $postResource->toArray($request);
|
||||
|
||||
$metaData['author'] = $postData['author'] ?? null;
|
||||
$metaData['created_at'] = $postData['created_at'] ?? null;
|
||||
$metaData['attachments'] = $postData['attachments'] ?? [];
|
||||
|
||||
// 수정 시 원글 정보가 있으면 포함
|
||||
if (! empty($postData['parent'])) {
|
||||
$metaData['parent_post'] = $postData['parent'];
|
||||
}
|
||||
}
|
||||
// 답변글 모드: 원글 정보 포함
|
||||
elseif ($request->filled('parent_id') && $request->get('parent_id') !== 'undefined' && $request->get('parent_id') !== '') {
|
||||
$parentId = (int) $request->get('parent_id');
|
||||
|
||||
if (! $board->use_reply) {
|
||||
return $this->error('sirsoft-board::validation.post.reply_not_allowed', 403);
|
||||
}
|
||||
|
||||
$parentPost = $this->postService->getPost($slug, $parentId, context: 'user');
|
||||
$parentPostResource = new PostResource($parentPost);
|
||||
$metaData['parent_post'] = $parentPostResource->toArray($request);
|
||||
}
|
||||
|
||||
return $this->success('sirsoft-board::messages.posts.form_meta_retrieved', $metaData);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException((int) ($request->get('post_id') ?? $request->get('parent_id') ?? 0));
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.form_meta_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 폼 화면용 데이터를 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @return JsonResponse 폼 데이터 응답
|
||||
*/
|
||||
public function getFormData(Request $request, string $slug): JsonResponse
|
||||
{
|
||||
try {
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
if (! $board || ! $board->is_active) {
|
||||
throw new BoardNotFoundException($slug);
|
||||
}
|
||||
|
||||
$formData = [];
|
||||
|
||||
// 수정 모드
|
||||
if ($request->filled('post_id') && $request->get('post_id') !== 'undefined' && $request->get('post_id') !== '') {
|
||||
$postId = (int) $request->get('post_id');
|
||||
$post = $this->postService->getPost($slug, $postId, context: 'user');
|
||||
|
||||
// 회원 게시글이고 본인이 아니거나, 관리자도 아닌 경우 권한 에러
|
||||
if ($post->user_id && Auth::id() !== $post->user_id) {
|
||||
if (! $this->checkBoardPermission($slug, 'admin.manage')) {
|
||||
return $this->error('sirsoft-board::messages.posts.no_permission', 403);
|
||||
}
|
||||
}
|
||||
|
||||
// 비밀글 또는 비회원 글의 검증 처리
|
||||
// 1. verification_token으로 검증 (권장 - 비밀번호 재전송 불필요)
|
||||
// 2. password로 검증 (fallback)
|
||||
if ($request->filled('verification_token')) {
|
||||
$token = $request->get('verification_token');
|
||||
if ($this->isVerificationTokenValid($slug, $postId, $token)) {
|
||||
$post->password_verified = true;
|
||||
}
|
||||
} elseif ($request->filled('password') && $post->password) {
|
||||
$password = $request->get('password');
|
||||
if (Hash::check($password, $post->password)) {
|
||||
$post->password_verified = true;
|
||||
}
|
||||
}
|
||||
|
||||
$postResource = new PostResource($post);
|
||||
$postData = $postResource->toArray($request);
|
||||
|
||||
$formData = [
|
||||
'id' => $postData['id'] ?? null,
|
||||
'title' => $postData['title'] ?? '',
|
||||
'content' => $postData['content'] ?? '',
|
||||
'content_mode' => $postData['content_mode'] ?? 'text',
|
||||
'category' => $postData['category'] ?? null,
|
||||
'is_notice' => $postData['is_notice'] ?? false,
|
||||
'is_secret' => $postData['is_secret'] ?? false,
|
||||
'parent_id' => $postData['parent_id'] ?? null,
|
||||
'attachments' => $postData['attachments'] ?? [],
|
||||
// 비회원 글 수정 시 verification_token 유지 (PUT 요청에 필요)
|
||||
'verification_token' => $request->get('verification_token', ''),
|
||||
];
|
||||
}
|
||||
// 답변글 모드
|
||||
elseif ($request->filled('parent_id') && $request->get('parent_id') !== 'undefined' && $request->get('parent_id') !== '') {
|
||||
$parentId = (int) $request->get('parent_id');
|
||||
|
||||
if (! $board->use_reply) {
|
||||
return $this->error('sirsoft-board::validation.post.reply_not_allowed', 403);
|
||||
}
|
||||
$parentPost = $this->postService->getPost($slug, $parentId, context: 'user');
|
||||
|
||||
$formData = [
|
||||
'title' => 'Re: '.$parentPost->title,
|
||||
'content' => '',
|
||||
'content_mode' => 'text',
|
||||
'category' => $parentPost->category ?? null,
|
||||
'is_notice' => false,
|
||||
'is_secret' => $parentPost->is_secret ?? false,
|
||||
'parent_id' => $parentId,
|
||||
];
|
||||
}
|
||||
// 생성 모드
|
||||
else {
|
||||
$formData = [
|
||||
'title' => '',
|
||||
'content' => '',
|
||||
'content_mode' => 'text',
|
||||
'category' => null,
|
||||
'is_notice' => false,
|
||||
'is_secret' => $board->secret_mode->value === 'always',
|
||||
'parent_id' => null,
|
||||
];
|
||||
}
|
||||
|
||||
return $this->success('sirsoft-board::messages.posts.form_data_retrieved', $formData);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
throw new PostNotFoundException((int) ($request->get('post_id') ?? $request->get('parent_id') ?? 0));
|
||||
} catch (BoardNotFoundException|PostNotFoundException $e) {
|
||||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.form_data_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글 수정/삭제 권한을 확인합니다.
|
||||
*
|
||||
* 다음 조건 중 하나라도 만족하면 수정/삭제 가능:
|
||||
* - 작성자 본인 (로그인 사용자의 user_id 일치)
|
||||
* - 비회원 게시글인 경우 비밀번호 확인
|
||||
* - 게시판 관리자 (admin.manage 권한)
|
||||
* - 시스템 관리자 (Super Admin 역할)
|
||||
*
|
||||
* @param \Modules\Sirsoft\Board\Models\Post $post 게시글 모델
|
||||
* @param Request $request HTTP 요청
|
||||
* @return bool 수정/삭제 가능 여부
|
||||
*/
|
||||
private function canModifyPost($post, Request $request): bool
|
||||
{
|
||||
$slug = $post->board->slug;
|
||||
|
||||
// 1. 게시판 관리자 권한 확인 (admin.manage 권한)
|
||||
if (Auth::check() && $this->checkBoardPermission($slug, 'admin.manage')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. 작성자 본인 확인 (회원 게시글)
|
||||
if (Auth::check() && $post->user_id && Auth::id() === $post->user_id) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. 비회원 게시글인 경우 verification_token 또는 비밀번호로 확인
|
||||
if (! $post->user_id && $post->password) {
|
||||
// 3-1. verification_token 확인 (권장)
|
||||
$token = $request->input('verification_token');
|
||||
if ($token && $this->isVerificationTokenValid($slug, $post->id, $token)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3-2. 비밀번호 확인 (fallback)
|
||||
$password = $request->input('password');
|
||||
if ($password && Hash::check($password, $post->password)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Verification Token 헬퍼 메서드
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* verification_token이 유효한지 확인합니다.
|
||||
*
|
||||
* @param string $slug 게시판 슬러그
|
||||
* @param int $postId 게시글 ID
|
||||
* @param string $token 검증 토큰
|
||||
* @return bool 토큰 유효 여부
|
||||
*/
|
||||
private function isVerificationTokenValid(string $slug, int $postId, string $token): bool
|
||||
{
|
||||
return (bool) Cache::get("board_post_verify_{$slug}_{$postId}_{$token}");
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// 사용자 공개 게시글 조회 메서드 (공개 프로필용)
|
||||
// =========================================================================
|
||||
|
||||
/**
|
||||
* 특정 사용자의 공개 게시글 목록을 조회합니다.
|
||||
*
|
||||
* 게시판 슬러그 없이 모든 게시판에서 해당 사용자의 공개 게시글을 조회합니다.
|
||||
* 비밀글은 제외됩니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param User $user 사용자 모델 (Route Model Binding, uuid 기반)
|
||||
* @return JsonResponse 게시글 목록 (페이지네이션)
|
||||
*/
|
||||
public function userPosts(Request $request, User $user): JsonResponse
|
||||
{
|
||||
try {
|
||||
$perPage = (int) $request->input('per_page', 20);
|
||||
$perPage = min(max($perPage, 1), 100);
|
||||
|
||||
$filters = [
|
||||
'sort' => $request->input('sort', 'latest'),
|
||||
];
|
||||
|
||||
$result = $this->postService->getUserPublicPosts($user->id, $filters, $perPage);
|
||||
|
||||
return $this->success('sirsoft-board::messages.posts.fetch_success', $result);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 사용자의 게시글/댓글 통계를 조회합니다.
|
||||
*
|
||||
* 공개 프로필 페이지에서 사용됩니다.
|
||||
* status=published인 게시글/댓글만 카운트합니다.
|
||||
*
|
||||
* @param User $user 사용자 모델 (Route Model Binding, uuid 기반)
|
||||
* @return JsonResponse 통계 정보
|
||||
*/
|
||||
public function userPostsStats(User $user): JsonResponse
|
||||
{
|
||||
try {
|
||||
$stats = $this->postService->getUserPublicStats($user->id);
|
||||
|
||||
return $this->success('common.success', $stats);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.posts.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Modules\Sirsoft\Board\Enums\ReportStatus;
|
||||
use Modules\Sirsoft\Board\Enums\ReportType;
|
||||
use Modules\Sirsoft\Board\Exceptions\DuplicateReportException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\StoreReportRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportResource;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Services\BoardSettingsService;
|
||||
use Modules\Sirsoft\Board\Services\ReportService;
|
||||
|
||||
/**
|
||||
* 사용자용 신고 컨트롤러
|
||||
*
|
||||
* 게시글/댓글 신고 기능을 제공합니다.
|
||||
*/
|
||||
class ReportController extends AuthBaseController
|
||||
{
|
||||
/**
|
||||
* ReportController 생성자
|
||||
*
|
||||
* @param ReportService $reportService 신고 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private ReportService $reportService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글을 신고합니다.
|
||||
*
|
||||
* @param StoreReportRequest $request 신고 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $postId 게시글 ID
|
||||
* @return JsonResponse 신고 결과 응답
|
||||
*/
|
||||
public function storePostReport(StoreReportRequest $request, string $slug, int $postId): JsonResponse
|
||||
{
|
||||
return $this->createReport($request, $slug, $postId, ReportType::Post);
|
||||
}
|
||||
|
||||
/**
|
||||
* 댓글을 신고합니다.
|
||||
*
|
||||
* @param StoreReportRequest $request 신고 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $commentId 댓글 ID
|
||||
* @return JsonResponse 신고 결과 응답
|
||||
*/
|
||||
public function storeCommentReport(StoreReportRequest $request, string $slug, int $commentId): JsonResponse
|
||||
{
|
||||
return $this->createReport($request, $slug, $commentId, ReportType::Comment);
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고를 생성합니다.
|
||||
*
|
||||
* @param StoreReportRequest $request 신고 요청
|
||||
* @param string $slug 게시판 slug
|
||||
* @param int $targetId 신고 대상 ID
|
||||
* @param ReportType $targetType 신고 대상 타입
|
||||
* @return JsonResponse 신고 결과 응답
|
||||
*/
|
||||
protected function createReport(
|
||||
StoreReportRequest $request,
|
||||
string $slug,
|
||||
int $targetId,
|
||||
ReportType $targetType
|
||||
): JsonResponse {
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
|
||||
if (! $board->use_report) {
|
||||
return $this->error('sirsoft-board::messages.reports.report_disabled', 403);
|
||||
}
|
||||
|
||||
// 본인 글 신고 검증
|
||||
if ($this->reportService->isOwnContent($board->id, $targetType->value, $targetId, Auth::id())) {
|
||||
return $this->error('sirsoft-board::messages.reports.cannot_report_own', 403);
|
||||
}
|
||||
|
||||
// 신고 대상 상태 검증 (블라인드/삭제된 대상은 신고 불가)
|
||||
if (! $this->reportService->isTargetReportable($board->id, $targetType->value, $targetId)) {
|
||||
return $this->error('sirsoft-board::messages.reports.target_not_reportable', 403);
|
||||
}
|
||||
|
||||
$data = array_merge($request->validated(), [
|
||||
'board_id' => $board->id,
|
||||
'target_type' => $targetType->value,
|
||||
'target_id' => $targetId,
|
||||
'reporter_id' => Auth::id(),
|
||||
'status' => ReportStatus::Pending->value,
|
||||
'metadata' => [
|
||||
'ip' => $request->ip(),
|
||||
'user_agent' => $request->userAgent(),
|
||||
],
|
||||
]);
|
||||
|
||||
$report = $this->reportService->createReport($data);
|
||||
|
||||
// 쿨다운 캐시 기록 (신고 생성 성공 후)
|
||||
// BoardSettingsService를 사용하여 최신 설정값 반영 (g7_module_settings는 부팅 시 Config 캐시 사용)
|
||||
$security = app(BoardSettingsService::class)->getSettings('spam_security');
|
||||
$cooldown = (int) ($security['report_cooldown_seconds'] ?? 60);
|
||||
if ($cooldown > 0) {
|
||||
$identifier = Auth::id() ?? $request->ip();
|
||||
Cache::put("report_cooldown_{$slug}_{$identifier}", true, $cooldown);
|
||||
}
|
||||
|
||||
$this->logUserActivity('board_report.create', [
|
||||
'report_id' => $report->id,
|
||||
'board_slug' => $slug,
|
||||
'target_type' => $targetType->value,
|
||||
'target_id' => $targetId,
|
||||
]);
|
||||
|
||||
return $this->successWithResource(
|
||||
'sirsoft-board::messages.reports.create_success',
|
||||
new ReportResource($report),
|
||||
201
|
||||
);
|
||||
} catch (ModelNotFoundException $e) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
} catch (DuplicateReportException $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.duplicate_report', 409);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.reports.create_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Board\Services\CommentService;
|
||||
use Modules\Sirsoft\Board\Services\PostService;
|
||||
|
||||
/**
|
||||
* 사용자 게시글 활동 컨트롤러
|
||||
*
|
||||
* 마이페이지에서 사용자의 게시글 활동(작성, 댓글, 신고)을 조회합니다.
|
||||
*/
|
||||
class UserActivityController extends AuthBaseController
|
||||
{
|
||||
/**
|
||||
* UserActivityController 생성자
|
||||
*
|
||||
* @param PostService $postService 게시글 서비스
|
||||
* @param CommentService $commentService 댓글 서비스
|
||||
*/
|
||||
public function __construct(
|
||||
private PostService $postService,
|
||||
private CommentService $commentService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 사용자의 게시글 활동 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 게시글 활동 목록 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$userId = Auth::id();
|
||||
|
||||
$filters = [
|
||||
'board_slug' => $request->input('board_slug'),
|
||||
'search' => $request->input('search'),
|
||||
'activity_type' => $request->input('activity_type'),
|
||||
'sort' => $request->input('sort', 'latest'), // latest, oldest, views
|
||||
];
|
||||
|
||||
$perPage = (int) $request->input('per_page', 20);
|
||||
|
||||
$activities = $this->postService->getUserActivities($userId, $filters, $perPage);
|
||||
|
||||
// 페이지네이션 결과를 배열로 변환하고 query 파라미터 추가
|
||||
$result = $activities->toArray();
|
||||
$result['query'] = [
|
||||
'board_slug' => $filters['board_slug'] ?? '',
|
||||
'search' => $filters['search'] ?? '',
|
||||
'sort' => $filters['sort'] ?? 'latest',
|
||||
'activity_type' => $filters['activity_type'] ?? '',
|
||||
];
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.user_activities.fetch_success',
|
||||
$result
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.user_activities.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자가 작성한 댓글 목록을 조회합니다.
|
||||
*
|
||||
* 댓글 기준 페이지네이션으로 작성일, 댓글 내용, 게시글 제목, 게시판 정보를 반환합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 댓글 목록 응답
|
||||
*/
|
||||
public function myComments(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$userId = Auth::id();
|
||||
|
||||
$filters = [
|
||||
'board_slug' => $request->input('board_slug'),
|
||||
'search' => $request->input('search'),
|
||||
'sort' => $request->input('sort', 'latest'),
|
||||
];
|
||||
|
||||
$perPage = (int) $request->input('per_page', 20);
|
||||
$perPage = min(max($perPage, 1), 100);
|
||||
|
||||
$comments = $this->commentService->getUserComments($userId, $filters, $perPage);
|
||||
|
||||
$result = $comments->toArray();
|
||||
$result['query'] = [
|
||||
'board_slug' => $filters['board_slug'] ?? '',
|
||||
'search' => $filters['search'] ?? '',
|
||||
'sort' => $filters['sort'] ?? 'latest',
|
||||
];
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.user_activities.fetch_success',
|
||||
$result
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.user_activities.fetch_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자의 게시판 활동 통계를 조회합니다.
|
||||
*
|
||||
* @return JsonResponse 활동 통계 응답 (total_posts, total_comments, total_views)
|
||||
*/
|
||||
public function stats(): JsonResponse
|
||||
{
|
||||
try {
|
||||
$userId = Auth::id();
|
||||
|
||||
$stats = $this->postService->getUserActivityStats($userId);
|
||||
|
||||
return $this->success(
|
||||
'sirsoft-board::messages.user_activities.stats_success',
|
||||
$stats
|
||||
);
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('sirsoft-board::messages.user_activities.stats_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user