fix(core,board,ecommerce,page,gdpr,basic): 깊은 OFFSET 목록 조회 개선 및 raw/테이블명 전수 정리
목록이 뒤쪽 페이지로 갈수록 느려지는 원인은 건너뛰는 행의 넓은 컬럼까지 읽는 것이었다. 지연 조인(inner 는 키 컬럼만, outer 는 이번 페이지 행만 전체 컬럼)과 정렬 컬럼 해석을 코어 공통 트레이트로 두고 코어 8 + 확장 6 저장소에 적용했다. 감사 지적 처리: - 그룹 쿼리의 총 건수 오산 — count 는 groupBy 를 벗기지 않아 첫 그룹의 행 수를 총 건수로 돌려준다. getCountForPagination 으로 교정. - audit 전수 스캔이 버퍼 한계로 한 번도 동작하지 않던 결함과, 확장 경로를 놓치던 정규식 5건을 함께 고쳤다. 그동안 번들 확장의 위반이 보이지 않았다. raw 20건을 빌더 표현으로 치환하고 하드코딩 테이블명 16건을 모델 유래로 바꿨다. 이 과정에서 마이페이지 「내가 댓글 단 글」 검색이 조인 별칭 충돌로 SQL 오류를 내던 결함이 해소됐다. 재발 차단용 룰 2종을 신설하고, 컬럼 프루닝 룰을 error 로 승격했다 (전역 위반 0건 — warning 으로 두면 "0 error" 판정을 통과하며 무음으로 재누적된다). 정렬 허용 목록은 FormRequest 게이트를 덮어야 한다. 좁으면 검증을 통과한 정렬이 422 도 로그도 없이 기본값으로 되돌아간다(스케줄 실행 이력의 종료시각·소요시간 정렬이 그랬다). 호출처를 스캔해 매핑 완전성까지 검사하는 계약 테스트로 전수 강제한다. 해외 배송지 결함도 함께 고쳤다 — 조회는 city/state/postal_code 로 내려주고 폼은 intl_* 로 제출하는 비대칭 때문에, 수정 시 입력칸이 비어 보이고 저장하면 기존 값이 유실됐다. 쿠폰 수정의 유효기간 미검증과 1인당 사용 제한 부분 수정 차단도 함께 수정.
This commit is contained in:
1 parent
95ffdf9eed
commit
be9befe023
81 files changed
+5799
-457
No files matched your search
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Gnuboard7\HelloModule\Repositories;
|
||||
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
use Modules\Gnuboard7\HelloModule\Models\Memo;
|
||||
use Modules\Gnuboard7\HelloModule\Repositories\Contracts\MemoRepositoryInterface;
|
||||
@@ -21,6 +22,8 @@ class MemoRepository implements MemoRepositoryInterface
|
||||
{
|
||||
return Memo::query()
|
||||
->orderByDesc('created_at')
|
||||
// audit:allow repository-paginate-column-pruning reason: 학습용 샘플 확장의 메모 테이블 —
|
||||
// 넓은 컬럼(text/JSON)이 없고, 지연 조인을 넣으면 샘플 코드의 학습 목적이 흐려진다
|
||||
->paginate($perPage);
|
||||
}
|
||||
|
||||
@@ -41,7 +44,7 @@ class MemoRepository implements MemoRepositoryInterface
|
||||
* @param int $id 메모 ID
|
||||
* @return Memo 메모 모델
|
||||
*
|
||||
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
|
||||
* @throws ModelNotFoundException
|
||||
*/
|
||||
public function findOrFail(int $id): Memo
|
||||
{
|
||||
|
||||
@@ -20,6 +20,9 @@
|
||||
### Changed
|
||||
|
||||
- 사이트맵을 만들 때 게시판과 게시글을 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 게시글이 많은 사이트에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
|
||||
- 게시글 목록을 뒤쪽 페이지에서도 빠르게 열 수 있도록 조회 방식을 바꿨습니다. 예전에는 페이지가 뒤로 갈수록 건너뛰는 게시글의 본문 앞부분까지 함께 읽어 느려졌지만, 이제 현재 페이지의 게시글만 본문 미리보기를 읽습니다. 공지 노출·답글 표시·다음 페이지 버튼은 이전과 동일하게 동작합니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 신고 관리 목록도 같은 방식으로 개선했습니다. 신고 건수·대상 글 상태처럼 목록에 함께 표시되는 정보를 예전에는 건너뛰는 신고까지 모두 계산했지만, 이제 현재 페이지의 신고에 대해서만 계산합니다. 신고가 많이 쌓인 사이트에서 목록 페이지 이동이 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 마이페이지의 「내가 쓴 댓글」·「내가 댓글 단 글」 목록도 같은 방식으로 개선했습니다. 각 글의 최근 댓글을 예전에는 건너뛰는 글까지 모두 찾아봤지만, 이제 현재 페이지의 글에 대해서만 찾습니다. 댓글 활동이 많은 회원의 목록 페이지 이동이 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
|
||||
|
||||
### Fixed
|
||||
@@ -32,7 +35,8 @@
|
||||
- 데이터베이스에서 일부 컬럼의 설명이 비어 있던 문제를 바로잡았습니다. 회원·작성자 등 다른 표를 가리키는 컬럼이 대상이며, 업그레이드하면 이미 운영 중인 데이터베이스에도 설명이 채워집니다(직접 적어 넣은 설명은 그대로 둡니다).
|
||||
- 관리자 게시글 목록에서 글을 열어 이전글·다음글로 넘어가거나 수정 후 돌아올 때 보고 있던 페이지·검색어·분류가 사라지던 문제를 수정했습니다. 목록 ↔ 상세 ↔ 이전/다음 글 ↔ 작성·수정 폼 어디로 오가든 목록 상태가 유지되며, 신고 관리와 게시판 목록도 동일하게 개선됐습니다. 새로고침 버튼도 걸어 둔 검색·필터를 지운 채 새로 부르지 않고 보고 있던 목록을 그대로 다시 부릅니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 관리자 게시글 목록에서 뒤쪽 페이지를 보던 중 검색하거나 게시 상태를 바꾸면 그 페이지 번호가 그대로 유지돼 결과가 없는 빈 화면이 열리던 문제를 수정했습니다. 검색과 상태 변경은 1페이지부터 보여주며, 사용자가 고른 표시 개수와 정렬은 그대로 유지됩니다. 검색창에서 엔터를 치는 경우와 검색 버튼을 누르는 경우가 서로 다르게 동작하던 것도 함께 맞췄습니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 첨부파일을 사용하지 않는 게시판을 아무것도 바꾸지 않고 저장해도 "허용 파일 확장자를 최소 1개 이상 입력하세요" 오류가 나며 저장이 막히던 문제를 수정했습니다. 첨부를 쓰지 않는 게시판에서는 허용 확장자를 비워 두어도 정상적으로 저장됩니다. 게시판 환경설정의 기본값도 동일하게 동작합니다. (#78 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 첨부파일을 사용하지 않는 게시판을 아무것도 바꾸지 않고 저장해도 "허용 파일 확장자를 최소 1개 이상 입력하세요" 오류가 나며 저장이 막히던 문제를 수정했습니다. 첨부를 쓰지 않는 게시판에서는 허용 확장자를 비워 두어도 정상적으로 저장됩니다. 게시판 환경설정의 기본값도 동일하게 동작합니다. (#78 @glitter-gim 님께서 제보해주셨습니다.)
|
||||
- 마이페이지 「내가 댓글 단 글」에서 검색어를 입력하면 목록이 열리지 않고 오류가 나던 문제를 수정했습니다. 이제 댓글 내용으로 정상 검색됩니다.
|
||||
- 새 글 표시 기간을 "0시간"(새 글 표시 안 함)으로 저장할 수 없던 문제를 수정했습니다. 0은 원래 새 글 배지를 끄는 값으로 동작하도록 되어 있었으나 저장 단계에서 막혀 있었습니다.
|
||||
- 게시판 환경설정에서 제목·댓글 최소 길이를 0(제한 없음)으로 저장할 수 없던 문제를 수정했습니다. 내용 최소 길이는 0이 허용되어 같은 화면에서 항목마다 동작이 달랐습니다.
|
||||
- 댓글 계층 정리 시 서로가 서로의 부모로 얽혀 최상위 댓글에서 닿을 수 없는 댓글이 아무 기록 없이 넘어가던 문제를 수정했습니다. 이런 댓글은 내용과 위치를 그대로 보존하되, 정리되지 않았다는 사실이 업데이트 기록에 남아 확인할 수 있습니다.
|
||||
|
||||
@@ -1232,7 +1232,7 @@ HTTP/1.1 200
|
||||
| use_file_upload | body | boolean | 예 | — | 파일 첨부 기능 사용 여부 (true일 때 allowed_extensions 최소 1개 필수) |
|
||||
| max_file_size | body | integer | 아니오 | min 1, max 200 | 첨부파일 1개당 최대 크기 (MB 단위) |
|
||||
| max_file_count | body | integer | 아니오 | min 1, max 20 | 게시글 1건당 첨부할 수 있는 최대 파일 개수 |
|
||||
| allowed_extensions | body | array | 조건부 | min 1 | 업로드 허용 확장자 목록 (예: jpg, png, pdf). `use_file_upload=true` 일 때만 필수이며 최소 1개가 있어야 한다. `use_file_upload=false` 이면 검증에서 제외되어 빈 배열·`null` 도 허용된다 |
|
||||
| allowed_extensions | body | array | 조건부 | min 1 | 업로드 허용 확장자 목록 (예: jpg, png, pdf). `use_file_upload=true` 일 때만 필수이며 최소 1개가 있어야 한다. `use_file_upload=false` 이면 검증에서 제외되어 빈 배열·`null` 도 허용된다. **`allowed_extensions` 만 보내고 `use_file_upload` 를 생략하면 저장된 게시판의 값을 기준으로 판정한다** — 첨부를 쓰지 않는 게시판은 빈 배열도 통과하고, 첨부를 쓰는 게시판은 그대로 차단된다 |
|
||||
| board_manager_ids | body | array | 예 | min 1 | board manager 식별자 배열 |
|
||||
| board_step_ids | body | array | 아니오 | — | board step 식별자 배열 |
|
||||
| permissions | body | array | 예 | — | 게시판별 세부 권한 매트릭스 (권한 키별 mode/roles — 각 권한을 all 또는 특정 역할에 부여) |
|
||||
|
||||
@@ -35,12 +35,25 @@ class UpdateBoardRequest extends FormRequest
|
||||
/**
|
||||
* 검증 전 데이터 전처리
|
||||
*
|
||||
* blocked_keywords가 문자열로 전송된 경우 배열로 변환합니다.
|
||||
* blocked_keywords가 문자열로 전송된 경우 배열로 변환하고, 조건부 배제(`exclude_if`)의
|
||||
* 판정 기준이 되는 토글이 요청에 없으면 기존 게시판의 저장값을 주입합니다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$data = $this->all();
|
||||
|
||||
// allowed_extensions 만 부분 전송되고 use_file_upload 가 없으면 exclude_if 가 동작하지
|
||||
// 않는다(ValidatesAttributes::validateExcludeIf 는 조건 필드가 데이터에 없으면 배제하지
|
||||
// 않는다). 그러면 첨부를 쓰지 않는 게시판인데도 확장자 필수 규칙이 발화한다.
|
||||
// 기존 게시판의 저장값을 주입해 "저장된 상태 + 페이로드" 결과 상태로 판정한다.
|
||||
if (array_key_exists('allowed_extensions', $data) && ! array_key_exists('use_file_upload', $data)) {
|
||||
$board = $this->route('board');
|
||||
|
||||
if ($board !== null && isset($board->use_file_upload)) {
|
||||
$data['use_file_upload'] = (bool) $board->use_file_upload;
|
||||
}
|
||||
}
|
||||
|
||||
// blocked_keywords가 문자열이면 배열로 변환 (validation 전)
|
||||
if (isset($data['blocked_keywords']) && is_string($data['blocked_keywords'])) {
|
||||
$keywords = array_filter(
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace Modules\Sirsoft\Board\Repositories;
|
||||
|
||||
use App\Enums\UserStatus;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\Attachment;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -147,6 +149,8 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
// 권한 스코프 필터링
|
||||
PermissionHelper::applyPermissionScope($query, 'sirsoft-board.boards.read');
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 게시판 정의 테이블 —
|
||||
// 행 수가 운영자가 만든 게시판 수에 묶이고(글이 아니라 게시판), 넓은 컬럼이 없다
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
@@ -434,27 +438,32 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
default => now()->subYear(),
|
||||
};
|
||||
|
||||
$prefix = DB::getTablePrefix();
|
||||
// 테이블명은 모델에서 얻는다 (문자열 하드코딩 금지). LEFT() 는 빌더에 대응 표현이
|
||||
// 없는 표준 SQL 함수라 이 컬럼 하나만 raw 로 두고, 프리픽스는 연결 설정에서 읽는다.
|
||||
$postsTable = (new Post)->getTable();
|
||||
$usersTable = (new User)->getTable();
|
||||
$attachmentsTable = (new Attachment)->getTable();
|
||||
$prefixedPostsTable = DB::getTablePrefix().$postsTable;
|
||||
|
||||
$query = Post::query()
|
||||
->with('board:id,slug,name')
|
||||
->leftJoin('users', 'board_posts.user_id', '=', 'users.id')
|
||||
->leftJoin('attachments', function ($join) {
|
||||
$join->on('attachments.attachmentable_id', '=', 'users.id')
|
||||
->where('attachments.attachmentable_type', '=', 'App\\Models\\User')
|
||||
->where('attachments.collection', '=', 'avatar');
|
||||
->leftJoin($usersTable, "{$postsTable}.user_id", '=', "{$usersTable}.id")
|
||||
->leftJoin($attachmentsTable, function ($join) use ($usersTable, $attachmentsTable) {
|
||||
$join->on("{$attachmentsTable}.attachmentable_id", '=', "{$usersTable}.id")
|
||||
->where("{$attachmentsTable}.attachmentable_type", '=', User::class)
|
||||
->where("{$attachmentsTable}.collection", '=', 'avatar');
|
||||
})
|
||||
->select([
|
||||
'board_posts.id',
|
||||
'board_posts.board_id',
|
||||
'board_posts.title',
|
||||
DB::raw("LEFT(`{$prefix}board_posts`.`content`, 300) as content_raw"),
|
||||
DB::raw("LEFT(`{$prefixedPostsTable}`.`content`, 300) as content_raw"),
|
||||
'board_posts.user_id',
|
||||
'board_posts.author_name as guest_author_name',
|
||||
'users.name as user_name',
|
||||
'users.email as user_email',
|
||||
'users.status as user_status',
|
||||
'attachments.hash as attachment_hash',
|
||||
"{$usersTable}.name as user_name",
|
||||
"{$usersTable}.email as user_email",
|
||||
"{$usersTable}.status as user_status",
|
||||
"{$attachmentsTable}.hash as attachment_hash",
|
||||
'board_posts.view_count',
|
||||
'board_posts.comments_count',
|
||||
'board_posts.created_at',
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Modules\Sirsoft\Board\Repositories;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
@@ -11,6 +12,7 @@ use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Board\Enums\TriggerType;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Models\Comment;
|
||||
use Modules\Sirsoft\Board\Models\Post;
|
||||
use Modules\Sirsoft\Board\Repositories\Contracts\CommentRepositoryInterface;
|
||||
use Modules\Sirsoft\Board\Traits\FormatsBoardDate;
|
||||
|
||||
@@ -22,6 +24,7 @@ use Modules\Sirsoft\Board\Traits\FormatsBoardDate;
|
||||
class CommentRepository implements CommentRepositoryInterface
|
||||
{
|
||||
use FormatsBoardDate;
|
||||
use PaginatesWithDeferredJoin;
|
||||
|
||||
/**
|
||||
* 특정 게시글의 댓글 목록을 조회합니다.
|
||||
@@ -546,18 +549,16 @@ class CommentRepository implements CommentRepositoryInterface
|
||||
// 비활성 게시판 제외 — JOIN 대신 whereNotIn으로 인덱스 활용
|
||||
$inactiveBoardIds = Board::where('is_active', false)->pluck('id')->all();
|
||||
|
||||
// 관계/정렬은 지연 조인이 담당한다 (inner 는 키 컬럼만 조회)
|
||||
$query = Comment::query()
|
||||
->select('board_comments.*')
|
||||
->where('board_comments.user_id', $userId)
|
||||
// 삭제된 게시글 제외 — whereExists로 JOIN 대체
|
||||
->whereExists(function ($q) {
|
||||
$q->select(DB::raw(1))
|
||||
->from('board_posts')
|
||||
->from((new Post)->getTable())
|
||||
->whereColumn('board_posts.id', 'board_comments.post_id')
|
||||
->whereNull('board_posts.deleted_at');
|
||||
})
|
||||
->with(['post.board'])
|
||||
->orderBy('board_comments.created_at', $orderDirection);
|
||||
});
|
||||
|
||||
// 비활성 게시판 제외
|
||||
if (! empty($inactiveBoardIds)) {
|
||||
@@ -578,7 +579,25 @@ class CommentRepository implements CommentRepositoryInterface
|
||||
$query->where('board_comments.content', 'like', $keyword);
|
||||
}
|
||||
|
||||
$paginator = $query->paginate($perPage, ['*'], 'page', null, $cachedTotal);
|
||||
// 캐시된 total 이 있으면 COUNT 를 건너뛴다. 검색/게시판 필터가 걸린 조회는 캐시를
|
||||
// 쓰지 않으므로 이때는 trait 이 직접 COUNT 한다.
|
||||
//
|
||||
// 목록 컬럼은 아래 through() 가 실제로 읽는 것만 남긴다 (post_id 는 post 관계 FK).
|
||||
// 넓은 컬럼인 content 는 화면에 표시하므로 유지하되, 지연 조인으로 읽는 행 수가
|
||||
// 페이지 크기에 고정된다.
|
||||
$paginator = $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: [
|
||||
'board_comments.id',
|
||||
'board_comments.post_id',
|
||||
'board_comments.content',
|
||||
'board_comments.created_at',
|
||||
],
|
||||
sort: [['column' => 'board_comments.created_at', 'direction' => $orderDirection]],
|
||||
perPage: $perPage,
|
||||
relations: ['post.board'],
|
||||
total: $cachedTotal,
|
||||
);
|
||||
|
||||
// paginate 후 현재 페이지 항목에만 PHP 가공 적용
|
||||
$paginator->through(function (Comment $comment) {
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Board\Repositories;
|
||||
|
||||
use App\Enums\PermissionType;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Contracts\Pagination\Paginator;
|
||||
@@ -31,6 +32,7 @@ class PostRepository implements PostRepositoryInterface
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
use FormatsBoardDate;
|
||||
use PaginatesWithDeferredJoin;
|
||||
|
||||
/**
|
||||
* PostRepository 생성자
|
||||
@@ -692,12 +694,13 @@ class PostRepository implements PostRepositoryInterface
|
||||
// → 콜드 스타트(버퍼 풀 미적재)에서도 ~2ms (range scan 대비 100배 이상 빠름)
|
||||
$aggregateFunc = $strictOp === '<' ? 'MAX' : 'MIN';
|
||||
$subQuery = $baseQuery()
|
||||
->select(DB::raw("{$aggregateFunc}(`{$orderBy}`)"))
|
||||
->select(DB::raw("{$aggregateFunc}({$orderBy})"))
|
||||
->where($orderBy, $strictOp, $currentValue);
|
||||
|
||||
// 서브쿼리는 빌더 그대로 넘긴다 — toSql() 로 문자열을 붙이고 mergeBindings 로
|
||||
// 바인딩을 손수 옮기면 조건 추가 순서에 따라 바인딩이 어긋날 수 있다.
|
||||
return $baseQuery()
|
||||
->where($orderBy, DB::raw("({$subQuery->toSql()})"))
|
||||
->mergeBindings($subQuery->getQuery())
|
||||
->where($orderBy, '=', $subQuery)
|
||||
->orderBy('id', $idSort)
|
||||
->first();
|
||||
}
|
||||
@@ -827,22 +830,33 @@ class PostRepository implements PostRepositoryInterface
|
||||
$orderDirection = 'desc'; // 기본값으로 폴백
|
||||
}
|
||||
|
||||
// 정렬 적용 (id를 2차 정렬로 추가 — 동일 값 내 순서를 결정론적으로 보장)
|
||||
// 정렬 스펙 (id를 2차 정렬로 추가 — 동일 값 내 순서를 결정론적으로 보장)
|
||||
// created_at은 초 단위라 실질적 중복이 드물지만, view_count/title/author_name은 중복이 많음
|
||||
$parentQuery->orderBy($orderBy, $orderDirection)->orderBy('id', $orderDirection);
|
||||
|
||||
if (! empty($relations)) {
|
||||
$parentQuery->with($relations);
|
||||
}
|
||||
$sort = [['column' => $orderBy, 'direction' => $orderDirection]];
|
||||
|
||||
// 페이지네이션 여부에 따라 분기
|
||||
if ($perPage !== null) {
|
||||
// simplePaginate 사용 — COUNT(*) 쿼리 제거로 대량 데이터 성능 개선
|
||||
// total은 Service 캐시 카운트로 별도 제공
|
||||
$paginator = $parentQuery->simplePaginate($perPage, $columns, 'page', $currentPage);
|
||||
// 지연 조인 — 이번 페이지의 원글 ID 를 먼저 구하고, 그 ID 에 대해서만 목록 컬럼과
|
||||
// 관계를 읽는다. OFFSET 이 건너뛰는 원글의 본문 앞부분(SUBSTRING)까지 읽던 비용이
|
||||
// 사라진다. COUNT 는 기존과 같이 수행하지 않는다(total 은 Service 캐시 카운트).
|
||||
$paginator = $this->paginateWithDeferredJoin(
|
||||
query: $parentQuery,
|
||||
columns: $columns,
|
||||
sort: $sort,
|
||||
perPage: $perPage,
|
||||
page: (int) $currentPage,
|
||||
relations: $relations,
|
||||
simple: true,
|
||||
);
|
||||
$parents = $paginator->getCollection();
|
||||
} else {
|
||||
// 전체 조회
|
||||
$parentQuery->orderBy($orderBy, $orderDirection)->orderBy('id', $orderDirection);
|
||||
|
||||
if (! empty($relations)) {
|
||||
$parentQuery->with($relations);
|
||||
}
|
||||
|
||||
$parents = $parentQuery->get($columns);
|
||||
$paginator = null;
|
||||
}
|
||||
@@ -1052,10 +1066,9 @@ class PostRepository implements PostRepositoryInterface
|
||||
$inactiveBoardIds = $this->getInactiveBoardIds();
|
||||
$allExcludeIds = array_unique(array_merge($excludeBoardIds, $inactiveBoardIds));
|
||||
|
||||
// 관계/정렬은 지연 조인이 담당한다 (inner 는 키 컬럼만 조회)
|
||||
$query = Post::query()
|
||||
->where('board_posts.user_id', $userId)
|
||||
->with('board')
|
||||
->orderBy($orderColumn, $orderDirection);
|
||||
->where('board_posts.user_id', $userId);
|
||||
|
||||
if ($boardIdFilter) {
|
||||
$query->where('board_posts.board_id', $boardIdFilter);
|
||||
@@ -1078,7 +1091,26 @@ class PostRepository implements PostRepositoryInterface
|
||||
});
|
||||
}
|
||||
|
||||
$paginator = $query->paginate($perPage, ['*'], 'page', null, $cachedTotal);
|
||||
// 본문(content)은 목록 가공에 앞부분만 쓰이지만 태그 제거 후 길이가 줄어드는 것을 감안해
|
||||
// 넉넉히 잘라 읽는다. 잘라 읽기는 이번 페이지 분량(outer)에서만 일어난다.
|
||||
$listColumns = [
|
||||
'board_posts.id', 'board_posts.board_id', 'board_posts.user_id',
|
||||
'board_posts.title', 'board_posts.status', 'board_posts.is_secret',
|
||||
'board_posts.content_mode', 'board_posts.view_count', 'board_posts.comments_count',
|
||||
'board_posts.created_at', 'board_posts.updated_at', 'board_posts.deleted_at',
|
||||
// DB::raw 는 테이블 프리픽스가 적용되지 않는다. 단일 테이블 조회라 컬럼만 적으면 충분하다.
|
||||
DB::raw('SUBSTRING(content, 1, 1000) as content'),
|
||||
];
|
||||
|
||||
// 캐시된 total 을 그대로 통과시켜 COUNT 를 다시 수행하지 않는다
|
||||
$paginator = $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: $listColumns,
|
||||
sort: [['column' => $orderColumn, 'direction' => $orderDirection]],
|
||||
perPage: $perPage,
|
||||
relations: ['board'],
|
||||
total: $cachedTotal,
|
||||
);
|
||||
|
||||
// paginate 후 10건에만 PHP 가공 적용 (N+1 아님)
|
||||
$paginator->through(function ($post) {
|
||||
@@ -1125,59 +1157,88 @@ class PostRepository implements PostRepositoryInterface
|
||||
int $perPage,
|
||||
?int $cachedTotal = null
|
||||
): LengthAwarePaginator {
|
||||
// DB::raw() / whereRaw() 내부 raw SQL은 prefix 자동 적용이 안 되므로 명시적으로 처리
|
||||
$prefix = DB::getTablePrefix();
|
||||
$commentsTable = $prefix.'board_comments';
|
||||
$postsTable = $prefix.'board_posts';
|
||||
// 테이블명은 모델에서 얻는다 — 문자열로 박으면 테이블명이 바뀔 때 조용히 깨진다
|
||||
$postsTable = (new Post)->getTable();
|
||||
$commentsTable = (new Comment)->getTable();
|
||||
|
||||
// 비활성 게시판 제외 — JOIN 없이 인덱스 활용
|
||||
$inactiveBoardIds = $this->getInactiveBoardIds();
|
||||
$allExcludeIds = array_unique(array_merge($excludeBoardIds, $inactiveBoardIds));
|
||||
|
||||
$latestCommentSub = DB::table(DB::raw("{$commentsTable} as bc_outer"))
|
||||
->selectRaw('bc_outer.post_id, bc_outer.content, bc_outer.created_at')
|
||||
->whereRaw("bc_outer.id = (
|
||||
SELECT bc2.id FROM {$commentsTable} bc2
|
||||
WHERE bc2.post_id = bc_outer.post_id
|
||||
AND bc2.user_id = ?
|
||||
AND bc2.deleted_at IS NULL
|
||||
ORDER BY bc2.created_at DESC
|
||||
LIMIT 1
|
||||
) AND bc_outer.user_id = ? AND bc_outer.deleted_at IS NULL", [$userId, $userId]);
|
||||
/**
|
||||
* 내가 이 글에 단 댓글 조건 (검색어까지 반영 — 활동 판정 · 건수 집계 공통).
|
||||
*
|
||||
* @param \Illuminate\Contracts\Database\Eloquent\Builder $q 댓글 하위 쿼리
|
||||
*/
|
||||
$myComment = function ($q) use ($userId, $search) {
|
||||
$q->where('user_id', $userId)->whereNull('deleted_at');
|
||||
|
||||
$query = Post::query()
|
||||
->join(DB::raw("{$commentsTable} AS uc"), function ($join) use ($userId, $postsTable) {
|
||||
$join->on(DB::raw("{$postsTable}.id"), '=', DB::raw('uc.post_id'))
|
||||
->whereRaw('uc.user_id = ?', [$userId])
|
||||
->whereRaw('uc.deleted_at IS NULL');
|
||||
})
|
||||
->leftJoinSub($latestCommentSub, 'lc', 'board_posts.id', '=', 'lc.post_id')
|
||||
->select([
|
||||
'board_posts.*',
|
||||
DB::raw('COUNT(DISTINCT uc.id) as activity_count'),
|
||||
// board_posts.* 에 이미 comments_count 가 포함되므로 중복 지정 금지
|
||||
// (pagination count 쿼리가 subquery 로 감싸질 때 SQLSTATE[42S21] 유발)
|
||||
'lc.content as comment_content',
|
||||
'lc.created_at as comment_created_at',
|
||||
])
|
||||
->with('board')
|
||||
->groupBy('board_posts.id', 'board_posts.board_id', 'board_posts.comments_count', 'lc.content', 'lc.created_at')
|
||||
->orderBy($orderColumn, $orderDirection);
|
||||
if ($search) {
|
||||
$q->where('content', 'like', '%'.$this->escapeLikeKeyword($search).'%');
|
||||
}
|
||||
};
|
||||
|
||||
// "내가 댓글을 단 글" 집합은 EXISTS 로 정한다. 조인으로 행을 불린 뒤 groupBy 로 접는
|
||||
// 방식은 inner 가 읽는 행 수를 댓글 수만큼 늘리고, 그룹 쿼리라 총 건수도 서브쿼리로
|
||||
// 감싸야 한다. EXISTS 는 글 1건당 1행이라 둘 다 필요 없다.
|
||||
$query = Post::query()->whereHas('comments', $myComment);
|
||||
|
||||
if ($boardIdFilter) {
|
||||
$query->where('board_posts.board_id', $boardIdFilter);
|
||||
$query->where("{$postsTable}.board_id", $boardIdFilter);
|
||||
}
|
||||
|
||||
if (! empty($allExcludeIds)) {
|
||||
$query->whereNotIn('board_posts.board_id', $allExcludeIds);
|
||||
$query->whereNotIn("{$postsTable}.board_id", $allExcludeIds);
|
||||
}
|
||||
|
||||
if ($search) {
|
||||
$keyword = $this->escapeLikeKeyword($search);
|
||||
$query->where('uc.content', 'like', "%{$keyword}%");
|
||||
}
|
||||
// 목록 컬럼: 본문 전체 대신 앞부분만 (가공 후 표시 자수보다 넉넉히 잘라 읽는다).
|
||||
// SUBSTRING 은 빌더에 대응 표현이 없는 표준 SQL 함수라 이 한 곳만 raw 로 남긴다.
|
||||
// 테이블명·프리픽스는 문자열로 박지 않고 모델과 연결 설정에서 얻는다.
|
||||
$listColumns = [
|
||||
"{$postsTable}.id", "{$postsTable}.board_id", "{$postsTable}.user_id",
|
||||
"{$postsTable}.title", "{$postsTable}.status", "{$postsTable}.is_secret",
|
||||
"{$postsTable}.content_mode", "{$postsTable}.view_count", "{$postsTable}.comments_count",
|
||||
"{$postsTable}.created_at", "{$postsTable}.updated_at", "{$postsTable}.deleted_at",
|
||||
DB::raw('SUBSTRING('.DB::getTablePrefix().$postsTable.'.content, 1, 1000) as content'),
|
||||
'lc.content as comment_content',
|
||||
'lc.created_at as comment_created_at',
|
||||
];
|
||||
|
||||
$paginator = $query->paginate($perPage, ['*'], 'page', null, $cachedTotal);
|
||||
// 정렬은 항상 board_posts 컬럼(작성일/조회수)이라 inner 에서 그대로 적용된다.
|
||||
// 캐시된 total 이 있으면 COUNT 를 건너뛴다. 검색/게시판 필터가 걸린 조회는 캐시를 쓰지
|
||||
// 않아 total 이 null 로 들어오며, 이때 trait 이 그룹 쿼리를 서브쿼리로 감싸 그룹 수를 센다.
|
||||
$paginator = $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: $listColumns,
|
||||
sort: [['column' => $orderColumn, 'direction' => $orderDirection]],
|
||||
perPage: $perPage,
|
||||
relations: ['board'],
|
||||
keyName: 'id',
|
||||
total: $cachedTotal,
|
||||
// 최근 댓글 조회와 활동 건수 집계는 이번 페이지의 게시글에 대해서만 실행한다.
|
||||
// inner 에 두면 건너뛸 행 전체에 대해 상관 서브쿼리가 돌아간다.
|
||||
outerUsing: function ($outer) use ($userId, $myComment, $postsTable, $commentsTable) {
|
||||
// 글마다 "내가 단 댓글 중 가장 최근 1건" — 원래 raw SQL 로 쓰던 상관 서브쿼리를
|
||||
// 빌더로 옮겼다. created_at 동률에서 순서가 흔들리지 않도록 id 를 덧붙인다.
|
||||
$latest = DB::table("{$commentsTable} as bc_outer")
|
||||
->select('bc_outer.post_id', 'bc_outer.content', 'bc_outer.created_at')
|
||||
->where('bc_outer.user_id', $userId)
|
||||
->whereNull('bc_outer.deleted_at')
|
||||
->where('bc_outer.id', '=', function ($q) use ($userId, $commentsTable) {
|
||||
$q->select('bc2.id')
|
||||
->from("{$commentsTable} as bc2")
|
||||
->whereColumn('bc2.post_id', 'bc_outer.post_id')
|
||||
->where('bc2.user_id', $userId)
|
||||
->whereNull('bc2.deleted_at')
|
||||
->orderByDesc('bc2.created_at')
|
||||
->orderByDesc('bc2.id')
|
||||
->limit(1);
|
||||
});
|
||||
|
||||
$outer->leftJoinSub($latest, 'lc', "{$postsTable}.id", '=', 'lc.post_id')
|
||||
->withCount(['comments as activity_count' => $myComment]);
|
||||
},
|
||||
);
|
||||
|
||||
// paginate 후 10건에만 PHP 가공 적용
|
||||
$paginator->through(function ($post) {
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
namespace Modules\Sirsoft\Board\Repositories;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Database\QueryException;
|
||||
use Illuminate\Pagination\LengthAwarePaginator;
|
||||
@@ -13,6 +16,8 @@ use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Board\Enums\ReportStatus;
|
||||
use Modules\Sirsoft\Board\Exceptions\DuplicateReportException;
|
||||
use Modules\Sirsoft\Board\Models\Comment;
|
||||
use Modules\Sirsoft\Board\Models\Post;
|
||||
use Modules\Sirsoft\Board\Models\Report;
|
||||
use Modules\Sirsoft\Board\Models\ReportLog;
|
||||
use Modules\Sirsoft\Board\Repositories\Contracts\ReportRepositoryInterface;
|
||||
@@ -24,16 +29,32 @@ use Modules\Sirsoft\Board\Repositories\Contracts\ReportRepositoryInterface;
|
||||
*/
|
||||
class ReportRepository implements ReportRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/**
|
||||
* 신고 대상 종류(`target_type`) → 대상 모델 매핑.
|
||||
*
|
||||
* 신고는 게시글 또는 댓글을 가리키므로 대상 테이블이 갈린다. 갈래를 SQL CASE 문자열로
|
||||
* 잇는 대신 이 매핑을 돌며 갈래별 빌더 조건을 만든다.
|
||||
*
|
||||
* @var array<string, class-string<Model>>
|
||||
*/
|
||||
private const TARGET_MODELS = [
|
||||
'post' => Post::class,
|
||||
'comment' => Comment::class,
|
||||
];
|
||||
|
||||
/**
|
||||
* 신고 목록을 페이지네이션하여 조회합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @return LengthAwarePaginator 페이지네이션된 신고 목록
|
||||
*/
|
||||
public function paginate(array $filters = [], int $perPage = 15): LengthAwarePaginator
|
||||
{
|
||||
$query = Report::query()
|
||||
->with(['board', 'author', 'processor']);
|
||||
$query = Report::query();
|
||||
|
||||
// 권한 스코프 필터링
|
||||
PermissionHelper::applyPermissionScope($query, 'sirsoft-board.reports.view');
|
||||
@@ -64,10 +85,14 @@ class ReportRepository implements ReportRepositoryInterface
|
||||
$query->where('created_at', '<=', $filters['reported_at_to'].' 23:59:59');
|
||||
}
|
||||
|
||||
// 정렬
|
||||
$query->orderBy('created_at', 'desc');
|
||||
|
||||
return $query->paginate($perPage);
|
||||
// 지연 조인: inner 는 id 만 훑고, 관계 로딩은 해당 페이지에만 적용된다
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: [['column' => 'created_at', 'direction' => 'desc']],
|
||||
perPage: $perPage,
|
||||
relations: ['board', 'author', 'processor'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -225,18 +250,35 @@ class ReportRepository implements ReportRepositoryInterface
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @return LengthAwarePaginator 페이지네이션된 신고 케이스 목록
|
||||
*/
|
||||
public function paginateGrouped(array $filters = [], int $perPage = 15): LengthAwarePaginator
|
||||
{
|
||||
$tableName = (new Report)->getTable();
|
||||
$prefix = DB::getTablePrefix();
|
||||
$fullTableName = $prefix.$tableName;
|
||||
$logsTable = $prefix.'boards_report_logs';
|
||||
$postsTable = $prefix.'board_posts';
|
||||
$commentsTable = $prefix.'board_comments';
|
||||
// 테이블명은 전부 모델에서 얻는다 (문자열 하드코딩 금지)
|
||||
$reportsTable = (new Report)->getTable();
|
||||
|
||||
$query = Report::query()
|
||||
->with(['board', 'author', 'processor', 'logs' => fn ($q) => $q->oldest()->limit(1)->with('reporter')]);
|
||||
/**
|
||||
* 대상(게시글/댓글) 컬럼을 신고 행에 대응시켜 읽는 상관 서브쿼리를 만듭니다.
|
||||
*
|
||||
* 신고는 target_type 에 따라 게시글 또는 댓글을 가리키므로 대상 테이블이 갈린다.
|
||||
* 두 갈래를 CASE 로 잇는 대신, 갈래마다 빌더 서브쿼리를 만들고 그 중 조건에 맞는
|
||||
* 쪽만 값을 내도록 한다 — 결과는 같고 SQL 문자열 조립이 사라진다.
|
||||
*
|
||||
* @param class-string<Model> $model 대상 모델
|
||||
* @param string $targetType 이 갈래가 담당하는 target_type 값
|
||||
* @param string $column 읽어올 대상 컬럼
|
||||
* @return Builder 상관 서브쿼리
|
||||
*/
|
||||
$targetColumn = function (string $model, string $targetType, string $column) use ($reportsTable) {
|
||||
return $model::query()
|
||||
->select($column)
|
||||
->whereColumn((new $model)->getTable().'.board_id', "{$reportsTable}.board_id")
|
||||
->whereColumn((new $model)->getTable().'.id', "{$reportsTable}.target_id")
|
||||
->where("{$reportsTable}.target_type", $targetType)
|
||||
->limit(1);
|
||||
};
|
||||
|
||||
$query = Report::query();
|
||||
|
||||
// 상태 필터
|
||||
if (! empty($filters['status'])) {
|
||||
@@ -272,52 +314,64 @@ class ReportRepository implements ReportRepositoryInterface
|
||||
// 검색
|
||||
$this->applySearchConditions($query, $filters, ['post_title']);
|
||||
|
||||
// 서브쿼리: 신고 건수, 대상 상태, trigger_type, post_id
|
||||
$query->selectRaw("`{$fullTableName}`.*")
|
||||
->selectRaw("(
|
||||
SELECT COUNT(*)
|
||||
FROM `{$logsTable}`
|
||||
WHERE `{$logsTable}`.report_id = `{$fullTableName}`.id
|
||||
) AS report_count")
|
||||
->selectRaw("(
|
||||
CASE `{$fullTableName}`.target_type
|
||||
WHEN 'post' THEN (SELECT bp.status FROM `{$postsTable}` bp WHERE bp.board_id = `{$fullTableName}`.board_id AND bp.id = `{$fullTableName}`.target_id LIMIT 1)
|
||||
WHEN 'comment' THEN (SELECT bc.status FROM `{$commentsTable}` bc WHERE bc.board_id = `{$fullTableName}`.board_id AND bc.id = `{$fullTableName}`.target_id LIMIT 1)
|
||||
END
|
||||
) AS target_status")
|
||||
->selectRaw("(
|
||||
CASE `{$fullTableName}`.target_type
|
||||
WHEN 'post' THEN (SELECT bp.trigger_type FROM `{$postsTable}` bp WHERE bp.board_id = `{$fullTableName}`.board_id AND bp.id = `{$fullTableName}`.target_id LIMIT 1)
|
||||
WHEN 'comment' THEN (SELECT bc.trigger_type FROM `{$commentsTable}` bc WHERE bc.board_id = `{$fullTableName}`.board_id AND bc.id = `{$fullTableName}`.target_id LIMIT 1)
|
||||
END
|
||||
) AS target_trigger_type")
|
||||
->selectRaw("(
|
||||
CASE `{$fullTableName}`.target_type
|
||||
WHEN 'post' THEN `{$fullTableName}`.target_id
|
||||
WHEN 'comment' THEN (SELECT bc.post_id FROM `{$commentsTable}` bc WHERE bc.board_id = `{$fullTableName}`.board_id AND bc.id = `{$fullTableName}`.target_id LIMIT 1)
|
||||
END
|
||||
) AS target_post_id");
|
||||
|
||||
// 대상 상태 필터
|
||||
// 대상 상태 필터 — 대상 종류에 따라 갈리는 조건을 CASE 문자열 대신 갈래별 조건으로 쓴다
|
||||
if (! empty($filters['target_status'])) {
|
||||
$targetStatuses = is_array($filters['target_status']) ? $filters['target_status'] : [$filters['target_status']];
|
||||
$targetStatuses = array_filter($targetStatuses, fn ($v) => $v !== 'all');
|
||||
|
||||
if (! empty($targetStatuses)) {
|
||||
$placeholders = implode(',', array_fill(0, count($targetStatuses), '?'));
|
||||
$query->whereRaw("(
|
||||
CASE `{$fullTableName}`.target_type
|
||||
WHEN 'post' THEN (SELECT bp.status FROM `{$postsTable}` bp WHERE bp.board_id = `{$fullTableName}`.board_id AND bp.id = `{$fullTableName}`.target_id LIMIT 1)
|
||||
WHEN 'comment' THEN (SELECT bc.status FROM `{$commentsTable}` bc WHERE bc.board_id = `{$fullTableName}`.board_id AND bc.id = `{$fullTableName}`.target_id LIMIT 1)
|
||||
END
|
||||
) IN ({$placeholders})", $targetStatuses);
|
||||
$query->where(function (Builder $outerWhere) use ($targetStatuses, $reportsTable) {
|
||||
foreach (self::TARGET_MODELS as $targetType => $model) {
|
||||
$outerWhere->orWhere(function (Builder $branch) use ($targetType, $model, $targetStatuses, $reportsTable) {
|
||||
$branch->where("{$reportsTable}.target_type", $targetType)
|
||||
->whereIn("{$reportsTable}.target_id", $model::query()
|
||||
->select('id')
|
||||
->whereIn('status', $targetStatuses)
|
||||
->whereColumn((new $model)->getTable().'.board_id', "{$reportsTable}.board_id"));
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 정렬: last_reported_at DESC (재신고 시 위로 올라옴)
|
||||
$sortOrder = $filters['sort_order'] ?? 'desc';
|
||||
$query->orderBy('last_reported_at', $sortOrder);
|
||||
$sortOrder = $this->normalizeSortDirection($filters['sort_order'] ?? null);
|
||||
|
||||
return $query->paginate($perPage);
|
||||
$paginator = $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ["{$reportsTable}.*"],
|
||||
sort: [['column' => 'last_reported_at', 'direction' => $sortOrder]],
|
||||
perPage: $perPage,
|
||||
relations: ['board', 'author', 'processor', 'logs' => fn ($q) => $q->oldest()->limit(1)->with('reporter')],
|
||||
// 신고 건수와 대상(게시글/댓글) 정보는 스캔되는 행마다 계산되므로
|
||||
// outer(이번 페이지 $perPage 건)에서만 붙인다.
|
||||
outerUsing: function (Builder $outer) use ($reportsTable, $targetColumn) {
|
||||
$outer->select("{$reportsTable}.*")->withCount(['logs as report_count']);
|
||||
|
||||
foreach (self::TARGET_MODELS as $targetType => $model) {
|
||||
$outer->addSelect([
|
||||
"target_status_{$targetType}" => $targetColumn($model, $targetType, 'status'),
|
||||
"target_trigger_type_{$targetType}" => $targetColumn($model, $targetType, 'trigger_type'),
|
||||
]);
|
||||
}
|
||||
|
||||
// 대상 글 ID — 게시글 신고는 target_id 자체, 댓글 신고는 그 댓글이 달린 글
|
||||
$outer->addSelect(['target_post_id_comment' => $targetColumn(Comment::class, 'comment', 'post_id')]);
|
||||
},
|
||||
);
|
||||
|
||||
// 갈래별로 나눠 읽은 대상 정보를 화면이 쓰는 단일 속성으로 합친다.
|
||||
// 이번 페이지 항목에만 적용되므로 추가 조회가 발생하지 않는다.
|
||||
return $paginator->through(function (Report $report) {
|
||||
$report->setAttribute('target_status', $report->target_status_post ?? $report->target_status_comment);
|
||||
$report->setAttribute('target_trigger_type', $report->target_trigger_type_post ?? $report->target_trigger_type_comment);
|
||||
$report->setAttribute(
|
||||
'target_post_id',
|
||||
$report->target_type === 'post' ? $report->target_id : $report->target_post_id_comment
|
||||
);
|
||||
|
||||
return $report;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -525,12 +579,15 @@ class ReportRepository implements ReportRepositoryInterface
|
||||
* @param int $reportId 신고 케이스 ID
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @param int $page 페이지 번호
|
||||
* @return LengthAwarePaginator 페이지네이션된 신고자 로그
|
||||
*/
|
||||
public function paginateLogsByReport(int $reportId, int $perPage = 10, int $page = 1): LengthAwarePaginator
|
||||
{
|
||||
return ReportLog::where('report_id', $reportId)
|
||||
->with('reporter')
|
||||
->latest()
|
||||
// audit:allow repository-paginate-column-pruning reason: 신고 케이스 1건에 종속된 신고자 로그 —
|
||||
// where(report_id) 로 이미 좁혀져 OFFSET 이 깊어질 수 없다
|
||||
->paginate($perPage, ['*'], 'page', $page);
|
||||
}
|
||||
|
||||
@@ -583,12 +640,12 @@ class ReportRepository implements ReportRepositoryInterface
|
||||
* ID 목록으로 조회하고 ID 키 맵으로 반환합니다 (bulk activity log lookup).
|
||||
*
|
||||
* @param array<int, int> $ids ID 목록
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
* @return Collection
|
||||
*/
|
||||
public function findByIdsKeyed(array $ids): \Illuminate\Database\Eloquent\Collection
|
||||
public function findByIdsKeyed(array $ids): Collection
|
||||
{
|
||||
if (empty($ids)) {
|
||||
return new \Illuminate\Database\Eloquent\Collection();
|
||||
return new Collection;
|
||||
}
|
||||
|
||||
return Report::whereIn('id', $ids)->get()->keyBy('id');
|
||||
|
||||
@@ -16,6 +16,7 @@ use Modules\Sirsoft\Board\Http\Requests\UpdateBoardRequest;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Models\BoardType;
|
||||
use Modules\Sirsoft\Board\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
|
||||
/**
|
||||
* 게시판 FormRequest 검증 통합 테스트
|
||||
@@ -287,26 +288,30 @@ class BoardRequestTest extends ModuleTestCase
|
||||
/**
|
||||
* Mock Board 객체 생성
|
||||
*/
|
||||
private function getMockBoard(): object
|
||||
private function getMockBoard(bool $useFileUpload = true): object
|
||||
{
|
||||
return (object) [
|
||||
'slug' => 'notice',
|
||||
'categories' => ['일반', '중요'],
|
||||
// prepareForValidation() 이 exclude_if 판정 기준으로 주입하는 저장값
|
||||
'use_file_upload' => $useFileUpload,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateBoardRequest 인스턴스 생성 (route 파라미터 포함)
|
||||
*
|
||||
* @param bool $boardUseFileUpload 기존 게시판에 저장된 첨부 사용 여부
|
||||
*/
|
||||
private function makeUpdateRequest(): UpdateBoardRequest
|
||||
private function makeUpdateRequest(bool $boardUseFileUpload = true): UpdateBoardRequest
|
||||
{
|
||||
$request = new UpdateBoardRequest;
|
||||
|
||||
$request->setRouteResolver(function () {
|
||||
$request->setRouteResolver(function () use ($boardUseFileUpload) {
|
||||
$route = \Mockery::mock(Route::class);
|
||||
$route->shouldReceive('parameter')
|
||||
->with('board', null)
|
||||
->andReturn($this->getMockBoard());
|
||||
->andReturn($this->getMockBoard($boardUseFileUpload));
|
||||
|
||||
return $route;
|
||||
});
|
||||
@@ -314,6 +319,27 @@ class BoardRequestTest extends ModuleTestCase
|
||||
return $request;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepareForValidation() 을 거친 검증 입력을 만듭니다.
|
||||
*
|
||||
* `Validator::make($data, $request->rules())` 만으로는 전처리가 실행되지 않아
|
||||
* 조건 필드 주입(기존 게시판 값)을 검증할 수 없다.
|
||||
*
|
||||
* @param UpdateBoardRequest $request 대상 요청
|
||||
* @param array<string, mixed> $data 전송 페이로드
|
||||
* @return array<string, mixed> 전처리를 마친 입력
|
||||
*/
|
||||
private function prepareUpdateInput(UpdateBoardRequest $request, array $data): array
|
||||
{
|
||||
$request->merge($data);
|
||||
|
||||
$prepare = new \ReflectionMethod($request, 'prepareForValidation');
|
||||
$prepare->setAccessible(true);
|
||||
$prepare->invoke($request);
|
||||
|
||||
return $request->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 정상적인 수정 데이터
|
||||
*/
|
||||
@@ -1010,21 +1036,89 @@ class BoardRequestTest extends ModuleTestCase
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateBoardRequest - allowed_extensions 빈 배열 전송 시 검증 실패해야 함 (회귀)
|
||||
* UpdateBoardRequest - 첨부 사용 게시판에서 allowed_extensions 빈 배열은 실패 (케이스 2)
|
||||
*
|
||||
* sometimes + array + min:1 로, 키가 전송되면 빈 배열은 차단된다.
|
||||
* (nullable 제거로 빈 배열이 통과되던 버그 차단)
|
||||
* 첨부를 쓰는 게시판에 확장자를 비워 저장하면 이후 모든 파일이 거부되므로 차단한다.
|
||||
* 첨부 미사용 게시판은 exclude_if 로 배제되어 통과한다(케이스 3 참조) — 이 테스트는
|
||||
* 그 경계 중 "차단되어야 하는 쪽"만 고정한다.
|
||||
*/
|
||||
public function test_update_request_empty_allowed_extensions_fails(): void
|
||||
public function test_update_request_empty_allowed_extensions_fails_when_upload_enabled(): void
|
||||
{
|
||||
$request = $this->makeUpdateRequest();
|
||||
|
||||
$validator = Validator::make(['allowed_extensions' => []], $request->rules());
|
||||
$validator = Validator::make(
|
||||
['use_file_upload' => true, 'allowed_extensions' => []],
|
||||
$request->rules()
|
||||
);
|
||||
|
||||
$this->assertFalse($validator->passes(), 'allowed_extensions=[] 전송 시 실패해야 함');
|
||||
$this->assertFalse($validator->passes(), 'use_file_upload=true + [] 는 실패해야 함');
|
||||
$this->assertArrayHasKey('allowed_extensions', $validator->errors()->toArray());
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateBoardRequest - 첨부 미사용 게시판의 빈 확장자는 통과 (케이스 3 · GH #78)
|
||||
*/
|
||||
public function test_update_request_empty_allowed_extensions_passes_when_upload_disabled(): void
|
||||
{
|
||||
$request = $this->makeUpdateRequest();
|
||||
|
||||
$validator = Validator::make(
|
||||
['use_file_upload' => false, 'allowed_extensions' => []],
|
||||
$request->rules()
|
||||
);
|
||||
|
||||
$this->assertTrue($validator->passes(), 'use_file_upload=false 이면 빈 확장자도 통과해야 함');
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateBoardRequest - 토글 미전송 + 확장자 전송 시 기존 게시판 값을 따른다 (케이스 5)
|
||||
*
|
||||
* exclude_if 는 조건 필드가 데이터에 없으면 배제하지 않는다. 부분 수정 요청이
|
||||
* use_file_upload 없이 allowed_extensions 만 보내면 첨부 미사용 게시판인데도
|
||||
* 확장자 필수 규칙이 발화하므로, prepareForValidation() 이 저장값을 주입해야 한다.
|
||||
*/
|
||||
public function test_update_request_omitted_toggle_follows_stored_board_value(): void
|
||||
{
|
||||
// 저장된 게시판이 첨부 미사용 → 빈 확장자 통과
|
||||
$disabled = $this->makeUpdateRequest(boardUseFileUpload: false);
|
||||
$disabledInput = $this->prepareUpdateInput($disabled, ['allowed_extensions' => []]);
|
||||
|
||||
$this->assertFalse(
|
||||
$disabledInput['use_file_upload'],
|
||||
'토글 미전송 시 기존 게시판의 use_file_upload 가 주입되어야 함'
|
||||
);
|
||||
$this->assertTrue(
|
||||
Validator::make($disabledInput, $disabled->rules())->passes(),
|
||||
'첨부 미사용 게시판은 토글 미전송 + 빈 확장자도 통과해야 함'
|
||||
);
|
||||
|
||||
// 저장된 게시판이 첨부 사용 → 빈 확장자 차단
|
||||
$enabled = $this->makeUpdateRequest(boardUseFileUpload: true);
|
||||
$enabledInput = $this->prepareUpdateInput($enabled, ['allowed_extensions' => []]);
|
||||
|
||||
$this->assertTrue($enabledInput['use_file_upload']);
|
||||
$this->assertFalse(
|
||||
Validator::make($enabledInput, $enabled->rules())->passes(),
|
||||
'첨부 사용 게시판은 토글 미전송이어도 빈 확장자를 차단해야 함'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateBoardRequest - 토글·확장자 모두 미전송이면 주입하지 않는다 (케이스 4 인접)
|
||||
*
|
||||
* 확장자를 건드리지 않는 부분 수정에 조건 필드를 주입하면, 보내지도 않은 토글이
|
||||
* 검증 대상으로 올라온다.
|
||||
*/
|
||||
public function test_update_request_does_not_inject_toggle_when_extensions_omitted(): void
|
||||
{
|
||||
$request = $this->makeUpdateRequest(boardUseFileUpload: false);
|
||||
|
||||
$input = $this->prepareUpdateInput($request, ['per_page' => 30]);
|
||||
|
||||
$this->assertArrayNotHasKey('use_file_upload', $input);
|
||||
$this->assertTrue(Validator::make($input, $request->rules())->passes());
|
||||
}
|
||||
|
||||
/**
|
||||
* UpdateBoardRequest - allowed_extensions 미전송(부분 수정)은 통과해야 함 (회귀 방지)
|
||||
*
|
||||
@@ -1250,8 +1344,6 @@ class BoardRequestTest extends ModuleTestCase
|
||||
*
|
||||
* 0 = NEW 배지 표시 안 함 (Post::isNew() 가 0 을 정상 처리).
|
||||
*
|
||||
* @dataProvider newDisplayHoursProvider
|
||||
*
|
||||
* @scenario case=new_display_hours_zero
|
||||
*
|
||||
* @effects new_display_hours_zero_passes, new_display_hours_out_of_range_fails
|
||||
@@ -1259,6 +1351,7 @@ class BoardRequestTest extends ModuleTestCase
|
||||
* @param mixed $value new_display_hours 값
|
||||
* @param bool $shouldPass 통과 기대 여부
|
||||
*/
|
||||
#[DataProvider('newDisplayHoursProvider')]
|
||||
public function test_update_matrix_new_display_hours_boundaries(mixed $value, bool $shouldPass): void
|
||||
{
|
||||
$request = $this->makeUpdateRequest();
|
||||
@@ -1408,14 +1501,13 @@ class BoardRequestTest extends ModuleTestCase
|
||||
* config('sirsoft-board.limits') 는 min_title_length_min / min_comment_length_min 을
|
||||
* 0 으로 선언하고 있으므로 하드코딩된 min:1 은 계약 위반이다.
|
||||
*
|
||||
* @dataProvider settingsZeroLowerBoundProvider
|
||||
*
|
||||
* @scenario case=zero_lower_bound_length_fields
|
||||
*
|
||||
* @effects zero_lower_bound_length_fields_pass
|
||||
*
|
||||
* @param string $field basic_defaults 하위 필드명
|
||||
*/
|
||||
#[DataProvider('settingsZeroLowerBoundProvider')]
|
||||
public function test_settings_matrix_zero_lower_bounds_pass(string $field): void
|
||||
{
|
||||
$request = new StoreBoardSettingsRequest;
|
||||
|
||||
+4
-4
@@ -8,6 +8,7 @@ use Illuminate\Support\LazyCollection;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Repositories\Contracts\BoardRepositoryInterface;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
use PHPUnit\Framework\Attributes\Group;
|
||||
|
||||
/**
|
||||
* BoardRepository::streamActiveForSitemap 단위 테스트
|
||||
@@ -16,11 +17,10 @@ use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
* - 순회자(LazyCollection) 를 반환한다 (전체 적재 금지)
|
||||
* - sitemap 에 필요한 컬럼만 적재한다 (전컬럼 적재 회귀 차단)
|
||||
* - 활성 게시판만 반환한다
|
||||
*
|
||||
* @group board
|
||||
* @group unit
|
||||
* @group seo
|
||||
*/
|
||||
#[Group('board')]
|
||||
#[Group('unit')]
|
||||
#[Group('seo')]
|
||||
class BoardRepositorySitemapTest extends BoardTestCase
|
||||
{
|
||||
private BoardRepositoryInterface $repository;
|
||||
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Tests\Unit\Repositories;
|
||||
|
||||
// ModuleTestCase 수동 로드 (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use Illuminate\Pagination\Paginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Board\Repositories\CommentRepository;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
|
||||
/**
|
||||
* 마이페이지 「내가 쓴 댓글」 목록 지연 조인 회귀 테스트
|
||||
*
|
||||
* 이 목록은 게시글 목록과 달리 **삭제된 게시글의 댓글 제외**(whereExists)와
|
||||
* **캐시된 총 건수 주입**이 함께 걸려 있다. 조회 방식이 2단계로 바뀌면서 두 성질 중
|
||||
* 하나라도 inner/outer 한쪽에만 적용되면 화면에서는 "이미 지운 글의 댓글이 보인다" 또는
|
||||
* "마지막 페이지가 비어 있다" 로만 드러난다. 그 성질들을 고정한다.
|
||||
*
|
||||
* @scenario case=user_comment_list_deferred_join
|
||||
*
|
||||
* @effects soft_deleted_excluded, page_boundary_stable, cached_total_skips_count
|
||||
*/
|
||||
class CommentListDeferredJoinTest extends BoardTestCase
|
||||
{
|
||||
private CommentRepository $repository;
|
||||
|
||||
/** 수집된 실행 쿼리 SQL 목록 */
|
||||
private array $queries = [];
|
||||
|
||||
/** 댓글 작성자로 사용할 사용자 ID */
|
||||
private int $userId = 4242;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->repository = app(CommentRepository::class);
|
||||
}
|
||||
|
||||
/** 쿼리 로그 수집을 시작합니다. */
|
||||
private function startCapture(): void
|
||||
{
|
||||
$this->queries = [];
|
||||
|
||||
DB::listen(function ($query) {
|
||||
$this->queries[] = $query->sql;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집된 쿼리 중 조건에 맞는 것만 돌려줍니다.
|
||||
*
|
||||
* @param string $needle 포함 문자열
|
||||
* @return array<int, string> 일치 쿼리 목록
|
||||
*/
|
||||
private function queriesContaining(string $needle): array
|
||||
{
|
||||
return array_values(array_filter($this->queries, fn (string $sql) => str_contains($sql, $needle)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 이 사용자의 댓글을 생성합니다.
|
||||
*
|
||||
* @param int $postId 대상 게시글 ID
|
||||
* @param array<string, mixed> $attributes 추가 속성
|
||||
* @return int 생성된 댓글 ID
|
||||
*/
|
||||
private function createUserComment(int $postId, array $attributes = []): int
|
||||
{
|
||||
return $this->createTestComment($postId, array_merge(['user_id' => $this->userId], $attributes));
|
||||
}
|
||||
|
||||
public function test_soft_deleted_comments_are_excluded(): void
|
||||
{
|
||||
$postId = $this->createTestPost();
|
||||
$this->createUserComment($postId, ['content' => '살아있는 댓글']);
|
||||
$this->createUserComment($postId, ['content' => '삭제된 댓글', 'deleted_at' => now()]);
|
||||
|
||||
$result = $this->repository->getUserComments($this->userId, [], 10);
|
||||
$contents = collect($result->items())->pluck('content')->all();
|
||||
|
||||
$this->assertContains('살아있는 댓글', $contents);
|
||||
$this->assertNotContains('삭제된 댓글', $contents);
|
||||
$this->assertSame(1, $result->total());
|
||||
}
|
||||
|
||||
public function test_comments_of_soft_deleted_posts_are_excluded(): void
|
||||
{
|
||||
$livePostId = $this->createTestPost(['title' => '살아있는 글']);
|
||||
$deletedPostId = $this->createTestPost(['title' => '삭제된 글', 'deleted_at' => now()]);
|
||||
|
||||
$this->createUserComment($livePostId, ['content' => '보여야 하는 댓글']);
|
||||
$this->createUserComment($deletedPostId, ['content' => '숨겨져야 하는 댓글']);
|
||||
|
||||
$result = $this->repository->getUserComments($this->userId, [], 10);
|
||||
$contents = collect($result->items())->pluck('content')->all();
|
||||
|
||||
$this->assertSame(['보여야 하는 댓글'], $contents);
|
||||
$this->assertSame(1, $result->total(), '삭제된 글의 댓글은 총 건수에서도 빠져야 한다');
|
||||
}
|
||||
|
||||
public function test_other_users_comments_are_not_included(): void
|
||||
{
|
||||
$postId = $this->createTestPost();
|
||||
$this->createUserComment($postId, ['content' => '내 댓글']);
|
||||
$this->createTestComment($postId, ['user_id' => $this->userId + 1, 'content' => '남의 댓글']);
|
||||
|
||||
$result = $this->repository->getUserComments($this->userId, [], 10);
|
||||
|
||||
$this->assertSame(['내 댓글'], collect($result->items())->pluck('content')->all());
|
||||
}
|
||||
|
||||
public function test_pages_do_not_overlap_and_last_page_is_reported(): void
|
||||
{
|
||||
$postId = $this->createTestPost();
|
||||
|
||||
for ($i = 1; $i <= 15; $i++) {
|
||||
$this->createUserComment($postId, [
|
||||
'content' => "댓글 {$i}",
|
||||
'created_at' => now()->subMinutes(20 - $i),
|
||||
]);
|
||||
}
|
||||
|
||||
// 저장소는 페이지 번호를 인자로 받지 않고 Paginator 가 요청에서 해석한다.
|
||||
// 단위 테스트에는 요청 컨텍스트가 없으므로 리졸버로 현재 페이지를 지정한다.
|
||||
Paginator::currentPageResolver(fn () => 1);
|
||||
$page1 = $this->repository->getUserComments($this->userId, [], 10);
|
||||
|
||||
Paginator::currentPageResolver(fn () => 2);
|
||||
$page2 = $this->repository->getUserComments($this->userId, [], 10);
|
||||
|
||||
Paginator::currentPageResolver(fn () => 1);
|
||||
|
||||
$this->assertSame(15, $page1->total());
|
||||
$this->assertSame(2, $page1->lastPage());
|
||||
$this->assertCount(10, $page1->items());
|
||||
$this->assertCount(5, $page2->items(), '마지막 페이지는 남은 5건만 있어야 한다');
|
||||
|
||||
$firstIds = collect($page1->items())->pluck('id')->all();
|
||||
$secondIds = collect($page2->items())->pluck('id')->all();
|
||||
|
||||
$this->assertEmpty(array_intersect($firstIds, $secondIds), '페이지 간 중복 행이 없어야 한다');
|
||||
$this->assertCount(15, array_unique(array_merge($firstIds, $secondIds)), '누락된 행이 없어야 한다');
|
||||
}
|
||||
|
||||
public function test_search_filter_counts_only_matching_rows(): void
|
||||
{
|
||||
$postId = $this->createTestPost();
|
||||
$this->createUserComment($postId, ['content' => '검색어 포함 댓글 A']);
|
||||
$this->createUserComment($postId, ['content' => '검색어 포함 댓글 B']);
|
||||
$this->createUserComment($postId, ['content' => '무관한 댓글']);
|
||||
|
||||
$result = $this->repository->getUserComments($this->userId, ['search' => '검색어'], 10);
|
||||
|
||||
$this->assertSame(2, $result->total(), '검색 조건이 총 건수에 반영되어야 한다');
|
||||
$this->assertCount(2, $result->items());
|
||||
}
|
||||
|
||||
public function test_cached_total_skips_the_count_query(): void
|
||||
{
|
||||
$postId = $this->createTestPost();
|
||||
$this->createUserComment($postId, ['content' => '댓글']);
|
||||
|
||||
$this->startCapture();
|
||||
$result = $this->repository->getUserComments($this->userId, ['cached_total' => 999], 10);
|
||||
|
||||
$this->assertEmpty($this->queriesContaining('count(*)'), '캐시된 total 이 있으면 COUNT 를 실행하지 않아야 한다');
|
||||
$this->assertSame(999, $result->total());
|
||||
}
|
||||
|
||||
public function test_offset_scan_does_not_read_comment_content(): void
|
||||
{
|
||||
$postId = $this->createTestPost();
|
||||
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$this->createUserComment($postId, ['content' => "댓글 본문 {$i}"]);
|
||||
}
|
||||
|
||||
$this->startCapture();
|
||||
$this->repository->getUserComments($this->userId, [], 10);
|
||||
|
||||
$offsetQueries = $this->queriesContaining('offset');
|
||||
|
||||
$this->assertNotEmpty($offsetQueries, 'inner 는 OFFSET 으로 ID 집합을 구해야 한다');
|
||||
|
||||
foreach ($offsetQueries as $sql) {
|
||||
$this->assertStringNotContainsString(
|
||||
'content`',
|
||||
$sql,
|
||||
'OFFSET 스캔 구간에서 댓글 본문을 읽으면 안 된다'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Tests\Unit\Repositories;
|
||||
|
||||
// ModuleTestCase 수동 로드 (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Board\Repositories\PostRepository;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
|
||||
/**
|
||||
* 게시글 목록 지연 조인 회귀 테스트
|
||||
*
|
||||
* 목록은 이제 "이번 페이지의 원글 ID 를 먼저 구하고, 그 ID 에 대해서만 목록 컬럼과 관계를
|
||||
* 읽는" 2단계 조회다. 이 화면은 공지 병합·답글 트리·다음 페이지 판정이 얽혀 있어, 조회 방식
|
||||
* 변경이 조용히 깨지면 화면에서 빈 값이나 누락으로만 드러난다. 그 성질들을 고정한다.
|
||||
*/
|
||||
class PostListDeferredJoinTest extends BoardTestCase
|
||||
{
|
||||
private PostRepository $repository;
|
||||
|
||||
/** 수집된 실행 쿼리 SQL 목록 */
|
||||
private array $queries = [];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->repository = app(PostRepository::class);
|
||||
}
|
||||
|
||||
/** 쿼리 로그 수집을 시작합니다. */
|
||||
private function startCapture(): void
|
||||
{
|
||||
$this->queries = [];
|
||||
|
||||
DB::listen(function ($query) {
|
||||
$this->queries[] = $query->sql;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집된 쿼리 중 조건에 맞는 것만 돌려줍니다.
|
||||
*
|
||||
* @param string $needle 포함 문자열
|
||||
* @return array<int, string> 일치 쿼리 목록
|
||||
*/
|
||||
private function queriesContaining(string $needle): array
|
||||
{
|
||||
return array_values(array_filter($this->queries, fn (string $sql) => str_contains($sql, $needle)));
|
||||
}
|
||||
|
||||
public function test_offset_scan_does_not_read_content_preview(): void
|
||||
{
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$this->createTestPost(['title' => "게시글 {$i}"]);
|
||||
}
|
||||
|
||||
$this->startCapture();
|
||||
$this->repository->paginate($this->board->slug, ['page' => 2], 10);
|
||||
|
||||
$offsetQueries = $this->queriesContaining('offset');
|
||||
|
||||
$this->assertNotEmpty($offsetQueries, '페이지 조회에는 OFFSET 쿼리가 있어야 한다');
|
||||
|
||||
foreach ($offsetQueries as $sql) {
|
||||
// 본문 앞부분을 잘라 읽는 것도 오버플로 페이지를 그대로 읽으므로 프루닝이 아니다.
|
||||
// 잘라 읽기는 이번 페이지 분량(outer)에서만 일어나야 한다.
|
||||
$this->assertStringNotContainsString('SUBSTRING', $sql);
|
||||
$this->assertStringNotContainsString('content', $sql);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_page_one_shows_notices_and_page_two_does_not(): void
|
||||
{
|
||||
$this->createTestPost(['title' => '공지사항', 'is_notice' => true]);
|
||||
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$this->createTestPost(['title' => "일반글 {$i}"]);
|
||||
}
|
||||
|
||||
$page1 = $this->repository->paginate($this->board->slug, ['page' => 1], 10);
|
||||
$page2 = $this->repository->paginate($this->board->slug, ['page' => 2], 10);
|
||||
|
||||
$titles1 = collect($page1->items())->pluck('title')->all();
|
||||
$titles2 = collect($page2->items())->pluck('title')->all();
|
||||
|
||||
$this->assertSame('공지사항', $titles1[0], '공지는 1페이지 선두에 있어야 한다');
|
||||
$this->assertNotContains('공지사항', $titles2, '공지는 2페이지에 반복되지 않아야 한다');
|
||||
}
|
||||
|
||||
public function test_replies_follow_their_parent_in_the_same_page(): void
|
||||
{
|
||||
$parentId = $this->createTestPost(['title' => '원글']);
|
||||
$this->createTestPost(['title' => '답글 1', 'parent_id' => $parentId, 'depth' => 1]);
|
||||
$this->createTestPost(['title' => '답글 2', 'parent_id' => $parentId, 'depth' => 1]);
|
||||
|
||||
$result = $this->repository->paginate($this->board->slug, [], 10);
|
||||
$titles = collect($result->items())->pluck('title')->all();
|
||||
|
||||
$this->assertSame(['원글', '답글 1', '답글 2'], $titles);
|
||||
}
|
||||
|
||||
public function test_reply_content_preview_is_available_like_parent(): void
|
||||
{
|
||||
$parentId = $this->createTestPost(['title' => '원글', 'content' => '원글 본문입니다.']);
|
||||
$this->createTestPost([
|
||||
'title' => '답글',
|
||||
'content' => '답글 본문입니다.',
|
||||
'parent_id' => $parentId,
|
||||
'depth' => 1,
|
||||
]);
|
||||
|
||||
$result = $this->repository->paginate($this->board->slug, [], 10);
|
||||
$items = collect($result->items());
|
||||
|
||||
// 원글과 답글은 같은 컬럼 목록으로 조회되므로 스키마가 어긋나면 안 된다
|
||||
// (한쪽만 바뀌면 화면에서 조용히 빈 값이 된다)
|
||||
foreach ($items as $item) {
|
||||
$this->assertNotNull($item->content_preview_raw ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_pages_do_not_overlap(): void
|
||||
{
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$this->createTestPost(['title' => "게시글 {$i}"]);
|
||||
}
|
||||
|
||||
$page1 = $this->repository->paginate($this->board->slug, ['page' => 1], 10);
|
||||
$page2 = $this->repository->paginate($this->board->slug, ['page' => 2], 10);
|
||||
|
||||
$ids1 = collect($page1->items())->pluck('id')->all();
|
||||
$ids2 = collect($page2->items())->pluck('id')->all();
|
||||
|
||||
$this->assertCount(10, $ids1);
|
||||
$this->assertEmpty(array_intersect($ids1, $ids2));
|
||||
}
|
||||
|
||||
public function test_last_page_reports_no_more_pages(): void
|
||||
{
|
||||
for ($i = 1; $i <= 15; $i++) {
|
||||
$this->createTestPost(['title' => "게시글 {$i}"]);
|
||||
}
|
||||
|
||||
$page1 = $this->repository->paginate($this->board->slug, ['page' => 1], 10);
|
||||
$page2 = $this->repository->paginate($this->board->slug, ['page' => 2], 10);
|
||||
|
||||
$this->assertTrue($page1->hasMorePages(), '1페이지에서는 다음 페이지가 있어야 한다');
|
||||
$this->assertFalse($page2->hasMorePages(), '마지막 페이지에서 다음 버튼이 남으면 안 된다');
|
||||
}
|
||||
|
||||
public function test_soft_deleted_posts_are_excluded_by_default(): void
|
||||
{
|
||||
$this->createTestPost(['title' => '살아있는 글']);
|
||||
$this->createTestPost(['title' => '삭제된 글', 'deleted_at' => now()]);
|
||||
|
||||
$result = $this->repository->paginate($this->board->slug, [], 10);
|
||||
$titles = collect($result->items())->pluck('title')->all();
|
||||
|
||||
$this->assertContains('살아있는 글', $titles);
|
||||
$this->assertNotContains('삭제된 글', $titles);
|
||||
}
|
||||
|
||||
public function test_with_trashed_includes_deleted_posts(): void
|
||||
{
|
||||
$this->createTestPost(['title' => '살아있는 글']);
|
||||
$this->createTestPost(['title' => '삭제된 글', 'deleted_at' => now()]);
|
||||
|
||||
$result = $this->repository->paginate($this->board->slug, [], 10, true);
|
||||
$titles = collect($result->items())->pluck('title')->all();
|
||||
|
||||
$this->assertContains('삭제된 글', $titles);
|
||||
}
|
||||
|
||||
public function test_sort_order_is_applied_and_deterministic(): void
|
||||
{
|
||||
// 조회수가 모두 같은 상태 — 2차 정렬(id)이 없으면 페이지 경계가 흔들린다
|
||||
for ($i = 1; $i <= 12; $i++) {
|
||||
$this->createTestPost(['title' => "게시글 {$i}", 'view_count' => 5]);
|
||||
}
|
||||
|
||||
$result = $this->repository->paginate(
|
||||
$this->board->slug,
|
||||
['order_by' => 'view_count', 'order_direction' => 'desc'],
|
||||
5
|
||||
);
|
||||
|
||||
$ids = collect($result->items())->pluck('id')->all();
|
||||
$sorted = $ids;
|
||||
rsort($sorted);
|
||||
|
||||
$this->assertSame($sorted, $ids, '동률 정렬에서도 id 내림차순이 유지되어야 한다');
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Tests\Unit\Repositories;
|
||||
|
||||
// ModuleTestCase 수동 로드 (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Board\Repositories\Contracts\PostRepositoryInterface;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
|
||||
/**
|
||||
* 마이페이지 「내가 댓글 단 글」 목록 지연 조인 회귀 테스트
|
||||
*
|
||||
* 이 목록은 `board_posts ⋈ board_comments`(1:N 증폭) + 최근 댓글 상관 서브쿼리 + `groupBy`
|
||||
* 조합이라 다른 목록과 성질이 다르다. 두 가지가 조용히 깨질 수 있다.
|
||||
*
|
||||
* ① 최근 댓글 서브쿼리가 inner(OFFSET 스캔)에 남으면, 건너뛸 행 전체에 대해 상관
|
||||
* 서브쿼리가 실행돼 뒤쪽 페이지의 비용이 그대로 남는다.
|
||||
* ② 그룹 쿼리의 총 건수를 `count()` 로 세면 첫 그룹의 행 수가 총 건수로 잡힌다.
|
||||
* 검색/게시판 필터가 걸리면 캐시 total 을 쓰지 않아 이 경로가 실제로 탄다.
|
||||
*
|
||||
* @scenario case=user_commented_activity_deferred_join
|
||||
*
|
||||
* @effects inner_excludes_wide_columns_from_offset_scan, grouped_query_total_counts_groups_not_first_group_rows
|
||||
*/
|
||||
class UserCommentedActivityDeferredJoinTest extends BoardTestCase
|
||||
{
|
||||
/** 수집된 실행 쿼리 SQL 목록 */
|
||||
private array $queries = [];
|
||||
|
||||
/**
|
||||
* 대상 저장소를 돌려줍니다.
|
||||
*
|
||||
* @return PostRepositoryInterface 게시글 저장소
|
||||
*/
|
||||
private function repository(): PostRepositoryInterface
|
||||
{
|
||||
return $this->app->make(PostRepositoryInterface::class);
|
||||
}
|
||||
|
||||
/** 쿼리 로그 수집을 시작합니다. */
|
||||
private function startCapture(): void
|
||||
{
|
||||
$this->queries = [];
|
||||
|
||||
DB::listen(function ($query) {
|
||||
$this->queries[] = $query->sql;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집된 쿼리 중 조건에 맞는 것만 돌려줍니다.
|
||||
*
|
||||
* @param string $needle 포함 문자열
|
||||
* @return array<int, string> 일치 쿼리 목록
|
||||
*/
|
||||
private function queriesContaining(string $needle): array
|
||||
{
|
||||
return array_values(array_filter($this->queries, fn (string $sql) => str_contains($sql, $needle)));
|
||||
}
|
||||
|
||||
public function test_offset_scan_excludes_latest_comment_subquery(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
$other = $this->createUser();
|
||||
|
||||
for ($i = 1; $i <= 25; $i++) {
|
||||
$postId = $this->createTestPost(['user_id' => $other->id, 'title' => "글 {$i}"]);
|
||||
$this->createTestComment($postId, ['user_id' => $user->id, 'content' => "댓글 {$i}"]);
|
||||
}
|
||||
|
||||
$this->startCapture();
|
||||
$this->repository()->getUserActivities($user->id, ['activity_type' => 'commented'], 10);
|
||||
|
||||
$offsetQueries = $this->queriesContaining('offset');
|
||||
|
||||
$this->assertNotEmpty($offsetQueries, 'inner 는 OFFSET 으로 ID 집합을 구해야 한다');
|
||||
|
||||
foreach ($offsetQueries as $sql) {
|
||||
$this->assertStringNotContainsString(
|
||||
'as `lc`',
|
||||
$sql,
|
||||
'OFFSET 스캔 구간에 최근 댓글 서브쿼리가 남으면 건너뛸 행마다 상관 서브쿼리가 실행된다'
|
||||
);
|
||||
$this->assertStringNotContainsString(
|
||||
'substring',
|
||||
strtolower($sql),
|
||||
'OFFSET 스캔 구간에서 본문을 읽으면 안 된다'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_latest_comment_columns_are_available_in_result(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
$other = $this->createUser();
|
||||
|
||||
$postId = $this->createTestPost(['user_id' => $other->id, 'title' => '대상 글']);
|
||||
$this->createTestComment($postId, [
|
||||
'user_id' => $user->id,
|
||||
'content' => '예전 댓글',
|
||||
'created_at' => now()->subDay(),
|
||||
]);
|
||||
$this->createTestComment($postId, [
|
||||
'user_id' => $user->id,
|
||||
'content' => '가장 최근 댓글',
|
||||
'created_at' => now(),
|
||||
]);
|
||||
|
||||
$items = $this->repository()
|
||||
->getUserActivities($user->id, ['activity_type' => 'commented'], 10)
|
||||
->items();
|
||||
|
||||
$this->assertCount(1, $items, '같은 글에 댓글을 여러 번 달아도 목록에는 글 1건으로 접혀야 한다');
|
||||
$this->assertSame(2, $items[0]['activity_count'], '해당 글에 단 댓글 수가 집계되어야 한다');
|
||||
}
|
||||
|
||||
public function test_total_counts_posts_not_comments_when_filter_bypasses_cache(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
$other = $this->createUser();
|
||||
|
||||
// 첫 글에만 댓글 3건 — 그룹 수(3)와 첫 그룹의 행 수(3)가 우연히 같아지지 않도록
|
||||
// 나머지 글은 댓글 1건씩 둔다.
|
||||
$firstPost = $this->createTestPost(['user_id' => $other->id, 'title' => '검색어 글 A']);
|
||||
for ($i = 0; $i < 3; $i++) {
|
||||
$this->createTestComment($firstPost, ['user_id' => $user->id, 'content' => '검색어 댓글']);
|
||||
}
|
||||
|
||||
foreach (['검색어 글 B', '검색어 글 C', '검색어 글 D', '검색어 글 E'] as $title) {
|
||||
$postId = $this->createTestPost(['user_id' => $other->id, 'title' => $title]);
|
||||
$this->createTestComment($postId, ['user_id' => $user->id, 'content' => '검색어 댓글']);
|
||||
}
|
||||
|
||||
// 검색 필터가 걸리면 서비스가 캐시 total 을 담지 않으므로 trait 이 직접 COUNT 한다.
|
||||
$paginator = $this->repository()->getUserActivities(
|
||||
$user->id,
|
||||
['activity_type' => 'commented', 'search' => '검색어'],
|
||||
10
|
||||
);
|
||||
|
||||
$this->assertSame(5, $paginator->total(), '총 건수는 댓글 수가 아니라 글(그룹) 수여야 한다');
|
||||
$this->assertCount(5, $paginator->items());
|
||||
}
|
||||
|
||||
public function test_pages_do_not_overlap(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
$other = $this->createUser();
|
||||
|
||||
for ($i = 1; $i <= 15; $i++) {
|
||||
$postId = $this->createTestPost([
|
||||
'user_id' => $other->id,
|
||||
'title' => "글 {$i}",
|
||||
'created_at' => now()->subMinutes(20 - $i),
|
||||
]);
|
||||
$this->createTestComment($postId, ['user_id' => $user->id, 'content' => "댓글 {$i}"]);
|
||||
}
|
||||
|
||||
$paginator = $this->repository()->getUserActivities($user->id, ['activity_type' => 'commented'], 10);
|
||||
|
||||
$this->assertSame(15, $paginator->total());
|
||||
$this->assertSame(2, $paginator->lastPage());
|
||||
$this->assertCount(10, $paginator->items());
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,9 @@
|
||||
|
||||
- 실제로 사용되지 않던 설정 항목(상품·주문 목록의 페이지당 개수, 결제 자동취소 기한 중복 항목)을 정리했습니다. 미입금 자동취소 기한은 관리자 환경설정의 값 하나만 사용합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 사이트맵을 만들 때 상품과 카테고리를 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 상품이 많은 쇼핑몰에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
|
||||
- 상품 리뷰·마일리지 내역·쿠폰 발급 내역 목록도 같은 방식으로 뒤쪽 페이지 조회를 개선했습니다. 상품 리뷰는 작성일 정렬용 인덱스를 추가하고 기간 검색 조건을 인덱스가 활용되는 형태로 바꿔, 리뷰가 많은 쇼핑몰에서 목록과 기간 검색이 함께 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 상품 목록(관리자·쇼핑몰 화면)·상품 문의 관리 목록·추가배송비 목록도 같은 방식으로 개선했습니다. 상품 문의는 기간 검색 조건도 인덱스가 활용되는 형태로 바꿔 기간을 좁혀 찾을 때 더 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 주문 목록을 뒤쪽 페이지에서도 빠르게 열 수 있도록 조회 방식을 바꿨습니다. 예전에는 페이지가 뒤로 갈수록 건너뛰는 주문의 스냅샷·관리자 메모 같은 큰 항목까지 함께 읽어 느려졌지만, 이제 현재 페이지의 주문만 상세 정보를 읽습니다. 주문 10만 건 기준 5,000번째 페이지에서 조회 시간이 약 6분의 1로 줄어듭니다. 화면에 보이는 내용은 이전과 동일합니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
|
||||
|
||||
### Fixed
|
||||
@@ -67,6 +70,10 @@
|
||||
- 관리자 목록에서 검색·필터·정렬을 바꿀 때 표가 다시 그려지는 동안 로딩 표시가 나오지 않던 문제를 수정했습니다. 응답이 늦으면 아무 반응이 없는 것처럼 보여 같은 조작을 반복하게 되던 상황이 사라집니다.
|
||||
- 관리자 화면 일부 아이콘이 의도한 크기보다 크거나 작게 보이던 문제를 수정했습니다.
|
||||
- 관리자 화면 일부 버튼·배지가 다크 모드에서 밝은 색 그대로 표시되던 문제를 수정했습니다.
|
||||
- 쿠폰을 수정할 때 유효기간을 비운 채로 저장할 수 있던 문제를 수정했습니다. 등록 화면과 동일하게, "기간 지정" 쿠폰은 시작일·종료일이, "발급일 기준" 쿠폰은 유효일수가 있어야 저장됩니다. (#78 @glitter-gim 님께서 제보해주셨습니다.)
|
||||
- 쿠폰의 다른 항목만 고치는 경우에도 "1인당 사용 제한"을 함께 보내지 않으면 저장이 거절되던 문제를 수정했습니다. (#78 @glitter-gim 님께서 제보해주셨습니다.)
|
||||
- 배송지를 수정할 때 주소를 통째로 비운 채 저장할 수 있던 문제를 수정했습니다. 국내 배송지는 우편번호와 주소가, 해외 배송지는 주소·도시·우편번호가 갖춰져야 저장됩니다. 기본 배송지 지정처럼 주소를 건드리지 않는 수정은 이전과 동일하게 저장됩니다. (#78 @glitter-gim 님께서 제보해주셨습니다.)
|
||||
- 해외 배송지를 수정하면 도시·주·우편번호가 안내 없이 비워지던 문제를 수정했습니다. 이번 수정에서 다시 입력하지 않은 항목은 저장된 값이 그대로 유지됩니다. (#78 @glitter-gim 님께서 제보해주셨습니다.)
|
||||
|
||||
## [1.0.4] - 2026-07-16
|
||||
|
||||
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* ecommerce_product_reviews 테이블 정렬 인덱스 추가.
|
||||
*
|
||||
* 리뷰 목록은 상품 상세와 관리자 화면 모두 작성일 내림차순이 기본 정렬인데, created_at 이
|
||||
* 후행하는 복합 인덱스가 없어 정렬마다 filesort 가 발생했다.
|
||||
*
|
||||
* - [product_id, status, deleted_at, created_at]: 상품 상세의 노출 리뷰 목록
|
||||
* (기존 [product_id, status] 인덱스를 포함하므로 그 인덱스는 후속 정리 대상)
|
||||
* - [deleted_at, created_at]: 관리자 리뷰 목록
|
||||
*
|
||||
* 관리자 목록에 [status, created_at] 을 두지 않는 이유: status 는 **선택적 필터**다
|
||||
* (ProductReviewRepository 의 상태 필터는 값이 있을 때만 where 를 붙인다). 선행 컬럼이
|
||||
* 등치로 고정되지 않으면 후행 created_at 의 정렬 순서를 쓸 수 없어, 필터를 걸지 않은
|
||||
* 기본 진입에서 filesort 가 그대로 남는다. 반면 deleted_at 은 SoftDeletes 가 항상
|
||||
* `IS NULL` 로 붙이므로 선행 컬럼이 고정된다. 상태 필터를 건 조회도 이 인덱스로 정렬을
|
||||
* 충족하고 status 만 추가로 걸러내면 된다.
|
||||
*
|
||||
* 별점(rating) 정렬용 인덱스는 추가하지 않는다. 값이 1~5 뿐이라 선택도가 낮아 인덱스 효용이
|
||||
* 없고, 쓰기 비용만 늘어난다.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable('ecommerce_product_reviews')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existingIndexes = array_column(Schema::getIndexes('ecommerce_product_reviews'), 'name');
|
||||
|
||||
Schema::table('ecommerce_product_reviews', function (Blueprint $table) use ($existingIndexes) {
|
||||
if (! in_array('idx_reviews_product_status_deleted_created', $existingIndexes)) {
|
||||
$table->index(
|
||||
['product_id', 'status', 'deleted_at', 'created_at'],
|
||||
'idx_reviews_product_status_deleted_created'
|
||||
);
|
||||
}
|
||||
|
||||
if (! in_array('idx_reviews_deleted_created', $existingIndexes)) {
|
||||
$table->index(['deleted_at', 'created_at'], 'idx_reviews_deleted_created');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('ecommerce_product_reviews')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existingIndexes = array_column(Schema::getIndexes('ecommerce_product_reviews'), 'name');
|
||||
|
||||
Schema::table('ecommerce_product_reviews', function (Blueprint $table) use ($existingIndexes) {
|
||||
$indexes = [
|
||||
'idx_reviews_product_status_deleted_created',
|
||||
'idx_reviews_deleted_created',
|
||||
];
|
||||
|
||||
foreach ($indexes as $index) {
|
||||
if (in_array($index, $existingIndexes)) {
|
||||
$table->dropIndex($index);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -402,6 +402,8 @@ HTTP/1.1 200
|
||||
| intl_postal_code | body | string | 아니오 | max 20 | 우편번호 (국제 주소) |
|
||||
| is_default | body | boolean | 아니오 | — | 기본값 지정 여부 |
|
||||
|
||||
개별 필드는 모두 선택이지만 주소 필수 조합은 "기존 저장값 + 이번 요청" 결과 상태 기준으로 검증됩니다. 국내(`country_code=KR` 또는 미전송 시 기존 국가가 KR)는 `zipcode` + `address`, 해외는 `address_line_1` + `intl_city` + `intl_postal_code` 가 결과적으로 모두 채워져 있어야 하며, 그렇지 않으면 422 로 거절됩니다. 요청에 없는 필드는 저장된 값으로 판정하므로 `is_default` 만 바꾸는 요청이나 도로명 주소만 교체하는 요청은 그대로 통과합니다. 해외 주소의 저장 컬럼은 `city`/`state`/`postal_code` 이므로 요청에 `intl_city`/`intl_postal_code` 가 없으면 그 저장값이 판정 기준이 됩니다.
|
||||
|
||||
> 이 엔드포인트는 확장이 파라미터를 추가할 수 있습니다 (`sirsoft-ecommerce.user_address.update_validation_rules`).
|
||||
|
||||
**요청 예시**
|
||||
|
||||
@@ -47,7 +47,7 @@
|
||||
| user_id | query | integer | 아니오 | — | user 식별자 |
|
||||
| orderer_uuid | query | uuid | 아니오 | — | 특정 회원의 주문만 조회하는 주문자 UUID 필터 (회원 검색 연동용) |
|
||||
| member_type | query | string | 아니오 | `member`, `guest` | 회원 구분 필터 (member 회원 주문 / guest 비회원 주문) |
|
||||
| sort_by | query | string | 아니오 | `ordered_at`, `paid_at`, `total_amount` | 정렬 기준 필드명 |
|
||||
| sort_by | query | string | 아니오 | `ordered_at`, `paid_at`, `total_amount` | 정렬 기준 필드명 (그 외 값은 422) |
|
||||
| sort_order | query | string | 아니오 | `asc`, `desc` | 정렬 방향 (asc 오름차순 / desc 내림차순) |
|
||||
| per_page | query | integer | 아니오 | min 10, max 100 | 페이지당 항목 수 |
|
||||
| page | query | integer | 아니오 | min 1 | 조회할 페이지 번호 (1부터 시작) |
|
||||
|
||||
@@ -701,6 +701,8 @@ HTTP/1.1 200
|
||||
| products | body | array | 아니오 | — | 적용 상품 목록 (`target_scope=products`), 항목별 `{id, type: include\|exclude}` |
|
||||
| categories | body | array | 아니오 | — | 적용 카테고리 목록 (`target_scope=categories`), 항목별 `{id, type: include\|exclude}` |
|
||||
|
||||
> 필수 표기는 "전송했을 때 값이 있어야 함"을 뜻합니다. 이 엔드포인트는 부분 수정을 지원하므로 body 필드는 모두 생략할 수 있습니다 (생략하면 기존 값 유지). 유효기간은 `valid_type` 을 함께 전송할 때만 조건부 필수가 적용됩니다 — `period` 면 `valid_from`/`valid_to`, `days_from_issue` 면 `valid_days` 가 비어 있으면 422 입니다. `valid_type` 을 보내지 않는 부분 수정은 유효기간 필드를 요구하지 않습니다.
|
||||
|
||||
> 이 엔드포인트는 확장이 파라미터를 추가할 수 있습니다 (`sirsoft-ecommerce.coupon.update_validation_rules`).
|
||||
|
||||
**요청 예시**
|
||||
|
||||
@@ -18,8 +18,8 @@ use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateStatusRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateStockRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductLogsRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductShowForCopyRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ReorderProductImagesRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ShowProductForCopyRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreProductRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateProductRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UploadProductImageRequest;
|
||||
@@ -566,11 +566,11 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 상품 복사용 데이터를 조회합니다.
|
||||
*
|
||||
* @param ShowProductForCopyRequest $request 복사 옵션 요청 데이터
|
||||
* @param ProductShowForCopyRequest $request 검증된 복사 옵션 요청
|
||||
* @param Product $product 복사할 상품 모델
|
||||
* @return JsonResponse 복사용 데이터 JSON 응답
|
||||
*/
|
||||
public function showForCopy(ShowProductForCopyRequest $request, Product $product): JsonResponse
|
||||
public function showForCopy(ProductShowForCopyRequest $request, Product $product): JsonResponse
|
||||
{
|
||||
try {
|
||||
$copyData = $this->productService->getDetailForCopy($product->id, $request->getCopyOptions());
|
||||
@@ -797,14 +797,14 @@ class ProductController extends AdminBaseController
|
||||
/**
|
||||
* 상품 처리로그(활동 로그) 목록을 조회합니다.
|
||||
*
|
||||
* @param ProductLogsRequest $request 활동 로그 조회 요청 데이터
|
||||
* @param ProductLogsRequest $request 검증된 조회 요청
|
||||
* @param Product $product 상품
|
||||
* @return JsonResponse 활동 로그 목록
|
||||
*/
|
||||
public function logs(ProductLogsRequest $request, Product $product): JsonResponse
|
||||
{
|
||||
try {
|
||||
// 상품 + 상품옵션 로그 합산 조회는 Repository 위임 (Service 경유)
|
||||
// 상품 + 상품옵션 로그 합산 조회는 Service → Repository 경유 (컨트롤러 직접 조회 금지)
|
||||
$logs = $this->productService->getActivityLogs($product, $request->getFilters());
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
/**
|
||||
* 상품 활동 로그 조회 요청 (관리자)
|
||||
* 상품 처리로그(활동 로그) 목록 조회 요청 (관리자)
|
||||
*
|
||||
* 권한은 라우트 미들웨어(permission:admin,sirsoft-ecommerce.products.read)에서 처리하며,
|
||||
* 여기서는 페이지 크기·정렬 옵션만 검증합니다.
|
||||
@@ -30,22 +31,27 @@ class ProductLogsRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
$rules = [
|
||||
'per_page' => ['sometimes', 'integer', 'min:1', 'max:100'],
|
||||
'sort_order' => ['sometimes', 'string', Rule::in(['asc', 'desc'])],
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.product.logs_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 활동 로그 조회 필터(페이지 크기·정렬)를 반환합니다.
|
||||
*
|
||||
* @return array{per_page: int, sort_order: string} 조회 필터
|
||||
* 고정 키만 열거하면 확장이 훅으로 규칙을 얹어도 그 값이 Service 까지 도달하지 못하므로,
|
||||
* 검증을 통과한 전체 데이터 위에 기본값이 적용된 고정 키를 덮어쓴다.
|
||||
*
|
||||
* @return array<string, mixed> 조회 필터 (per_page, sort_order + 확장 추가 필드)
|
||||
*/
|
||||
public function getFilters(): array
|
||||
{
|
||||
return [
|
||||
return array_merge($this->validated(), [
|
||||
'per_page' => (int) ($this->query('per_page', 10)),
|
||||
'sort_order' => $this->query('sort_order', 'desc'),
|
||||
];
|
||||
]);
|
||||
}
|
||||
}
|
||||
+12
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
@@ -10,7 +11,7 @@ use Illuminate\Foundation\Http\FormRequest;
|
||||
* 권한은 라우트 미들웨어(permission:admin,sirsoft-ecommerce.products.create)에서 처리하며,
|
||||
* 여기서는 어떤 항목을 함께 복사할지 고르는 플래그만 검증합니다.
|
||||
*/
|
||||
class ShowProductForCopyRequest extends FormRequest
|
||||
class ProductShowForCopyRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 복사 대상 항목과 미지정 시 기본값
|
||||
@@ -54,22 +55,29 @@ class ShowProductForCopyRequest extends FormRequest
|
||||
$rules["copy_{$target}"] = ['sometimes', 'boolean'];
|
||||
}
|
||||
|
||||
return $rules;
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.product.show_for_copy_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 복사 옵션을 반환합니다.
|
||||
*
|
||||
* @return array<string, bool> 항목별 복사 여부
|
||||
* 코어 항목은 `copy_` 접두사를 뗀 키로, 확장이 훅으로 추가한 필드는 검증된 이름 그대로
|
||||
* 함께 담는다 — 고정 키만 열거하면 확장이 규칙을 얹어도 값이 Service 에 도달하지 못한다.
|
||||
*
|
||||
* @return array<string, mixed> 항목별 복사 여부 + 확장 추가 필드
|
||||
*/
|
||||
public function getCopyOptions(): array
|
||||
{
|
||||
$coreKeys = [];
|
||||
$options = [];
|
||||
|
||||
foreach (self::COPY_TARGETS as $target => $default) {
|
||||
$coreKeys[] = "copy_{$target}";
|
||||
$options[$target] = $this->boolean("copy_{$target}", $default);
|
||||
}
|
||||
|
||||
return $options;
|
||||
$extra = array_diff_key($this->validated(), array_flip($coreKeys));
|
||||
|
||||
return array_merge($extra, $options);
|
||||
}
|
||||
}
|
||||
@@ -98,13 +98,17 @@ class UpdateCouponRequest extends FormRequest
|
||||
'issue_condition' => 'sometimes|required|string|in:'.implode(',', CouponIssueCondition::values()),
|
||||
'issue_status' => 'sometimes|required|string|in:'.implode(',', CouponIssueStatus::values()),
|
||||
'total_quantity' => 'nullable|integer|min:1',
|
||||
'per_user_limit' => 'required|integer|min:0',
|
||||
// 같은 파일의 다른 필드와 동일하게 부분 수정을 지원한다. sometimes 가 없으면
|
||||
// 다른 탭만 고치는 요청도 1인당 사용 제한을 매번 실어 보내야 저장된다.
|
||||
'per_user_limit' => 'sometimes|required|integer|min:0',
|
||||
|
||||
// 유효기간
|
||||
// 유효기간 — 조건부 규칙은 StoreCouponRequest 와 동일해야 한다.
|
||||
// required_if 는 조건 필드(valid_type)가 요청에 없으면 발화하지 않으므로
|
||||
// 부분 수정을 깨지 않으면서 "기간 지정인데 기간이 비어 있는" 저장만 차단한다.
|
||||
'valid_type' => 'sometimes|required|string|in:period,days_from_issue',
|
||||
'valid_days' => 'nullable|integer|min:1',
|
||||
'valid_from' => 'nullable|date',
|
||||
'valid_to' => 'nullable|date|after_or_equal:valid_from',
|
||||
'valid_days' => 'nullable|required_if:valid_type,days_from_issue|integer|min:1',
|
||||
'valid_from' => 'nullable|required_if:valid_type,period|date',
|
||||
'valid_to' => 'nullable|required_if:valid_type,period|date|after_or_equal:valid_from',
|
||||
|
||||
// 발급기간
|
||||
'issue_from' => 'nullable|date',
|
||||
@@ -195,6 +199,9 @@ class UpdateCouponRequest extends FormRequest
|
||||
? __('sirsoft-ecommerce::validation.coupon.discount_value_rate_min')
|
||||
: __('sirsoft-ecommerce::validation.coupon.discount_value_fixed_min'),
|
||||
'discount_value.max' => __('sirsoft-ecommerce::validation.coupon.discount_value_rate_max'),
|
||||
'valid_days.required_if' => __('sirsoft-ecommerce::validation.coupon.valid_days_required'),
|
||||
'valid_from.required_if' => __('sirsoft-ecommerce::validation.coupon.valid_from_required'),
|
||||
'valid_to.required_if' => __('sirsoft-ecommerce::validation.coupon.valid_to_required'),
|
||||
'valid_to.after_or_equal' => __('sirsoft-ecommerce::validation.coupon.valid_to_after_from'),
|
||||
];
|
||||
}
|
||||
|
||||
+13
-3
@@ -12,6 +12,10 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\Concerns;
|
||||
* 본 트레이트는 validated() 결과를 국가별로 정규화한다:
|
||||
* - KR(국내): zipcode/address/address_detail 만 유지, 해외 필드 제거
|
||||
* - 그 외(해외): intl_* → city/state/postal_code 변환, 국내 필드 제거
|
||||
*
|
||||
* 변환은 요청에 실려 온 intl_* 키에 대해서만 수행한다. 조회 응답은 해외 주소를
|
||||
* city/state/postal_code 로 내보내므로 폼이 intl_* 를 다시 싣지 않는 수정 요청이 존재하며,
|
||||
* 미전송 키를 null 로 채우면 저장된 도시/주/우편번호가 조용히 유실된다.
|
||||
*/
|
||||
trait MapsAddressBookFields
|
||||
{
|
||||
@@ -51,9 +55,15 @@ trait MapsAddressBookFields
|
||||
);
|
||||
} else {
|
||||
// 해외: intl_* → city/state/postal_code 변환, 국내 전용 필드 제거
|
||||
$data['city'] = $data['intl_city'] ?? null;
|
||||
$data['state'] = $data['intl_state'] ?? null;
|
||||
$data['postal_code'] = $data['intl_postal_code'] ?? null;
|
||||
//
|
||||
// 전송되지 않은 intl_* 는 매핑 대상에서 제외한다. `?? null` 로 채우면 부분 수정
|
||||
// 요청(조회 응답이 city/state/postal_code 키로 내보내므로 폼이 intl_* 를 다시
|
||||
// 싣지 않는 경우)에서 저장된 도시/주/우편번호가 null 로 덮어써져 조용히 유실된다.
|
||||
foreach (['city' => 'intl_city', 'state' => 'intl_state', 'postal_code' => 'intl_postal_code'] as $column => $formKey) {
|
||||
if (array_key_exists($formKey, $data)) {
|
||||
$data[$column] = $data[$formKey];
|
||||
}
|
||||
}
|
||||
|
||||
unset(
|
||||
$data['intl_city'],
|
||||
|
||||
+141
-1
@@ -4,7 +4,11 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Concerns\MapsAddressBookFields;
|
||||
use Modules\Sirsoft\Ecommerce\Models\UserAddress;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\UserAddressRepositoryInterface;
|
||||
|
||||
/**
|
||||
* 사용자 배송지 수정 요청
|
||||
@@ -39,6 +43,11 @@ class UpdateUserAddressRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* 주소 필수 조합(국내 = 우편번호+주소 / 해외 = 주소+도시+우편번호)은 규칙 배열이
|
||||
* 아니라 withValidator() 에서 검증한다. StoreUserAddressRequest 의
|
||||
* required_with/required_without 를 그대로 옮기면 부분 수정이 깨지기 때문이다 —
|
||||
* 상세 근거는 validateAddressPresence() docblock 참조.
|
||||
*
|
||||
* @return array 주소록 수정 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
@@ -55,18 +64,26 @@ class UpdateUserAddressRequest extends FormRequest
|
||||
'country_code' => 'nullable|string|size:2',
|
||||
|
||||
// 국내 배송 주소
|
||||
// audit:allow formrequest-store-update-conditional-symmetry reason: 주소 필수 조합은
|
||||
// 페이로드 단독이 아니라 "기존 레코드 + 페이로드" 결과 상태 기준으로 판정한다
|
||||
// (validateAddressPresence). Store 의 required_without 를 그대로 옮기면 배송지명만
|
||||
// 바꾸는 요청과 해외 배송지 수정 요청이 422 가 된다.
|
||||
'zipcode' => 'nullable|string|max:10',
|
||||
'province_code' => 'nullable|string|max:10',
|
||||
'city' => 'nullable|string|max:100',
|
||||
// audit:allow formrequest-store-update-conditional-symmetry reason: 결과 상태 기준 판정 (validateAddressPresence)
|
||||
'address' => 'nullable|string|max:255',
|
||||
'address_detail' => 'nullable|string|max:255',
|
||||
'address_type_code' => 'nullable|string|in:R,J',
|
||||
|
||||
// 해외 배송 주소
|
||||
// 해외 배송 주소 (필수 조합은 위와 동일하게 validateAddressPresence 가 담당)
|
||||
// audit:allow formrequest-store-update-conditional-symmetry reason: 결과 상태 기준 판정 (validateAddressPresence)
|
||||
'address_line_1' => 'nullable|string|max:255',
|
||||
'address_line_2' => 'nullable|string|max:255',
|
||||
// audit:allow formrequest-store-update-conditional-symmetry reason: 결과 상태 기준 판정 (validateAddressPresence)
|
||||
'intl_city' => 'nullable|string|max:100',
|
||||
'intl_state' => 'nullable|string|max:100',
|
||||
// audit:allow formrequest-store-update-conditional-symmetry reason: 결과 상태 기준 판정 (validateAddressPresence)
|
||||
'intl_postal_code' => 'nullable|string|max:20',
|
||||
|
||||
// 기본 배송지 여부
|
||||
@@ -76,6 +93,129 @@ class UpdateUserAddressRequest extends FormRequest
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.user_address.update_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증기에 주소 필수 조합 검증을 추가합니다.
|
||||
*
|
||||
* @param Validator $validator 검증기
|
||||
*/
|
||||
public function withValidator(Validator $validator): void
|
||||
{
|
||||
$validator->after(function (Validator $validator) {
|
||||
$this->validateAddressPresence($validator);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 주소 필수 조합을 "기존 레코드 + 요청 페이로드" 결과 상태 기준으로 검증합니다.
|
||||
*
|
||||
* StoreUserAddressRequest 는 required_with/required_without 로 같은 정책을 강제하지만,
|
||||
* 그 규칙을 수정 요청에 그대로 쓰면 두 가지 정상 경로가 막힌다.
|
||||
*
|
||||
* 1) 부분 수정 — 기본 배송지 토글처럼 주소를 건드리지 않는 요청도 required_without 이
|
||||
* "상대 필드 부재" 자체를 발화 조건으로 삼아 422 가 된다.
|
||||
* 2) 해외 배송지 수정 — 조회 응답은 해외 주소를 city/state/postal_code 로 내보내고
|
||||
* 폼은 intl_* 로 제출하므로, 사용자가 도시/우편번호를 다시 입력하지 않으면 요청에
|
||||
* intl_city/intl_postal_code 가 없다. 페이로드만 보면 값이 비어 보인다.
|
||||
*
|
||||
* 따라서 요청에 없는 필드는 저장된 값으로 메워 판정한다. 판정 기준 국가는
|
||||
* MapsAddressBookFields 의 매핑 기준과 동일하게 country_code(미전송 시 기존 값)다.
|
||||
*
|
||||
* @param Validator $validator 검증기
|
||||
*/
|
||||
protected function validateAddressPresence(Validator $validator): void
|
||||
{
|
||||
$payload = $this->all();
|
||||
|
||||
// 주소를 정의하는 필드도 국가도 건드리지 않는 요청은 판정 대상이 아니다.
|
||||
$addressKeys = ['zipcode', 'address', 'address_line_1', 'intl_city', 'intl_postal_code', 'country_code'];
|
||||
|
||||
if (! array_intersect($addressKeys, array_keys($payload))) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = $this->findExistingAddress();
|
||||
|
||||
// 저장된 컬럼명 → 요청 키 매핑 (해외는 city/state/postal_code 컬럼에 저장된다)
|
||||
$fallback = [
|
||||
'zipcode' => $existing?->zipcode,
|
||||
'address' => $existing?->address,
|
||||
'address_line_1' => $existing?->address_line_1,
|
||||
'intl_city' => $existing?->city,
|
||||
'intl_postal_code' => $existing?->postal_code,
|
||||
];
|
||||
|
||||
$effective = [];
|
||||
|
||||
foreach ($fallback as $key => $storedValue) {
|
||||
$effective[$key] = array_key_exists($key, $payload) ? $payload[$key] : $storedValue;
|
||||
}
|
||||
|
||||
$country = array_key_exists('country_code', $payload)
|
||||
? strtoupper((string) $payload['country_code'])
|
||||
: strtoupper((string) ($existing?->country_code ?? 'KR'));
|
||||
|
||||
if ($country === '') {
|
||||
$country = 'KR';
|
||||
}
|
||||
|
||||
if ($country === 'KR') {
|
||||
if (! $this->isFilled($effective['zipcode'])) {
|
||||
$validator->errors()->add('zipcode', __('sirsoft-ecommerce::validation.user_address.zipcode_required'));
|
||||
}
|
||||
|
||||
if (! $this->isFilled($effective['address'])) {
|
||||
$validator->errors()->add('address', __('sirsoft-ecommerce::validation.user_address.address_required'));
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $this->isFilled($effective['address_line_1'])) {
|
||||
$validator->errors()->add('address_line_1', __('sirsoft-ecommerce::validation.user_address.address_line_1_required'));
|
||||
}
|
||||
|
||||
if (! $this->isFilled($effective['intl_city'])) {
|
||||
$validator->errors()->add('intl_city', __('sirsoft-ecommerce::validation.user_address.intl_city_required'));
|
||||
}
|
||||
|
||||
if (! $this->isFilled($effective['intl_postal_code'])) {
|
||||
$validator->errors()->add('intl_postal_code', __('sirsoft-ecommerce::validation.user_address.intl_postal_code_required'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 수정 대상 배송지를 조회합니다. (본인 소유 스코프)
|
||||
*
|
||||
* @return UserAddress|null 배송지 (없으면 null — 404 는 컨트롤러가 판정)
|
||||
*/
|
||||
protected function findExistingAddress(): ?UserAddress
|
||||
{
|
||||
$userId = Auth::id();
|
||||
$addressId = (int) $this->route('id');
|
||||
|
||||
if ($userId === null || $addressId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Repository 인터페이스 경유 — FormRequest 의 Model 직접 호출 금지 규정 준수
|
||||
return app(UserAddressRepositoryInterface::class)->findByUserIdAndId($userId, $addressId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 값이 실제로 채워져 있는지 판정합니다. (공백만 있는 문자열은 빈 값)
|
||||
*
|
||||
* @param mixed $value 판정 대상 값
|
||||
* @return bool 채워져 있으면 true
|
||||
*/
|
||||
private function isFilled(mixed $value): bool
|
||||
{
|
||||
if ($value === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return trim((string) $value) !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
|
||||
+1
-1
@@ -258,7 +258,7 @@ interface ProductRepositoryInterface
|
||||
* 상품과 그 옵션의 활동 로그를 합쳐 페이지네이션으로 조회
|
||||
*
|
||||
* @param Product $product 대상 상품
|
||||
* @param array $filters 조회 필터 (per_page, sort_order)
|
||||
* @param array $filters 조회 필터 (per_page, sort_order + 확장이 훅으로 추가한 필드)
|
||||
* @return LengthAwarePaginator 활동 로그 페이지네이터
|
||||
*/
|
||||
public function getActivityLogsForProduct(Product $product, array $filters = []): LengthAwarePaginator;
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Collection;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueRecordStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Models\CouponIssue;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
@@ -14,6 +16,8 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CouponIssueRepositoryInterf
|
||||
*/
|
||||
class CouponIssueRepository implements CouponIssueRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
|
||||
public function __construct(
|
||||
protected CouponIssue $model
|
||||
) {}
|
||||
@@ -161,14 +165,19 @@ class CouponIssueRepository implements CouponIssueRepositoryInterface
|
||||
}
|
||||
}
|
||||
|
||||
return $query->orderByDesc('created_at')
|
||||
->paginate($perPage);
|
||||
// 쿠폰 발급 내역은 발급량에 비례해 계속 늘어난다
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: [['column' => 'created_at', 'direction' => 'desc']],
|
||||
perPage: $perPage,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritDoc}
|
||||
*/
|
||||
public function findByIdsForUser(array $couponIssueIds, int $userId): \Illuminate\Support\Collection
|
||||
public function findByIdsForUser(array $couponIssueIds, int $userId): Collection
|
||||
{
|
||||
if (empty($couponIssueIds)) {
|
||||
return collect();
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -18,6 +20,12 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CouponRepositoryInterface;
|
||||
*/
|
||||
class CouponRepository implements CouponRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/** 허용 정렬 컬럼 (CouponListRequest 와 동일 집합) */
|
||||
private const SORTABLE_COLUMNS = ['created_at', 'name', 'discount_value', 'issued_count'];
|
||||
|
||||
public function __construct(
|
||||
protected Coupon $model,
|
||||
protected CouponIssue $issueModel
|
||||
@@ -89,10 +97,9 @@ class CouponRepository implements CouponRepositoryInterface
|
||||
*/
|
||||
private function finalizeListQuery(Builder $query, array $filters, array $with, int $perPage): LengthAwarePaginator
|
||||
{
|
||||
// 정렬
|
||||
$sortBy = $filters['sort_by'] ?? 'created_at';
|
||||
$sortOrder = $filters['sort_order'] ?? 'desc';
|
||||
$query->orderBy($sortBy, $sortOrder)->orderBy('id', $sortOrder);
|
||||
// 정렬 (허용 컬럼 화이트리스트로 해석)
|
||||
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'created_at')[0];
|
||||
$query->orderBy($sort['column'], $sort['direction'])->orderBy('id', $sort['direction']);
|
||||
|
||||
// Eager loading
|
||||
if (! empty($with)) {
|
||||
@@ -102,6 +109,8 @@ class CouponRepository implements CouponRepositoryInterface
|
||||
// 기본 관계 로드
|
||||
$query->with(['creator:id,uuid,name,email']);
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 쿠폰 "정의" 목록 —
|
||||
// 행 수가 운영자가 만든 쿠폰 수에 묶인다(발급 이력은 별도 테이블). description 외에 넓은 컬럼이 없다
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
@@ -178,13 +187,19 @@ class CouponRepository implements CouponRepositoryInterface
|
||||
$query->where('status', $filters['status']);
|
||||
}
|
||||
|
||||
// 기본 정렬: 발급일 최신순
|
||||
$query->orderBy('issued_at', 'desc')->orderBy('id', 'desc');
|
||||
|
||||
// 관계 로드 (사용처 주문번호 표시를 위해 order 도 로드)
|
||||
$query->with(['user:id,uuid,name', 'order:id,order_number']);
|
||||
|
||||
return $query->paginate($perPage);
|
||||
// 지연 조인: 쿠폰 1건의 발급 이력은 대량 발급 시 수십만 건이 될 수 있어
|
||||
// 뒤쪽 페이지에서 OFFSET 비용이 그대로 누적된다. inner 는 id 만 훑는다.
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: [
|
||||
['column' => 'issued_at', 'direction' => 'desc'],
|
||||
['column' => 'id', 'direction' => 'desc'],
|
||||
],
|
||||
perPage: $perPage,
|
||||
// 관계 로드 (사용처 주문번호 표시를 위해 order 도 로드)
|
||||
relations: ['user:id,uuid,name', 'order:id,order_number'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -249,6 +264,8 @@ class CouponRepository implements CouponRepositoryInterface
|
||||
->orderBy('created_at', 'desc');
|
||||
|
||||
if ($perPage !== null) {
|
||||
// audit:allow repository-paginate-column-pruning reason: 다운로드 가능 쿠폰 "정의" 목록 —
|
||||
// 발급중 상태의 쿠폰만 남는 좁은 집합이라 OFFSET 이 깊어질 수 없다
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ExtraFeeTemplate;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ExtraFeeTemplateRepositoryInterface;
|
||||
|
||||
@@ -13,6 +14,12 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ExtraFeeTemplateRepositoryI
|
||||
*/
|
||||
class ExtraFeeTemplateRepository implements ExtraFeeTemplateRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/** 허용 정렬 컬럼 (ExtraFeeTemplate::scopeOrderByField 와 동일 집합) */
|
||||
private const SORTABLE_COLUMNS = ['id', 'zipcode', 'fee', 'region', 'is_active', 'created_at', 'updated_at'];
|
||||
|
||||
public function __construct(
|
||||
protected ExtraFeeTemplate $model
|
||||
) {}
|
||||
@@ -56,12 +63,17 @@ class ExtraFeeTemplateRepository implements ExtraFeeTemplateRepositoryInterface
|
||||
$query->where('is_active', $isActive);
|
||||
}
|
||||
|
||||
// 정렬
|
||||
$sortBy = $filters['sort_by'] ?? 'zipcode';
|
||||
$sortOrder = $filters['sort_order'] ?? 'asc';
|
||||
$query->orderByField($sortBy, $sortOrder);
|
||||
// 정렬 (모델 scopeOrderByField 와 동일한 허용 집합)
|
||||
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'zipcode', 'asc');
|
||||
|
||||
return $query->paginate($perPage);
|
||||
// 지연 조인: 우편번호 단위 행이라 건수가 커질 수 있고 description(text)이 있어
|
||||
// OFFSET 이 훑는 구간에서 넓은 컬럼까지 읽힌다. inner 는 id 만 훑는다.
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $sort,
|
||||
perPage: $perPage,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,12 +240,12 @@ class ExtraFeeTemplateRepository implements ExtraFeeTemplateRepositoryInterface
|
||||
* ID 목록으로 조회하고 ID 키 맵으로 반환합니다 (bulk activity log lookup).
|
||||
*
|
||||
* @param array<int, int> $ids ID 목록
|
||||
* @return \Illuminate\Database\Eloquent\Collection
|
||||
* @return Collection
|
||||
*/
|
||||
public function findByIdsKeyed(array $ids): \Illuminate\Database\Eloquent\Collection
|
||||
public function findByIdsKeyed(array $ids): Collection
|
||||
{
|
||||
if (empty($ids)) {
|
||||
return new \Illuminate\Database\Eloquent\Collection();
|
||||
return new Collection;
|
||||
}
|
||||
|
||||
return ExtraFeeTemplate::whereIn('id', $ids)->get()->keyBy('id');
|
||||
|
||||
@@ -7,6 +7,8 @@ use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\MileageTransactionTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\MileageBalance;
|
||||
use Modules\Sirsoft\Ecommerce\Models\MileageTransaction;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\MileageBalanceRepositoryInterface;
|
||||
|
||||
/**
|
||||
@@ -202,15 +204,21 @@ class MileageBalanceRepository implements MileageBalanceRepositoryInterface
|
||||
*/
|
||||
private function computePending(int $userId, string $currency): float
|
||||
{
|
||||
return (float) DB::table('ecommerce_order_options as opt')
|
||||
->join('ecommerce_orders as ord', 'opt.order_id', '=', 'ord.id')
|
||||
// 테이블명은 모델에서 얻는다 (문자열 하드코딩 금지). 별칭은 빌더가 붙이므로
|
||||
// 프리픽스 처리도 빌더가 맡는다.
|
||||
$optionsTable = (new OrderOption)->getTable();
|
||||
$ordersTable = (new Order)->getTable();
|
||||
$transactionsTable = (new MileageTransaction)->getTable();
|
||||
|
||||
return (float) DB::table("{$optionsTable} as opt")
|
||||
->join("{$ordersTable} as ord", 'opt.order_id', '=', 'ord.id')
|
||||
->where('ord.user_id', $userId)
|
||||
->where('ord.currency', $currency)
|
||||
->whereNotIn('opt.option_status', self::CANCELLED_STATUSES)
|
||||
->where('opt.subtotal_earned_points_amount', '>', 0)
|
||||
->whereNotExists(function ($q) {
|
||||
->whereNotExists(function ($q) use ($transactionsTable) {
|
||||
$q->select(DB::raw(1))
|
||||
->from('ecommerce_mileage_transactions as tx')
|
||||
->from("{$transactionsTable} as tx")
|
||||
->whereColumn('tx.order_option_id', 'opt.id')
|
||||
->whereIn('tx.type', self::EARN_TYPES);
|
||||
})
|
||||
|
||||
+30
-11
@@ -3,6 +3,7 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
@@ -10,6 +11,8 @@ use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\MileageTransactionTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\MileageTransaction;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\MileageTransactionRepositoryInterface;
|
||||
|
||||
/**
|
||||
@@ -17,6 +20,8 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\MileageTransactionRepositor
|
||||
*/
|
||||
class MileageTransactionRepository implements MileageTransactionRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
|
||||
/**
|
||||
* 적립(잔액 증가) 유형 목록
|
||||
*
|
||||
@@ -170,17 +175,20 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
public function paginateWithFilters(array $filters, int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
// 적립 lot 의 소멸 합 eager 집계 (N+1 회피) — 이 lot 을 source 로 하는 expired 거래 amount 합(음수).
|
||||
// 상관 서브쿼리는 self-reference + alias 가 빌더 prefix 처리와 충돌하므로 raw 로 일관 작성한다
|
||||
// (prefix 는 실제 테이블명에 한 번만 직접 적용).
|
||||
$prefixedTable = DB::connection()->getTablePrefix().(new MileageTransaction)->getTable();
|
||||
$expiredType = MileageTransactionTypeEnum::EXPIRED->value;
|
||||
$expiredSumSub = "(select COALESCE(SUM(ABS(exp.amount)), 0) from `{$prefixedTable}` as exp"
|
||||
." where exp.type = '{$expiredType}' and exp.source_transaction_id = `{$prefixedTable}`.id)";
|
||||
// 소멸분 합계는 같은 테이블을 다시 보는 상관 서브쿼리다. 별칭은 빌더가 만들고
|
||||
// (grammar 가 프리픽스를 별칭에도 붙인다), raw 는 집계 함수 한 곳만 남긴다.
|
||||
// 서브쿼리 FROM 이 한 테이블뿐이라 집계 대상 컬럼은 한정 없이 써도 모호하지 않다.
|
||||
$table = (new MileageTransaction)->getTable();
|
||||
|
||||
$expiredAmount = DB::table("{$table} as exp")
|
||||
->select(DB::raw('COALESCE(SUM(ABS(amount)), 0)'))
|
||||
->where('exp.type', MileageTransactionTypeEnum::EXPIRED->value)
|
||||
->whereColumn('exp.source_transaction_id', "{$table}.id");
|
||||
|
||||
$query = MileageTransaction::query()
|
||||
->with(['user', 'grantedByUser', 'order'])
|
||||
->addSelect('*')
|
||||
->addSelect(DB::raw("{$expiredSumSub} as expired_amount"));
|
||||
->addSelect(['expired_amount' => $expiredAmount]);
|
||||
|
||||
if (! empty($filters['user_id'])) {
|
||||
$query->where('user_id', $filters['user_id']);
|
||||
@@ -233,8 +241,12 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
});
|
||||
}
|
||||
|
||||
// 적립/사용 이력은 계속 쌓이므로 지연 조인으로 뒤쪽 페이지 비용을 고정한다.
|
||||
// 정렬은 applySort 가 닫힌 슬러그 집합으로 해석해 이미 쿼리에 적용돼 있다.
|
||||
$this->applySort($query, $filters['sort'] ?? 'created_at_desc');
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 정렬이 applySort 로 쿼리에 직접
|
||||
// 적용돼 지연 조인 계약(정렬 미적용 쿼리)을 만족하지 않는다. 컬럼 프루닝은 후속 정리 대상.
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
@@ -278,7 +290,13 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
$query->where('currency', $filters['currency']);
|
||||
}
|
||||
|
||||
return $query->orderByDesc('id')->paginate($perPage);
|
||||
// 회원 마일리지 내역 — 계속 쌓이는 이력이라 지연 조인으로 뒤쪽 페이지 비용을 고정한다
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: [['column' => 'id', 'direction' => 'desc']],
|
||||
perPage: $perPage,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -360,8 +378,9 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
{
|
||||
$threshold = $now->copy()->subDays($delayDays);
|
||||
|
||||
$query = DB::table('ecommerce_order_options as opt')
|
||||
->join('ecommerce_orders as ord', 'opt.order_id', '=', 'ord.id')
|
||||
// 테이블명은 모델에서 얻는다 (문자열 하드코딩 금지)
|
||||
$query = DB::table((new OrderOption)->getTable().' as opt')
|
||||
->join((new Order)->getTable().' as ord', 'opt.order_id', '=', 'ord.id')
|
||||
->whereNotNull('ord.user_id')
|
||||
->where('opt.option_status', $triggerStatus)
|
||||
->whereNotNull("opt.{$triggerColumn}")
|
||||
@@ -371,7 +390,7 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
// (나눠 확정·병합으로 목표액이 늘어난 옵션의 잔여분까지 스케줄러가 포착)
|
||||
// 빌더 서브쿼리로 표현 — raw SQL/테이블 별칭은 prefix 자동 적용을 받지 못하므로 별칭 없이 컬럼만 참조.
|
||||
->where('opt.subtotal_earned_points_amount', '>', function ($sub) {
|
||||
$sub->from('ecommerce_mileage_transactions')
|
||||
$sub->from((new MileageTransaction)->getTable())
|
||||
->selectRaw('COALESCE(SUM(amount), 0)')
|
||||
->whereColumn('order_option_id', 'opt.id')
|
||||
->where('type', MileageTransactionTypeEnum::PURCHASE_EARN->value);
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Models\User;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -23,6 +25,63 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
|
||||
*/
|
||||
class OrderRepository implements OrderRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/**
|
||||
* 주문 목록이 실제로 사용하는 컬럼
|
||||
*
|
||||
* `ecommerce_orders` 는 스냅샷 mediumText 5종 + 관리자 메모 + 통화별 금액 text 16종을 갖는다.
|
||||
* 목록에서 쓰지 않는 이 컬럼들까지 읽으면 뒤쪽 페이지에서 건너뛸 행의 넓은 컬럼까지 함께
|
||||
* 읽혀 비용이 선형으로 커진다. 관리자 목록(OrderListResource)과 회원 주문내역
|
||||
* (UserOrderListResource)이 참조하는 컬럼의 합집합만 남긴다.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const LIST_COLUMNS = [
|
||||
'id',
|
||||
'user_id',
|
||||
'order_number',
|
||||
'order_status',
|
||||
'order_device',
|
||||
'is_first_order',
|
||||
'currency',
|
||||
'currency_snapshot',
|
||||
'total_amount',
|
||||
'total_shipping_amount',
|
||||
'total_paid_amount',
|
||||
'total_cancelled_amount',
|
||||
'total_refunded_amount',
|
||||
'total_points_used_amount',
|
||||
'total_earned_points_amount',
|
||||
'mc_total_amount',
|
||||
'mc_total_shipping_amount',
|
||||
'ordered_at',
|
||||
'created_at',
|
||||
'updated_at',
|
||||
'deleted_at',
|
||||
];
|
||||
|
||||
/**
|
||||
* 주문 목록 정렬 허용 컬럼
|
||||
*
|
||||
* 요청 값을 그대로 orderBy 에 넘기면 없는 컬럼으로 SQL 오류가 나거나 인덱스 없는 넓은
|
||||
* 컬럼 정렬을 강제할 수 있다.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const SORTABLE_COLUMNS = [
|
||||
'id',
|
||||
'order_number',
|
||||
'order_status',
|
||||
'total_amount',
|
||||
'total_shipping_amount',
|
||||
'total_paid_amount',
|
||||
'ordered_at',
|
||||
'paid_at',
|
||||
'created_at',
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
protected Order $model
|
||||
) {}
|
||||
@@ -90,14 +149,9 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
*/
|
||||
public function getListWithFilters(array $filters, int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
$query = $this->model->newQuery()
|
||||
->with([
|
||||
'user',
|
||||
'options',
|
||||
'shippingAddress',
|
||||
'payment',
|
||||
'shippings',
|
||||
]);
|
||||
// 관계는 지연 조인의 outer 에서만 로드한다 (inner 에 붙으면 관계 쿼리가 두 번 실행되고,
|
||||
// inner 는 키 컬럼만 조회하므로 eager load 가 성립하지도 않는다).
|
||||
$query = $this->model->newQuery();
|
||||
|
||||
// 권한 스코프 필터링
|
||||
PermissionHelper::applyPermissionScope($query, 'sirsoft-ecommerce.orders.read');
|
||||
@@ -119,8 +173,8 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
if ($ordererUser) {
|
||||
$query->where('user_id', $ordererUser->id);
|
||||
} else {
|
||||
// UUID에 해당하는 회원이 없으면 결과 없음
|
||||
$query->whereRaw('1 = 0');
|
||||
// UUID에 해당하는 회원이 없으면 결과 없음. 빈 whereIn 은 `0 = 1` 로 컴파일된다
|
||||
$query->whereIn($query->getModel()->getKeyName(), []);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,12 +339,22 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
$query->whereIn('order_device', $devices);
|
||||
}
|
||||
|
||||
// 정렬
|
||||
$sortBy = $filters['sort_by'] ?? 'ordered_at';
|
||||
$sortOrder = $filters['sort_order'] ?? 'desc';
|
||||
$query->orderBy($sortBy, $sortOrder);
|
||||
// 정렬 — 요청 값은 허용 목록으로만 해석한다
|
||||
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'ordered_at');
|
||||
|
||||
return $query->paginate($perPage);
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: self::LIST_COLUMNS,
|
||||
sort: $sort,
|
||||
perPage: $perPage,
|
||||
relations: [
|
||||
'user',
|
||||
'options',
|
||||
'shippingAddress',
|
||||
'payment',
|
||||
'shippings',
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -496,10 +560,10 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
$this->applyFiltersToQuery($query, $filters);
|
||||
}
|
||||
|
||||
// 정렬
|
||||
$sortBy = $filters['sort_by'] ?? 'ordered_at';
|
||||
$sortOrder = $filters['sort_order'] ?? 'desc';
|
||||
$query->orderBy($sortBy, $sortOrder);
|
||||
// 정렬 (목록 조회와 동일한 허용 컬럼 화이트리스트)
|
||||
foreach ($this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'ordered_at') as $sort) {
|
||||
$query->orderBy($sort['column'], $sort['direction']);
|
||||
}
|
||||
|
||||
return $query->get();
|
||||
}
|
||||
@@ -639,7 +703,7 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
$optionIds = $order->options()->pluck('id')->toArray();
|
||||
$addressIds = $order->addresses()->pluck('id')->toArray();
|
||||
|
||||
return ActivityLog::where(function (Builder $q) use ($order, $optionIds, $addressIds) {
|
||||
$query = ActivityLog::where(function (Builder $q) use ($order, $optionIds, $addressIds) {
|
||||
// 주문 자체 로그
|
||||
$q->where(function (Builder $sub) use ($order) {
|
||||
$sub->where('loggable_type', $order->getMorphClass())
|
||||
@@ -661,6 +725,15 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
->whereIn('loggable_id', $addressIds);
|
||||
});
|
||||
}
|
||||
})->orderBy('created_at', $sortOrder)->paginate($perPage);
|
||||
});
|
||||
|
||||
// 활동 로그는 변경 내역(mediumText)을 리소스가 그대로 노출하므로 컬럼은 좁히지 않고
|
||||
// 지연 조인으로 넓은 컬럼을 읽는 행 수만 이번 페이지 분량으로 고정한다.
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: [['column' => 'created_at', 'direction' => $sortOrder]],
|
||||
perPage: $perPage,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,8 @@ class ProductCommonInfoRepository implements ProductCommonInfoRepositoryInterfac
|
||||
$query->with($with);
|
||||
}
|
||||
})
|
||||
// audit:allow repository-paginate-column-pruning reason: 상품 공통정보 "템플릿" 목록 —
|
||||
// 행 수가 운영자가 만든 템플릿 수에 묶여 OFFSET 이 깊어질 수 없다
|
||||
->paginate($perPage);
|
||||
}
|
||||
|
||||
@@ -113,6 +115,8 @@ class ProductCommonInfoRepository implements ProductCommonInfoRepositoryInterfac
|
||||
$query->with($with);
|
||||
}
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 상품 공통정보 "템플릿" 목록 —
|
||||
// 행 수가 운영자가 만든 템플릿 수에 묶여 OFFSET 이 깊어질 수 없다
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductInquiry;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductInquiryRepositoryInterface;
|
||||
|
||||
@@ -12,6 +14,8 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductInquiryRepositoryInt
|
||||
*/
|
||||
class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
|
||||
public function __construct(
|
||||
protected ProductInquiry $model
|
||||
) {}
|
||||
@@ -43,6 +47,8 @@ class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
return $this->model->newQuery()
|
||||
->where('product_id', $productId)
|
||||
->orderBy('created_at', 'desc')
|
||||
// audit:allow repository-paginate-column-pruning reason: 상품 1건에 종속된 문의 목록 —
|
||||
// where(product_id) 로 이미 좁혀져 OFFSET 이 깊어질 수 없고, 목록이 본문을 그대로 쓴다
|
||||
->paginate($perPage);
|
||||
}
|
||||
|
||||
@@ -86,6 +92,8 @@ class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
});
|
||||
}
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 사용자 1명에 종속된 내 문의 목록 —
|
||||
// where(user_id) 로 이미 좁혀져 OFFSET 이 깊어질 수 없다
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
@@ -94,9 +102,7 @@ class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
*/
|
||||
public function getListWithFilters(array $filters, int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
$query = $this->model->newQuery()
|
||||
->with(['product', 'user'])
|
||||
->orderBy('created_at', 'desc');
|
||||
$query = $this->model->newQuery();
|
||||
|
||||
// 상품명 검색
|
||||
if (! empty($filters['search_keyword'])) {
|
||||
@@ -116,15 +122,23 @@ class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
$query->where('is_answered', (bool) $filters['is_answered']);
|
||||
}
|
||||
|
||||
// 기간 필터
|
||||
// 기간 필터 — whereDate 는 컬럼에 함수를 씌워 인덱스를 무력화하므로 범위 조건으로 준다
|
||||
if (! empty($filters['date_from'])) {
|
||||
$query->whereDate('created_at', '>=', $filters['date_from']);
|
||||
$query->where('created_at', '>=', Carbon::parse($filters['date_from'])->startOfDay());
|
||||
}
|
||||
if (! empty($filters['date_to'])) {
|
||||
$query->whereDate('created_at', '<=', $filters['date_to']);
|
||||
$query->where('created_at', '<=', Carbon::parse($filters['date_to'])->endOfDay());
|
||||
}
|
||||
|
||||
return $query->paginate($perPage);
|
||||
// 지연 조인: 전역 문의 목록은 무제한 성장하고 content(text)가 있어
|
||||
// OFFSET 이 훑는 구간에서 넓은 컬럼까지 읽힌다. inner 는 id 만 훑는다.
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: [['column' => 'created_at', 'direction' => 'desc']],
|
||||
perPage: $perPage,
|
||||
relations: ['product', 'user'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+2
@@ -90,6 +90,8 @@ class ProductNoticeTemplateRepository implements ProductNoticeTemplateRepository
|
||||
$query->with($with);
|
||||
}
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 상품 안내 "템플릿" 목록 —
|
||||
// 행 수가 운영자가 만든 템플릿 수에 묶여 OFFSET 이 깊어질 수 없다
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\ActivityLog;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
@@ -21,6 +23,12 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
*/
|
||||
class ProductRepository implements ProductRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/** 허용 정렬 컬럼 (ProductListRequest 와 동일 집합) */
|
||||
private const ADMIN_SORTABLE_COLUMNS = ['created_at', 'updated_at', 'selling_price', 'stock_quantity', 'name'];
|
||||
|
||||
public function __construct(
|
||||
protected Product $model
|
||||
) {}
|
||||
@@ -69,11 +77,14 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
*/
|
||||
public function getListWithFilters(array $filters, int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
$query = $this->model->newQuery()->with(['options', 'categories', 'images', 'brand', 'shippingPolicy']);
|
||||
$query = $this->model->newQuery();
|
||||
|
||||
// 권한 스코프 필터링
|
||||
PermissionHelper::applyPermissionScope($query, 'sirsoft-ecommerce.products.read');
|
||||
|
||||
// 지연 조인 outer 전용 관계 (inner 는 id 만 훑으므로 여기서 with() 를 걸지 않는다)
|
||||
$listRelations = ['options', 'categories', 'images', 'brand', 'shippingPolicy'];
|
||||
|
||||
// 문자열 검색
|
||||
if (! empty($filters['search_keyword'])) {
|
||||
$keyword = $filters['search_keyword'];
|
||||
@@ -110,11 +121,16 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
// 매칭 ID 로 조건 한정 (빈 매칭은 존재하지 않는 ID 로 빈 결과 → total=0 이 정상)
|
||||
$query->whereIn('id', $matchedIds ?: [0]);
|
||||
|
||||
// 필터 + 정렬 적용
|
||||
// 필터 적용
|
||||
$this->applyAdminFilters($query, $filters);
|
||||
$this->applyAdminSorting($query, $filters);
|
||||
|
||||
return $query->paginate($perPage);
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $this->resolveAdminSortSpec($filters),
|
||||
perPage: $perPage,
|
||||
relations: $listRelations,
|
||||
);
|
||||
}
|
||||
|
||||
// FULLTEXT 미대상 필드 (product_code, sku, barcode) → LIKE 직접
|
||||
@@ -134,10 +150,13 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
// 필터 적용
|
||||
$this->applyAdminFilters($query, $filters);
|
||||
|
||||
// 정렬
|
||||
$this->applyAdminSorting($query, $filters);
|
||||
|
||||
return $query->paginate($perPage);
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $this->resolveAdminSortSpec($filters),
|
||||
perPage: $perPage,
|
||||
relations: $listRelations,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -398,11 +417,13 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
public function getPublicList(array $filters, int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
$query = $this->model->newQuery()
|
||||
->with(['images', 'categories', 'brand', 'activeLabelAssignments.label'])
|
||||
->withCount('visibleReviews as review_count')
|
||||
->withAvg('visibleReviews as rating_avg', 'rating')
|
||||
->where('display_status', 'visible');
|
||||
|
||||
// 지연 조인 outer 전용 관계 (inner 는 id 만 훑으므로 with() 를 걸지 않는다)
|
||||
$listRelations = ['images', 'categories', 'brand', 'activeLabelAssignments.label'];
|
||||
|
||||
// 카테고리 필터 (ID) — 선택 카테고리 + 모든 하위 카테고리 포함
|
||||
if (! empty($filters['category_id'])) {
|
||||
$categoryIds = Category::selfAndDescendantIds((int) $filters['category_id']);
|
||||
@@ -420,8 +441,8 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
$q->whereIn('ecommerce_product_categories.category_id', $categoryIds);
|
||||
});
|
||||
} else {
|
||||
// 존재하지 않는 slug → 빈 결과 (500 아님)
|
||||
$query->whereRaw('1 = 0');
|
||||
// 존재하지 않는 slug → 빈 결과 (500 아님). 빈 whereIn 은 `0 = 1` 로 컴파일된다
|
||||
$query->whereIn($query->getModel()->getKeyName(), []);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -446,18 +467,35 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
|
||||
// 정렬
|
||||
$sort = $filters['sort'] ?? 'latest';
|
||||
match ($sort) {
|
||||
'sales' => $query
|
||||
|
||||
// 판매량 정렬은 집계 서브쿼리(total_sold) 를 select 에 올려 두고 그 별칭으로 정렬한다.
|
||||
// 지연 조인의 inner 는 select 를 id 하나로 교체하므로 별칭이 사라져 성립하지 않는다.
|
||||
if ($sort === 'sales') {
|
||||
$query
|
||||
->addSelect(['total_sold' => OrderOption::selectRaw('COALESCE(SUM(quantity), 0)')
|
||||
->whereColumn('product_id', 'ecommerce_products.id'),
|
||||
])
|
||||
->orderByDesc('total_sold'),
|
||||
'price_asc' => $query->orderBy('selling_price', 'asc'),
|
||||
'price_desc' => $query->orderBy('selling_price', 'desc'),
|
||||
default => $query->orderBy('created_at', 'desc'), // latest
|
||||
->orderByDesc('total_sold')
|
||||
->with($listRelations);
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 판매량 정렬은 집계 서브쿼리
|
||||
// 별칭 기준이라 지연 조인 inner(=id 단일 select)로 옮길 수 없다. 나머지 정렬은 지연 조인 적용
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
$sortSpec = match ($sort) {
|
||||
'price_asc' => [['column' => 'selling_price', 'direction' => 'asc']],
|
||||
'price_desc' => [['column' => 'selling_price', 'direction' => 'desc']],
|
||||
default => [['column' => 'created_at', 'direction' => 'desc']], // latest
|
||||
};
|
||||
|
||||
return $query->paginate($perPage);
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $sortSpec,
|
||||
perPage: $perPage,
|
||||
relations: $listRelations,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -536,6 +574,10 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
->withAvg('visibleReviews as rating_avg', 'rating')
|
||||
->when($categoryId !== null, fn ($q) => $q->whereHas('categories', fn ($c) => $c->where('ecommerce_categories.id', $categoryId)))
|
||||
->orderBy($orderBy, $direction)
|
||||
// audit:allow repository-paginate-column-pruning reason: 통합검색 —
|
||||
// whereIn(id, $matchedIds) 로 FULLTEXT 매칭 ID 집합에 먼저 한정되므로 스캔 대상이
|
||||
// 상품 전체가 아니라 매칭 건수로 묶인다(OFFSET 이 훑는 범위도 그 안). 지연 조인의
|
||||
// inner 가 하는 일을 매칭 ID 산출이 이미 수행하는 구조다
|
||||
->paginate($limit, ['*'], 'page', $page);
|
||||
|
||||
return ['total' => $paginator->total(), 'items' => $paginator->getCollection()];
|
||||
@@ -672,23 +714,25 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 상품 목록 정렬을 쿼리에 적용합니다.
|
||||
* 관리자 상품 목록 정렬 스펙을 해석합니다.
|
||||
*
|
||||
* 지연 조인은 정렬을 inner/outer 양쪽에 동일하게 적용해야 하므로, 쿼리에 직접 orderBy 를
|
||||
* 거는 대신 스펙 배열을 돌려준다.
|
||||
*
|
||||
* @param Builder $query Eloquent 쿼리 빌더
|
||||
* @param array $filters 필터 배열
|
||||
* @return array<int, array{column: string, direction: string}> 정렬 스펙
|
||||
*/
|
||||
private function applyAdminSorting($query, array $filters): void
|
||||
private function resolveAdminSortSpec(array $filters): array
|
||||
{
|
||||
$sortBy = $filters['sort_by'] ?? 'created_at';
|
||||
$sortOrder = $filters['sort_order'] ?? 'desc';
|
||||
// 허용 컬럼 화이트리스트로 해석 (없는 컬럼 정렬은 기본값으로 흡수)
|
||||
$sort = $this->resolveSortSpec($filters, self::ADMIN_SORTABLE_COLUMNS, 'created_at')[0];
|
||||
|
||||
// 다국어 이름 정렬 처리
|
||||
if ($sortBy === 'name') {
|
||||
$locale = app()->getLocale();
|
||||
$query->orderBy("name->{$locale}", $sortOrder);
|
||||
} else {
|
||||
$query->orderBy($sortBy, $sortOrder);
|
||||
if ($sort['column'] === 'name') {
|
||||
$sort['column'] = 'name->'.app()->getLocale();
|
||||
}
|
||||
|
||||
return [$sort];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -755,7 +799,7 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
|
||||
$optionIds = $product->options()->pluck('id')->toArray();
|
||||
|
||||
return ActivityLog::where(function (Builder $q) use ($product, $optionIds) {
|
||||
$query = ActivityLog::where(function (Builder $q) use ($product, $optionIds) {
|
||||
// 상품 자체 로그
|
||||
$q->where(function (Builder $sub) use ($product) {
|
||||
$sub->where('loggable_type', $product->getMorphClass())
|
||||
@@ -769,6 +813,15 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
->whereIn('loggable_id', $optionIds);
|
||||
});
|
||||
}
|
||||
})->orderBy('created_at', $sortOrder)->paginate($perPage);
|
||||
});
|
||||
|
||||
// 활동 로그는 변경 내역(mediumText)을 리소스가 그대로 노출하므로 컬럼은 좁히지 않고
|
||||
// 지연 조인으로 넓은 컬럼을 읽는 행 수만 이번 페이지 분량으로 고정한다.
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: [['column' => 'created_at', 'direction' => $sortOrder]],
|
||||
perPage: $perPage,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,14 @@
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ReviewStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductOption;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductReview;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewRepositoryInterface;
|
||||
|
||||
@@ -14,6 +18,8 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductReviewRepositoryInte
|
||||
*/
|
||||
class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
|
||||
public function __construct(
|
||||
protected ProductReview $model
|
||||
) {}
|
||||
@@ -96,24 +102,31 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
$query->where('status', $filters['status']);
|
||||
}
|
||||
|
||||
// 기간 필터
|
||||
// 기간 필터 — whereDate 는 컬럼에 DATE() 를 씌워 인덱스를 못 쓰게 만든다.
|
||||
// 같은 결과를 내는 범위 조건으로 바꿔 created_at 인덱스를 살린다
|
||||
// (종료일은 그날 23:59:59.999999 까지 포함해야 whereDate 와 동일한 경계를 갖는다).
|
||||
if (! empty($filters['start_date'])) {
|
||||
$query->whereDate('created_at', '>=', $filters['start_date']);
|
||||
$query->where('created_at', '>=', Carbon::parse($filters['start_date'])->startOfDay());
|
||||
}
|
||||
if (! empty($filters['end_date'])) {
|
||||
$query->whereDate('created_at', '<=', $filters['end_date']);
|
||||
$query->where('created_at', '<=', Carbon::parse($filters['end_date'])->endOfDay());
|
||||
}
|
||||
|
||||
// 정렬
|
||||
$sort = $filters['sort'] ?? 'created_at_desc';
|
||||
match ($sort) {
|
||||
'created_at_asc' => $query->orderBy('created_at'),
|
||||
'rating_desc' => $query->orderByDesc('rating'),
|
||||
'rating_asc' => $query->orderBy('rating'),
|
||||
default => $query->orderByDesc('created_at'),
|
||||
// 정렬 — 선택지가 닫힌 집합이라 match 로 충분하다
|
||||
$sort = match ($filters['sort'] ?? 'created_at_desc') {
|
||||
'created_at_asc' => [['column' => 'created_at', 'direction' => 'asc']],
|
||||
'rating_desc' => [['column' => 'rating', 'direction' => 'desc']],
|
||||
'rating_asc' => [['column' => 'rating', 'direction' => 'asc']],
|
||||
default => [['column' => 'created_at', 'direction' => 'desc']],
|
||||
};
|
||||
|
||||
return $query->paginate($perPage);
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $sort,
|
||||
perPage: $perPage,
|
||||
relations: ['user', 'product', 'images', 'orderOption.order', 'replyAdmin'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -143,7 +156,7 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
if ($value === '' || $value === null) {
|
||||
continue;
|
||||
}
|
||||
$optionIds = DB::table('ecommerce_product_options')
|
||||
$optionIds = DB::table((new ProductOption)->getTable())
|
||||
->where('product_id', $productId)
|
||||
->whereRaw(
|
||||
"JSON_CONTAINS(option_values, JSON_OBJECT('key', JSON_OBJECT('ko', ?), 'value', JSON_OBJECT('ko', ?)))",
|
||||
@@ -153,7 +166,8 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
->toArray();
|
||||
|
||||
if (empty($optionIds)) {
|
||||
$query->whereRaw('0 = 1');
|
||||
// 일치 옵션 없음 → 빈 결과. 빈 whereIn 은 `0 = 1` 로 컴파일된다
|
||||
$query->whereIn($query->getModel()->getKeyName(), []);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -163,15 +177,20 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
}
|
||||
}
|
||||
|
||||
// 정렬
|
||||
$sort = $filters['sort'] ?? 'created_at_desc';
|
||||
match ($sort) {
|
||||
'rating_desc' => $query->orderByDesc('rating'),
|
||||
'rating_asc' => $query->orderBy('rating'),
|
||||
default => $query->orderByDesc('created_at'),
|
||||
// 정렬 — 선택지가 닫힌 집합이라 match 로 충분하다
|
||||
$sort = match ($filters['sort'] ?? 'created_at_desc') {
|
||||
'rating_desc' => [['column' => 'rating', 'direction' => 'desc']],
|
||||
'rating_asc' => [['column' => 'rating', 'direction' => 'asc']],
|
||||
default => [['column' => 'created_at', 'direction' => 'desc']],
|
||||
};
|
||||
|
||||
return $query->paginate($perPage);
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $sort,
|
||||
perPage: $perPage,
|
||||
relations: ['user', 'images'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -222,7 +241,7 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
public function getOptionFilters(int $productId): array
|
||||
{
|
||||
// 상품의 모든 옵션 조회 (기준: product_options 전체)
|
||||
$options = DB::table('ecommerce_product_options')
|
||||
$options = DB::table((new ProductOption)->getTable())
|
||||
->where('product_id', $productId)
|
||||
->orderBy('sort_order')
|
||||
->pluck('option_values', 'id')
|
||||
@@ -233,8 +252,9 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
}
|
||||
|
||||
// 옵션별 리뷰 건수 집계 (option_id → review count)
|
||||
$reviewCounts = DB::table('ecommerce_product_reviews as r')
|
||||
->join('ecommerce_order_options as oo', 'r.order_option_id', '=', 'oo.id')
|
||||
// 테이블명은 모델에서 얻는다 (문자열 하드코딩 금지)
|
||||
$reviewCounts = DB::table((new ProductReview)->getTable().' as r')
|
||||
->join((new OrderOption)->getTable().' as oo', 'r.order_option_id', '=', 'oo.id')
|
||||
->where('r.product_id', $productId)
|
||||
->where('r.status', ReviewStatus::VISIBLE->value)
|
||||
->whereNull('r.deleted_at')
|
||||
|
||||
@@ -59,6 +59,8 @@ class ProductWishlistRepository implements ProductWishlistRepositoryInterface
|
||||
->where('user_id', $userId)
|
||||
->with(['product.brand', 'product.categories', 'product.activeLabelAssignments.label'])
|
||||
->orderByDesc('created_at')
|
||||
// audit:allow repository-paginate-column-pruning reason: 사용자 1명에 종속된 찜 목록 —
|
||||
// where(user_id) 로 이미 좁혀지고, 피벗 성격의 테이블이라 넓은 컬럼이 없다
|
||||
->paginate($perPage);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
@@ -15,6 +16,11 @@ use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ShippingPolicyRepositoryInt
|
||||
*/
|
||||
class ShippingPolicyRepository implements ShippingPolicyRepositoryInterface
|
||||
{
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/** 허용 정렬 컬럼 (ShippingPolicyListRequest 와 동일 집합) */
|
||||
private const SORTABLE_COLUMNS = ['id', 'name', 'is_active', 'sort_order', 'created_at', 'updated_at'];
|
||||
|
||||
public function __construct(
|
||||
protected ShippingPolicy $model
|
||||
) {}
|
||||
@@ -75,18 +81,19 @@ class ShippingPolicyRepository implements ShippingPolicyRepositoryInterface
|
||||
$query->where('is_active', $isActive);
|
||||
}
|
||||
|
||||
// 정렬
|
||||
$sortBy = $filters['sort_by'] ?? 'created_at';
|
||||
$sortOrder = $filters['sort_order'] ?? 'desc';
|
||||
// 정렬 (허용 컬럼 화이트리스트로 해석)
|
||||
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'created_at')[0];
|
||||
|
||||
// 다국어 이름 정렬 처리
|
||||
if ($sortBy === 'name') {
|
||||
if ($sort['column'] === 'name') {
|
||||
$locale = app()->getLocale();
|
||||
$query->orderBy("name->{$locale}", $sortOrder);
|
||||
$query->orderBy("name->{$locale}", $sort['direction']);
|
||||
} else {
|
||||
$query->orderBy($sortBy, $sortOrder);
|
||||
$query->orderBy($sort['column'], $sort['direction']);
|
||||
}
|
||||
|
||||
// audit:allow repository-paginate-column-pruning reason: 배송정책 "정의" 목록 —
|
||||
// 행 수가 운영자가 만든 정책 수에 묶여 OFFSET 이 깊어질 수 없다
|
||||
return $query->paginate($perPage);
|
||||
}
|
||||
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Http\Controllers\Admin;
|
||||
|
||||
use App\Models\User;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponDiscountType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueCondition;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueMethod;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponTargetType;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 쿠폰 수정 요청의 조건부 검증 대칭성
|
||||
*
|
||||
* StoreCouponRequest 는 valid_type 에 따라 유효기간 필드를 required_if 로 강제하지만
|
||||
* UpdateCouponRequest 에는 그 조건부 규칙이 없어, 수정 경로로 "기간 지정" 쿠폰의
|
||||
* 시작일/종료일을 비운 채 저장할 수 있었습니다(검증 우회). 반대로 per_user_limit 은
|
||||
* sometimes 가 없어 다른 탭만 수정할 때도 항상 전송해야 했습니다(부분 수정 실패).
|
||||
*/
|
||||
class CouponUpdateConditionalValidationTest extends ModuleTestCase
|
||||
{
|
||||
private string $baseUrl = '/api/modules/sirsoft-ecommerce/admin/promotion-coupons';
|
||||
|
||||
protected User $adminUser;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
app()->setLocale('ko');
|
||||
|
||||
$this->adminUser = $this->createAdminUser([
|
||||
'sirsoft-ecommerce.promotion-coupon.read',
|
||||
'sirsoft-ecommerce.promotion-coupon.create',
|
||||
'sirsoft-ecommerce.promotion-coupon.update',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿠폰 생성 데이터
|
||||
*
|
||||
* @param array $overrides 오버라이드할 속성
|
||||
* @return array 생성 요청 본문
|
||||
*/
|
||||
private function validCouponData(array $overrides = []): array
|
||||
{
|
||||
return array_merge([
|
||||
'name' => ['ko' => '유효기간 쿠폰', 'en' => 'Validity Coupon'],
|
||||
'target_type' => CouponTargetType::PRODUCT_AMOUNT->value,
|
||||
'discount_type' => CouponDiscountType::FIXED->value,
|
||||
'discount_value' => 1000,
|
||||
'min_order_amount' => 5000,
|
||||
'issue_method' => CouponIssueMethod::DIRECT->value,
|
||||
'issue_condition' => CouponIssueCondition::MANUAL->value,
|
||||
'issue_status' => CouponIssueStatus::ISSUING->value,
|
||||
'per_user_limit' => 0,
|
||||
'valid_type' => 'period',
|
||||
'valid_from' => now()->format('Y-m-d'),
|
||||
'valid_to' => now()->addMonth()->format('Y-m-d'),
|
||||
], $overrides);
|
||||
}
|
||||
|
||||
/**
|
||||
* 테스트용 쿠폰을 생성하고 ID를 반환합니다.
|
||||
*
|
||||
* @param array $overrides 생성 데이터 오버라이드
|
||||
* @return int 생성된 쿠폰 ID
|
||||
*/
|
||||
private function createCoupon(array $overrides = []): int
|
||||
{
|
||||
$response = $this->actingAs($this->adminUser)
|
||||
->postJson($this->baseUrl, $this->validCouponData($overrides));
|
||||
|
||||
$response->assertStatus(201);
|
||||
|
||||
return (int) $response->json('data.id');
|
||||
}
|
||||
|
||||
/**
|
||||
* 기간 지정 쿠폰의 시작일/종료일을 비운 수정은 거부됩니다.
|
||||
*/
|
||||
public function test_update_period_type_without_dates_fails(): void
|
||||
{
|
||||
$couponId = $this->createCoupon();
|
||||
|
||||
$response = $this->actingAs($this->adminUser)
|
||||
->putJson("{$this->baseUrl}/{$couponId}", [
|
||||
'valid_type' => 'period',
|
||||
'valid_from' => null,
|
||||
'valid_to' => null,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['valid_from', 'valid_to']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 발급일 기준 쿠폰의 유효일수를 비운 수정은 거부됩니다.
|
||||
*/
|
||||
public function test_update_days_from_issue_type_without_valid_days_fails(): void
|
||||
{
|
||||
$couponId = $this->createCoupon([
|
||||
'valid_type' => 'days_from_issue',
|
||||
'valid_days' => 30,
|
||||
'valid_from' => null,
|
||||
'valid_to' => null,
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($this->adminUser)
|
||||
->putJson("{$this->baseUrl}/{$couponId}", [
|
||||
'valid_type' => 'days_from_issue',
|
||||
'valid_days' => null,
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['valid_days']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효기간을 함께 보내는 정상 수정은 통과합니다.
|
||||
*/
|
||||
public function test_update_period_type_with_dates_passes(): void
|
||||
{
|
||||
$couponId = $this->createCoupon();
|
||||
|
||||
$response = $this->actingAs($this->adminUser)
|
||||
->putJson("{$this->baseUrl}/{$couponId}", [
|
||||
'valid_type' => 'period',
|
||||
'valid_from' => now()->addDay()->format('Y-m-d'),
|
||||
'valid_to' => now()->addMonths(2)->format('Y-m-d'),
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* valid_type 을 보내지 않는 부분 수정은 유효기간 필드를 요구하지 않습니다.
|
||||
*
|
||||
* required_if 는 조건 필드가 요청에 없으면 발화하지 않으므로, 다른 탭만 수정하는
|
||||
* 요청이 유효기간 때문에 막히지 않아야 합니다.
|
||||
*/
|
||||
public function test_update_without_valid_type_does_not_require_dates(): void
|
||||
{
|
||||
$couponId = $this->createCoupon();
|
||||
|
||||
$response = $this->actingAs($this->adminUser)
|
||||
->putJson("{$this->baseUrl}/{$couponId}", [
|
||||
'min_order_amount' => 7000,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* per_user_limit 을 보내지 않는 부분 수정이 통과합니다.
|
||||
*
|
||||
* 같은 파일의 다른 필드는 모두 sometimes 를 갖는데 per_user_limit 만 누락돼 있어
|
||||
* 부분 수정 요청이 "1인당 사용 제한" 미전송으로 422 가 되던 결함입니다.
|
||||
*/
|
||||
public function test_update_without_per_user_limit_passes(): void
|
||||
{
|
||||
$couponId = $this->createCoupon();
|
||||
|
||||
$response = $this->actingAs($this->adminUser)
|
||||
->putJson("{$this->baseUrl}/{$couponId}", [
|
||||
'min_order_amount' => 8000,
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
}
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Http\Controllers\Admin;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Pagination\Paginator;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 주문 목록 지연 조인 회귀 테스트
|
||||
*
|
||||
* 주문 목록은 이제 "이번 페이지의 ID 를 먼저 구하고, 그 ID 에 대해서만 목록 컬럼과 관계를
|
||||
* 읽는" 2단계 조회다. 성능 수치는 머신에 좌우되므로 단언하지 않고, 그 성질이 유지되는지를
|
||||
* 쿼리 구조로 고정한다 — 누군가 목록 컬럼을 되돌리거나 관계를 inner 에 다시 붙이면 실패한다.
|
||||
*
|
||||
* 결과 정합성(무엇이 몇 건 어떤 순서로 나오는가)도 함께 고정한다. 조회 방식을 바꾸는 변경에서
|
||||
* 가장 조용히 깨지는 것이 정렬과 페이지 경계다.
|
||||
*/
|
||||
class OrderListDeferredJoinTest extends ModuleTestCase
|
||||
{
|
||||
protected User $adminUser;
|
||||
|
||||
/** 수집된 실행 쿼리 SQL 목록 */
|
||||
private array $queries = [];
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->adminUser = $this->createAdminUser(['sirsoft-ecommerce.orders.read']);
|
||||
}
|
||||
|
||||
/** 쿼리 로그 수집을 시작합니다. */
|
||||
private function startCapture(): void
|
||||
{
|
||||
$this->queries = [];
|
||||
|
||||
DB::listen(function ($query) {
|
||||
$this->queries[] = $query->sql;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 수집된 쿼리 중 조건에 맞는 것만 돌려줍니다.
|
||||
*
|
||||
* @param string $needle 포함 문자열
|
||||
* @return array<int, string> 일치 쿼리 목록
|
||||
*/
|
||||
private function queriesContaining(string $needle): array
|
||||
{
|
||||
return array_values(array_filter($this->queries, fn (string $sql) => str_contains($sql, $needle)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문 목록을 조회합니다.
|
||||
*
|
||||
* 페이지 번호는 페이지네이터가 요청에서 해석하므로(HTTP 경로와 동일), 저장소를 직접
|
||||
* 호출하는 테스트에서는 resolver 로 지정한다.
|
||||
*
|
||||
* @param array $filters 조회 필터
|
||||
* @param int $perPage 페이지당 건수
|
||||
* @param int $page 조회할 페이지
|
||||
* @return LengthAwarePaginator 조회 결과
|
||||
*/
|
||||
private function listOrders(array $filters = [], int $perPage = 10, int $page = 1)
|
||||
{
|
||||
Paginator::currentPageResolver(fn () => $page);
|
||||
|
||||
try {
|
||||
return app(OrderRepositoryInterface::class)->getListWithFilters($filters, $perPage);
|
||||
} finally {
|
||||
Paginator::currentPageResolver(fn () => 1);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_offset_scan_reads_only_id_column(): void
|
||||
{
|
||||
OrderFactory::new()->count(25)->create();
|
||||
|
||||
$this->startCapture();
|
||||
$this->listOrders(page: 2);
|
||||
|
||||
$offsetQueries = $this->queriesContaining('offset');
|
||||
|
||||
$this->assertNotEmpty($offsetQueries, '페이지 조회에는 OFFSET 쿼리가 있어야 한다');
|
||||
|
||||
foreach ($offsetQueries as $sql) {
|
||||
// 넓은 컬럼이 OFFSET 스캔에 실리면 뒤쪽 페이지 비용이 선형으로 커진다
|
||||
$this->assertStringNotContainsString('admin_memo', $sql);
|
||||
$this->assertStringNotContainsString('order_meta', $sql);
|
||||
$this->assertStringNotContainsString('promotions_applied_snapshot', $sql);
|
||||
$this->assertStringNotContainsString('mc_subtotal_amount', $sql);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_list_query_does_not_select_unused_wide_columns(): void
|
||||
{
|
||||
OrderFactory::new()->count(3)->create();
|
||||
|
||||
$this->startCapture();
|
||||
$this->listOrders();
|
||||
|
||||
$selectQueries = $this->queriesContaining('from `g7_ecommerce_orders`');
|
||||
|
||||
$this->assertNotEmpty($selectQueries);
|
||||
|
||||
foreach ($selectQueries as $sql) {
|
||||
$this->assertStringNotContainsString('admin_memo', $sql, '목록은 관리자 메모를 읽지 않는다');
|
||||
$this->assertStringNotContainsString('mileage_policy_snapshot', $sql);
|
||||
}
|
||||
}
|
||||
|
||||
public function test_relation_queries_run_once_for_the_page(): void
|
||||
{
|
||||
OrderFactory::new()->count(5)->create();
|
||||
|
||||
$this->startCapture();
|
||||
$result = $this->listOrders();
|
||||
|
||||
// 관계는 outer 에서만 로드된다 — inner 에도 붙으면 같은 관계 쿼리가 2회 실행된다
|
||||
$this->assertCount(1, $this->queriesContaining('from `g7_ecommerce_order_options`'));
|
||||
$this->assertTrue($result->getCollection()->first()->relationLoaded('options'));
|
||||
$this->assertTrue($result->getCollection()->first()->relationLoaded('shippingAddress'));
|
||||
}
|
||||
|
||||
public function test_pages_do_not_overlap_and_follow_sort_order(): void
|
||||
{
|
||||
// ordered_at 이 같은 주문이 섞여 있어도 페이지 경계가 흔들리면 안 된다
|
||||
$sharedTime = now()->subDay();
|
||||
OrderFactory::new()->count(12)->create(['ordered_at' => $sharedTime]);
|
||||
OrderFactory::new()->count(8)->create();
|
||||
|
||||
$page1 = $this->listOrders([], 10, 1);
|
||||
$page2 = $this->listOrders([], 10, 2);
|
||||
|
||||
$firstIds = $page1->getCollection()->pluck('id')->all();
|
||||
$secondIds = $page2->getCollection()->pluck('id')->all();
|
||||
|
||||
$this->assertCount(10, $firstIds);
|
||||
$this->assertEmpty(array_intersect($firstIds, $secondIds), '페이지 간 중복 주문이 없어야 한다');
|
||||
$this->assertSame(20, $page1->total());
|
||||
}
|
||||
|
||||
public function test_sort_by_falls_back_when_column_is_not_allowed(): void
|
||||
{
|
||||
OrderFactory::new()->count(3)->create();
|
||||
|
||||
// 예전에는 요청 값이 그대로 orderBy 로 흘러 SQL 오류가 났다
|
||||
$result = $this->listOrders(['sort_by' => 'admin_memo; drop table users', 'sort_order' => 'sideways']);
|
||||
|
||||
$this->assertSame(3, $result->total());
|
||||
}
|
||||
|
||||
public function test_filters_still_narrow_the_result(): void
|
||||
{
|
||||
OrderFactory::new()->count(4)->create(['order_device' => 'pc']);
|
||||
OrderFactory::new()->count(3)->create(['order_device' => 'mobile']);
|
||||
|
||||
$result = $this->listOrders(['order_device' => 'mobile']);
|
||||
|
||||
$this->assertSame(3, $result->total());
|
||||
$this->assertCount(3, $result->getCollection());
|
||||
}
|
||||
|
||||
public function test_soft_deleted_orders_stay_excluded(): void
|
||||
{
|
||||
$orders = OrderFactory::new()->count(5)->create();
|
||||
$orders->first()->delete();
|
||||
|
||||
$result = $this->listOrders();
|
||||
|
||||
$this->assertSame(4, $result->total());
|
||||
$this->assertNotContains($orders->first()->id, $result->getCollection()->pluck('id')->all());
|
||||
}
|
||||
|
||||
public function test_admin_list_endpoint_still_returns_expected_payload(): void
|
||||
{
|
||||
OrderFactory::new()->count(3)->create();
|
||||
|
||||
$response = $this->actingAs($this->adminUser)
|
||||
->getJson('/api/modules/sirsoft-ecommerce/admin/orders');
|
||||
|
||||
$response->assertOk()
|
||||
->assertJsonStructure([
|
||||
'data' => [
|
||||
'data' => [
|
||||
'*' => ['id', 'order_number', 'order_status', 'total_amount', 'ordered_at'],
|
||||
],
|
||||
'pagination',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertCount(3, $response->json('data.data'));
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Http\Controllers\User;
|
||||
|
||||
use App\Models\User;
|
||||
use Modules\Sirsoft\Ecommerce\Models\UserAddress;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 배송지 수정 요청의 주소 필수 조합 검증
|
||||
*
|
||||
* StoreUserAddressRequest 는 "국내(우편번호+주소) 또는 해외(주소+도시+우편번호)" 중
|
||||
* 한 조합을 required_with/required_without 로 강제하지만, UpdateUserAddressRequest 에는
|
||||
* 그 규칙이 없어 수정 경로로 주소를 통째로 비울 수 있었습니다(검증 우회).
|
||||
*
|
||||
* 다만 Store 규칙을 그대로 옮기면 부분 수정이 깨집니다. 검증은 "요청 페이로드"가 아니라
|
||||
* "기존 레코드 + 페이로드를 합친 결과 상태"를 기준으로 해야 하며, 이 테스트가 그 계약을
|
||||
* 양방향(우회 차단 / 부분 수정 보존)으로 고정합니다.
|
||||
*/
|
||||
class UserAddressUpdatePresenceValidationTest extends ModuleTestCase
|
||||
{
|
||||
private string $baseUrl = '/api/modules/sirsoft-ecommerce/user/addresses';
|
||||
|
||||
/**
|
||||
* 기본 배송지 여부만 바꾸는 요청은 주소 규칙을 발화시키지 않습니다.
|
||||
*
|
||||
* 주소 필드를 전혀 건드리지 않는 요청이 422 가 되면 부분 수정이 통째로 깨집니다.
|
||||
*/
|
||||
public function test_update_only_is_default_passes(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create(['user_id' => $user->id]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", ['is_default' => true]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* 국내 주소를 통째로 비우는 수정은 거부됩니다.
|
||||
*/
|
||||
public function test_update_blanking_domestic_address_fails(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create(['user_id' => $user->id]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", [
|
||||
'zipcode' => '',
|
||||
'address' => '',
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['zipcode', 'address']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 우편번호만 비우는 수정은 거부됩니다.
|
||||
*/
|
||||
public function test_update_blanking_zipcode_only_fails(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create(['user_id' => $user->id]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", ['zipcode' => '']);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['zipcode']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 도로명 주소만 바꾸는 수정은 기존 우편번호를 근거로 통과합니다.
|
||||
*/
|
||||
public function test_update_address_only_passes_with_existing_zipcode(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create([
|
||||
'user_id' => $user->id,
|
||||
'zipcode' => '06236',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", [
|
||||
'address' => '서울시 강남구 테헤란로 500',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* 해외 배송지 수정 요청(조회 응답 형태 그대로 PUT)이 통과합니다.
|
||||
*
|
||||
* 배송지 조회 응답은 해외 주소를 city/state/postal_code 키로 내보내고 폼은 intl_*
|
||||
* 키로 제출하므로, 해외 주소를 수정할 때 요청에 intl_city/intl_postal_code 가 없는
|
||||
* 경우가 정상 경로에 존재합니다. 페이로드만 보고 required_with 를 걸면 이 경로가
|
||||
* 전부 422 가 됩니다.
|
||||
*/
|
||||
public function test_update_overseas_address_without_intl_keys_passes(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create([
|
||||
'user_id' => $user->id,
|
||||
'country_code' => 'US',
|
||||
'zipcode' => null,
|
||||
'address' => null,
|
||||
'address_detail' => null,
|
||||
'address_line_1' => '350 5th Ave',
|
||||
'address_line_2' => 'Suite 1000',
|
||||
'city' => 'New York',
|
||||
'state' => 'NY',
|
||||
'postal_code' => '10118',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", [
|
||||
'name' => '뉴욕 사무실',
|
||||
'recipient_name' => 'John Doe',
|
||||
'recipient_phone' => '010-1234-5678',
|
||||
'country_code' => 'US',
|
||||
'address_line_1' => '350 5th Ave',
|
||||
'address_line_2' => 'Suite 2000',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
// 전송되지 않은 해외 도시/주/우편번호는 저장된 값이 유지되어야 한다.
|
||||
// (intl_* 미전송 시 null 로 덮어써져 조용히 유실되던 회귀 방지)
|
||||
$this->assertDatabaseHas('ecommerce_user_addresses', [
|
||||
'id' => $address->id,
|
||||
'city' => 'New York',
|
||||
'state' => 'NY',
|
||||
'postal_code' => '10118',
|
||||
'address_line_2' => 'Suite 2000',
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 국내 주소를 해외로 전환하면서 도시/우편번호를 빠뜨리면 거부됩니다.
|
||||
*/
|
||||
public function test_update_switching_to_overseas_without_city_fails(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create(['user_id' => $user->id]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", [
|
||||
'country_code' => 'US',
|
||||
'zipcode' => '',
|
||||
'address' => '',
|
||||
'address_line_1' => '350 5th Ave',
|
||||
]);
|
||||
|
||||
$response->assertStatus(422)
|
||||
->assertJsonValidationErrors(['intl_city', 'intl_postal_code']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 해외 주소 3필드를 모두 채운 전환은 통과합니다.
|
||||
*/
|
||||
public function test_update_switching_to_overseas_with_intl_fields_passes(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create(['user_id' => $user->id]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", [
|
||||
'country_code' => 'US',
|
||||
'zipcode' => '',
|
||||
'address' => '',
|
||||
'address_line_1' => '350 5th Ave',
|
||||
'intl_city' => 'New York',
|
||||
'intl_state' => 'NY',
|
||||
'intl_postal_code' => '10118',
|
||||
]);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$this->assertDatabaseHas('ecommerce_user_addresses', [
|
||||
'id' => $address->id,
|
||||
'country_code' => 'US',
|
||||
'city' => 'New York',
|
||||
'postal_code' => '10118',
|
||||
]);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_5\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 상품 리뷰 목록의 정렬 인덱스를 추가합니다.
|
||||
*
|
||||
* 리뷰 목록은 상품 상세와 관리자 화면 모두 작성일 내림차순이 기본 정렬인데, created_at 이
|
||||
* 후행하는 복합 인덱스가 없어 정렬마다 filesort 가 발생했습니다. 신규 설치는 마이그레이션이
|
||||
* 처리하지만 기존 사이트에는 반영되지 않으므로 업그레이드 시점에 동일 인덱스를 추가합니다.
|
||||
*
|
||||
* 리뷰가 많은 쇼핑몰에서는 ALTER TABLE 이 수 분 걸릴 수 있고 그동안 해당 테이블 쓰기가
|
||||
* 대기합니다. 진행 상황을 로그로 남깁니다.
|
||||
*
|
||||
* idempotent: 이미 존재하는 인덱스는 건너뜁니다. V-1 안전: Facades\Schema 만 사용합니다.
|
||||
*/
|
||||
class AddProductReviewSortIndexes implements DataMigration
|
||||
{
|
||||
private const TABLE = 'ecommerce_product_reviews';
|
||||
|
||||
/**
|
||||
* 추가할 인덱스 정의 (이름 => 컬럼 목록)
|
||||
*
|
||||
* @var array<string, array<int, string>>
|
||||
*/
|
||||
private const INDEXES = [
|
||||
'idx_reviews_product_status_deleted_created' => ['product_id', 'status', 'deleted_at', 'created_at'],
|
||||
// 관리자 목록: status 는 선택적 필터라 선행 컬럼으로 두면 필터 없는 기본 진입에서
|
||||
// created_at 정렬을 못 덮는다. 항상 IS NULL 로 붙는 deleted_at 을 선행에 둔다.
|
||||
'idx_reviews_deleted_created' => ['deleted_at', 'created_at'],
|
||||
];
|
||||
|
||||
/**
|
||||
* 마이그레이션 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 마이그레이션 이름
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return 'AddProductReviewSortIndexes';
|
||||
}
|
||||
|
||||
/**
|
||||
* 정렬 인덱스를 추가합니다.
|
||||
*
|
||||
* @param UpgradeContext $context 업그레이드 컨텍스트
|
||||
*/
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
$context->logger->info('[ecommerce:1.0.5] 상품 리뷰 테이블 부재 — 정렬 인덱스 추가 스킵');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes(self::TABLE), 'name');
|
||||
|
||||
foreach (self::INDEXES as $name => $columns) {
|
||||
if (in_array($name, $existing, true)) {
|
||||
$context->logger->info("[ecommerce:1.0.5] 이미 존재하는 인덱스 — 스킵: {$name}");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$context->logger->info("[ecommerce:1.0.5] 정렬 인덱스 추가 시작: {$name} (리뷰가 많으면 수 분 걸릴 수 있고 그동안 리뷰 쓰기가 대기합니다)");
|
||||
|
||||
Schema::table(self::TABLE, function ($table) use ($columns, $name) {
|
||||
$table->index($columns, $name);
|
||||
});
|
||||
|
||||
$context->logger->info("[ecommerce:1.0.5] 정렬 인덱스 추가 완료: {$name}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
### Changed
|
||||
|
||||
- 사이트맵을 만들 때 페이지를 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 페이지가 많은 사이트에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
|
||||
- 페이지 목록을 뒤쪽 페이지에서도 빠르게 열 수 있도록 조회 방식을 바꿨습니다. 예전에는 페이지가 뒤로 갈수록 건너뛰는 항목의 본문까지 함께 읽어 느려졌지만, 이제 현재 페이지의 항목만 본문을 읽습니다. 화면에 보이는 내용은 이전과 동일합니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
|
||||
- 첨부파일 저장 디스크 설정 항목을 제거했습니다. 설정 파일 자체가 그 디스크에 저장되는 구조라 값을 바꿔도 반영될 수 없는 항목이었습니다(기존에도 항상 기본값으로 동작). 저장 위치는 서버 파일 저장소 설정으로 관리합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace Modules\Sirsoft\Page\Repositories;
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Repositories\Concerns\HasMultipleSearchFilters;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use App\Search\Engines\DatabaseFulltextEngine;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -20,6 +22,11 @@ use Modules\Sirsoft\Page\Repositories\Contracts\PageRepositoryInterface;
|
||||
class PageRepository implements PageRepositoryInterface
|
||||
{
|
||||
use HasMultipleSearchFilters;
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/** 허용 정렬 컬럼 (PageListRequest 와 동일 집합) */
|
||||
private const SORTABLE_COLUMNS = ['created_at', 'published_at'];
|
||||
|
||||
/**
|
||||
* 페이지 목록을 페이지네이션하여 조회합니다.
|
||||
@@ -39,15 +46,22 @@ class PageRepository implements PageRepositoryInterface
|
||||
// - slug : 슬러그만
|
||||
// - all : 제목 + 슬러그 (본문 content 은 검색 대상 아님 — UI '제목 또는 슬러그로 검색')
|
||||
// (Scout 콜백에 slug orWhere 를 넣으면 total 카운트가 부풀려지는 회귀가 있어 #225 에서 제거됨)
|
||||
$query = Page::with(['creator', 'updater']);
|
||||
$query = Page::query();
|
||||
|
||||
// 권한 스코프 필터링
|
||||
PermissionHelper::applyPermissionScope($query, 'sirsoft-page.pages.read');
|
||||
|
||||
$this->applyFilters($query, $filters);
|
||||
$this->applySorting($query, $filters);
|
||||
|
||||
return $query->paginate($perPage);
|
||||
// 지연 조인: 본문 content(longText)는 목록에 쓰이지 않는데도 OFFSET 이 훑는
|
||||
// 모든 행에서 함께 읽힌다. inner 는 id 만 훑고 본문은 이번 페이지에서만 읽는다.
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $this->resolveListSortSpec($filters),
|
||||
perPage: $perPage,
|
||||
relations: ['creator', 'updater'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -170,6 +184,9 @@ class PageRepository implements PageRepositoryInterface
|
||||
{
|
||||
$results = $this->buildKeywordQuery($keyword)
|
||||
->orderBy($orderBy, $direction)
|
||||
// audit:allow repository-paginate-column-pruning reason: 통합검색 전용 진입점 —
|
||||
// 유일한 호출자(SearchPagesListener)가 전체 탭은 limit=5, 페이지 탭은 limit=PHP_INT_MAX 로
|
||||
// 1페이지에 결과를 받아가므로 OFFSET 이 발생하지 않는다
|
||||
->paginate($limit);
|
||||
|
||||
return [
|
||||
@@ -224,14 +241,20 @@ class PageRepository implements PageRepositoryInterface
|
||||
*/
|
||||
private function applySorting($query, array $filters): void
|
||||
{
|
||||
$sortBy = $filters['sort_by'] ?? 'created_at';
|
||||
$sortOrder = strtolower($filters['sort_order'] ?? 'desc');
|
||||
|
||||
if (! in_array($sortOrder, ['asc', 'desc'])) {
|
||||
$sortOrder = 'desc';
|
||||
foreach ($this->resolveListSortSpec($filters) as $sort) {
|
||||
$query->orderBy($sort['column'], $sort['direction']);
|
||||
}
|
||||
}
|
||||
|
||||
$query->orderBy($sortBy, $sortOrder);
|
||||
/**
|
||||
* 목록 정렬 스펙을 허용 컬럼 화이트리스트로 해석합니다.
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @return array<int, array{column: string, direction: string}> 정렬 스펙
|
||||
*/
|
||||
private function resolveListSortSpec(array $filters): array
|
||||
{
|
||||
return $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'created_at');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user