fix(core,board,ecommerce,page,gdpr,ckeditor5,kginicis,admin_basic,basic): 목록 조회·검증 계층 정비 및 감사 지적 전건 처리
목록 조회 성능 축(깊은 OFFSET·정렬·색인)과 그 검증 계층에서 계획서 전수검수와 3회에 걸친 감사가 지적한 항목을 처리했다. 세부 경위는 의 각 회차 문서에 있다. 검증 계층 — 컨트롤러가 base Request 를 직접 주입받던 확장 13곳을 전용 FormRequest 로 옮겼다. 옮기면서 기존 동작 계약은 그대로 두었다: 상한 초과 limit 을 거부하지 않고 상한까지 반환하던 공개 API, per_page 를 범위로 조정하던 관리자 목록, 미지원 period 를 year 로 해석하던 인기글 목록 모두 종전과 같은 응답을 낸다. 상한/폴백을 rules 로 승격시키면 200 이던 응답이 422 가 되어 기존 링크가 깨지므로, 규칙은 타입만 닫고 클램프·폴백은 접근자가 맡는다. period 는 접근자가 닫힌 집합만 반환해 캐시 키 공간도 함께 닫힌다. ckeditor5 이미지 업로드만 ResponseHelper 봉투를 쓰지 않는다. 응답을 파싱하는 주체가 CDN 으로 로드되는 상위 CKEditor5 43.3.1 의 SimpleUploadAdapter 라 규약을 바꿀 수 없어, 각 응답 지점에 사유를 명시한 면제를 부착하고 근거를 API 문서에 남겼다. 하네스 — 룰 5개의 대상 경로 패턴이 매처와 맞지 않아 번들 확장 컨트롤러가 검사 대상에서 통째로 빠져 있었다. 패턴을 고치자 확장 위반 17건이 드러나 전건 처리했다. severity 오타가 요약 집계 양쪽에 안 잡혀 "0 error" 로 보고되던 문제도 런너 사전 검증으로 막았다. 정렬 게이트 대조 하네스는 관계 정렬 변형만 쓰는 저장소를 탐지하지 못한 채 통과시키고 있었다. 탐지·제외·인자 파싱을 함께 고치고 단위 테스트를 신설했다.
This commit is contained in:
1 parent
5f4a733b3b
commit
b10e89bef0
276 files changed
+12519
-1438
No files matched your search
@@ -4,11 +4,19 @@
|
||||
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
|
||||
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
|
||||
|
||||
## [0.1.1] - 2026-07-31
|
||||
|
||||
### Fixed
|
||||
|
||||
- 관리자 메모 목록 화면에 메모가 하나도 보이지 않던 문제를 수정했습니다. 화면이 부르는 주소와 실제로 열려 있는 주소가 달라 목록을 받아오지 못하고 있었습니다.
|
||||
- 메모 목록에서 한 페이지에 보여줄 개수를 0·음수·과도하게 큰 값으로 요청하면 오류가 나거나 메모 전체가 한 번에 조회되던 문제를 수정했습니다. 1~100 범위를 벗어나면 요청이 거부됩니다.
|
||||
|
||||
## [0.1.0] - 2026-07-01
|
||||
|
||||
### Fixed
|
||||
|
||||
- 메모 목록에서 작성·수정 화면에 다녀오면 보고 있던 페이지가 사라지고 1페이지로 되돌아가던 문제를 수정했습니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 메모 목록에서 같은 시각에 등록된 메모가 여러 건일 때 페이지를 넘기면 같은 메모가 두 번 보이던 문제를 수정했습니다.
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "modules/gnuboard7-hello_module",
|
||||
"description": "Hello sample module for Gnuboard7 (learning purpose)",
|
||||
"type": "library",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"license": "MIT",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
> 아래 표는 자동 생성됩니다. 각 문서를 열면 엔드포인트별 파라미터·응답·예시를 볼 수 있습니다.
|
||||
|
||||
<!-- @generated:start:api-readme-index -->
|
||||
- **문서 수**: 1 · **엔드포인트 수**: 2
|
||||
- **문서 수**: 1 · **엔드포인트 수**: 7
|
||||
|
||||
| 문서 | 도메인 | 엔드포인트 |
|
||||
| --- | --- | --- |
|
||||
| [memos.md](memos.md) | `memos` | 2 |
|
||||
| [memos.md](memos.md) | `memos` | 7 |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
|
||||
```text
|
||||
1. 이 문서는 실제 API 호출로 실측한 Memos 엔드포인트 레퍼런스입니다
|
||||
2. 각 엔드포인트: 메서드/URI/권한 + 요청 파라미터 표 + 실측 응답 필드 표
|
||||
3. 응답 필드의 예시값은 실제 호출 응답에서 관측된 값입니다
|
||||
2. 각 엔드포인트: 메서드/URI/권한 + 요청 파라미터 표 + 요청 예시(curl) + 실측 응답 필드 표 + 응답 예시(envelope)
|
||||
3. 응답 필드의 예시값·응답 예시 JSON 은 실제 호출 응답에서 관측된 값입니다
|
||||
4. 갱신: 코드 변경 후 php artisan api:docgen 재실행
|
||||
5. 설명(TODO) 칸은 사람이 채웁니다
|
||||
```
|
||||
@@ -17,6 +17,233 @@
|
||||
---
|
||||
|
||||
|
||||
### GET /api/modules/gnuboard7-hello_module/admin/memos
|
||||
<!-- @generated:start:api.modules.gnuboard7-hello_module.admin.memos.index -->
|
||||
- **라우트명**: `api.modules.gnuboard7-hello_module.admin.memos.index`
|
||||
- **컨트롤러**: `Modules\Gnuboard7\HelloModule\Http\Controllers\Admin\MemoController@index`
|
||||
- **인증/권한**: `auth:sanctum` + `permission:gnuboard7-hello_module.memos.read`
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| page | query | integer | 아니오 | min 1 | 조회할 페이지 번호 (1부터 시작) |
|
||||
| per_page | query | integer | 아니오 | min 1, max 100 | 페이지당 항목 수 |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
GET /api/modules/gnuboard7-hello_module/admin/memos?page=1&per_page=1 HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Authorization: Bearer {YOUR_TOKEN}
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
<!-- 실측 제외: http-403 — 응답 필드는 사람이 작성하세요. -->
|
||||
|
||||
**응답 예시**
|
||||
|
||||
<!-- 실측 제외: http-403 — 응답 예시는 사람이 작성하세요. -->
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
|
||||
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.read`)이 없는 경우 |
|
||||
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
|
||||
|
||||
|
||||
### POST /api/modules/gnuboard7-hello_module/admin/memos
|
||||
<!-- @generated:start:api.modules.gnuboard7-hello_module.admin.memos.store -->
|
||||
- **라우트명**: `api.modules.gnuboard7-hello_module.admin.memos.store`
|
||||
- **컨트롤러**: `Modules\Gnuboard7\HelloModule\Http\Controllers\Admin\MemoController@store`
|
||||
- **인증/권한**: `auth:sanctum` + `permission:gnuboard7-hello_module.memos.create`
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| title | body | string | 예 | max 255 | 제목 |
|
||||
| content | body | string | 예 | — | 본문 내용 |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
POST /api/modules/gnuboard7-hello_module/admin/memos HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Authorization: Bearer {YOUR_TOKEN}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"title": "예시 제목",
|
||||
"content": "예시 내용입니다."
|
||||
}
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
<!-- 실측 제외: http-403 — 응답 필드는 사람이 작성하세요. -->
|
||||
|
||||
**응답 예시**
|
||||
|
||||
<!-- 실측 제외: http-403 — 응답 예시는 사람이 작성하세요. -->
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
|
||||
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.create`)이 없는 경우 |
|
||||
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
|
||||
|
||||
|
||||
### DELETE /api/modules/gnuboard7-hello_module/admin/memos/{id}
|
||||
<!-- @generated:start:api.modules.gnuboard7-hello_module.admin.memos.destroy -->
|
||||
- **라우트명**: `api.modules.gnuboard7-hello_module.admin.memos.destroy`
|
||||
- **컨트롤러**: `Modules\Gnuboard7\HelloModule\Http\Controllers\Admin\MemoController@destroy`
|
||||
- **인증/권한**: `auth:sanctum` + `permission:gnuboard7-hello_module.memos.delete`
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| id | path | string | 예 | — | 대상 리소스의 식별자 |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
DELETE /api/modules/gnuboard7-hello_module/admin/memos/{id} HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Authorization: Bearer {YOUR_TOKEN}
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 필드는 사람이 작성하세요. -->
|
||||
|
||||
**응답 예시**
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
|
||||
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.delete`)이 없는 경우 |
|
||||
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
|
||||
|
||||
|
||||
### GET /api/modules/gnuboard7-hello_module/admin/memos/{id}
|
||||
<!-- @generated:start:api.modules.gnuboard7-hello_module.admin.memos.show -->
|
||||
- **라우트명**: `api.modules.gnuboard7-hello_module.admin.memos.show`
|
||||
- **컨트롤러**: `Modules\Gnuboard7\HelloModule\Http\Controllers\Admin\MemoController@show`
|
||||
- **인증/권한**: `auth:sanctum` + `permission:gnuboard7-hello_module.memos.read`
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| id | path | string | 예 | — | 대상 리소스의 식별자 |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
GET /api/modules/gnuboard7-hello_module/admin/memos/{id} HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Authorization: Bearer {YOUR_TOKEN}
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 필드는 사람이 작성하세요. -->
|
||||
|
||||
**응답 예시**
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
|
||||
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.read`)이 없는 경우 |
|
||||
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
|
||||
|
||||
|
||||
### PUT /api/modules/gnuboard7-hello_module/admin/memos/{id}
|
||||
<!-- @generated:start:api.modules.gnuboard7-hello_module.admin.memos.update -->
|
||||
- **라우트명**: `api.modules.gnuboard7-hello_module.admin.memos.update`
|
||||
- **컨트롤러**: `Modules\Gnuboard7\HelloModule\Http\Controllers\Admin\MemoController@update`
|
||||
- **인증/권한**: `auth:sanctum` + `permission:gnuboard7-hello_module.memos.update`
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| id | path | string | 예 | — | 대상 리소스의 식별자 |
|
||||
| title | body | string | 예 | max 255 | 제목 |
|
||||
| content | body | string | 예 | — | 본문 내용 |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
PUT /api/modules/gnuboard7-hello_module/admin/memos/{id} HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Authorization: Bearer {YOUR_TOKEN}
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"title": "예시 제목",
|
||||
"content": "예시 내용입니다."
|
||||
}
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 필드는 사람이 작성하세요. -->
|
||||
|
||||
**응답 예시**
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
|
||||
| 403 | Forbidden | 요구 권한(`gnuboard7-hello_module.memos.update`)이 없는 경우 |
|
||||
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
|
||||
| 404 | Not Found | path 파라미터에 해당하는 리소스가 없는 경우 |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** <!-- TODO: 이 엔드포인트의 용도·주의사항·예시 시나리오를 작성하세요 -->
|
||||
|
||||
|
||||
### GET /api/modules/gnuboard7-hello_module/memos
|
||||
<!-- @generated:start:api.modules.gnuboard7-hello_module.memos.index -->
|
||||
- **라우트명**: `api.modules.gnuboard7-hello_module.memos.index`
|
||||
@@ -25,12 +252,15 @@
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
_요청 파라미터 없음._
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| page | query | integer | 아니오 | min 1 | 조회할 페이지 번호 (1부터 시작) |
|
||||
| per_page | query | integer | 아니오 | min 1, max 100 | 페이지당 항목 수 |
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
GET /api/modules/gnuboard7-hello_module/memos HTTP/1.1
|
||||
GET /api/modules/gnuboard7-hello_module/memos?page=1&per_page=1 HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Authorization: Bearer {YOUR_TOKEN} (optional.sanctum: 비회원은 헤더 생략 가능)
|
||||
@@ -38,11 +268,78 @@ Authorization: Bearer {YOUR_TOKEN} (optional.sanctum: 비회원은 헤더 생
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
<!-- 실측 제외: http-404 — 응답 필드는 사람이 작성하세요. -->
|
||||
_목록 응답: `data.data[]` 배열 항목의 필드._
|
||||
|
||||
| 필드 | 타입 | 실측 예시값 | 용도/설명 |
|
||||
| --- | --- | --- | --- |
|
||||
| id | integer | `2` | 기본 키 (내부 식별자) |
|
||||
| uuid | string | `4473e9ee-ecdf-4ad0-afb3-78ada47265af` | 외부 노출용 UUID (URL/API 식별자, 내부 id 비노출) |
|
||||
| title | string | `두 번째 메모` | 제목 |
|
||||
| content | string | `Memo 엔티티의 CRUD 동작을 확인할 수 있는 추가 샘플입니다.` | 본문 내용 |
|
||||
| created_at | string | `2026-07-31 22:09:15` | 생성 일시 |
|
||||
| updated_at | string | `2026-07-31 22:09:15` | 최종 수정 일시 |
|
||||
| abilities | object | `{"can_create":false,"can_update":false,"can_delete":false}` | 현재 사용자가 이 리소스에 수행 가능한 작업 불리언 맵 (can_update, can_delete 등 — 권한 맵 기반) |
|
||||
|
||||
**응답 예시**
|
||||
|
||||
```http
|
||||
HTTP/1.1 200
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "메모를 조회했습니다.",
|
||||
"data": {
|
||||
"data": [
|
||||
{
|
||||
"id": 2,
|
||||
"uuid": "4473e9ee-ecdf-4ad0-afb3-78ada47265af",
|
||||
"title": "두 번째 메모",
|
||||
"content": "Memo 엔티티의 CRUD 동작을 확인할 수 있는 추가 샘플입니다.",
|
||||
"created_at": "2026-07-31 22:09:15",
|
||||
"updated_at": "2026-07-31 22:09:15",
|
||||
"abilities": {
|
||||
"can_create": false,
|
||||
"can_update": false,
|
||||
"can_delete": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"uuid": "86a29502-24cd-4124-a283-b0454d499fc1",
|
||||
"title": "환영합니다",
|
||||
"content": "Hello 모듈의 첫 번째 샘플 메모입니다. 학습용으로 제공됩니다.",
|
||||
"created_at": "2026-07-31 22:09:15",
|
||||
"updated_at": "2026-07-31 22:09:15",
|
||||
"abilities": {
|
||||
"can_create": false,
|
||||
"can_update": false,
|
||||
"can_delete": false
|
||||
}
|
||||
},
|
||||
"... (총 25건 중 2건 표시)"
|
||||
],
|
||||
"meta": {
|
||||
"current_page": 1,
|
||||
"last_page": 2,
|
||||
"per_page": 25,
|
||||
"total": 34
|
||||
},
|
||||
"abilities": {
|
||||
"can_create": false,
|
||||
"can_update": false,
|
||||
"can_delete": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**에러 응답**
|
||||
|
||||
_대표 에러 없음 (공개 조회). <!-- TODO: 도메인 특이 에러가 있으면 보강 -->_
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
@@ -96,6 +393,10 @@ Authorization: Bearer {YOUR_TOKEN} (optional.sanctum: 비회원은 헤더 생
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 필드는 사람이 작성하세요. -->
|
||||
|
||||
**응답 예시**
|
||||
|
||||
<!-- 실측 제외: unresolved-path-param — 응답 예시는 사람이 작성하세요. -->
|
||||
|
||||
**에러 응답**
|
||||
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"ko": "Hello 모듈",
|
||||
"en": "Hello Module"
|
||||
},
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.1",
|
||||
"license": "MIT",
|
||||
"description": {
|
||||
"ko": "학습용 최소 샘플 모듈 (Memo CRUD)",
|
||||
|
||||
+3
-3
@@ -92,20 +92,20 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "memo_items",
|
||||
"id": "memo_items_{{idx}}",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
"className": "row-stack"
|
||||
},
|
||||
"iteration": {
|
||||
"data": "{{memos?.data?.data ?? []}}",
|
||||
"source": "{{memos?.data?.data ?? []}}",
|
||||
"item_var": "memo",
|
||||
"index_var": "idx"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"id": "memo_item",
|
||||
"id": "memo_item_{{idx}}",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
|
||||
@@ -51,20 +51,20 @@
|
||||
"text": "$t:gnuboard7-hello_module.user.memos.index.title"
|
||||
},
|
||||
{
|
||||
"id": "user_memo_items",
|
||||
"id": "user_memo_items_{{idx}}",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
"className": "space-y-3"
|
||||
},
|
||||
"iteration": {
|
||||
"data": "{{memos?.data?.data ?? []}}",
|
||||
"source": "{{memos?.data?.data ?? []}}",
|
||||
"item_var": "memo",
|
||||
"index_var": "idx"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"id": "user_memo_item",
|
||||
"id": "user_memo_item_{{idx}}",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"props": {
|
||||
|
||||
+8
-7
@@ -3,10 +3,11 @@
|
||||
namespace Modules\Gnuboard7\HelloModule\Http\Controllers\Admin;
|
||||
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Requests\Admin\StoreMemoRequest;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Requests\Admin\UpdateMemoRequest;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Requests\MemoListRequest;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Resources\MemoCollection;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Resources\MemoResource;
|
||||
use Modules\Gnuboard7\HelloModule\Services\MemoService;
|
||||
@@ -32,13 +33,13 @@ class MemoController extends AdminBaseController
|
||||
/**
|
||||
* 메모 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param MemoListRequest $request 목록 조회 요청 (페이지네이션 상·하한 검증)
|
||||
* @return JsonResponse 메모 목록 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
public function index(MemoListRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$perPage = (int) $request->query('per_page', 10);
|
||||
$perPage = (int) ($request->validated()['per_page'] ?? 10);
|
||||
$memos = $this->memoService->getMemos($perPage);
|
||||
|
||||
return $this->success(
|
||||
@@ -65,7 +66,7 @@ class MemoController extends AdminBaseController
|
||||
'gnuboard7-hello_module::messages.memo.fetch_success',
|
||||
new MemoResource($memo)
|
||||
);
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException) {
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('gnuboard7-hello_module::messages.memo.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('gnuboard7-hello_module::messages.memo.fetch_failed', 500, $e->getMessage());
|
||||
@@ -110,7 +111,7 @@ class MemoController extends AdminBaseController
|
||||
'gnuboard7-hello_module::messages.memo.update_success',
|
||||
new MemoResource($memo)
|
||||
);
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException) {
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('gnuboard7-hello_module::messages.memo.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('gnuboard7-hello_module::messages.memo.update_failed', 500, $e->getMessage());
|
||||
@@ -130,7 +131,7 @@ class MemoController extends AdminBaseController
|
||||
$this->memoService->deleteMemo($memo);
|
||||
|
||||
return $this->success('gnuboard7-hello_module::messages.memo.delete_success');
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException) {
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('gnuboard7-hello_module::messages.memo.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('gnuboard7-hello_module::messages.memo.delete_failed', 500, $e->getMessage());
|
||||
|
||||
@@ -3,8 +3,9 @@
|
||||
namespace Modules\Gnuboard7\HelloModule\Http\Controllers\Api;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Requests\MemoListRequest;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Resources\MemoCollection;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Resources\MemoResource;
|
||||
use Modules\Gnuboard7\HelloModule\Services\MemoService;
|
||||
@@ -30,13 +31,13 @@ class MemoController extends PublicBaseController
|
||||
/**
|
||||
* 메모 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request HTTP 요청
|
||||
* @param MemoListRequest $request 목록 조회 요청 (페이지네이션 상·하한 검증)
|
||||
* @return JsonResponse 메모 목록 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
public function index(MemoListRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$perPage = (int) $request->query('per_page', 10);
|
||||
$perPage = (int) ($request->validated()['per_page'] ?? 10);
|
||||
$memos = $this->memoService->getMemos($perPage);
|
||||
|
||||
return $this->success(
|
||||
@@ -63,7 +64,7 @@ class MemoController extends PublicBaseController
|
||||
'gnuboard7-hello_module::messages.memo.fetch_success',
|
||||
new MemoResource($memo)
|
||||
);
|
||||
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException) {
|
||||
} catch (ModelNotFoundException) {
|
||||
return $this->notFound('gnuboard7-hello_module::messages.memo.not_found');
|
||||
} catch (\Exception $e) {
|
||||
return $this->error('gnuboard7-hello_module::messages.memo.fetch_failed', 500, $e->getMessage());
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Gnuboard7\HelloModule\Http\Requests;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 메모 목록 조회 요청
|
||||
*
|
||||
* 목록 조회도 FormRequest 로 검증한다는 규정을 보여주는 샘플이다.
|
||||
* 페이지네이션 파라미터에 상·하한이 없으면 per_page=0 은 모델 기본값으로 조용히 바뀌고,
|
||||
* 음수는 예외가 되며, 과대값은 테이블 전량을 반환한다.
|
||||
*/
|
||||
class MemoListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* 인증·권한은 라우트 미들웨어가 담당하므로 항상 true 를 반환합니다.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ class MemoRepository implements MemoRepositoryInterface
|
||||
{
|
||||
return Memo::query()
|
||||
->orderByDesc('created_at')
|
||||
// 전순서 보장 — created_at 동률에서 페이지 경계가 흔들리지 않도록 기본키를 덧붙인다
|
||||
->orderByDesc('id')
|
||||
// audit:allow repository-paginate-column-pruning reason: 학습용 샘플 확장의 메모 테이블 —
|
||||
// 넓은 컬럼(text/JSON)이 없고, 지연 조인을 넣으면 샘플 코드의 학습 목적이 흐려진다
|
||||
->paginate($perPage);
|
||||
|
||||
@@ -1,17 +1,26 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Controllers\Admin\MemoController as AdminMemoController;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Controllers\Api\MemoController;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Hello Module Public API Routes
|
||||
| Hello Module API Routes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| 비로그인 사용자도 접근 가능한 공개 읽기 API.
|
||||
| ModuleRouteServiceProvider 가 자동으로 prefix 를 적용합니다.
|
||||
| - URL prefix: 'api/modules/gnuboard7-hello_module'
|
||||
| - Name prefix: 'api.modules.gnuboard7-hello_module.'
|
||||
|
|
||||
| 레이아웃 JSON 의 data_sources 가 소비하는 엔드포인트는 전부 이 파일에 둔다.
|
||||
| routes/web.php 는 'modules/{id}' prefix + web 미들웨어라 JSON API 로는 도달하지 않는다.
|
||||
|
|
||||
*/
|
||||
|
||||
/*
|
||||
| 공개 읽기 API — 비로그인 사용자도 접근 가능
|
||||
*/
|
||||
Route::prefix('memos')
|
||||
->middleware(['optional.sanctum', 'throttle:600,1'])
|
||||
->name('memos.')
|
||||
@@ -21,3 +30,34 @@ Route::prefix('memos')
|
||||
->whereNumber('id')
|
||||
->name('show');
|
||||
});
|
||||
|
||||
/*
|
||||
| 관리자 CRUD API — 인증 + 권한 미들웨어로 보호
|
||||
*/
|
||||
Route::prefix('admin/memos')
|
||||
->middleware(['auth:sanctum', 'throttle:600,1'])
|
||||
->name('admin.memos.')
|
||||
->group(function () {
|
||||
Route::get('/', [AdminMemoController::class, 'index'])
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.read')
|
||||
->name('index');
|
||||
|
||||
Route::post('/', [AdminMemoController::class, 'store'])
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.create')
|
||||
->name('store');
|
||||
|
||||
Route::get('/{id}', [AdminMemoController::class, 'show'])
|
||||
->whereNumber('id')
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.read')
|
||||
->name('show');
|
||||
|
||||
Route::put('/{id}', [AdminMemoController::class, 'update'])
|
||||
->whereNumber('id')
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.update')
|
||||
->name('update');
|
||||
|
||||
Route::delete('/{id}', [AdminMemoController::class, 'destroy'])
|
||||
->whereNumber('id')
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.delete')
|
||||
->name('destroy');
|
||||
});
|
||||
@@ -1,43 +1,20 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Modules\Gnuboard7\HelloModule\Http\Controllers\Admin\MemoController;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Hello Module Admin Routes
|
||||
| Hello Module Web Routes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| ModuleRouteServiceProvider 가 자동으로 prefix 를 적용합니다.
|
||||
| - URL prefix: 'api/modules/gnuboard7-hello_module'
|
||||
| - Name prefix: 'api.modules.gnuboard7-hello_module.'
|
||||
| - URL prefix: 'modules/gnuboard7-hello_module'
|
||||
| - Name prefix: 'web.modules.gnuboard7-hello_module.'
|
||||
| - 미들웨어 그룹: 'web' (세션/CSRF)
|
||||
|
|
||||
| 이 모듈은 화면을 레이아웃 JSON 으로 그리고 데이터는 JSON API 로만 받으므로
|
||||
| 웹(세션) 라우트가 필요 없다. 관리자 CRUD 는 routes/api.php 의
|
||||
| 'api/modules/gnuboard7-hello_module/admin/memos' 그룹에 있다.
|
||||
|
|
||||
| 레이아웃 data_sources 가 호출하는 엔드포인트를 이 파일에 두면 prefix 가
|
||||
| 'api/modules/...' 가 아니라 'modules/...' 가 되어 화면에서 404 가 된다.
|
||||
|
|
||||
*/
|
||||
|
||||
Route::prefix('admin/memos')
|
||||
->middleware(['auth:sanctum', 'throttle:600,1'])
|
||||
->name('admin.memos.')
|
||||
->group(function () {
|
||||
Route::get('/', [MemoController::class, 'index'])
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.read')
|
||||
->name('index');
|
||||
|
||||
Route::post('/', [MemoController::class, 'store'])
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.create')
|
||||
->name('store');
|
||||
|
||||
Route::get('/{id}', [MemoController::class, 'show'])
|
||||
->whereNumber('id')
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.read')
|
||||
->name('show');
|
||||
|
||||
Route::put('/{id}', [MemoController::class, 'update'])
|
||||
->whereNumber('id')
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.update')
|
||||
->name('update');
|
||||
|
||||
Route::delete('/{id}', [MemoController::class, 'destroy'])
|
||||
->whereNumber('id')
|
||||
->middleware('permission:admin,gnuboard7-hello_module.memos.delete')
|
||||
->name('destroy');
|
||||
});
|
||||
@@ -23,6 +23,7 @@
|
||||
- 게시글 목록을 뒤쪽 페이지에서도 빠르게 열 수 있도록 조회 방식을 바꿨습니다. 예전에는 페이지가 뒤로 갈수록 건너뛰는 게시글의 본문 앞부분까지 함께 읽어 느려졌지만, 이제 현재 페이지의 게시글만 본문 미리보기를 읽습니다. 공지 노출·답글 표시·다음 페이지 버튼은 이전과 동일하게 동작합니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 신고 관리 목록도 같은 방식으로 개선했습니다. 신고 건수·대상 글 상태처럼 목록에 함께 표시되는 정보를 예전에는 건너뛰는 신고까지 모두 계산했지만, 이제 현재 페이지의 신고에 대해서만 계산합니다. 신고가 많이 쌓인 사이트에서 목록 페이지 이동이 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 마이페이지의 「내가 쓴 댓글」·「내가 댓글 단 글」 목록도 같은 방식으로 개선했습니다. 각 글의 최근 댓글을 예전에는 건너뛰는 글까지 모두 찾아봤지만, 이제 현재 페이지의 글에 대해서만 찾습니다. 댓글 활동이 많은 회원의 목록 페이지 이동이 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 게시글이 많은 게시판에서 목록 정렬이 더 빨라지도록 색인을 정비했습니다. 신고 관리 목록에도 같은 정비를 적용했습니다. 같은 시각에 등록된 게시글이 많은 구간에서 순서를 정하느라 생기던 추가 작업이 사라집니다. 기존 사이트도 업데이트 시 자동으로 반영되며, 게시글이 아주 많은 경우 이 과정에 수 분이 걸리고 그동안 글쓰기가 잠시 대기할 수 있습니다.
|
||||
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
|
||||
|
||||
### Fixed
|
||||
@@ -35,13 +36,19 @@
|
||||
- 데이터베이스에서 일부 컬럼의 설명이 비어 있던 문제를 바로잡았습니다. 회원·작성자 등 다른 표를 가리키는 컬럼이 대상이며, 업그레이드하면 이미 운영 중인 데이터베이스에도 설명이 채워집니다(직접 적어 넣은 설명은 그대로 둡니다).
|
||||
- 관리자 게시글 목록에서 글을 열어 이전글·다음글로 넘어가거나 수정 후 돌아올 때 보고 있던 페이지·검색어·분류가 사라지던 문제를 수정했습니다. 목록 ↔ 상세 ↔ 이전/다음 글 ↔ 작성·수정 폼 어디로 오가든 목록 상태가 유지되며, 신고 관리와 게시판 목록도 동일하게 개선됐습니다. 새로고침 버튼도 걸어 둔 검색·필터를 지운 채 새로 부르지 않고 보고 있던 목록을 그대로 다시 부릅니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 관리자 게시글 목록에서 뒤쪽 페이지를 보던 중 검색하거나 게시 상태를 바꾸면 그 페이지 번호가 그대로 유지돼 결과가 없는 빈 화면이 열리던 문제를 수정했습니다. 검색과 상태 변경은 1페이지부터 보여주며, 사용자가 고른 표시 개수와 정렬은 그대로 유지됩니다. 검색창에서 엔터를 치는 경우와 검색 버튼을 누르는 경우가 서로 다르게 동작하던 것도 함께 맞췄습니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 신고 상세의 신고자 목록에서 한 페이지에 보여줄 개수를 0 이나 음수로 요청하면 오류가 나던 문제를 수정했습니다.
|
||||
- 게시판 관리 목록과 신고 처리 로그에서 같은 시각에 등록된 항목이 여러 건일 때, 페이지를 넘기면 같은 항목이 두 번 보이고 다른 항목은 아예 보이지 않던 문제를 수정했습니다.
|
||||
- 첨부파일을 사용하지 않는 게시판을 아무것도 바꾸지 않고 저장해도 "허용 파일 확장자를 최소 1개 이상 입력하세요" 오류가 나며 저장이 막히던 문제를 수정했습니다. 첨부를 쓰지 않는 게시판에서는 허용 확장자를 비워 두어도 정상적으로 저장됩니다. 게시판 환경설정의 기본값도 동일하게 동작합니다. (#78 @glitter-gim 님께서 제보해주셨습니다.)
|
||||
- 마이페이지 「내가 댓글 단 글」에서 검색어를 입력하면 목록이 열리지 않고 오류가 나던 문제를 수정했습니다. 이제 댓글 내용으로 정상 검색됩니다.
|
||||
- 새 글 표시 기간을 "0시간"(새 글 표시 안 함)으로 저장할 수 없던 문제를 수정했습니다. 0은 원래 새 글 배지를 끄는 값으로 동작하도록 되어 있었으나 저장 단계에서 막혀 있었습니다.
|
||||
- 게시판 환경설정에서 제목·댓글 최소 길이를 0(제한 없음)으로 저장할 수 없던 문제를 수정했습니다. 내용 최소 길이는 0이 허용되어 같은 화면에서 항목마다 동작이 달랐습니다.
|
||||
- 댓글 계층 정리 시 서로가 서로의 부모로 얽혀 최상위 댓글에서 닿을 수 없는 댓글이 아무 기록 없이 넘어가던 문제를 수정했습니다. 이런 댓글은 내용과 위치를 그대로 보존하되, 정리되지 않았다는 사실이 업데이트 기록에 남아 확인할 수 있습니다.
|
||||
- 마이페이지 활동 목록에서 한 페이지에 표시할 개수를 0이나 음수로 요청하면 서버 오류가 나던 문제를 수정했습니다. 이제 허용 범위(1~100)로 자동 조정되며, 지나치게 큰 값도 상한으로 잘립니다.
|
||||
- 게시판 신고현황 목록에서 뒤쪽 페이지를 보던 중 정렬을 바꾸면 이전 페이지 번호에 그대로 머물러 엉뚱한 구간이 보이던 문제를 수정했습니다. 이제 정렬을 바꾸면 첫 페이지부터 보여줍니다.
|
||||
- 허용 확장자를 지정하지 않은 게시판에서 어떤 파일도 첨부할 수 없던 문제를 수정했습니다. 파일 선택 단계에서 막히던 것과 서버에서 거부되던 것을 함께 고쳐, 확장자를 지정하지 않은 게시판은 기본 확장자 목록을 사용합니다. 첨부 안내에 확장자가 비어 표시되던 것도 함께 해소됩니다. 확장자를 지정한 게시판은 지금처럼 목록에 없는 파일을 계속 거부합니다.
|
||||
- 게시판 알림 설정에서 저장에 실패해도 아무 안내 없이 넘어가던 화면을 수정했습니다. 실패하면 그 이유가 화면에 표시됩니다.
|
||||
- 신고 상세의 신고자 목록에서 한 페이지에 표시할 개수에 상한이 없어 신고자 전체를 한 번에 불러올 수 있던 문제를 수정했습니다. 이제 다른 목록과 같은 상한(100)이 적용됩니다.
|
||||
- 게시판 유형 상세를 조회한 기록이 활동 로그에 내부 식별자로 표시되던 문제를 수정했습니다.
|
||||
- 일부 안내 문구가 실제 문장 대신 내부 식별자(`sirsoft-board::messages....` 같은 문자열)로 표시되던 문제를 수정했습니다. 첨부파일이 있는 게시판을 찾지 못했을 때, 댓글 목록을 불러오지 못했을 때, 비회원 댓글의 비밀번호를 확인할 때, 삭제·블라인드된 글에 댓글을 달려 할 때, 권한이 없어 거절될 때가 해당됩니다.
|
||||
- 비밀글을 쓸 수 없는 게시판에서 비밀글로 저장하려 할 때, 답글 대상 게시판을 찾지 못했을 때, 신고 상태를 바꿀 수 없는 상태로 변경하려 할 때 나오던 안내가 정상 문장으로 표시됩니다.
|
||||
- 댓글 수정, 신고 접수·처리, 블라인드·복원, 게시판 설정 일괄 적용 화면에서 오류 안내에 항목 이름이 영문 필드명으로 나오던 것을 한글 항목명으로 바로잡았습니다.
|
||||
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 게시글 목록 인덱스 말미에 기본키를 덧붙여 정렬을 완전히 덮습니다.
|
||||
*
|
||||
* 기존 `idx_board_posts_list_count` 는 [board_id, is_notice, parent_id, deleted_at, created_at]
|
||||
* 로 끝난다. 목록 정렬은 `created_at DESC, id DESC` 인데 인덱스가 created_at 에서 끝나므로
|
||||
* 동률 구간의 id 순서를 인덱스로 만들 수 없어 filesort 가 붙는다.
|
||||
*
|
||||
* 20만 행 계측(2026-08-01, MySQL 8.4.3)에서 지연 조인의 inner 쿼리가
|
||||
* `key=idx_board_posts_list_count ... Using index; Using filesort` 로 잡혔고, OFFSET 199,980
|
||||
* 에서 77.8ms 였다. inner 는 키 컬럼만 읽으므로 filesort 만 걷어내면 인덱스 순서 그대로
|
||||
* 끝난다(= `Using index` 단독).
|
||||
*
|
||||
* 같은 선행 컬럼을 가진 인덱스를 새로 만들면 기존 인덱스가 그대로 남아 쓰기 비용만 늘어나므로
|
||||
* **교체**한다. 뒤에 id 를 덧붙인 인덱스는 기존 인덱스가 답하던 조회를 모두 포함한다.
|
||||
*
|
||||
* `idx_board_posts_adjacent` 로는 대체되지 않는다 — 그 인덱스는 2번째가 `status` 인데
|
||||
* 목록 조회가 status 를 등치로 고정하지 않는 경우가 있어 그 지점에서 등치 사슬이 끊기고
|
||||
* 뒤의 created_at 을 정렬에 쓸 수 없다.
|
||||
*
|
||||
* 소프트 삭제 단독 인덱스(`g7_board_posts_deleted_at_index`) 제거는 다른 조회가 의존할 수
|
||||
* 있으므로 이번 범위에서 다루지 않는다.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
private const TABLE = 'board_posts';
|
||||
|
||||
private const OLD_INDEX = 'idx_board_posts_list_count';
|
||||
|
||||
private const NEW_INDEX = 'idx_board_posts_list_count_id';
|
||||
|
||||
/** @var array<int, string> */
|
||||
private const OLD_COLUMNS = ['board_id', 'is_notice', 'parent_id', 'deleted_at', 'created_at'];
|
||||
|
||||
/** @var array<int, string> */
|
||||
private const NEW_COLUMNS = ['board_id', 'is_notice', 'parent_id', 'deleted_at', 'created_at', 'id'];
|
||||
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes(self::TABLE), 'name');
|
||||
|
||||
Schema::table(self::TABLE, function (Blueprint $table) use ($existing) {
|
||||
if (! in_array(self::NEW_INDEX, $existing, true)) {
|
||||
$table->index(self::NEW_COLUMNS, self::NEW_INDEX);
|
||||
}
|
||||
|
||||
// 새 인덱스가 기존 인덱스의 상위집합이므로 남겨 두면 쓰기 비용만 늘어난다
|
||||
if (in_array(self::OLD_INDEX, $existing, true)) {
|
||||
$table->dropIndex(self::OLD_INDEX);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes(self::TABLE), 'name');
|
||||
|
||||
Schema::table(self::TABLE, function (Blueprint $table) use ($existing) {
|
||||
if (! in_array(self::OLD_INDEX, $existing, true)) {
|
||||
$table->index(self::OLD_COLUMNS, self::OLD_INDEX);
|
||||
}
|
||||
|
||||
if (in_array(self::NEW_INDEX, $existing, true)) {
|
||||
$table->dropIndex(self::NEW_INDEX);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 신고 목록의 정렬 색인을 추가합니다.
|
||||
*
|
||||
* 신고 관리 목록은 `deleted_at IS NULL` 로 좁힌 뒤 `created_at DESC, id DESC` 로 정렬하는데,
|
||||
* 그 순서를 덮는 색인이 없어 뒤쪽 페이지가 테이블 전체를 훑고 정렬했다. 지연 조인의 inner 가
|
||||
* 키 컬럼만 읽어도 인덱스 순서로 끝나지 못하면 깊은 OFFSET 개선 폭이 사라진다.
|
||||
*
|
||||
* 필요한 색인은 계측 프로파일 선언(filters / order / soft_delete)에서 도출한 것이며,
|
||||
* 게시판 모듈의 `ListIndexCoverageTest` 가 같은 규칙으로 전 목록을 검사한다.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
private const TABLE = 'boards_reports';
|
||||
|
||||
private const INDEX_NAME = 'idx_boards_reports_deleted_created_id';
|
||||
|
||||
/** @var array<int, string> */
|
||||
private const INDEX_COLUMNS = ['deleted_at', 'created_at', 'id'];
|
||||
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes(self::TABLE), 'name');
|
||||
|
||||
Schema::table(self::TABLE, function (Blueprint $table) use ($existing) {
|
||||
if (! in_array(self::INDEX_NAME, $existing, true)) {
|
||||
$table->index(self::INDEX_COLUMNS, self::INDEX_NAME);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes(self::TABLE), 'name');
|
||||
|
||||
Schema::table(self::TABLE, function (Blueprint $table) use ($existing) {
|
||||
if (in_array(self::INDEX_NAME, $existing, true)) {
|
||||
$table->dropIndex(self::INDEX_NAME);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -133,6 +133,6 @@ HTTP/1.1 200
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** 로그인한 회원 본인의 게시글 활동을 마이페이지에 표시하기 위해 반환합니다. `auth:sanctum` 인증이 필요한 회원 전용 엔드포인트로, 대상 사용자는 항상 인증된 본인(`Auth::id()`)입니다. `board_slug`·`search`·`activity_type`·`sort`(latest/oldest/views) 필터와 `per_page`(기본 20) 페이지네이션을 지원하며, 응답에는 적용된 필터가 `query` 로 함께 담깁니다.
|
||||
**설명** 로그인한 회원 본인의 게시글 활동을 마이페이지에 표시하기 위해 반환합니다. `auth:sanctum` 인증이 필요한 회원 전용 엔드포인트로, 대상 사용자는 항상 인증된 본인(`Auth::id()`)입니다. `board_slug`·`search`·`activity_type`·`sort`(latest/oldest/views) 필터와 `per_page`(기본 20, 허용 범위 1~100) 페이지네이션을 지원하며, 응답에는 적용된 필터가 `query` 로 함께 담깁니다. 범위를 벗어난 `per_page` 는 오류 대신 경계값으로 잘립니다(0·음수 → 1, 100 초과 → 100).
|
||||
|
||||
|
||||
@@ -873,8 +873,11 @@ class Module extends AbstractModule
|
||||
'trigger_type', 'ip_address', 'created_at', 'updated_at', 'deleted_at',
|
||||
],
|
||||
'order' => [['created_at', 'desc'], ['id', 'desc']],
|
||||
'filters' => ['board_id' => 1],
|
||||
'seed_overrides' => ['board_id' => 1, 'is_notice' => 0],
|
||||
// 실제 목록 쿼리(PostRepository::buildSortedPostList)는 공지와 답글을 빼고
|
||||
// 원글만 페이지네이션한다. 필터를 board_id 만 걸면 등치 사슬이 is_notice 에서
|
||||
// 끊겨 옵티마이저가 다른 인덱스를 골라, 제품이 실행하지 않는 실행 계획을 재게 된다.
|
||||
'filters' => ['board_id' => 1, 'is_notice' => 0, 'parent_id' => null],
|
||||
'seed_overrides' => ['board_id' => 1, 'is_notice' => 0, 'parent_id' => null],
|
||||
'soft_delete' => true,
|
||||
],
|
||||
// 댓글은 계측 프로파일을 두지 않는다. 페이지네이션되는 댓글 목록은 회원 본인 댓글
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'description' => [
|
||||
// Board management (Admin)
|
||||
'board_index' => 'Board list viewed',
|
||||
'board_show' => 'Board details viewed (:board_name)',
|
||||
'board_create' => 'Board created (:board_name)',
|
||||
'board_update' => 'Board updated (:board_name)',
|
||||
'board_delete' => 'Board deleted (:board_name)',
|
||||
'board_copy' => 'Board copied (:board_name)',
|
||||
'board_add_to_menu' => 'Board added to menu (:board_name)',
|
||||
|
||||
// Board type (Admin)
|
||||
'board_type_index' => 'Board type list viewed',
|
||||
'board_type_show' => 'Board type details viewed (:type_name)',
|
||||
'board_type_create' => 'Board type created (:type_name)',
|
||||
'board_type_update' => 'Board type updated (:type_name)',
|
||||
'board_type_delete' => 'Board type deleted (:type_name)',
|
||||
|
||||
// Posts
|
||||
'post_create' => 'Post created (Board: :board_name, Title: :title)',
|
||||
'post_update' => 'Post updated (Board: :board_name, Title: :title)',
|
||||
'post_delete' => 'Post deleted (Board: :board_name, ID: :post_id)',
|
||||
'post_blind' => 'Post blinded (Board: :board_name, ID: :post_id)',
|
||||
'post_restore' => 'Post restored (Board: :board_name, ID: :post_id)',
|
||||
|
||||
// Comments
|
||||
'comment_create' => 'Comment created (Board: :board_name, Post: :post_id)',
|
||||
'comment_update' => 'Comment updated (ID: :comment_id)',
|
||||
'comment_delete' => 'Comment deleted (ID: :comment_id)',
|
||||
'comment_blind' => 'Comment blinded (ID: :comment_id)',
|
||||
'comment_restore' => 'Comment restored (ID: :comment_id)',
|
||||
|
||||
// Attachments
|
||||
'board_attachment_upload' => 'Attachment uploaded (Post: :post_id)',
|
||||
'board_attachment_delete' => 'Attachment deleted (Post: :post_id)',
|
||||
'board_attachment_download' => 'Attachment downloaded (Post: :post_id)',
|
||||
'board_attachment_reorder' => 'Attachment order changed (Post: :post_id)',
|
||||
|
||||
// Report management (Admin)
|
||||
'report_create' => 'Report created (ID: :report_id)',
|
||||
'report_update_status' => 'Report status changed (ID: :report_id)',
|
||||
'report_bulk_update_status' => 'Report statuses bulk changed (:count items)',
|
||||
'report_delete' => 'Report deleted (ID: :report_id)',
|
||||
'report_restore_content' => 'Report content restored (ID: :report_id)',
|
||||
'report_blind_content' => 'Report content blinded (ID: :report_id)',
|
||||
'report_delete_content' => 'Report content deleted (ID: :report_id)',
|
||||
|
||||
// Board settings
|
||||
'board_settings_index' => 'Board settings viewed',
|
||||
'board_settings_bulk_apply' => 'Board settings bulk applied',
|
||||
'board_settings_bulk_apply_aborted' => 'Board settings bulk apply aborted (full rollback, failed board: :failed_board_name, :failed_at/:total)',
|
||||
],
|
||||
];
|
||||
@@ -1,55 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'description' => [
|
||||
// 게시판 관리 (Admin)
|
||||
'board_index' => '게시판 목록 조회',
|
||||
'board_show' => '게시판 상세 조회 (:board_name)',
|
||||
'board_create' => '게시판 생성 (:board_name)',
|
||||
'board_update' => '게시판 수정 (:board_name)',
|
||||
'board_delete' => '게시판 삭제 (:board_name)',
|
||||
'board_copy' => '게시판 복사 (:board_name)',
|
||||
'board_add_to_menu' => '게시판 메뉴 추가 (:board_name)',
|
||||
|
||||
// 게시판 유형 (Admin)
|
||||
'board_type_index' => '게시판 유형 목록 조회',
|
||||
'board_type_show' => '게시판 유형 상세 조회 (:type_name)',
|
||||
'board_type_create' => '게시판 유형 생성 (:type_name)',
|
||||
'board_type_update' => '게시판 유형 수정 (:type_name)',
|
||||
'board_type_delete' => '게시판 유형 삭제 (:type_name)',
|
||||
|
||||
// 게시물
|
||||
'post_create' => '게시물 작성 (게시판: :board_name, 제목: :title)',
|
||||
'post_update' => '게시물 수정 (게시판: :board_name, 제목: :title)',
|
||||
'post_delete' => '게시물 삭제 (게시판: :board_name, ID: :post_id)',
|
||||
'post_blind' => '게시물 블라인드 (게시판: :board_name, ID: :post_id)',
|
||||
'post_restore' => '게시물 복원 (게시판: :board_name, ID: :post_id)',
|
||||
|
||||
// 댓글
|
||||
'comment_create' => '댓글 작성 (게시판: :board_name, 게시물: :post_id)',
|
||||
'comment_update' => '댓글 수정 (ID: :comment_id)',
|
||||
'comment_delete' => '댓글 삭제 (ID: :comment_id)',
|
||||
'comment_blind' => '댓글 블라인드 (ID: :comment_id)',
|
||||
'comment_restore' => '댓글 복원 (ID: :comment_id)',
|
||||
|
||||
// 첨부파일
|
||||
'board_attachment_upload' => '첨부파일 업로드 (게시물: :post_id)',
|
||||
'board_attachment_delete' => '첨부파일 삭제 (게시물: :post_id)',
|
||||
'board_attachment_download' => '첨부파일 다운로드 (게시물: :post_id)',
|
||||
'board_attachment_reorder' => '첨부파일 순서 변경 (게시물: :post_id)',
|
||||
|
||||
// 신고 관리 (Admin)
|
||||
'report_create' => '신고 접수 (ID: :report_id)',
|
||||
'report_update_status' => '신고 상태 변경 (ID: :report_id)',
|
||||
'report_bulk_update_status' => '신고 일괄 상태 변경 (:count건)',
|
||||
'report_delete' => '신고 삭제 (ID: :report_id)',
|
||||
'report_restore_content' => '신고 콘텐츠 복원 (ID: :report_id)',
|
||||
'report_blind_content' => '신고 콘텐츠 블라인드 (ID: :report_id)',
|
||||
'report_delete_content' => '신고 콘텐츠 삭제 (ID: :report_id)',
|
||||
|
||||
// 게시판 설정
|
||||
'board_settings_index' => '게시판 설정 조회',
|
||||
'board_settings_bulk_apply' => '게시판 설정 일괄 적용',
|
||||
'board_settings_bulk_apply_aborted' => '게시판 설정 일괄 적용 중단 (전체 롤백, 실패 게시판: :failed_board_name, :failed_at/:total)',
|
||||
],
|
||||
];
|
||||
+5
-2
@@ -2164,10 +2164,13 @@
|
||||
"params": {
|
||||
"path": "/admin/boards/reports",
|
||||
"mergeQuery": true,
|
||||
"replace": true,
|
||||
"query": {
|
||||
"sort_by": "{{$args[0]}}",
|
||||
"sort_order": "{{$args[1]}}"
|
||||
}
|
||||
"sort_order": "{{$args[1]}}",
|
||||
"page": 1
|
||||
},
|
||||
"transition_overlay_target": "reports_data_grid__body"
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
@@ -5,12 +5,12 @@ namespace Modules\Sirsoft\Board\Http\Controllers\Admin;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Database\Eloquent\ModelNotFoundException;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Board\Enums\ReportStatus;
|
||||
use Modules\Sirsoft\Board\Exceptions\DeletedReportStatusChangeException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\Admin\IndexReportRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\Admin\ReportersRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\Admin\StatusCountsRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\BulkUpdateStatusRequest;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\UpdateStatusRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportCollection;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportDetailResource;
|
||||
@@ -18,6 +18,7 @@ use Modules\Sirsoft\Board\Http\Resources\ReportLogResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportResource;
|
||||
use Modules\Sirsoft\Board\Services\ReportService;
|
||||
use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
|
||||
|
||||
/**
|
||||
* 관리자용 신고 관리 컨트롤러
|
||||
@@ -27,6 +28,7 @@ use Modules\Sirsoft\Board\Traits\ChecksBoardPermission;
|
||||
class ReportController extends AdminBaseController
|
||||
{
|
||||
use ChecksBoardPermission;
|
||||
|
||||
/**
|
||||
* ReportController 생성자
|
||||
*
|
||||
@@ -127,7 +129,7 @@ class ReportController extends AdminBaseController
|
||||
/**
|
||||
* 신고 케이스의 신고자 목록을 페이지네이션으로 반환합니다.
|
||||
*
|
||||
* @param int $id 신고 케이스 ID
|
||||
* @param int $id 신고 케이스 ID
|
||||
* @param ReportersRequest $request 신고자 목록 조회 요청
|
||||
* @return JsonResponse 신고자 목록 응답
|
||||
*/
|
||||
@@ -138,7 +140,9 @@ class ReportController extends AdminBaseController
|
||||
return $this->forbidden('sirsoft-board::messages.reports.permission_denied');
|
||||
}
|
||||
|
||||
$perPage = min((int) $request->query('per_page', 10), 50);
|
||||
// 상한만으로는 0/음수를 막지 못한다 — 페이지네이터에서 나눗셈 오류(500)가 되거나
|
||||
// 음수 per_page 가 그대로 응답 메타에 실린다. 하한을 함께 닫는다.
|
||||
$perPage = min(max((int) $request->query('per_page', 10), 1), 50);
|
||||
$page = max((int) $request->query('page', 1), 1);
|
||||
|
||||
$paginator = $this->reportService->paginateReporters($id, $perPage, $page);
|
||||
@@ -148,12 +152,12 @@ class ReportController extends AdminBaseController
|
||||
[
|
||||
'data' => ReportLogResource::collection($paginator->items())->resolve(),
|
||||
'pagination' => [
|
||||
'total' => $paginator->total(),
|
||||
'from' => $paginator->firstItem() ?? 0,
|
||||
'to' => $paginator->lastItem() ?? 0,
|
||||
'per_page' => $paginator->perPage(),
|
||||
'total' => $paginator->total(),
|
||||
'from' => $paginator->firstItem() ?? 0,
|
||||
'to' => $paginator->lastItem() ?? 0,
|
||||
'per_page' => $paginator->perPage(),
|
||||
'current_page' => $paginator->currentPage(),
|
||||
'last_page' => $paginator->lastPage(),
|
||||
'last_page' => $paginator->lastPage(),
|
||||
],
|
||||
]
|
||||
);
|
||||
@@ -258,7 +262,7 @@ class ReportController extends AdminBaseController
|
||||
$affectedCount = $result['affected_count'];
|
||||
|
||||
// 상태명 다국어 키 가져오기
|
||||
$statusEnum = \Modules\Sirsoft\Board\Enums\ReportStatus::from($targetStatus);
|
||||
$statusEnum = ReportStatus::from($targetStatus);
|
||||
$statusLabel = $statusEnum->label();
|
||||
|
||||
// 성공 메시지 생성
|
||||
|
||||
@@ -4,7 +4,10 @@ namespace Modules\Sirsoft\Board\Http\Controllers\User;
|
||||
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Board\Http\Requests\User\IndexBoardRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\User\PopularBoardsRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\User\PopularPostsRequest;
|
||||
use Modules\Sirsoft\Board\Http\Requests\User\RecentPostsRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardMenuResource;
|
||||
use Modules\Sirsoft\Board\Http\Resources\BoardResource;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
@@ -37,16 +40,16 @@ class BoardController extends PublicBaseController
|
||||
* - 각 게시판별 최신글 N개 포함 (답변글, 삭제, 블라인드 제외)
|
||||
* - limit 파라미터로 게시글 개수 조절 가능 (기본: 0, 최대: 10)
|
||||
*
|
||||
* @param Request $request
|
||||
* @param IndexBoardRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
public function index(IndexBoardRequest $request): JsonResponse
|
||||
{
|
||||
// 활성화된 게시판만 조회
|
||||
$boards = $this->boardService->getActiveBoards();
|
||||
|
||||
// limit 파라미터 (0이면 최신글 미포함, 최대 10개)
|
||||
$recentPostsLimit = min(max((int) $request->input('limit', 0), 0), 10);
|
||||
$recentPostsLimit = $request->recentPostsLimit();
|
||||
|
||||
// toListArray() 메서드를 사용하여 경량 데이터 반환
|
||||
$data = $boards->map(function ($board) use ($recentPostsLimit) {
|
||||
@@ -128,14 +131,12 @@ class BoardController extends PublicBaseController
|
||||
* 모든 게시판의 최근 게시글을 통합하여 반환합니다.
|
||||
* - 기본 5개, 최대 20개까지 조회 가능
|
||||
*
|
||||
* @param Request $request
|
||||
* @param RecentPostsRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function recentPosts(Request $request): JsonResponse
|
||||
public function recentPosts(RecentPostsRequest $request): JsonResponse
|
||||
{
|
||||
$limit = min((int) $request->input('limit', 5), 20);
|
||||
|
||||
return $this->success('common.success', $this->boardService->getCachedRecentPosts($limit));
|
||||
return $this->success('common.success', $this->boardService->getCachedRecentPosts($request->limit()));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -146,19 +147,16 @@ class BoardController extends PublicBaseController
|
||||
* - 기간별 필터링: today, week, month, year (기본: week)
|
||||
* - period=all은 하위 호환을 위해 year로 매핑
|
||||
*
|
||||
* @param Request $request
|
||||
* @param PopularPostsRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function popular(Request $request): JsonResponse
|
||||
public function popular(PopularPostsRequest $request): JsonResponse
|
||||
{
|
||||
$period = $request->input('period', 'week');
|
||||
// all → year 매핑 (하위 호환)
|
||||
if ($period === 'all') {
|
||||
$period = 'year';
|
||||
}
|
||||
$limit = min((int) $request->input('limit', 20), 50);
|
||||
|
||||
return $this->success('common.success', $this->boardService->getCachedPopularPosts($period, $limit));
|
||||
// period 의 all → year 매핑(하위 호환)은 FormRequest 접근자가 담당한다.
|
||||
return $this->success(
|
||||
'common.success',
|
||||
$this->boardService->getCachedPopularPosts($request->period(), $request->limit())
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -167,13 +165,11 @@ class BoardController extends PublicBaseController
|
||||
* 게시글 수가 많은 순으로 게시판 목록을 반환합니다.
|
||||
* - 기본 4개, 최대 20개까지 조회 가능
|
||||
*
|
||||
* @param Request $request
|
||||
* @param PopularBoardsRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function popularBoards(Request $request): JsonResponse
|
||||
public function popularBoards(PopularBoardsRequest $request): JsonResponse
|
||||
{
|
||||
$limit = min((int) $request->input('limit', 4), 20);
|
||||
|
||||
return $this->success('common.success', $this->boardService->getCachedPopularBoards($limit));
|
||||
return $this->success('common.success', $this->boardService->getCachedPopularBoards($request->limit()));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,7 @@ use Modules\Sirsoft\Board\Enums\ReportType;
|
||||
use Modules\Sirsoft\Board\Exceptions\DuplicateReportException;
|
||||
use Modules\Sirsoft\Board\Http\Requests\StoreReportRequest;
|
||||
use Modules\Sirsoft\Board\Http\Resources\ReportResource;
|
||||
use Modules\Sirsoft\Board\Models\Board;
|
||||
use Modules\Sirsoft\Board\Services\BoardService;
|
||||
use Modules\Sirsoft\Board\Services\BoardSettingsService;
|
||||
use Modules\Sirsoft\Board\Services\ReportService;
|
||||
|
||||
@@ -26,9 +26,11 @@ class ReportController extends AuthBaseController
|
||||
* ReportController 생성자
|
||||
*
|
||||
* @param ReportService $reportService 신고 서비스
|
||||
* @param BoardService $boardService 게시판 서비스 (slug → 게시판 해석)
|
||||
*/
|
||||
public function __construct(
|
||||
private ReportService $reportService
|
||||
private ReportService $reportService,
|
||||
private BoardService $boardService
|
||||
) {
|
||||
parent::__construct();
|
||||
}
|
||||
@@ -75,7 +77,12 @@ class ReportController extends AuthBaseController
|
||||
ReportType $targetType
|
||||
): JsonResponse {
|
||||
try {
|
||||
$board = Board::where('slug', $slug)->firstOrFail();
|
||||
// 신고는 게시판 읽기 스코프와 무관하게 slug 로만 해석한다 (기존 동작 유지).
|
||||
$board = $this->boardService->getBoardBySlug($slug, checkScope: false);
|
||||
|
||||
if (! $board) {
|
||||
return $this->notFound('sirsoft-board::messages.boards.error_404');
|
||||
}
|
||||
|
||||
if (! $board->use_report) {
|
||||
return $this->error('sirsoft-board::messages.reports.report_disabled', 403);
|
||||
@@ -134,5 +141,4 @@ class ReportController extends AuthBaseController
|
||||
return $this->error('sirsoft-board::messages.reports.create_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -33,6 +33,7 @@ class UserActivityController extends AuthBaseController
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 게시글 활동 목록 응답
|
||||
*/
|
||||
// audit:allow controller-base-request-injection reason: GET 본인 활동 목록. 필터·페이징 파라미터만 input() 으로 읽고, per_page 는 아래에서 1~100 으로 잘라낸다 (같은 모듈 PostController::userPosts 와 동일 패턴)
|
||||
public function index(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
@@ -45,7 +46,11 @@ class UserActivityController extends AuthBaseController
|
||||
'sort' => $request->input('sort', 'latest'), // latest, oldest, views
|
||||
];
|
||||
|
||||
// 요청 per_page 는 그대로 페이지네이터에 넘기지 않는다. 0/음수는 페이지네이터에서
|
||||
// 나눗셈 오류(500)가 되고, 큰 값은 목록 전량을 한 번에 읽는다.
|
||||
// 같은 컨트롤러의 myComments 와 동일한 상·하한을 적용한다.
|
||||
$perPage = (int) $request->input('per_page', 20);
|
||||
$perPage = min(max($perPage, 1), 100);
|
||||
|
||||
$activities = $this->postService->getUserActivities($userId, $filters, $perPage);
|
||||
|
||||
@@ -75,6 +80,7 @@ class UserActivityController extends AuthBaseController
|
||||
* @param Request $request HTTP 요청
|
||||
* @return JsonResponse 댓글 목록 응답
|
||||
*/
|
||||
// audit:allow controller-base-request-injection reason: GET 본인 댓글 목록. 필터·페이징 파라미터만 input() 으로 읽고, per_page 는 아래에서 1~100 으로 잘라낸다
|
||||
public function myComments(Request $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
@@ -127,4 +133,4 @@ class UserActivityController extends AuthBaseController
|
||||
return $this->error('sirsoft-board::messages.user_activities.stats_failed', 500, $e->getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,8 @@ class ReportersRequest extends FormRequest
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'per_page' => ['nullable', 'integer', 'min:1'],
|
||||
// 상한이 없으면 신고자 수만큼을 한 번에 요청할 수 있어 목록 조회가 전량 조회가 된다
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 활성 게시판 목록(경량) 조회 요청을 검증합니다.
|
||||
*
|
||||
* 비로그인도 접근하는 공개 엔드포인트라 권한 검사는 없고, 쿼리 파라미터의 범위만 닫습니다.
|
||||
*/
|
||||
class IndexBoardRequest extends FormRequest
|
||||
{
|
||||
/** 게시판별 최신글 동시 조회 상한 */
|
||||
public const MAX_RECENT_POSTS = 10;
|
||||
|
||||
/**
|
||||
* 요청 권한 — 공개 엔드포인트이므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// 상한은 규칙이 아니라 접근자에서 클램프한다 — 이 엔드포인트는 공개 API 이고, 상한
|
||||
// 초과 요청을 거부하지 않고 상한까지만 돌려주는 것이 기존 계약이다.
|
||||
return [
|
||||
'limit' => ['nullable', 'integer', 'min:0'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시판별로 함께 조회할 최신글 개수를 반환합니다.
|
||||
*
|
||||
* @return int 0 이면 최신글 미포함 (상한 초과 요청은 상한으로 클램프)
|
||||
*/
|
||||
public function recentPostsLimit(): int
|
||||
{
|
||||
return min((int) $this->validated('limit', 0), self::MAX_RECENT_POSTS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 인기 게시판(게시글 수 기준) 조회 요청을 검증합니다.
|
||||
*/
|
||||
class PopularBoardsRequest extends FormRequest
|
||||
{
|
||||
/** 조회 상한 */
|
||||
public const MAX_LIMIT = 20;
|
||||
|
||||
/** 기본 조회 개수 */
|
||||
public const DEFAULT_LIMIT = 4;
|
||||
|
||||
/**
|
||||
* 요청 권한 — 공개 엔드포인트이므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// 상한은 규칙이 아니라 접근자에서 클램프한다 (기존 공개 API 계약).
|
||||
return [
|
||||
'limit' => ['nullable', 'integer', 'min:0'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 조회할 게시판 개수를 반환합니다.
|
||||
*
|
||||
* @return int 조회 개수 (상한 초과 요청은 상한으로 클램프)
|
||||
*/
|
||||
public function limit(): int
|
||||
{
|
||||
return min((int) $this->validated('limit', self::DEFAULT_LIMIT), self::MAX_LIMIT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 인기 게시글(조회수 기준) 조회 요청을 검증합니다.
|
||||
*
|
||||
* `period=all` 은 과거 링크/북마크 호환을 위해 계속 허용하며 `year` 로 해석됩니다.
|
||||
*/
|
||||
class PopularPostsRequest extends FormRequest
|
||||
{
|
||||
/** 조회 상한 */
|
||||
public const MAX_LIMIT = 50;
|
||||
|
||||
/** 기본 조회 개수 */
|
||||
public const DEFAULT_LIMIT = 20;
|
||||
|
||||
/** 기본 기간 */
|
||||
public const DEFAULT_PERIOD = 'week';
|
||||
|
||||
/**
|
||||
* 저장소가 실제로 해석하는 기간 어휘 (`all` 은 여기에 없는 하위 호환 별칭이다).
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
public const RESOLVED_PERIODS = ['today', 'week', 'month', 'year'];
|
||||
|
||||
/**
|
||||
* 요청 권한 — 공개 엔드포인트이므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// 상한/어휘를 규칙으로 거부하지 않는 이유: 이 엔드포인트는 북마크 가능한 공개 URL 이고,
|
||||
// 기존 계약이 "상한 초과는 상한까지, 미지원 period 는 year 로 해석" 이다. 정규화는
|
||||
// 접근자가 담당한다 (period() 가 닫힌 집합만 반환하므로 캐시 키 공간도 함께 닫힌다).
|
||||
return [
|
||||
'period' => ['nullable', 'string'],
|
||||
'limit' => ['nullable', 'integer', 'min:0'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 조회 기간을 닫힌 집합 안의 값으로 반환합니다.
|
||||
*
|
||||
* 미지정은 기본 기간, `all` 은 하위 호환 별칭이라 `year`, 그 밖의 미지원 값도 `year` 로
|
||||
* 해석합니다 — 저장소가 미지원 period 를 1년 범위로 처리해 온 기존 동작과 같습니다.
|
||||
* 반환값을 닫아 두면 이 값을 그대로 쓰는 캐시 키가 임의 문자열로 늘어나지 않습니다.
|
||||
*
|
||||
* @return string 기간 키 (today|week|month|year)
|
||||
*/
|
||||
public function period(): string
|
||||
{
|
||||
$period = $this->validated('period');
|
||||
|
||||
if ($period === null || $period === '') {
|
||||
return self::DEFAULT_PERIOD;
|
||||
}
|
||||
|
||||
return in_array((string) $period, self::RESOLVED_PERIODS, true)
|
||||
? (string) $period
|
||||
: 'year';
|
||||
}
|
||||
|
||||
/**
|
||||
* 조회할 게시글 개수를 반환합니다.
|
||||
*
|
||||
* @return int 조회 개수 (상한 초과 요청은 상한으로 클램프)
|
||||
*/
|
||||
public function limit(): int
|
||||
{
|
||||
return min((int) $this->validated('limit', self::DEFAULT_LIMIT), self::MAX_LIMIT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 전체 게시판 통합 최근 게시글 조회 요청을 검증합니다.
|
||||
*/
|
||||
class RecentPostsRequest extends FormRequest
|
||||
{
|
||||
/** 조회 상한 */
|
||||
public const MAX_LIMIT = 20;
|
||||
|
||||
/** 기본 조회 개수 */
|
||||
public const DEFAULT_LIMIT = 5;
|
||||
|
||||
/**
|
||||
* 요청 권한 — 공개 엔드포인트이므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// 상한은 규칙이 아니라 접근자에서 클램프한다 — 이 엔드포인트는 공개 API 이고, 상한
|
||||
// 초과 요청을 거부하지 않고 상한까지만 돌려주는 것이 기존 계약이다.
|
||||
return [
|
||||
'limit' => ['nullable', 'integer', 'min:0'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 조회할 게시글 개수를 반환합니다.
|
||||
*
|
||||
* @return int 조회 개수 (상한 초과 요청은 상한으로 클램프)
|
||||
*/
|
||||
public function limit(): int
|
||||
{
|
||||
return min((int) $this->validated('limit', self::DEFAULT_LIMIT), self::MAX_LIMIT);
|
||||
}
|
||||
}
|
||||
@@ -144,7 +144,8 @@ class BoardRepository implements BoardRepositoryInterface
|
||||
*/
|
||||
public function paginate(int $perPage = 15): LengthAwarePaginator
|
||||
{
|
||||
$query = Board::orderBy('created_at', 'desc');
|
||||
// 정렬 마지막의 기본키는 전순서 보장용이다 (created_at 동률에서 페이지 경계 흔들림 방지)
|
||||
$query = Board::orderBy('created_at', 'desc')->orderBy('id', 'desc');
|
||||
|
||||
// 권한 스코프 필터링
|
||||
PermissionHelper::applyPermissionScope($query, 'sirsoft-board.boards.read');
|
||||
|
||||
@@ -586,6 +586,8 @@ class ReportRepository implements ReportRepositoryInterface
|
||||
return ReportLog::where('report_id', $reportId)
|
||||
->with('reporter')
|
||||
->latest()
|
||||
// 전순서 보장 — 같은 초에 기록된 처리 로그가 페이지 경계에서 뒤섞이지 않도록
|
||||
->orderByDesc('id')
|
||||
// audit:allow repository-paginate-column-pruning reason: 신고 케이스 1건에 종속된 신고자 로그 —
|
||||
// where(report_id) 로 이미 좁혀져 OFFSET 이 깊어질 수 없다
|
||||
->paginate($perPage, ['*'], 'page', $page);
|
||||
|
||||
@@ -35,6 +35,7 @@ return [
|
||||
|
||||
// Board type (Admin)
|
||||
'board_type_index' => 'Board type list viewed',
|
||||
'board_type_show' => 'Board type viewed (:type_name)',
|
||||
'board_type_create' => 'Board type created (:type_name)',
|
||||
'board_type_update' => 'Board type updated (:type_name)',
|
||||
'board_type_delete' => 'Board type deleted (:type_name)',
|
||||
|
||||
@@ -35,6 +35,7 @@ return [
|
||||
|
||||
// 게시판 유형 (Admin)
|
||||
'board_type_index' => '게시판 유형 목록 조회',
|
||||
'board_type_show' => '게시판 유형 상세 조회 (:type_name)',
|
||||
'board_type_create' => '게시판 유형 생성 (:type_name)',
|
||||
'board_type_update' => '게시판 유형 수정 (:type_name)',
|
||||
'board_type_delete' => '게시판 유형 삭제 (:type_name)',
|
||||
|
||||
@@ -177,4 +177,32 @@ class ReportRequestValidationTest extends ModuleTestCase
|
||||
$response->assertStatus(200)
|
||||
->assertJson(['success' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고자 목록의 per_page 가 상·하한 밖 값을 거부하는지 검증합니다.
|
||||
*
|
||||
* 상한이 없으면 한 요청으로 신고자 전량을 끌어올 수 있어 페이지네이션이 무의미해진다.
|
||||
*/
|
||||
public function test_reporters_per_page_is_bounded(): void
|
||||
{
|
||||
$report = Report::factory()->create([
|
||||
'board_id' => $this->board->id,
|
||||
'status' => ReportStatus::Pending,
|
||||
]);
|
||||
|
||||
$url = "/api/modules/sirsoft-board/admin/reports/{$report->id}/reporters";
|
||||
|
||||
foreach ([0, -3, 101, 100000] as $perPage) {
|
||||
$this->actingAs($this->admin)
|
||||
->getJson("{$url}?per_page={$perPage}")
|
||||
->assertStatus(422);
|
||||
}
|
||||
|
||||
// 경계 안쪽 값은 그대로 통과해야 한다
|
||||
foreach ([1, 100] as $perPage) {
|
||||
$this->actingAs($this->admin)
|
||||
->getJson("{$url}?per_page={$perPage}")
|
||||
->assertStatus(200);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -231,6 +231,36 @@ class BoardPopularApiTest extends ModuleTestCase
|
||||
$this->assertNotContains('Over One Year', $titles);
|
||||
}
|
||||
|
||||
/**
|
||||
* 미지원 period 가 거부되지 않고 year 로 해석되며, 캐시 키도 정규화되는지 테스트
|
||||
*
|
||||
* 북마크 가능한 공개 URL 이라 미지원 값에 422 를 돌려주면 기존 링크가 깨진다.
|
||||
* 동시에 period 는 캐시 키에 들어가므로, 원문을 그대로 쓰면 임의 문자열마다
|
||||
* 캐시 엔트리가 생겨 키 공간이 무한히 늘어난다 (요청 값이 아니라 해석된 값으로 키를 만든다).
|
||||
*/
|
||||
public function test_popular_unsupported_period_falls_back_to_year_and_normalizes_cache_key(): void
|
||||
{
|
||||
// Given: 1년 이내/이전 게시글 생성
|
||||
$board = Board::factory()->create(['is_active' => true]);
|
||||
DB::table('board_posts')->insert([
|
||||
['board_id' => $board->id, 'title' => 'Recent', 'content' => 'Content', 'view_count' => 100, 'status' => PostStatus::Published->value, 'ip_address' => '127.0.0.1', 'created_at' => now(), 'updated_at' => now()],
|
||||
['board_id' => $board->id, 'title' => 'Over One Year', 'content' => 'Content', 'view_count' => 300, 'status' => PostStatus::Published->value, 'ip_address' => '127.0.0.1', 'created_at' => now()->subMonths(13), 'updated_at' => now()],
|
||||
]);
|
||||
|
||||
// When: 지원하지 않는 period 로 호출
|
||||
$response = $this->getJson('/api/modules/sirsoft-board/boards/popular?period=nonsense&limit=5');
|
||||
|
||||
// Then: 422 가 아니라 200 이고, year 와 동일한 범위(1년 이내)로 해석된다
|
||||
$response->assertStatus(200);
|
||||
$titles = array_column($response->json('data'), 'title');
|
||||
$this->assertContains('Recent', $titles);
|
||||
$this->assertNotContains('Over One Year', $titles);
|
||||
|
||||
// Then: 캐시 키에는 요청 원문이 아니라 해석된 값이 들어간다
|
||||
$this->assertTrue(Cache::has('g7:module.sirsoft-board:popular_posts_year_5'));
|
||||
$this->assertFalse(Cache::has('g7:module.sirsoft-board:popular_posts_nonsense_5'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 게시글이 없을 때 빈 배열을 반환하는지 테스트
|
||||
*/
|
||||
@@ -352,7 +382,7 @@ class BoardPopularApiTest extends ModuleTestCase
|
||||
$response1->assertStatus(200);
|
||||
|
||||
// 캐시 키 확인 (형식: g7:module.sirsoft-board:popular_posts_{period}_{limit})
|
||||
$this->assertTrue(Cache::has("g7:module.sirsoft-board:popular_posts_week_5"));
|
||||
$this->assertTrue(Cache::has('g7:module.sirsoft-board:popular_posts_week_5'));
|
||||
|
||||
// When: 두 번째 API 호출
|
||||
$response2 = $this->getJson('/api/modules/sirsoft-board/boards/popular?limit=5&period=week');
|
||||
@@ -413,8 +443,8 @@ class BoardPopularApiTest extends ModuleTestCase
|
||||
/**
|
||||
* 게시판을 생성하고 게시글을 삽입하는 헬퍼
|
||||
*
|
||||
* @param int $postCount 생성할 게시글 수
|
||||
* @param Board|null $board 기존 게시판 (null이면 새로 생성)
|
||||
* @param int $postCount 생성할 게시글 수
|
||||
* @param Board|null $board 기존 게시판 (null이면 새로 생성)
|
||||
* @return Board 생성된 게시판
|
||||
*/
|
||||
private function createBoardWithPosts(int $postCount, ?Board $board = null): Board
|
||||
|
||||
@@ -237,6 +237,40 @@ class UserActivityApiTest extends BoardTestCase
|
||||
/**
|
||||
* 댓글을 단 게시글이 활동에 포함된다.
|
||||
*/
|
||||
/**
|
||||
* per_page 경계값 회귀 가드 (#492 브라우저 실측).
|
||||
*
|
||||
* 같은 컨트롤러의 my-comments 는 min(max(per_page,1),100) 로 잘라내는데
|
||||
* board-activities 만 원시 입력을 그대로 페이지네이터에 넘겨,
|
||||
* per_page=0 / 음수에서 500 이 나고 큰 값은 전량 조회가 됐다.
|
||||
*/
|
||||
public function test_board_activities_per_page_는_상한_100_으로_잘린다(): void
|
||||
{
|
||||
$response = $this->actingAs($this->user)
|
||||
->getJson('/api/modules/sirsoft-board/me/board-activities?per_page=100000');
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertSame(100, $response->json('data.per_page'));
|
||||
}
|
||||
|
||||
public function test_board_activities_per_page_0_은_500_이_아니라_최소값으로_처리된다(): void
|
||||
{
|
||||
$response = $this->actingAs($this->user)
|
||||
->getJson('/api/modules/sirsoft-board/me/board-activities?per_page=0');
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertSame(1, $response->json('data.per_page'));
|
||||
}
|
||||
|
||||
public function test_board_activities_per_page_음수는_500_이_아니라_최소값으로_처리된다(): void
|
||||
{
|
||||
$response = $this->actingAs($this->user)
|
||||
->getJson('/api/modules/sirsoft-board/me/board-activities?per_page=-5');
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertSame(1, $response->json('data.per_page'));
|
||||
}
|
||||
|
||||
public function test_activity_includes_commented_posts(): void
|
||||
{
|
||||
// Given: 다른 사용자의 게시글에 댓글 작성
|
||||
@@ -766,10 +800,10 @@ class UserActivityApiTest extends BoardTestCase
|
||||
// 비즈니스 로직: 통계 쿼리는 board_posts.comments_count 컬럼 (SUM) 기반이므로
|
||||
// CommentService 를 거치지 않는 직접 Comment::create 시에도 카운터 수동 동기화 필요.
|
||||
// (Listener 는 Service 레벨 훅에만 반응하므로 테스트에서 Model::create 직접 사용 시 미반영)
|
||||
\Illuminate\Support\Facades\DB::table('board_posts')
|
||||
DB::table('board_posts')
|
||||
->where('id', $postId)
|
||||
->update([
|
||||
'comments_count' => \Illuminate\Support\Facades\DB::table('board_comments')
|
||||
'comments_count' => DB::table('board_comments')
|
||||
->where('post_id', $postId)
|
||||
->whereNull('deleted_at')
|
||||
->count(),
|
||||
@@ -777,4 +811,4 @@ class UserActivityApiTest extends BoardTestCase
|
||||
|
||||
return $comment;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Board\Tests\Unit\Benchmark;
|
||||
|
||||
// ModuleTestCase 수동 로드 (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use Modules\Sirsoft\Board\Module;
|
||||
use Modules\Sirsoft\Board\Tests\ModuleTestCase;
|
||||
use Tests\Support\Concerns\AssertsListIndexCoverage;
|
||||
|
||||
/**
|
||||
* 게시판 모듈 목록 프로파일의 색인 커버리지 검사
|
||||
*
|
||||
* 모듈 테이블은 이 스위트에서만 마이그레이션되므로, 코어 스위트에 몰면 테이블이 없어
|
||||
* 건너뛰고 초록인 채 미검사가 된다. 모듈 프로파일은 반드시 자기 스위트에서 검사한다.
|
||||
*
|
||||
* @scenario case=list_index_coverage
|
||||
*
|
||||
* @effects list_profiles_declare_matching_index
|
||||
*/
|
||||
class ListIndexCoverageTest extends ModuleTestCase
|
||||
{
|
||||
use AssertsListIndexCoverage;
|
||||
|
||||
public function test_module_list_profiles_have_matching_indexes(): void
|
||||
{
|
||||
$this->assertListIndexCoverageForExtension(new Module);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,10 @@ namespace Modules\Sirsoft\Board\Tests\Unit\Repositories;
|
||||
// ModuleTestCase 수동 로드 (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Board\Repositories\PostRepository;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
@@ -15,6 +19,10 @@ use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
* 목록은 이제 "이번 페이지의 원글 ID 를 먼저 구하고, 그 ID 에 대해서만 목록 컬럼과 관계를
|
||||
* 읽는" 2단계 조회다. 이 화면은 공지 병합·답글 트리·다음 페이지 판정이 얽혀 있어, 조회 방식
|
||||
* 변경이 조용히 깨지면 화면에서 빈 값이나 누락으로만 드러난다. 그 성질들을 고정한다.
|
||||
*
|
||||
* @scenario case=post_list_deferred_join
|
||||
*
|
||||
* @effects self_scoped_list_returns_only_own_rows, soft_deleted_rows_stay_excluded, with_trashed_scope_is_preserved
|
||||
*/
|
||||
class PostListDeferredJoinTest extends BoardTestCase
|
||||
{
|
||||
@@ -193,4 +201,92 @@ class PostListDeferredJoinTest extends BoardTestCase
|
||||
|
||||
$this->assertSame($sorted, $ids, '동률 정렬에서도 id 내림차순이 유지되어야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* self 스코프 사용자의 목록에 타인 글이 섞이지 않는지 검증합니다.
|
||||
*
|
||||
* 권한 스코프는 `PermissionHelper::applyPermissionScope()` 가 쿼리에 붙이는 where 다.
|
||||
* 지연 조인은 이 쿼리를 clone 해 inner/outer 두 번 실행하므로, 스코프가 한쪽에만
|
||||
* 걸리면 목록에 타인 글이 노출되거나(권한 누출) 페이지가 비게 된다. 이 실패는
|
||||
* 예외 없이 조용히 일어나므로 결과 집합으로 직접 단언한다.
|
||||
*/
|
||||
public function test_self_scoped_list_returns_only_own_rows(): void
|
||||
{
|
||||
$owner = User::factory()->create();
|
||||
$other = User::factory()->create();
|
||||
|
||||
for ($i = 1; $i <= 6; $i++) {
|
||||
$this->createTestPost(['title' => "내 글 {$i}", 'user_id' => $owner->id]);
|
||||
$this->createTestPost(['title' => "남의 글 {$i}", 'user_id' => $other->id]);
|
||||
}
|
||||
|
||||
$permission = "sirsoft-board.{$this->board->slug}.admin.posts.read";
|
||||
|
||||
// owner_key 는 config/board.php 의 권한 정의가 SSoT 다. 여기에 값을 적어 두면
|
||||
// 정의가 바뀌어 스코프가 꺼져도 테스트는 계속 통과한다.
|
||||
$scopeMeta = config('sirsoft-board.board_permission_definitions')['admin.posts.read']['scope'] ?? null;
|
||||
|
||||
$this->assertNotNull($scopeMeta, 'admin.posts.read 에 scope 정의가 없다 — 스코프 필터가 적용되지 않는다');
|
||||
|
||||
$this->grantScopedPermission($owner, $permission, 'self', $scopeMeta);
|
||||
|
||||
// 권한 메타가 실제로 스코프를 켜는지 확인 — 이게 null 이면 아래 단언이 무의미해진다
|
||||
$this->assertSame(
|
||||
$scopeMeta['owner_key'],
|
||||
PermissionHelper::getOwnerKey($permission),
|
||||
"권한 {$permission} 의 owner_key 가 config 정의와 다르다"
|
||||
);
|
||||
$this->actingAs($owner);
|
||||
|
||||
$result = $this->repository->paginate(
|
||||
$this->board->slug,
|
||||
['scope_permission' => $permission],
|
||||
5
|
||||
);
|
||||
|
||||
$titles = collect($result->items())->pluck('title')->all();
|
||||
$userIds = collect($result->items())->pluck('user_id')->unique()->all();
|
||||
|
||||
$this->assertNotEmpty($titles, 'self 스코프에서도 본인 글은 조회되어야 한다');
|
||||
$this->assertSame([$owner->id], $userIds, 'self 스코프 목록에 타인 글이 섞이면 안 된다');
|
||||
|
||||
foreach ($titles as $title) {
|
||||
$this->assertStringNotContainsString('남의 글', $title);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 사용자에게 지정한 스코프로 권한을 부여합니다.
|
||||
*
|
||||
* @param User $user 대상 사용자
|
||||
* @param string $identifier 권한 식별자
|
||||
* @param string $scopeType 스코프 유형 (self/role)
|
||||
* @param array $scopeMeta config 의 scope 정의 (resource_route_key / owner_key)
|
||||
*/
|
||||
private function grantScopedPermission(User $user, string $identifier, string $scopeType, array $scopeMeta): void
|
||||
{
|
||||
$permission = Permission::updateOrCreate(
|
||||
['identifier' => $identifier],
|
||||
[
|
||||
'name' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'description' => json_encode(['ko' => $identifier, 'en' => $identifier]),
|
||||
'extension_type' => 'module',
|
||||
'extension_identifier' => 'sirsoft-board',
|
||||
'type' => 'admin',
|
||||
'resource_route_key' => $scopeMeta['resource_route_key'],
|
||||
'owner_key' => $scopeMeta['owner_key'],
|
||||
]
|
||||
);
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'scoped_test_'.uniqid(),
|
||||
'name' => json_encode(['ko' => '스코프 테스트', 'en' => 'Scoped Test']),
|
||||
'is_active' => true,
|
||||
]);
|
||||
|
||||
$role->permissions()->attach($permission->id, ['scope_type' => $scopeType]);
|
||||
$user->roles()->attach($role->id, ['assigned_at' => now()]);
|
||||
|
||||
$user->refresh();
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades\Data\Ext\Modules\SirsoftBoard\V1_0_3\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 게시글 목록 인덱스 말미에 기본키를 덧붙여 정렬을 완전히 덮습니다.
|
||||
*
|
||||
* 기존 `idx_board_posts_list_count` 는 created_at 에서 끝나는데 목록 정렬은
|
||||
* `created_at DESC, id DESC` 라, 동률 구간의 id 순서를 인덱스로 만들 수 없어 filesort 가
|
||||
* 붙습니다. 지연 조인의 inner 는 키 컬럼만 읽으므로 filesort 만 걷어내면 인덱스 순서 그대로
|
||||
* 끝납니다.
|
||||
*
|
||||
* 신규 설치는 마이그레이션이 처리하지만 기존 사이트에는 반영되지 않으므로 업그레이드
|
||||
* 시점에 같은 교체를 수행합니다.
|
||||
*
|
||||
* 게시글이 많은 사이트에서는 인덱스 교체가 수 분 이상 걸릴 수 있고 그동안 게시글 쓰기가
|
||||
* 대기합니다. 새 인덱스를 먼저 만들고 기존 인덱스를 나중에 지우므로, 중간에 중단되어도
|
||||
* 조회가 인덱스 없이 남는 구간은 없습니다.
|
||||
*
|
||||
* 소요 시간 주의 — `board_posts` 는 `PARTITION BY LIST (board_id)` 파티션 테이블입니다
|
||||
* (`2026_04_01_000004_create_board_posts_table.php`). 로컬 인덱스라 인덱스 생성·삭제가
|
||||
* 게시판 수만큼의 **전 파티션에 각각 적용**되므로, 같은 행 수의 비파티션 테이블보다 소요
|
||||
* 시간이 큽니다. 게시판이 많은 사이트일수록 차이가 커지니 트래픽이 적은 시간대에 실행하세요.
|
||||
*
|
||||
* idempotent: 이미 교체된 경우 아무것도 하지 않습니다. V-1 안전: Facades\Schema 만 사용합니다.
|
||||
*/
|
||||
class AddTiebreakToPostListIndex implements DataMigration
|
||||
{
|
||||
private const TABLE = 'board_posts';
|
||||
|
||||
private const OLD_INDEX = 'idx_board_posts_list_count';
|
||||
|
||||
private const NEW_INDEX = 'idx_board_posts_list_count_id';
|
||||
|
||||
/** @var array<int, string> */
|
||||
private const NEW_COLUMNS = ['board_id', 'is_notice', 'parent_id', 'deleted_at', 'created_at', 'id'];
|
||||
|
||||
/**
|
||||
* 마이그레이션 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 마이그레이션 이름
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return 'AddTiebreakToPostListIndex';
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 인덱스를 기본키 포함 형태로 교체합니다.
|
||||
*
|
||||
* @param UpgradeContext $context 업그레이드 컨텍스트
|
||||
*/
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
$context->logger->info('[board:1.0.3] 게시글 테이블 부재 — 목록 인덱스 교체 스킵');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes(self::TABLE), 'name');
|
||||
|
||||
if (! in_array(self::NEW_INDEX, $existing, true)) {
|
||||
$context->logger->info('[board:1.0.3] 목록 인덱스 교체 시작 (게시글이 많으면 수 분 이상 걸릴 수 있고 그동안 게시글 쓰기가 대기합니다)');
|
||||
|
||||
Schema::table(self::TABLE, function ($table) {
|
||||
$table->index(self::NEW_COLUMNS, self::NEW_INDEX);
|
||||
});
|
||||
|
||||
$context->logger->info('[board:1.0.3] 새 목록 인덱스 생성 완료: '.self::NEW_INDEX);
|
||||
} else {
|
||||
$context->logger->info('[board:1.0.3] 새 목록 인덱스가 이미 존재 — 생성 스킵');
|
||||
}
|
||||
|
||||
// 새 인덱스가 기존 인덱스의 상위집합이므로 남겨 두면 쓰기 비용만 늘어난다.
|
||||
// 반드시 새 인덱스 생성 이후에 지운다 — 순서를 바꾸면 중간 중단 시 목록 조회가
|
||||
// 인덱스 없이 남는 구간이 생긴다.
|
||||
if (in_array(self::OLD_INDEX, $existing, true)) {
|
||||
Schema::table(self::TABLE, function ($table) {
|
||||
$table->dropIndex(self::OLD_INDEX);
|
||||
});
|
||||
|
||||
$context->logger->info('[board:1.0.3] 상위집합에 포함된 기존 인덱스 제거: '.self::OLD_INDEX);
|
||||
}
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades\Data\Ext\Modules\SirsoftBoard\V1_0_3\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 신고 목록의 정렬 색인을 추가합니다.
|
||||
*
|
||||
* 신고 관리 목록은 삭제되지 않은 신고를 접수일 내림차순으로 보여주는데, 그 순서를 덮는
|
||||
* 색인이 없어 뒤쪽 페이지가 테이블 전체를 훑고 정렬했습니다.
|
||||
*
|
||||
* 신규 설치는 마이그레이션이 처리하지만 기존 사이트에는 반영되지 않으므로 업그레이드
|
||||
* 시점에 같은 색인을 추가합니다.
|
||||
*
|
||||
* 신고가 많이 쌓인 사이트에서는 수 분 걸릴 수 있고 그동안 신고 접수가 대기합니다.
|
||||
*
|
||||
* idempotent: 이미 존재하는 색인은 건너뜁니다. V-1 안전: Facades\Schema 만 사용합니다.
|
||||
*/
|
||||
class AddReportListSortIndex implements DataMigration
|
||||
{
|
||||
private const TABLE = 'boards_reports';
|
||||
|
||||
private const INDEX_NAME = 'idx_boards_reports_deleted_created_id';
|
||||
|
||||
/** @var array<int, string> */
|
||||
private const INDEX_COLUMNS = ['deleted_at', 'created_at', 'id'];
|
||||
|
||||
/**
|
||||
* 마이그레이션 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 마이그레이션 이름
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return 'AddReportListSortIndex';
|
||||
}
|
||||
|
||||
/**
|
||||
* 신고 목록 정렬 색인을 추가합니다.
|
||||
*
|
||||
* @param UpgradeContext $context 업그레이드 컨텍스트
|
||||
*/
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
$context->logger->info('[board:1.0.3] 신고 테이블 부재 — 정렬 색인 추가 스킵');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes(self::TABLE), 'name');
|
||||
|
||||
if (in_array(self::INDEX_NAME, $existing, true)) {
|
||||
$context->logger->info('[board:1.0.3] 이미 존재하는 색인 — 스킵: '.self::INDEX_NAME);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$context->logger->info('[board:1.0.3] 신고 목록 정렬 색인 추가 시작 (신고가 많으면 수 분 걸릴 수 있고 그동안 신고 접수가 대기합니다)');
|
||||
|
||||
Schema::table(self::TABLE, function ($table) {
|
||||
$table->index(self::INDEX_COLUMNS, self::INDEX_NAME);
|
||||
});
|
||||
|
||||
$context->logger->info('[board:1.0.3] 신고 목록 정렬 색인 추가 완료: '.self::INDEX_NAME);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
- 실제로 사용되지 않던 설정 항목(상품·주문 목록의 페이지당 개수, 결제 자동취소 기한 중복 항목)을 정리했습니다. 미입금 자동취소 기한은 관리자 환경설정의 값 하나만 사용합니다. (#81 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 사이트맵을 만들 때 상품과 카테고리를 한 번에 모두 메모리에 올리지 않고 나눠서 읽도록 바꿨습니다. 상품이 많은 쇼핑몰에서 사이트맵 생성 중 메모리가 부족해 실패하던 문제가 줄어듭니다.
|
||||
- 상품 리뷰·마일리지 내역·쿠폰 발급 내역 목록도 같은 방식으로 뒤쪽 페이지 조회를 개선했습니다. 상품 리뷰는 작성일 정렬용 인덱스를 추가하고 기간 검색 조건을 인덱스가 활용되는 형태로 바꿔, 리뷰가 많은 쇼핑몰에서 목록과 기간 검색이 함께 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 주문·상품·상품문의·상품후기·쿠폰 발급이력 목록의 정렬 색인을 정비했습니다. 정렬 순서를 색인이 그대로 담고 있지 않아 목록을 열 때마다 따로 줄을 세우던 작업이 사라져, 데이터가 많은 쇼핑몰일수록 목록이 빨라집니다. 기존 쇼핑몰도 업데이트 시 자동으로 반영되며, 데이터가 아주 많은 경우 이 과정에 수 분이 걸리고 그동안 해당 데이터의 저장이 잠시 대기할 수 있습니다.
|
||||
- 상품 목록(관리자·쇼핑몰 화면)·상품 문의 관리 목록·추가배송비 목록도 같은 방식으로 개선했습니다. 상품 문의는 기간 검색 조건도 인덱스가 활용되는 형태로 바꿔 기간을 좁혀 찾을 때 더 빨라집니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 주문 목록을 뒤쪽 페이지에서도 빠르게 열 수 있도록 조회 방식을 바꿨습니다. 예전에는 페이지가 뒤로 갈수록 건너뛰는 주문의 스냅샷·관리자 메모 같은 큰 항목까지 함께 읽어 느려졌지만, 이제 현재 페이지의 주문만 상세 정보를 읽습니다. 주문 10만 건 기준 5,000번째 페이지에서 조회 시간이 약 6분의 1로 줄어듭니다. 화면에 보이는 내용은 이전과 동일합니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
|
||||
@@ -51,13 +52,25 @@
|
||||
- 관리자 상품 등록/수정 화면의 배송 정보에서 '배송정책 등록' 버튼을 눌러도 아무 반응이 없던 문제를 수정했습니다. 이제 배송정책 등록 화면으로 이동합니다.
|
||||
- 관리자 브랜드·상품 카테고리·상품 공통정보·상품 고시정보 목록에서 왼쪽 목록의 항목을 고르면 걸어 둔 검색어(브랜드는 정렬 포함)가 사라지던 문제를 수정했습니다. 항목 선택은 선택 상태만 주소에 기록하고 목록 조건은 그대로 둡니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 관리자 쿠폰 목록에서 '등록' 으로 들어가거나 상품을 새로 저장한 직후, 보고 있던 목록의 조건이 사라져 취소·복귀 시 1페이지로 돌아가던 문제를 수정했습니다. (#75 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 상품 문의 등록이 실패했을 때 "문의 등록에 실패했습니다." 만 뜨고 이유를 알 수 없던 문제를 수정했습니다. 이제 "문의 게시판이 설정되지 않았습니다" 처럼 구체적인 사유가 표시되어, 문의 수정·답변 화면과 안내 수준이 같아집니다.
|
||||
- 찜 목록에서 판매자가 삭제한 상품이 빈 칸으로 남아 "데이터를 표시할 수 없습니다" 로 보이던 문제를 수정했습니다. 삭제된 상품은 목록에서 빠집니다.
|
||||
- 회원 마일리지 내역에서 사용·차감 내역만 「내용」 칸이 비어 있던 문제를 수정했습니다. 적립과 동일하게 사유가 표시됩니다.
|
||||
- 관리자 마일리지 내역 목록의 NO 칸이 항상 비어 있던 문제를 수정했습니다.
|
||||
- 내 쿠폰 목록에서 유효기간이 지난 쿠폰이 "사용가능" 으로 표시되던 문제를 수정했습니다. 만료 상태로 표시됩니다.
|
||||
- 상품 문의 목록과 찜 목록에서 한 페이지에 보여줄 개수를 0·음수·과도하게 큰 값으로 요청하면 오류가 나거나 목록 전체가 한 번에 조회되던 문제를 수정했습니다. 1~100 범위를 벗어나면 요청이 거부됩니다.
|
||||
- 상품 문의 목록·찜 목록·다운로드 가능 쿠폰 목록·통합검색 상품 목록에서 같은 시각에 등록된 항목이 여러 건일 때, 페이지를 넘기면 같은 항목이 두 번 보이고 다른 항목은 아예 보이지 않던 문제를 수정했습니다. 이제 페이지를 모두 넘겨도 목록에 있는 항목이 빠짐없이 한 번씩만 나옵니다.
|
||||
- 주문 관리 목록에서 "최근 발송순" 또는 "오래된 발송순"을 고르면 목록이 갱신되지 않고 정렬 이름만 바뀌던 문제를 수정했습니다. 이제 주문별 발송일 기준으로 정렬되며, 발송 이력이 없는 주문도 목록에서 사라지지 않습니다. 주문이 많아도 빠르게 정렬되도록 색인을 함께 추가했습니다.
|
||||
- 쿠폰 관리 목록에서 "유효기간 임박순"·"유효기간 여유순"을 고르면 목록이 그대로이던 문제를 수정했습니다. 화면이 제공하는 정렬인데 서버가 거부하고 있었으며, 이제 두 정렬 모두 정상 동작합니다.
|
||||
- 상품을 장바구니에 담거나 바로 구매할 때, 표시 언어(로케일)나 관리자의 옵션 이름 수정과 무관하게 선택한 옵션이 정확히 담기도록 개선했습니다. 특정 상황에서 "해당 옵션 조합을 찾을 수 없습니다" 오류로 담기가 실패하던 문제가 해소됩니다.
|
||||
- 오류 안내가 뜨기는 하지만 내용이 비어 있던 문제를 수정했습니다. 서버가 알려 준 실패 사유가 그대로 표시됩니다.
|
||||
- 헤더에서 통화나 배송 국가를 바꿀 때 저장에 실패해도 아무 안내 없이 넘어가던 문제를 수정했습니다. 실패하면 그 이유가 화면에 표시됩니다.
|
||||
- 일부 안내 문구가 실제 문장 대신 내부 식별자로 표시되던 문제를 수정했습니다. 리뷰 작성·답글·일괄처리, 장바구니 선택 항목 처리, 주문서 쿠폰 적용, 클레임 사유 관리, 주문 목록의 배송비 검색 조건, 택배사·상품 공통정보 관리, 결제 대기 주문 취소가 해당됩니다.
|
||||
- 관리자 주문 메모 안내가 실제 입력 한도(2,000자)와 다르게 "최대 1000자"로 표시되던 문제를 수정했습니다.
|
||||
- 금액·가격 범위 검색에서 상한을 0으로 지정하면 조건이 무시되고 전체 목록이 나오던 문제를 수정했습니다. 주문 목록의 "배송비 0원(무료배송)만 보기", 결제금액 0원 조회, 상품 목록의 가격 범위, 쿠폰 목록의 혜택금액·최소주문금액 범위가 해당됩니다. 이제 0도 정상적인 경계값으로 처리됩니다.
|
||||
- 쇼핑몰 환경설정 저장·조회, 카테고리 이미지 등록·삭제·순서 변경, 브랜드·상품 카테고리 전시 상태 변경, 검색 프리셋 조회, 결제 설정 조회 화면에서 결과 안내가 실제 문장 대신 내부 식별자로 표시되던 문제를 수정했습니다.
|
||||
- 화면과 문서에 "클래임"으로 잘못 적혀 있던 용어를 "클레임"으로 바로잡았습니다.
|
||||
- 쿠폰 목록의 "발급수"가 실제 발급 건수보다 적게 표시되던 문제를 수정했습니다. 목록의 발급수와 발급 내역 창의 "총 N건"이 서로 달랐으며, 이제 두 값이 일치합니다.
|
||||
- 활동 로그 내용에 실제 값 대신 `:option_id` 같은 표시가 그대로 나오던 문제를 수정했습니다. 주문 상세의 활동 로그 탭, 상품 수정 화면의 로그 탭, 관리자 활동 로그 목록이 해당됩니다.
|
||||
- 클레임 사유 목록 조회 시 유형·귀책 구분·사용여부·검색어에 잘못된 값을 넣어도 그대로 조회되던 것을 검증하도록 바꿨습니다. 잘못된 값은 이제 안내와 함께 거절됩니다.
|
||||
- 검색 프리셋의 대상 화면 이름(상품 목록·주문 목록·고객 목록)이 표시되지 않던 문제를 수정했습니다.
|
||||
- 상품 문의 답변 상태와 배송정책이 없는 배송 그룹의 표시명이 비어 보이던 문제를 수정했습니다.
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 주문 목록 "발송일" 정렬용 복합 인덱스 추가.
|
||||
*
|
||||
* 주문 목록은 배송 테이블의 `shipped_at` 을 상관 서브쿼리로 읽어 정렬한다
|
||||
* (`SortsByRelatedColumn`). 주문 1건마다 서브쿼리가 한 번씩 실행되므로
|
||||
* `(order_id, shipped_at)` 복합 인덱스가 없으면 주문 수만큼 배송 테이블을 스캔한다.
|
||||
*
|
||||
* 기존 단일 인덱스 `order_id` 만으로는 정렬 컬럼이 인덱스에 없어 매번 행을 읽고
|
||||
* 정렬해야 한다. 선행 컬럼이 같으므로 단일 인덱스는 이 복합 인덱스로 대체된다.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable('ecommerce_order_shippings')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existingIndexes = array_column(Schema::getIndexes('ecommerce_order_shippings'), 'name');
|
||||
|
||||
Schema::table('ecommerce_order_shippings', function (Blueprint $table) use ($existingIndexes) {
|
||||
if (! in_array('ecommerce_order_shippings_order_id_shipped_at_index', $existingIndexes)) {
|
||||
$table->index(['order_id', 'shipped_at'], 'ecommerce_order_shippings_order_id_shipped_at_index');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
if (! Schema::hasTable('ecommerce_order_shippings')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existingIndexes = array_column(Schema::getIndexes('ecommerce_order_shippings'), 'name');
|
||||
|
||||
Schema::table('ecommerce_order_shippings', function (Blueprint $table) use ($existingIndexes) {
|
||||
if (in_array('ecommerce_order_shippings_order_id_shipped_at_index', $existingIndexes)) {
|
||||
$table->dropIndex('ecommerce_order_shippings_order_id_shipped_at_index');
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 이커머스 목록의 정렬 색인을 추가·교체합니다.
|
||||
*
|
||||
* 각 목록은 소프트 삭제 조건으로 좁힌 뒤 작성일(또는 주문일·발급일) 내림차순으로 정렬하는데,
|
||||
* 그 순서를 덮는 색인이 없거나 색인이 정렬 컬럼에서 끝나 동률 구간에 filesort 가 남았다.
|
||||
* 지연 조인의 inner 가 키 컬럼만 읽어도 인덱스 순서로 끝나지 못하면 깊은 OFFSET 개선 폭이
|
||||
* 사라진다.
|
||||
*
|
||||
* 필요한 색인은 계측 프로파일 선언(filters / order / soft_delete)에서 도출한 것이며,
|
||||
* 이커머스 모듈의 `ListIndexCoverageTest` 가 같은 규칙으로 전 목록을 검사한다.
|
||||
*
|
||||
* 신설 — 정렬을 덮는 색인이 아예 없던 목록
|
||||
* - ecommerce_orders (deleted_at, ordered_at, id) 주문 관리 목록
|
||||
* - ecommerce_products (deleted_at, created_at, id) 상품 관리 목록
|
||||
* - ecommerce_product_inquiries (created_at, id) 상품 문의 목록
|
||||
*
|
||||
* 교체 — 색인은 있으나 정렬 컬럼에서 끝나 동률 구간이 filesort 로 남던 목록
|
||||
* - ecommerce_product_reviews (deleted_at, created_at) → + id
|
||||
* - ecommerce_promotion_coupon_issues (issued_at) → + id
|
||||
*
|
||||
* 교체 대상 색인은 새 색인의 좌측 프리픽스라 그대로 두면 쓰기 비용만 늘어난다. 새 색인을
|
||||
* 먼저 만들고 기존 색인을 나중에 지우므로, 중간에 중단되어도 조회가 색인 없이 남는 구간은 없다.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* 대상 [테이블 => [신규 색인명, 컬럼, 교체 대상 기존 색인명(없으면 null), 되돌릴 컬럼]]
|
||||
*
|
||||
* @var array<string, array{0: string, 1: array<int, string>, 2: string|null, 3: array<int, string>}>
|
||||
*/
|
||||
private const TARGETS = [
|
||||
'ecommerce_orders' => [
|
||||
'idx_orders_deleted_ordered_id', ['deleted_at', 'ordered_at', 'id'], null, [],
|
||||
],
|
||||
'ecommerce_products' => [
|
||||
'idx_products_deleted_created_id', ['deleted_at', 'created_at', 'id'], null, [],
|
||||
],
|
||||
'ecommerce_product_inquiries' => [
|
||||
'idx_inquiries_created_id', ['created_at', 'id'], null, [],
|
||||
],
|
||||
'ecommerce_product_reviews' => [
|
||||
'idx_reviews_deleted_created_id', ['deleted_at', 'created_at', 'id'],
|
||||
'idx_reviews_deleted_created', ['deleted_at', 'created_at'],
|
||||
],
|
||||
'ecommerce_promotion_coupon_issues' => [
|
||||
'idx_coupon_issues_issued_id', ['issued_at', 'id'], 'idx_issued_at', ['issued_at'],
|
||||
],
|
||||
];
|
||||
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
foreach (self::TARGETS as $table => [$newIndex, $columns, $oldIndex, $oldColumns]) {
|
||||
if (! Schema::hasTable($table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes($table), 'name');
|
||||
|
||||
Schema::table($table, function (Blueprint $blueprint) use ($existing, $newIndex, $columns, $oldIndex) {
|
||||
if (! in_array($newIndex, $existing, true)) {
|
||||
$blueprint->index($columns, $newIndex);
|
||||
}
|
||||
|
||||
if ($oldIndex !== null && in_array($oldIndex, $existing, true)) {
|
||||
$blueprint->dropIndex($oldIndex);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
foreach (self::TARGETS as $table => [$newIndex, $columns, $oldIndex, $oldColumns]) {
|
||||
if (! Schema::hasTable($table)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes($table), 'name');
|
||||
|
||||
Schema::table($table, function (Blueprint $blueprint) use ($existing, $newIndex, $oldIndex, $oldColumns) {
|
||||
if ($oldIndex !== null && $oldColumns !== [] && ! in_array($oldIndex, $existing, true)) {
|
||||
$blueprint->index($oldColumns, $oldIndex);
|
||||
}
|
||||
|
||||
if (in_array($newIndex, $existing, true)) {
|
||||
$blueprint->dropIndex($newIndex);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -204,17 +204,17 @@ class ActivityLogSampleSeeder extends Seeder
|
||||
|
||||
$actions = [
|
||||
['action' => 'product_option.bulk_price_update', 'key' => 'product_option_bulk_price_update', 'loggable' => true,
|
||||
'params' => fn ($opt) => ['count' => rand(2, 20)],
|
||||
'params' => fn ($opt) => ['option_id' => $opt->id],
|
||||
'changes' => fn ($opt) => [
|
||||
['field' => 'price_adjustment', 'label_key' => 'sirsoft-ecommerce::activity_log.fields.price_adjustment', 'old' => rand(0, 5000), 'new' => $opt->price_adjustment ?? 0, 'type' => 'currency'],
|
||||
]],
|
||||
['action' => 'product_option.bulk_stock_update', 'key' => 'product_option_bulk_stock_update', 'loggable' => true,
|
||||
'params' => fn ($opt) => ['count' => rand(2, 20)],
|
||||
'params' => fn ($opt) => ['option_id' => $opt->id],
|
||||
'changes' => fn ($opt) => [
|
||||
['field' => 'stock_quantity', 'label_key' => 'sirsoft-ecommerce::activity_log.fields.stock_quantity', 'old' => rand(0, 30), 'new' => $opt->stock_quantity ?? rand(10, 100), 'type' => 'number'],
|
||||
]],
|
||||
['action' => 'product_option.bulk_update', 'key' => 'product_option_bulk_update', 'loggable' => true,
|
||||
'params' => fn ($opt) => ['count' => rand(2, 20)],
|
||||
'params' => fn ($opt) => ['option_id' => $opt->id],
|
||||
'changes' => fn ($opt) => [
|
||||
['field' => 'sku', 'label_key' => 'sirsoft-ecommerce::activity_log.fields.sku', 'old' => 'OLD-SKU-'.rand(100, 999), 'new' => $opt->sku ?? 'SKU-'.rand(100, 999), 'type' => 'text'],
|
||||
]],
|
||||
@@ -271,7 +271,7 @@ class ActivityLogSampleSeeder extends Seeder
|
||||
'params' => fn ($o) => ['order_number' => $o->order_number, 'count' => 1],
|
||||
'changes' => fn ($o) => [
|
||||
['field' => 'order_status', 'label_key' => 'sirsoft-ecommerce::activity_log.fields.order_status', 'old' => OrderStatusEnum::PREPARING->value, 'new' => OrderStatusEnum::SHIPPING->value, 'type' => 'enum',
|
||||
'old_label_key' => OrderStatusEnum::PREPARING->labelKey(), 'new_label_key' => OrderStatusEnum::SHIPPING->labelKey()],
|
||||
'old_label_key' => OrderStatusEnum::PREPARING->labelKey(), 'new_label_key' => OrderStatusEnum::SHIPPING->labelKey()],
|
||||
]],
|
||||
['action' => 'order.payment_complete', 'key' => 'order_payment_complete', 'loggable' => true,
|
||||
'params' => fn ($o) => ['order_number' => $o->order_number]],
|
||||
@@ -310,11 +310,11 @@ class ActivityLogSampleSeeder extends Seeder
|
||||
['action' => 'order_option.bulk_status_change', 'key' => 'order_option_bulk_status_change', 'loggable' => true,
|
||||
'params' => fn ($opt) => ['count' => 1]],
|
||||
['action' => 'order_option.confirm', 'key' => 'order_option_confirm', 'loggable' => true,
|
||||
'params' => fn ($opt) => ['order_number' => $opt->order?->order_number ?? 'N/A'],
|
||||
'properties' => fn ($opt) => ['order_id' => $opt->order_id]],
|
||||
'params' => fn ($opt) => ['option_id' => $opt->id],
|
||||
'properties' => fn ($opt) => ['order_id' => $opt->order_id, 'option_id' => $opt->id]],
|
||||
['action' => 'order_option.partial_cancel', 'key' => 'order_option_partial_cancel', 'loggable' => true,
|
||||
'params' => fn ($opt) => ['order_number' => $opt->order?->order_number ?? 'N/A'],
|
||||
'properties' => fn ($opt) => ['order_id' => $opt->order_id, 'product_name' => $opt->product_name, 'quantity' => $opt->quantity]],
|
||||
'params' => fn ($opt) => ['option_id' => $opt->id],
|
||||
'properties' => fn ($opt) => ['order_id' => $opt->order_id, 'option_id' => $opt->id, 'product_name' => $opt->product_name, 'quantity' => $opt->quantity]],
|
||||
];
|
||||
|
||||
$count += $this->generateResourceLogs($allOptions, $admins, ActivityLogType::Admin, (new OrderOption)->getMorphClass(), $optionActions);
|
||||
@@ -524,9 +524,9 @@ class ActivityLogSampleSeeder extends Seeder
|
||||
['action' => 'product_review.bulk_delete', 'key' => 'review_bulk_delete', 'loggable' => true,
|
||||
'params' => fn ($r) => ['review_id' => $r->id, 'count' => 1]],
|
||||
['action' => 'product_review.create', 'key' => 'product_review_create', 'loggable' => true,
|
||||
'params' => fn ($r) => ['product_name' => $r->product ? $this->getLocalizedName($r->product->name) : '삭제된 상품']],
|
||||
'params' => fn ($r) => ['review_id' => $r->id]],
|
||||
['action' => 'product_review.delete', 'key' => 'product_review_delete', 'loggable' => false,
|
||||
'params' => fn ($r) => ['product_name' => $r->product ? $this->getLocalizedName($r->product->name) : '삭제된 상품'],
|
||||
'params' => fn ($r) => ['review_id' => $r->id],
|
||||
'properties' => fn ($r) => ['deleted_id' => $r->id]],
|
||||
];
|
||||
|
||||
@@ -855,7 +855,8 @@ class ActivityLogSampleSeeder extends Seeder
|
||||
// 주문 레벨
|
||||
$orderActions = [
|
||||
['action' => 'order.create', 'key' => 'user_order_create', 'loggable' => true,
|
||||
'params' => fn ($o) => ['order_number' => $o->order_number]],
|
||||
'params' => fn ($o) => ['order_id' => $o->id],
|
||||
'properties' => fn ($o) => ['order_id' => $o->id, 'order_number' => $o->order_number]],
|
||||
];
|
||||
|
||||
$count = $this->generateResourceLogs($orders, $users, ActivityLogType::User, (new Order)->getMorphClass(), $orderActions);
|
||||
@@ -865,8 +866,8 @@ class ActivityLogSampleSeeder extends Seeder
|
||||
if ($allOptions->isNotEmpty()) {
|
||||
$optionActions = [
|
||||
['action' => 'order_option.confirm', 'key' => 'user_order_option_confirm', 'loggable' => true,
|
||||
'params' => fn ($opt) => ['order_number' => $opt->order?->order_number ?? 'N/A'],
|
||||
'properties' => fn ($opt) => ['order_id' => $opt->order_id]],
|
||||
'params' => fn ($opt) => ['option_id' => $opt->id],
|
||||
'properties' => fn ($opt) => ['order_id' => $opt->order_id, 'option_id' => $opt->id]],
|
||||
];
|
||||
|
||||
$count += $this->generateResourceLogs($allOptions, $users, ActivityLogType::User, (new OrderOption)->getMorphClass(), $optionActions);
|
||||
|
||||
@@ -1553,6 +1553,7 @@ class OrderSeeder extends Seeder
|
||||
|
||||
$now = now();
|
||||
$replenished = 0;
|
||||
$perCoupon = [];
|
||||
|
||||
foreach ($unique as $record) {
|
||||
CouponIssue::create([
|
||||
@@ -1567,9 +1568,16 @@ class OrderSeeder extends Seeder
|
||||
'discount_amount' => null,
|
||||
]);
|
||||
|
||||
$perCoupon[$record['coupon_id']] = ($perCoupon[$record['coupon_id']] ?? 0) + 1;
|
||||
$replenished++;
|
||||
}
|
||||
|
||||
// 발급수 카운터 동기화 — 보충 발급도 발급이므로 issued_count 에 반영한다.
|
||||
// 누락하면 쿠폰 목록의 "발급수" 와 발급 이력의 "총 N건" 이 영구히 어긋난다.
|
||||
foreach ($perCoupon as $couponId => $count) {
|
||||
Coupon::where('id', $couponId)->increment('issued_count', $count);
|
||||
}
|
||||
|
||||
$this->command->line(" - 주문서 테스트용 쿠폰 {$replenished}건 보충 발급 완료");
|
||||
}
|
||||
}
|
||||
@@ -298,7 +298,16 @@ HTTP/1.1 200
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** 로그인 회원이 마이페이지에서 자신이 작성한 상품 문의 목록을 조회합니다. `auth:sanctum` 인증만 요구하며, `ProductInquiryService::getUserInquiries()` 가 로그인 사용자(`Auth::id()`)의 문의를 `search`(검색어)·`is_answered`(답변 여부) 필터와 `per_page`(기본 10)로 페이지네이션해 `items`(문의 배열)와 `meta`(페이지 정보)로 반환합니다. 마이페이지 문의 내역 화면을 채우는 데 사용합니다.
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 타입 | 필수 | 기본값 | 설명 |
|
||||
| --- | --- | :---: | --- | --- |
|
||||
| `page` | integer | - | 1 | 페이지 번호 (최소 1) |
|
||||
| `per_page` | integer | - | 10 | 페이지당 건수 (1~100). 범위를 벗어나면 422 |
|
||||
| `search` | string | - | - | 검색어 — **상품명**(`product_name_snapshot` 의 로케일별 값) 대상. 문의 제목·본문은 검색하지 않음 |
|
||||
| `is_answered` | boolean | - | - | 답변 여부 (`0` 답변대기 / `1` 답변완료) |
|
||||
|
||||
**설명** 로그인 회원이 마이페이지에서 자신이 작성한 상품 문의 목록을 조회합니다. `auth:sanctum` 인증만 요구하며, `ProductInquiryService::getUserInquiries()` 가 로그인 사용자(`Auth::id()`)의 문의를 `search`(검색어)·`is_answered`(답변 여부) 필터와 `per_page`(기본 10, 허용 1~100)로 페이지네이션해 `items`(문의 배열)와 `meta`(페이지 정보)로 반환합니다. 마이페이지 문의 내역 화면을 채우는 데 사용합니다.
|
||||
|
||||
|
||||
### DELETE /api/modules/sirsoft-ecommerce/user/inquiries/{inquiryId}
|
||||
|
||||
@@ -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` | 정렬 기준 필드명 (그 외 값은 422) |
|
||||
| sort_by | query | string | 아니오 | `ordered_at`, `paid_at`, `total_amount`, `shipped_at` | 정렬 기준 필드명 (그 외 값은 422). `shipped_at` 은 배송 테이블 기준 — `desc` 는 주문별 **가장 늦은** 발송일, `asc` 는 **가장 이른** 발송일로 정렬하며 발송 이력이 없는 주문도 목록에 남는다 |
|
||||
| sort_order | query | string | 아니오 | `asc`, `desc` | 정렬 방향 (asc 오름차순 / desc 내림차순) |
|
||||
| per_page | query | integer | 아니오 | min 10, max 100 | 페이지당 항목 수 |
|
||||
| page | query | integer | 아니오 | min 1 | 조회할 페이지 번호 (1부터 시작) |
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| page | query | integer | 아니오 | min 1 | 조회할 페이지 번호 (1부터 시작) |
|
||||
| per_page | query | integer | 아니오 | min 1, max 100 | 페이지당 항목 수 |
|
||||
| sort_by | query | string | 아니오 | `created_at`, `name`, `discount_value`, `issued_count` | 정렬 기준 필드명 |
|
||||
| sort_by | query | string | 아니오 | `created_at`, `name`, `discount_value`, `issued_count`, `valid_to` | 정렬 기준 필드명 (그 외 값은 422). `valid_to` 는 유효기간 종료일 |
|
||||
| sort_order | query | string | 아니오 | `asc`, `desc` | 정렬 방향 (asc 오름차순 / desc 내림차순) |
|
||||
| search_field | query | string | 아니오 | `all`, `name`, `description`, `created_by` | 검색 대상 필드명 (검색어를 적용할 컬럼) |
|
||||
| search_keyword | query | string | 아니오 | max 255 | 검색 키워드 (부분 일치) |
|
||||
|
||||
@@ -72,10 +72,18 @@ HTTP/1.1 200
|
||||
| 상태코드 | 의미 | 발생 조건 |
|
||||
| --- | --- | --- |
|
||||
| 401 | Unauthenticated | 유효한 Bearer 토큰이 없거나 만료된 경우 |
|
||||
| 422 | Validation Error | `page` < 1, `per_page` 가 1~100 범위를 벗어나거나 정수가 아닌 경우 |
|
||||
|
||||
<!-- @generated:end -->
|
||||
|
||||
**설명** 로그인한 회원의 찜(위시리스트) 목록을 페이지네이션으로 조회합니다. `auth:sanctum` 인증이 필요하며, `WishlistController@index`가 `ProductWishlistService::getByUser()`로 본인 찜 목록만 가져와 `WishlistCollection`으로 반환합니다. `per_page`는 기본 20건이며 최대 100건으로 제한됩니다. 마이페이지의 찜 목록 화면에서 사용합니다.
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 타입 | 필수 | 기본값 | 설명 |
|
||||
| --- | --- | :---: | --- | --- |
|
||||
| `page` | integer | - | 1 | 페이지 번호 (최소 1) |
|
||||
| `per_page` | integer | - | 20 | 페이지당 건수 (1~100). 범위를 벗어나면 422 |
|
||||
|
||||
**설명** 로그인한 회원의 찜(위시리스트) 목록을 페이지네이션으로 조회합니다. `auth:sanctum` 인증이 필요하며, `WishlistController@index`가 `ProductWishlistService::getByUser()`로 본인 찜 목록만 가져와 `WishlistCollection`으로 반환합니다. 페이지네이션 파라미터는 `WishlistListRequest` 가 검증하며 `per_page` 는 기본 20건, 허용 범위 1~100건입니다(범위를 벗어나면 422). 소프트 삭제된 상품의 찜 행은 목록에서 제외되므로 `total` 은 찜 테이블의 행 수보다 작을 수 있습니다. 마이페이지의 찜 목록 화면에서 사용합니다.
|
||||
|
||||
|
||||
### POST /api/modules/sirsoft-ecommerce/wishlist/toggle
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'description' => [
|
||||
// Product management (Admin)
|
||||
'product_index' => 'Product list viewed',
|
||||
'product_show' => 'Product details viewed (ID: :product_id)',
|
||||
'product_create' => 'Product created (:product_name)',
|
||||
'product_update' => 'Product updated (:product_name)',
|
||||
'product_delete' => 'Product deleted (:product_name)',
|
||||
'product_bulk_update' => 'Products bulk updated (:count items)',
|
||||
'product_bulk_price_update' => 'Product prices bulk updated (:count items)',
|
||||
'product_bulk_stock_update' => 'Product stocks bulk updated (:count items)',
|
||||
'product_stock_sync' => 'Product stock synced (:product_name)',
|
||||
|
||||
// Order management (Admin)
|
||||
'order_index' => 'Order list viewed',
|
||||
'order_show' => 'Order details viewed (:order_number)',
|
||||
'order_create' => 'Order created (:order_number)',
|
||||
'order_update' => 'Order updated (:order_number)',
|
||||
'order_delete' => 'Order deleted (:order_number)',
|
||||
'order_payment_complete' => 'Payment completed (:order_number)',
|
||||
'order_payment_failed' => 'Payment failed (:order_number)',
|
||||
'order_cancel' => 'Order fully cancelled (:order_number)',
|
||||
'order_partial_cancel' => 'Order partially cancelled (:order_number)',
|
||||
'order_coupon_restore' => 'Order cancellation coupon restored (:order_number)',
|
||||
'order_mileage_restore' => 'Order cancellation mileage restored (:order_number, :amount)',
|
||||
'order_bulk_update' => 'Orders bulk updated (:count items)',
|
||||
'order_bulk_status_update' => 'Order statuses bulk updated (:count items)',
|
||||
'order_bulk_shipping_update' => 'Shipping info bulk entered (:count items)',
|
||||
'order_update_shipping_address' => 'Shipping address changed (:order_number)',
|
||||
'order_send_email' => 'Order email sent (:order_number)',
|
||||
'order_option_status_change' => 'Order option status changed (Order: :order_number)',
|
||||
'order_option_bulk_status_change' => 'Order option statuses bulk changed (:count items)',
|
||||
'order_option_confirm' => 'Order option purchase confirmed (Order: :order_number)',
|
||||
'order_option_partial_cancel' => 'Order option partially cancelled (Order: :order_number)',
|
||||
|
||||
// Coupon management (Admin)
|
||||
'coupon_index' => 'Coupon list viewed',
|
||||
'coupon_show' => 'Coupon details viewed (:coupon_name)',
|
||||
'coupon_create' => 'Coupon created (:coupon_name)',
|
||||
'coupon_update' => 'Coupon updated (:coupon_name)',
|
||||
'coupon_delete' => 'Coupon deleted (:coupon_name)',
|
||||
'coupon_bulk_status' => 'Coupon statuses bulk changed (:count items)',
|
||||
|
||||
// Shipping policy management (Admin)
|
||||
'shipping_policy_index' => 'Shipping policy list viewed',
|
||||
'shipping_policy_create' => 'Shipping policy created (:policy_name)',
|
||||
'shipping_policy_update' => 'Shipping policy updated (:policy_name)',
|
||||
'shipping_policy_delete' => 'Shipping policy deleted (:policy_name)',
|
||||
'shipping_policy_toggle_active' => 'Shipping policy active status changed (:policy_name)',
|
||||
'shipping_policy_set_default' => 'Default shipping policy set (:policy_name)',
|
||||
'shipping_policy_bulk_delete' => 'Shipping policies bulk deleted (:count items)',
|
||||
'shipping_policy_bulk_toggle_active' => 'Shipping policy active statuses bulk changed (:count items)',
|
||||
|
||||
// Shipping carrier management (Admin)
|
||||
'shipping_carrier_index' => 'Shipping carrier list viewed',
|
||||
'shipping_carrier_show' => 'Shipping carrier details viewed (:carrier_name)',
|
||||
'shipping_carrier_create' => 'Shipping carrier created (:carrier_name)',
|
||||
'shipping_carrier_update' => 'Shipping carrier updated (:carrier_name)',
|
||||
'shipping_carrier_delete' => 'Shipping carrier deleted (:carrier_name)',
|
||||
'shipping_carrier_toggle_status' => 'Shipping carrier status toggled (:carrier_name)',
|
||||
|
||||
// Category management (Admin)
|
||||
'category_index' => 'Category list viewed',
|
||||
'category_show' => 'Category details viewed (:category_name)',
|
||||
'category_create' => 'Category created (:category_name)',
|
||||
'category_update' => 'Category updated (:category_name)',
|
||||
'category_delete' => 'Category deleted (:category_name)',
|
||||
'category_reorder' => 'Category order changed',
|
||||
'category_toggle_status' => 'Category status toggled (:category_name)',
|
||||
|
||||
// Brand management (Admin)
|
||||
'brand_index' => 'Brand list viewed',
|
||||
'brand_show' => 'Brand details viewed (:brand_name)',
|
||||
'brand_create' => 'Brand created (:brand_name)',
|
||||
'brand_update' => 'Brand updated (:brand_name)',
|
||||
'brand_delete' => 'Brand deleted (:brand_name)',
|
||||
'brand_toggle_status' => 'Brand status toggled (:brand_name)',
|
||||
|
||||
// Label management (Admin)
|
||||
'label_index' => 'Product label list viewed',
|
||||
'label_create' => 'Product label created (:label_name)',
|
||||
'label_update' => 'Product label updated (:label_name)',
|
||||
'label_delete' => 'Product label deleted (:label_name)',
|
||||
'label_toggle_status' => 'Product label status toggled (:label_name)',
|
||||
|
||||
// Product common info (Admin)
|
||||
'product_common_info_index' => 'Product common info list viewed',
|
||||
'product_common_info_create' => 'Product common info created (:info_name)',
|
||||
'product_common_info_update' => 'Product common info updated (:info_name)',
|
||||
'product_common_info_delete' => 'Product common info deleted (:info_name)',
|
||||
|
||||
// Product notice template (Admin)
|
||||
'product_notice_template_index' => 'Product notice template list viewed',
|
||||
'product_notice_template_create' => 'Product notice template created (:template_name)',
|
||||
'product_notice_template_update' => 'Product notice template updated (:template_name)',
|
||||
'product_notice_template_delete' => 'Product notice template deleted (:template_name)',
|
||||
'product_notice_template_copy' => 'Product notice template copied (:template_name)',
|
||||
|
||||
// Extra fee template (Admin)
|
||||
'extra_fee_template_index' => 'Extra fee template list viewed',
|
||||
'extra_fee_template_create' => 'Extra fee template created (:template_name)',
|
||||
'extra_fee_template_update' => 'Extra fee template updated (:template_name)',
|
||||
'extra_fee_template_delete' => 'Extra fee template deleted (:template_name)',
|
||||
'extra_fee_template_toggle_active' => 'Extra fee template active status changed (:template_name)',
|
||||
'extra_fee_template_bulk_delete' => 'Extra fee templates bulk deleted (:count items)',
|
||||
'extra_fee_template_bulk_toggle_active' => 'Extra fee template active statuses bulk changed (:count items)',
|
||||
'extra_fee_template_bulk_create' => 'Extra fee templates bulk created (:count items)',
|
||||
|
||||
// Product option (Admin)
|
||||
'product_option_bulk_price_update' => 'Product option prices bulk updated (:count items)',
|
||||
'product_option_bulk_stock_update' => 'Product option stocks bulk updated (:count items)',
|
||||
'product_option_bulk_update' => 'Product options bulk updated (:count items)',
|
||||
|
||||
// Product image (Admin)
|
||||
'product_image_upload' => 'Product image uploaded (Product: :product_name)',
|
||||
'product_image_delete' => 'Product image deleted (Product: :product_name)',
|
||||
'product_image_reorder' => 'Product image order changed (Product: :product_name)',
|
||||
|
||||
// Review management (Admin)
|
||||
'review_index' => 'Review list viewed',
|
||||
'review_show' => 'Review details viewed (ID: :review_id)',
|
||||
'review_create' => 'Review created (Product: :product_name)',
|
||||
'review_delete' => 'Review deleted (ID: :review_id)',
|
||||
'review_bulk_delete' => 'Reviews bulk deleted (:count items)',
|
||||
'review_reply' => 'Review reply created (ID: :review_id)',
|
||||
'product_review_create' => 'Product review created (Product: :product_name)',
|
||||
'product_review_delete' => 'Product review deleted (Product: :product_name)',
|
||||
|
||||
// Ecommerce settings
|
||||
'ecommerce_settings_index' => 'Ecommerce settings viewed',
|
||||
|
||||
// Payment (Admin)
|
||||
'payment_refund' => 'Payment refunded (Order: :order_number)',
|
||||
|
||||
// User actions (ActivityLogType::User)
|
||||
'cart_add' => 'Added to cart (:product_name)',
|
||||
'cart_update_quantity' => 'Cart quantity changed (:product_name)',
|
||||
'cart_change_option' => 'Cart option changed (:product_name)',
|
||||
'cart_delete' => 'Cart item deleted',
|
||||
'cart_delete_all' => 'Cart cleared',
|
||||
'wishlist_add' => 'Added to wishlist (:product_name)',
|
||||
'wishlist_remove' => 'Removed from wishlist (:product_name)',
|
||||
'coupon_use' => 'Coupon used (:coupon_name)',
|
||||
'coupon_restore' => 'Coupon restored (:coupon_name)',
|
||||
'user_coupon_download' => 'Coupon downloaded (:coupon_name)',
|
||||
'mileage_earn' => 'Mileage earned (:amount)',
|
||||
'mileage_use' => 'Mileage used (:amount)',
|
||||
'mileage_restore' => 'Mileage restored (:amount)',
|
||||
'mileage_expire' => 'Mileage expired (:amount)',
|
||||
'mileage_earn_cancel' => 'Mileage earning canceled (:amount)',
|
||||
'mileage_admin_earn' => 'Mileage granted manually (:amount)',
|
||||
'mileage_admin_deduct' => 'Mileage deducted manually (:amount)',
|
||||
'mileage_extend_expiry' => 'Mileage expiry extended (:days days)',
|
||||
'user_order_create' => 'Order created (:order_number)',
|
||||
'user_order_option_confirm' => 'Purchase confirmed (Order: :order_number)',
|
||||
],
|
||||
];
|
||||
@@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Ecommerce Module Enums (English)
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
'review_status' => [
|
||||
'visible' => 'Visible',
|
||||
'hidden' => 'Hidden',
|
||||
],
|
||||
|
||||
'has_reply' => [
|
||||
'replied' => 'Replied',
|
||||
'not_replied' => 'Not Replied',
|
||||
],
|
||||
];
|
||||
@@ -1,87 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Ecommerce Module Messages (English)
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
'order' => [
|
||||
// Order creation
|
||||
'created' => 'Your order has been placed.',
|
||||
'create_failed' => 'Failed to create order.',
|
||||
|
||||
// Order status
|
||||
'status_changed' => 'Order status has been changed.',
|
||||
'cancelled' => 'Order has been cancelled.',
|
||||
'cancel_failed' => 'Failed to cancel order.',
|
||||
|
||||
// Auto cancel
|
||||
'auto_cancel_expired_reason' => 'Automatically cancelled due to payment deadline expiration',
|
||||
|
||||
// Payment
|
||||
'payment_cancelled' => 'Payment cancellation has been recorded.',
|
||||
'payment_pending' => 'Awaiting payment.',
|
||||
'payment_completed' => 'Payment completed.',
|
||||
'payment_failed' => 'Payment failed.',
|
||||
|
||||
// Stock
|
||||
'stock_insufficient' => 'Insufficient stock.',
|
||||
'stock_restored' => 'Stock has been restored.',
|
||||
|
||||
// Validation
|
||||
'not_found' => 'Order not found.',
|
||||
'invalid_status' => 'Invalid order status.',
|
||||
'amount_mismatch' => 'Payment amount does not match.',
|
||||
],
|
||||
|
||||
'address' => [
|
||||
'created' => 'Address has been added.',
|
||||
'create_failed' => 'Failed to add address.',
|
||||
'updated' => 'Address has been updated.',
|
||||
'update_failed' => 'Failed to update address.',
|
||||
'deleted' => 'Address has been deleted.',
|
||||
'delete_failed' => 'Failed to delete address.',
|
||||
'not_found' => 'Address not found.',
|
||||
'fetched' => 'Address retrieved.',
|
||||
'fetch_failed' => 'Failed to retrieve address.',
|
||||
'list_fetched' => 'Address list retrieved.',
|
||||
'list_fetch_failed' => 'Failed to retrieve address list.',
|
||||
'set_default' => 'Set as default address.',
|
||||
'default_set' => 'Set as default address.',
|
||||
'set_default_failed' => 'Failed to set default address.',
|
||||
'name_duplicate' => 'An address with the same name already exists.',
|
||||
'auto_saved_label' => 'Auto-saved address',
|
||||
],
|
||||
|
||||
'cart' => [
|
||||
'added' => 'Added to cart.',
|
||||
'updated' => 'Cart has been updated.',
|
||||
'removed' => 'Removed from cart.',
|
||||
'empty' => 'Your cart is empty.',
|
||||
],
|
||||
|
||||
'product' => [
|
||||
'not_found' => 'Product not found.',
|
||||
'not_available' => 'This product is currently not available.',
|
||||
'option_not_found' => 'Product option not found.',
|
||||
],
|
||||
|
||||
'coupon' => [
|
||||
'applied' => 'Coupon applied.',
|
||||
'removed' => 'Coupon removed.',
|
||||
'invalid' => 'Invalid coupon.',
|
||||
'expired' => 'This coupon has expired.',
|
||||
'already_used' => 'This coupon has already been used.',
|
||||
'min_amount_not_met' => 'Minimum order amount not met.',
|
||||
],
|
||||
|
||||
'payment' => [
|
||||
'method_not_supported' => 'Payment method not supported.',
|
||||
'dbank_account_required' => 'Please select a bank account for bank transfer.',
|
||||
'depositor_name_required' => 'Please enter the depositor name.',
|
||||
'provider_not_found' => 'Payment provider not found.',
|
||||
'client_config_success' => 'Payment client configuration retrieved.',
|
||||
],
|
||||
];
|
||||
@@ -1,159 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'description' => [
|
||||
// 상품 관리 (Admin)
|
||||
'product_index' => '상품 목록 조회',
|
||||
'product_show' => '상품 상세 조회 (ID: :product_id)',
|
||||
'product_create' => '상품 생성 (:product_name)',
|
||||
'product_update' => '상품 수정 (:product_name)',
|
||||
'product_delete' => '상품 삭제 (:product_name)',
|
||||
'product_bulk_update' => '상품 일괄 수정 (:count건)',
|
||||
'product_bulk_price_update' => '상품 일괄 가격 수정 (:count건)',
|
||||
'product_bulk_stock_update' => '상품 일괄 재고 수정 (:count건)',
|
||||
'product_stock_sync' => '상품 재고 동기화 (:product_name)',
|
||||
|
||||
// 주문 관리 (Admin)
|
||||
'order_index' => '주문 목록 조회',
|
||||
'order_show' => '주문 상세 조회 (:order_number)',
|
||||
'order_create' => '주문 생성 (:order_number)',
|
||||
'order_update' => '주문 수정 (:order_number)',
|
||||
'order_delete' => '주문 삭제 (:order_number)',
|
||||
'order_payment_complete' => '결제 완료 (:order_number)',
|
||||
'order_payment_failed' => '결제 실패 (:order_number)',
|
||||
'order_cancel' => '주문 전체 취소 (:order_number)',
|
||||
'order_partial_cancel' => '주문 부분 취소 (:order_number)',
|
||||
'order_coupon_restore' => '주문 취소 쿠폰 복원 (:order_number)',
|
||||
'order_mileage_restore' => '주문 취소 마일리지 복원 (:order_number, :amount원)',
|
||||
'order_bulk_update' => '주문 일괄 변경 (:count건)',
|
||||
'order_bulk_status_update' => '주문 일괄 상태 변경 (:count건)',
|
||||
'order_bulk_shipping_update' => '운송장 일괄 입력 (:count건)',
|
||||
'order_update_shipping_address' => '배송지 변경 (:order_number)',
|
||||
'order_send_email' => '주문 이메일 발송 (:order_number)',
|
||||
'order_option_status_change' => '주문 옵션 상태 변경 (주문: :order_number)',
|
||||
'order_option_bulk_status_change' => '주문 옵션 일괄 상태 변경 (:count건)',
|
||||
'order_option_confirm' => '주문 옵션 구매 확정 (주문: :order_number)',
|
||||
'order_option_partial_cancel' => '주문 옵션 부분 취소 (주문: :order_number)',
|
||||
|
||||
// 쿠폰 관리 (Admin)
|
||||
'coupon_index' => '쿠폰 목록 조회',
|
||||
'coupon_show' => '쿠폰 상세 조회 (:coupon_name)',
|
||||
'coupon_create' => '쿠폰 생성 (:coupon_name)',
|
||||
'coupon_update' => '쿠폰 수정 (:coupon_name)',
|
||||
'coupon_delete' => '쿠폰 삭제 (:coupon_name)',
|
||||
'coupon_bulk_status' => '쿠폰 일괄 상태 변경 (:count건)',
|
||||
|
||||
// 배송정책 관리 (Admin)
|
||||
'shipping_policy_index' => '배송정책 목록 조회',
|
||||
'shipping_policy_create' => '배송정책 생성 (:policy_name)',
|
||||
'shipping_policy_update' => '배송정책 수정 (:policy_name)',
|
||||
'shipping_policy_delete' => '배송정책 삭제 (:policy_name)',
|
||||
'shipping_policy_toggle_active' => '배송정책 활성 상태 변경 (:policy_name)',
|
||||
'shipping_policy_set_default' => '기본 배송정책 설정 (:policy_name)',
|
||||
'shipping_policy_bulk_delete' => '배송정책 일괄 삭제 (:count건)',
|
||||
'shipping_policy_bulk_toggle_active' => '배송정책 일괄 활성 상태 변경 (:count건)',
|
||||
|
||||
// 배송업체 관리 (Admin)
|
||||
'shipping_carrier_index' => '배송업체 목록 조회',
|
||||
'shipping_carrier_show' => '배송업체 상세 조회 (:carrier_name)',
|
||||
'shipping_carrier_create' => '배송업체 생성 (:carrier_name)',
|
||||
'shipping_carrier_update' => '배송업체 수정 (:carrier_name)',
|
||||
'shipping_carrier_delete' => '배송업체 삭제 (:carrier_name)',
|
||||
'shipping_carrier_toggle_status' => '배송업체 상태 전환 (:carrier_name)',
|
||||
|
||||
// 카테고리 관리 (Admin)
|
||||
'category_index' => '카테고리 목록 조회',
|
||||
'category_show' => '카테고리 상세 조회 (:category_name)',
|
||||
'category_create' => '카테고리 생성 (:category_name)',
|
||||
'category_update' => '카테고리 수정 (:category_name)',
|
||||
'category_delete' => '카테고리 삭제 (:category_name)',
|
||||
'category_reorder' => '카테고리 순서 변경',
|
||||
'category_toggle_status' => '카테고리 상태 전환 (:category_name)',
|
||||
|
||||
// 브랜드 관리 (Admin)
|
||||
'brand_index' => '브랜드 목록 조회',
|
||||
'brand_show' => '브랜드 상세 조회 (:brand_name)',
|
||||
'brand_create' => '브랜드 생성 (:brand_name)',
|
||||
'brand_update' => '브랜드 수정 (:brand_name)',
|
||||
'brand_delete' => '브랜드 삭제 (:brand_name)',
|
||||
'brand_toggle_status' => '브랜드 상태 전환 (:brand_name)',
|
||||
|
||||
// 라벨 관리 (Admin)
|
||||
'label_index' => '상품 라벨 목록 조회',
|
||||
'label_create' => '상품 라벨 생성 (:label_name)',
|
||||
'label_update' => '상품 라벨 수정 (:label_name)',
|
||||
'label_delete' => '상품 라벨 삭제 (:label_name)',
|
||||
'label_toggle_status' => '상품 라벨 상태 전환 (:label_name)',
|
||||
|
||||
// 상품 공통정보 (Admin)
|
||||
'product_common_info_index' => '상품 공통정보 목록 조회',
|
||||
'product_common_info_create' => '상품 공통정보 생성 (:info_name)',
|
||||
'product_common_info_update' => '상품 공통정보 수정 (:info_name)',
|
||||
'product_common_info_delete' => '상품 공통정보 삭제 (:info_name)',
|
||||
|
||||
// 상품 고시정보 템플릿 (Admin)
|
||||
'product_notice_template_index' => '상품 고시정보 템플릿 목록 조회',
|
||||
'product_notice_template_create' => '상품 고시정보 템플릿 생성 (:template_name)',
|
||||
'product_notice_template_update' => '상품 고시정보 템플릿 수정 (:template_name)',
|
||||
'product_notice_template_delete' => '상품 고시정보 템플릿 삭제 (:template_name)',
|
||||
'product_notice_template_copy' => '상품 고시정보 템플릿 복제 (:template_name)',
|
||||
|
||||
// 추가비용 템플릿 (Admin)
|
||||
'extra_fee_template_index' => '추가비용 템플릿 목록 조회',
|
||||
'extra_fee_template_create' => '추가비용 템플릿 생성 (:template_name)',
|
||||
'extra_fee_template_update' => '추가비용 템플릿 수정 (:template_name)',
|
||||
'extra_fee_template_delete' => '추가비용 템플릿 삭제 (:template_name)',
|
||||
'extra_fee_template_toggle_active' => '추가비용 템플릿 활성 상태 변경 (:template_name)',
|
||||
'extra_fee_template_bulk_delete' => '추가비용 템플릿 일괄 삭제 (:count건)',
|
||||
'extra_fee_template_bulk_toggle_active' => '추가비용 템플릿 일괄 활성 상태 변경 (:count건)',
|
||||
'extra_fee_template_bulk_create' => '추가비용 템플릿 일괄 생성 (:count건)',
|
||||
|
||||
// 상품옵션 (Admin)
|
||||
'product_option_bulk_price_update' => '상품옵션 일괄 가격 수정 (:count건)',
|
||||
'product_option_bulk_stock_update' => '상품옵션 일괄 재고 수정 (:count건)',
|
||||
'product_option_bulk_update' => '상품옵션 일괄 수정 (:count건)',
|
||||
|
||||
// 상품 이미지 (Admin)
|
||||
'product_image_upload' => '상품 이미지 업로드 (상품: :product_name)',
|
||||
'product_image_delete' => '상품 이미지 삭제 (상품: :product_name)',
|
||||
'product_image_reorder' => '상품 이미지 순서 변경 (상품: :product_name)',
|
||||
|
||||
// 리뷰 관리 (Admin)
|
||||
'review_index' => '리뷰 목록 조회',
|
||||
'review_show' => '리뷰 상세 조회 (ID: :review_id)',
|
||||
'review_create' => '리뷰 작성 (상품: :product_name)',
|
||||
'review_delete' => '리뷰 삭제 (ID: :review_id)',
|
||||
'review_bulk_delete' => '리뷰 일괄 삭제 (:count건)',
|
||||
'review_reply' => '리뷰 답변 작성 (ID: :review_id)',
|
||||
'product_review_create' => '상품 리뷰 작성 (상품: :product_name)',
|
||||
'product_review_delete' => '상품 리뷰 삭제 (상품: :product_name)',
|
||||
|
||||
// 이커머스 설정
|
||||
'ecommerce_settings_index' => '이커머스 설정 조회',
|
||||
|
||||
// 결제 (Admin)
|
||||
'payment_refund' => '결제 환불 (주문: :order_number)',
|
||||
|
||||
// 사용자 행위 (ActivityLogType::User)
|
||||
'cart_add' => '장바구니 추가 (:product_name)',
|
||||
'cart_update_quantity' => '장바구니 수량 변경 (:product_name)',
|
||||
'cart_change_option' => '장바구니 옵션 변경 (:product_name)',
|
||||
'cart_delete' => '장바구니 삭제',
|
||||
'cart_delete_all' => '장바구니 전체 삭제',
|
||||
'wishlist_add' => '위시리스트 추가 (:product_name)',
|
||||
'wishlist_remove' => '위시리스트 제거 (:product_name)',
|
||||
'coupon_use' => '쿠폰 사용 (:coupon_name)',
|
||||
'coupon_restore' => '쿠폰 복원 (:coupon_name)',
|
||||
'user_coupon_download' => '쿠폰 다운로드 (:coupon_name)',
|
||||
'mileage_earn' => '마일리지 적립 (:amount원)',
|
||||
'mileage_use' => '마일리지 사용 (:amount원)',
|
||||
'mileage_restore' => '마일리지 복원 (:amount원)',
|
||||
'mileage_expire' => '마일리지 소멸 (:amount원)',
|
||||
'mileage_earn_cancel' => '마일리지 적립 회수 (:amount원)',
|
||||
'mileage_admin_earn' => '마일리지 수동 지급 (:amount원)',
|
||||
'mileage_admin_deduct' => '마일리지 수동 차감 (:amount원)',
|
||||
'mileage_extend_expiry' => '마일리지 유효기간 연장 (:days일)',
|
||||
'user_order_create' => '주문 생성 (:order_number)',
|
||||
'user_order_option_confirm' => '구매 확정 (주문: :order_number)',
|
||||
],
|
||||
];
|
||||
@@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Ecommerce Module Enums (Korean)
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
'review_status' => [
|
||||
'visible' => '전시중',
|
||||
'hidden' => '숨김',
|
||||
],
|
||||
|
||||
'has_reply' => [
|
||||
'replied' => '답변완료',
|
||||
'not_replied' => '미답변',
|
||||
],
|
||||
];
|
||||
@@ -1,87 +0,0 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Ecommerce Module Messages (Korean)
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
'order' => [
|
||||
// 주문 생성
|
||||
'created' => '주문이 완료되었습니다.',
|
||||
'create_failed' => '주문 생성에 실패했습니다.',
|
||||
|
||||
// 주문 상태
|
||||
'status_changed' => '주문 상태가 변경되었습니다.',
|
||||
'cancelled' => '주문이 취소되었습니다.',
|
||||
'cancel_failed' => '주문 취소에 실패했습니다.',
|
||||
|
||||
// 자동 취소
|
||||
'auto_cancel_expired_reason' => '입금 기한 만료로 인한 자동 취소',
|
||||
|
||||
// 결제
|
||||
'payment_cancelled' => '결제 취소가 기록되었습니다.',
|
||||
'payment_pending' => '입금 대기 중입니다.',
|
||||
'payment_completed' => '결제가 완료되었습니다.',
|
||||
'payment_failed' => '결제에 실패했습니다.',
|
||||
|
||||
// 재고
|
||||
'stock_insufficient' => '재고가 부족합니다.',
|
||||
'stock_restored' => '재고가 복원되었습니다.',
|
||||
|
||||
// 검증
|
||||
'not_found' => '주문을 찾을 수 없습니다.',
|
||||
'invalid_status' => '유효하지 않은 주문 상태입니다.',
|
||||
'amount_mismatch' => '결제 금액이 일치하지 않습니다.',
|
||||
],
|
||||
|
||||
'address' => [
|
||||
'created' => '배송지가 추가되었습니다.',
|
||||
'create_failed' => '배송지 추가에 실패했습니다.',
|
||||
'updated' => '배송지가 수정되었습니다.',
|
||||
'update_failed' => '배송지 수정에 실패했습니다.',
|
||||
'deleted' => '배송지가 삭제되었습니다.',
|
||||
'delete_failed' => '배송지 삭제에 실패했습니다.',
|
||||
'not_found' => '배송지를 찾을 수 없습니다.',
|
||||
'fetched' => '배송지 정보를 조회했습니다.',
|
||||
'fetch_failed' => '배송지 조회에 실패했습니다.',
|
||||
'list_fetched' => '배송지 목록을 조회했습니다.',
|
||||
'list_fetch_failed' => '배송지 목록 조회에 실패했습니다.',
|
||||
'set_default' => '기본 배송지로 설정되었습니다.',
|
||||
'default_set' => '기본 배송지로 설정되었습니다.',
|
||||
'set_default_failed' => '기본 배송지 설정에 실패했습니다.',
|
||||
'name_duplicate' => '동일한 이름의 배송지가 이미 존재합니다.',
|
||||
'auto_saved_label' => '자동 저장된 배송지',
|
||||
],
|
||||
|
||||
'cart' => [
|
||||
'added' => '장바구니에 추가되었습니다.',
|
||||
'updated' => '장바구니가 수정되었습니다.',
|
||||
'removed' => '장바구니에서 삭제되었습니다.',
|
||||
'empty' => '장바구니가 비어있습니다.',
|
||||
],
|
||||
|
||||
'product' => [
|
||||
'not_found' => '상품을 찾을 수 없습니다.',
|
||||
'not_available' => '현재 구매할 수 없는 상품입니다.',
|
||||
'option_not_found' => '상품 옵션을 찾을 수 없습니다.',
|
||||
],
|
||||
|
||||
'coupon' => [
|
||||
'applied' => '쿠폰이 적용되었습니다.',
|
||||
'removed' => '쿠폰이 해제되었습니다.',
|
||||
'invalid' => '유효하지 않은 쿠폰입니다.',
|
||||
'expired' => '만료된 쿠폰입니다.',
|
||||
'already_used' => '이미 사용된 쿠폰입니다.',
|
||||
'min_amount_not_met' => '최소 주문 금액 조건을 충족하지 않습니다.',
|
||||
],
|
||||
|
||||
'payment' => [
|
||||
'method_not_supported' => '지원하지 않는 결제 수단입니다.',
|
||||
'dbank_account_required' => '무통장입금 계좌를 선택해주세요.',
|
||||
'depositor_name_required' => '입금자명을 입력해주세요.',
|
||||
'provider_not_found' => '결제 제공자를 찾을 수 없습니다.',
|
||||
'client_config_success' => '결제 클라이언트 설정을 조회했습니다.',
|
||||
],
|
||||
];
|
||||
+2
-2
@@ -36,7 +36,7 @@
|
||||
"alwaysShowPagination": true,
|
||||
"columns": [
|
||||
{
|
||||
"field": "no",
|
||||
"field": "number",
|
||||
"header": "NO",
|
||||
"width": "56px",
|
||||
"sortable": false,
|
||||
@@ -47,7 +47,7 @@
|
||||
"props": {
|
||||
"className": "text-gray-500 dark:text-gray-400"
|
||||
},
|
||||
"text": "{{row.no}}"
|
||||
"text": "{{row.number}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+2
-2
@@ -82,7 +82,7 @@
|
||||
"name": "Icon",
|
||||
"props": {
|
||||
"name": "x",
|
||||
"className": "w-3 h-3"
|
||||
"className": "text-xs"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -182,7 +182,7 @@
|
||||
"name": "Icon",
|
||||
"props": {
|
||||
"name": "user",
|
||||
"className": "w-4 h-4 text-gray-400 dark:text-gray-500"
|
||||
"className": "text-base text-gray-400 dark:text-gray-500"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
+12
-22
@@ -6,7 +6,7 @@ use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\IndexProductCommonInfoRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreProductCommonInfoRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateProductCommonInfoRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductCommonInfoCollection;
|
||||
@@ -27,25 +27,15 @@ class ProductCommonInfoController extends AdminBaseController
|
||||
/**
|
||||
* 공통정보 목록을 조회합니다.
|
||||
*
|
||||
* @param Request $request 요청 데이터
|
||||
* @param IndexProductCommonInfoRequest $request 요청 데이터
|
||||
* @return JsonResponse 공통정보 목록 JSON 응답
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
public function index(IndexProductCommonInfoRequest $request): JsonResponse
|
||||
{
|
||||
$filters = [
|
||||
'search' => $request->get('search'),
|
||||
'is_active' => $request->boolean('active_only', false) ? true : null,
|
||||
'is_default' => $request->has('default_only') && $request->boolean('default_only') ? true : null,
|
||||
];
|
||||
|
||||
// null 값 제거
|
||||
$filters = array_filter($filters, fn ($v) => $v !== null);
|
||||
|
||||
// 페이지네이션 파라미터
|
||||
$perPage = (int) $request->get('per_page', 20);
|
||||
$filters = $request->filters();
|
||||
|
||||
// per_page가 0 이하이거나 all이면 전체 조회
|
||||
if ($perPage <= 0 || $request->get('per_page') === 'all') {
|
||||
if ($request->wantsAll()) {
|
||||
$commonInfos = $this->commonInfoService->getAllCommonInfos($filters);
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
@@ -56,7 +46,7 @@ class ProductCommonInfoController extends AdminBaseController
|
||||
}
|
||||
|
||||
// 페이지네이션 조회
|
||||
$commonInfos = $this->commonInfoService->getPaginatedCommonInfos($filters, $perPage);
|
||||
$commonInfos = $this->commonInfoService->getPaginatedCommonInfos($filters, $request->perPage());
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
@@ -68,7 +58,7 @@ class ProductCommonInfoController extends AdminBaseController
|
||||
/**
|
||||
* 공통정보 상세를 조회합니다.
|
||||
*
|
||||
* @param int $id 공통정보 ID
|
||||
* @param int $id 공통정보 ID
|
||||
* @return JsonResponse 공통정보 상세 JSON 응답
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
@@ -93,7 +83,7 @@ class ProductCommonInfoController extends AdminBaseController
|
||||
/**
|
||||
* 공통정보를 생성합니다.
|
||||
*
|
||||
* @param StoreProductCommonInfoRequest $request 생성 요청
|
||||
* @param StoreProductCommonInfoRequest $request 생성 요청
|
||||
* @return JsonResponse 생성된 공통정보 JSON 응답
|
||||
*/
|
||||
public function store(StoreProductCommonInfoRequest $request): JsonResponse
|
||||
@@ -119,8 +109,8 @@ class ProductCommonInfoController extends AdminBaseController
|
||||
/**
|
||||
* 공통정보를 수정합니다.
|
||||
*
|
||||
* @param UpdateProductCommonInfoRequest $request 수정 요청
|
||||
* @param int $id 공통정보 ID
|
||||
* @param UpdateProductCommonInfoRequest $request 수정 요청
|
||||
* @param int $id 공통정보 ID
|
||||
* @return JsonResponse 수정된 공통정보 JSON 응답
|
||||
*/
|
||||
public function update(UpdateProductCommonInfoRequest $request, int $id): JsonResponse
|
||||
@@ -145,7 +135,7 @@ class ProductCommonInfoController extends AdminBaseController
|
||||
/**
|
||||
* 공통정보를 삭제합니다.
|
||||
*
|
||||
* @param int $id 공통정보 ID
|
||||
* @param int $id 공통정보 ID
|
||||
* @return JsonResponse 삭제 결과 JSON 응답
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
@@ -170,7 +160,7 @@ class ProductCommonInfoController extends AdminBaseController
|
||||
/**
|
||||
* 공통정보 사용 여부를 토글합니다.
|
||||
*
|
||||
* @param int $id 공통정보 ID
|
||||
* @param int $id 공통정보 ID
|
||||
* @return JsonResponse 토글된 공통정보 JSON 응답
|
||||
*/
|
||||
public function toggleActive(int $id): JsonResponse
|
||||
|
||||
+14
-14
@@ -5,7 +5,8 @@ namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Admin;
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\AdminBaseController;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ActiveShippingCarrierRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\IndexShippingCarrierRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\StoreShippingCarrierRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\UpdateShippingCarrierRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ShippingCarrierCollection;
|
||||
@@ -24,12 +25,12 @@ class ShippingCarrierController extends AdminBaseController
|
||||
/**
|
||||
* 배송사 목록 조회
|
||||
*
|
||||
* @param Request $request
|
||||
* @param IndexShippingCarrierRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
public function index(IndexShippingCarrierRequest $request): JsonResponse
|
||||
{
|
||||
$carriers = $this->carrierService->getAllCarriers($request->all());
|
||||
$carriers = $this->carrierService->getAllCarriers($request->filters());
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
@@ -41,7 +42,7 @@ class ShippingCarrierController extends AdminBaseController
|
||||
/**
|
||||
* 배송사 생성
|
||||
*
|
||||
* @param StoreShippingCarrierRequest $request
|
||||
* @param StoreShippingCarrierRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function store(StoreShippingCarrierRequest $request): JsonResponse
|
||||
@@ -59,13 +60,12 @@ class ShippingCarrierController extends AdminBaseController
|
||||
/**
|
||||
* 활성 배송사 목록 조회 (Select 옵션용)
|
||||
*
|
||||
* @param Request $request
|
||||
* @param ActiveShippingCarrierRequest $request
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function active(Request $request): JsonResponse
|
||||
public function active(ActiveShippingCarrierRequest $request): JsonResponse
|
||||
{
|
||||
$type = $request->query('type');
|
||||
$carriers = $this->carrierService->getActiveCarriers($type);
|
||||
$carriers = $this->carrierService->getActiveCarriers($request->type());
|
||||
|
||||
$data = $carriers->map(function ($carrier) {
|
||||
return [
|
||||
@@ -87,7 +87,7 @@ class ShippingCarrierController extends AdminBaseController
|
||||
/**
|
||||
* 배송사 상세 조회
|
||||
*
|
||||
* @param int $id
|
||||
* @param int $id
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function show(int $id): JsonResponse
|
||||
@@ -112,8 +112,8 @@ class ShippingCarrierController extends AdminBaseController
|
||||
/**
|
||||
* 배송사 수정
|
||||
*
|
||||
* @param UpdateShippingCarrierRequest $request
|
||||
* @param int $carrier
|
||||
* @param UpdateShippingCarrierRequest $request
|
||||
* @param int $carrier
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function update(UpdateShippingCarrierRequest $request, int $carrier): JsonResponse
|
||||
@@ -138,7 +138,7 @@ class ShippingCarrierController extends AdminBaseController
|
||||
/**
|
||||
* 배송사 삭제
|
||||
*
|
||||
* @param int $carrier
|
||||
* @param int $carrier
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function destroy(int $carrier): JsonResponse
|
||||
@@ -173,7 +173,7 @@ class ShippingCarrierController extends AdminBaseController
|
||||
/**
|
||||
* 배송사 상태 토글
|
||||
*
|
||||
* @param int $carrier
|
||||
* @param int $carrier
|
||||
* @return JsonResponse
|
||||
*/
|
||||
public function toggleStatus(int $carrier): JsonResponse
|
||||
|
||||
+14
-6
@@ -6,6 +6,7 @@ use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\ProductInquiryListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\StoreInquiryRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductInquiryService;
|
||||
@@ -25,16 +26,18 @@ class ProductInquiryController extends PublicBaseController
|
||||
/**
|
||||
* 상품 문의 목록 조회
|
||||
*
|
||||
* @param ProductInquiryListRequest $request 목록 조회 요청 (페이지네이션 상·하한 검증)
|
||||
* @param Product $product 라우트 바인딩된 상품 (product_code 또는 id)
|
||||
* @return JsonResponse 문의 목록 및 board_settings 메타 JSON 응답
|
||||
*/
|
||||
public function index(Product $product): JsonResponse
|
||||
public function index(ProductInquiryListRequest $request, Product $product): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->logApiUsage('inquiry.index');
|
||||
$perPage = (int) (request()->query('per_page', 10));
|
||||
$page = (int) (request()->query('page', 1));
|
||||
$excludeSecret = filter_var(request()->query('exclude_secret', false), FILTER_VALIDATE_BOOLEAN);
|
||||
$validated = $request->validated();
|
||||
$perPage = (int) ($validated['per_page'] ?? 10);
|
||||
$page = (int) ($validated['page'] ?? 1);
|
||||
$excludeSecret = filter_var($validated['exclude_secret'] ?? false, FILTER_VALIDATE_BOOLEAN);
|
||||
|
||||
$result = $this->inquiryService->getProductInquiries($product->id, $perPage, $page, $excludeSecret);
|
||||
|
||||
@@ -72,10 +75,15 @@ class ProductInquiryController extends PublicBaseController
|
||||
201
|
||||
);
|
||||
} catch (\RuntimeException $e) {
|
||||
// 실패 사유(문의 게시판 미설정·게시판 모듈 불가 등)를 그대로 보여준다.
|
||||
// 일반 문구만 남기면 서버 기록을 봐야만 원인을 알 수 있다 — 같은 기능의
|
||||
// 수정·답변 경로는 이미 사유를 노출하고 있어 안내 수준을 맞춘다.
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.inquiries.create_failed',
|
||||
422
|
||||
'messages.inquiries.operation_failed_reason',
|
||||
422,
|
||||
null,
|
||||
['reason' => $e->getMessage()]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
|
||||
+4
-4
@@ -6,7 +6,7 @@ use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\DownloadableCouponsRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserCouponService;
|
||||
|
||||
@@ -27,11 +27,11 @@ class PublicCouponController extends PublicBaseController
|
||||
* 선택적 인증: 라우트에 optional.sanctum 미들웨어 적용
|
||||
* 로그인 시 is_downloaded 정보가 추가됩니다.
|
||||
*
|
||||
* @param Request $request 요청 데이터
|
||||
* @param Product $product 라우트 바인딩된 상품 (product_code 또는 id)
|
||||
* @param DownloadableCouponsRequest $request 요청 데이터
|
||||
* @param Product $product 라우트 바인딩된 상품 (product_code 또는 id)
|
||||
* @return JsonResponse 쿠폰 목록
|
||||
*/
|
||||
public function downloadableCoupons(Request $request, Product $product): JsonResponse
|
||||
public function downloadableCoupons(DownloadableCouponsRequest $request, Product $product): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->logApiUsage('products.downloadable_coupons');
|
||||
|
||||
+6
-6
@@ -6,9 +6,9 @@ use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\ToggleWishlistRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\WishlistListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\WishlistCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductWishlistService;
|
||||
|
||||
@@ -26,7 +26,7 @@ class WishlistController extends PublicBaseController
|
||||
/**
|
||||
* 찜 토글 (추가/제거)
|
||||
*
|
||||
* @param ToggleWishlistRequest $request 검증된 요청
|
||||
* @param ToggleWishlistRequest $request 검증된 요청
|
||||
* @return JsonResponse 토글 결과
|
||||
*/
|
||||
public function toggle(ToggleWishlistRequest $request): JsonResponse
|
||||
@@ -54,16 +54,16 @@ class WishlistController extends PublicBaseController
|
||||
/**
|
||||
* 사용자 찜 목록 조회
|
||||
*
|
||||
* @param Request $request 요청
|
||||
* @param WishlistListRequest $request 목록 조회 요청 (페이지네이션 상·하한 검증)
|
||||
* @return JsonResponse 찜 목록
|
||||
*/
|
||||
public function index(Request $request): JsonResponse
|
||||
public function index(WishlistListRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->logApiUsage('wishlist.index');
|
||||
|
||||
$userId = Auth::id();
|
||||
$perPage = min((int) $request->input('per_page', 20), 100);
|
||||
$perPage = (int) ($request->validated()['per_page'] ?? 20);
|
||||
|
||||
$wishlists = $this->wishlistService->getByUser($userId, $perPage);
|
||||
|
||||
@@ -80,7 +80,7 @@ class WishlistController extends PublicBaseController
|
||||
/**
|
||||
* 찜 삭제
|
||||
*
|
||||
* @param int $id 찜 ID
|
||||
* @param int $id 찜 ID
|
||||
* @return JsonResponse 삭제 결과
|
||||
*/
|
||||
public function destroy(int $id): JsonResponse
|
||||
|
||||
+44
-9
@@ -8,8 +8,9 @@ use App\Http\Controllers\Api\Base\AuthBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UpdateInquiryRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UpdateInquiryReplyRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UpdateInquiryRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\User\UserInquiryListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductInquiryService;
|
||||
|
||||
/**
|
||||
@@ -26,16 +27,18 @@ class ProductInquiryController extends AuthBaseController
|
||||
/**
|
||||
* 마이페이지 문의 목록 조회
|
||||
*
|
||||
* @param UserInquiryListRequest $request 목록 조회 요청 (페이지네이션 상·하한 검증)
|
||||
* @return JsonResponse 내 문의 목록 JSON 응답
|
||||
*/
|
||||
public function index(): JsonResponse
|
||||
public function index(UserInquiryListRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->logApiUsage('inquiry.user_list');
|
||||
$perPage = (int) (request()->query('per_page', 10));
|
||||
$validated = $request->validated();
|
||||
$perPage = (int) ($validated['per_page'] ?? 10);
|
||||
$filters = array_filter([
|
||||
'search' => request()->query('search'),
|
||||
'is_answered' => request()->query('is_answered'),
|
||||
'search' => $validated['search'] ?? null,
|
||||
'is_answered' => $validated['is_answered'] ?? null,
|
||||
], fn ($v) => ! is_null($v));
|
||||
$result = $this->inquiryService->getUserInquiries(Auth::id(), $filters, $perPage);
|
||||
|
||||
@@ -74,7 +77,15 @@ class ProductInquiryController extends AuthBaseController
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.inquiries.updated', ['id' => $inquiryId]);
|
||||
} catch (\RuntimeException $e) {
|
||||
return ResponseHelper::error($e->getMessage(), 422);
|
||||
// 서비스가 던지는 RuntimeException 은 생성 시점에 __() 로 번역된 사용자 문구다.
|
||||
// 사유를 파라미터로 넘겨 실패 원인이 화면에 그대로 남게 한다.
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.inquiries.operation_failed_reason',
|
||||
422,
|
||||
null,
|
||||
['reason' => $e->getMessage()]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError('sirsoft-ecommerce', 'messages.inquiries.update_failed', 500);
|
||||
}
|
||||
@@ -134,7 +145,15 @@ class ProductInquiryController extends AuthBaseController
|
||||
201
|
||||
);
|
||||
} catch (\RuntimeException $e) {
|
||||
return ResponseHelper::error($e->getMessage(), 422);
|
||||
// 서비스가 던지는 RuntimeException 은 생성 시점에 __() 로 번역된 사용자 문구다.
|
||||
// 사유를 파라미터로 넘겨 실패 원인이 화면에 그대로 남게 한다.
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.inquiries.operation_failed_reason',
|
||||
422,
|
||||
null,
|
||||
['reason' => $e->getMessage()]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError('sirsoft-ecommerce', 'messages.inquiries.reply_failed', 500);
|
||||
}
|
||||
@@ -161,7 +180,15 @@ class ProductInquiryController extends AuthBaseController
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.inquiries.reply_updated', ['id' => $inquiryId]);
|
||||
} catch (\RuntimeException $e) {
|
||||
return ResponseHelper::error($e->getMessage(), 422);
|
||||
// 서비스가 던지는 RuntimeException 은 생성 시점에 __() 로 번역된 사용자 문구다.
|
||||
// 사유를 파라미터로 넘겨 실패 원인이 화면에 그대로 남게 한다.
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.inquiries.operation_failed_reason',
|
||||
422,
|
||||
null,
|
||||
['reason' => $e->getMessage()]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError('sirsoft-ecommerce', 'messages.inquiries.reply_update_failed', 500);
|
||||
}
|
||||
@@ -187,7 +214,15 @@ class ProductInquiryController extends AuthBaseController
|
||||
|
||||
return ResponseHelper::moduleSuccess('sirsoft-ecommerce', 'messages.inquiries.reply_deleted', ['deleted' => true]);
|
||||
} catch (\RuntimeException $e) {
|
||||
return ResponseHelper::error($e->getMessage(), 422);
|
||||
// 서비스가 던지는 RuntimeException 은 생성 시점에 __() 로 번역된 사용자 문구다.
|
||||
// 사유를 파라미터로 넘겨 실패 원인이 화면에 그대로 남게 한다.
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.inquiries.operation_failed_reason',
|
||||
422,
|
||||
null,
|
||||
['reason' => $e->getMessage()]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError('sirsoft-ecommerce', 'messages.inquiries.reply_delete_failed', 500);
|
||||
}
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 활성 배송사 목록(Select 옵션용) 조회 요청을 검증합니다.
|
||||
*/
|
||||
class ActiveShippingCarrierRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한 — 라우트 permission 미들웨어가 담당하므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'type' => ['nullable', 'string', 'max:50'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송사 유형 필터를 반환합니다.
|
||||
*
|
||||
* @return string|null 유형 (미지정 시 null)
|
||||
*/
|
||||
public function type(): ?string
|
||||
{
|
||||
$type = $this->validated('type');
|
||||
|
||||
return $type === null ? null : (string) $type;
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,10 @@ class CouponListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 인증/권한은 permission 미들웨어 체인이 담당하므로 항상 true 를 반환한다.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -34,7 +38,7 @@ class CouponListRequest extends FormRequest
|
||||
return [
|
||||
'page' => 'nullable|integer|min:1',
|
||||
'per_page' => 'nullable|integer|min:1|max:100',
|
||||
'sort_by' => 'nullable|string|in:created_at,name,discount_value,issued_count',
|
||||
'sort_by' => 'nullable|string|in:created_at,name,discount_value,issued_count,valid_to',
|
||||
'sort_order' => 'nullable|string|in:asc,desc',
|
||||
'search_field' => 'nullable|string|in:all,name,description,created_by',
|
||||
'search_keyword' => 'nullable|string|max:255',
|
||||
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 공통정보 목록 조회 요청을 검증합니다.
|
||||
*
|
||||
* `per_page` 는 정수 외에 `all` 을 허용합니다 (전체 조회 — Select 옵션 채우기 용도).
|
||||
*/
|
||||
class IndexProductCommonInfoRequest extends FormRequest
|
||||
{
|
||||
/** 기본 페이지 크기 */
|
||||
public const DEFAULT_PER_PAGE = 20;
|
||||
|
||||
/**
|
||||
* 요청 권한 — 라우트 permission 미들웨어가 담당하므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿼리 문자열로 도착하는 불리언을 검증 전에 정규화합니다.
|
||||
*
|
||||
* 쿼리는 `?active_only=true` 형태의 문자열로 도착하는데 `boolean` 규칙은 `"true"`/`"false"`
|
||||
* 를 받지 않는다. 해석 가능한 값만 캐스팅하고, 해석 불가한 값은 그대로 두어 422 로 드러낸다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
$normalized = [];
|
||||
|
||||
foreach (['active_only', 'default_only'] as $key) {
|
||||
if (! $this->has($key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = filter_var($this->input($key), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
|
||||
if ($value !== null) {
|
||||
$normalized[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if ($normalized !== []) {
|
||||
$this->merge($normalized);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'search' => ['nullable', 'string', 'max:255'],
|
||||
'active_only' => ['nullable', 'boolean'],
|
||||
'default_only' => ['nullable', 'boolean'],
|
||||
// 정수 또는 `all`. 0 이하는 전체 조회로 해석된다.
|
||||
'per_page' => ['nullable', 'regex:/^(all|-?\d+)$/'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 필터를 반환합니다 (미지정 필터는 키 자체가 빠집니다).
|
||||
*
|
||||
* @return array<string, mixed> 필터 배열
|
||||
*/
|
||||
public function filters(): array
|
||||
{
|
||||
$filters = [
|
||||
'search' => $this->validated('search'),
|
||||
'is_active' => $this->boolean('active_only') ? true : null,
|
||||
'is_default' => $this->has('default_only') && $this->boolean('default_only') ? true : null,
|
||||
];
|
||||
|
||||
return array_filter($filters, fn ($value) => $value !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 전체 조회 여부를 반환합니다.
|
||||
*
|
||||
* @return bool `per_page=all` 이거나 0 이하이면 true
|
||||
*/
|
||||
public function wantsAll(): bool
|
||||
{
|
||||
$perPage = $this->validated('per_page');
|
||||
|
||||
return $perPage === 'all' || (int) ($perPage ?? self::DEFAULT_PER_PAGE) <= 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 페이지 크기를 반환합니다.
|
||||
*
|
||||
* @return int 페이지 크기
|
||||
*/
|
||||
public function perPage(): int
|
||||
{
|
||||
return (int) ($this->validated('per_page') ?? self::DEFAULT_PER_PAGE);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 배송사 목록 조회 요청을 검증합니다.
|
||||
*
|
||||
* 저장소(`ShippingCarrierRepository::getAll`)가 해석하는 필터만 통과시킵니다 — 검증되지 않은
|
||||
* 요청 배열을 그대로 Service 로 넘기지 않기 위함입니다.
|
||||
*/
|
||||
class IndexShippingCarrierRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한 — 라우트 permission 미들웨어가 담당하므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 쿼리 문자열로 도착하는 불리언을 검증 전에 정규화합니다.
|
||||
*
|
||||
* 해석 가능한 값만 캐스팅하고, 해석 불가한 값은 그대로 두어 422 로 드러낸다.
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if (! $this->has('is_active')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$value = filter_var($this->input('is_active'), FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
|
||||
|
||||
if ($value !== null) {
|
||||
$this->merge(['is_active' => $value]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => ['nullable', 'boolean'],
|
||||
'type' => ['nullable', 'string', 'max:50'],
|
||||
'search' => ['nullable', 'string', 'max:255'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 필터를 반환합니다.
|
||||
*
|
||||
* @return array<string, mixed> 필터 배열
|
||||
*/
|
||||
public function filters(): array
|
||||
{
|
||||
return array_filter(
|
||||
$this->validated(),
|
||||
fn ($value) => $value !== null
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\DeviceTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderDateTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ShippingType;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ShippingTypeRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Services\PaymentMethodResolver;
|
||||
|
||||
/**
|
||||
@@ -53,7 +53,11 @@ class OrderListRequest extends FormRequest
|
||||
|
||||
// 배송유형 (다중선택)
|
||||
'shipping_type' => ['nullable', 'array'],
|
||||
'shipping_type.*' => ['string', Rule::in(ShippingType::pluck('code')->toArray())],
|
||||
// 비활성 배송유형으로도 과거 주문을 필터링할 수 있어야 하므로 전체 코드를 허용한다
|
||||
// (getActiveCodes() 를 쓰면 비활성 유형의 기존 주문이 조회 불가가 된다).
|
||||
'shipping_type.*' => ['string', Rule::in(
|
||||
app(ShippingTypeRepositoryInterface::class)->getAll()->pluck('code')->toArray()
|
||||
)],
|
||||
|
||||
// 결제수단 (다중선택)
|
||||
'payment_method' => ['nullable', 'array'],
|
||||
@@ -92,7 +96,9 @@ class OrderListRequest extends FormRequest
|
||||
'member_type' => ['nullable', 'in:member,guest'],
|
||||
|
||||
// 정렬 및 페이지네이션
|
||||
'sort_by' => ['nullable', 'in:ordered_at,paid_at,total_amount'],
|
||||
// shipped_at 은 주문이 아니라 배송 테이블 컬럼이다 — OrderRepository 가
|
||||
// RELATED_SORTABLE_COLUMNS 로 상관 서브쿼리 정렬을 수행한다.
|
||||
'sort_by' => ['nullable', 'in:ordered_at,paid_at,total_amount,shipped_at'],
|
||||
'sort_order' => ['nullable', 'in:asc,desc'],
|
||||
'per_page' => ['nullable', 'integer', 'min:10', 'max:100'],
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 상품별 다운로드 가능 쿠폰 목록 조회 요청을 검증합니다.
|
||||
*
|
||||
* 상품은 라우트 모델 바인딩으로 해석되고 그 밖의 쿼리 파라미터는 사용하지 않으므로 규칙이
|
||||
* 비어 있습니다. 로그인 여부는 optional.sanctum 미들웨어가 해석한 사용자로 판단합니다.
|
||||
*/
|
||||
class DownloadableCouponsRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 요청 권한 — 공개 엔드포인트이므로 true 고정.
|
||||
*
|
||||
* @return bool 항상 true
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 규칙을 반환합니다.
|
||||
*
|
||||
* @return array<string, array<int, mixed>> 검증 규칙 (사용 파라미터 없음)
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 상품 상세 문의 목록 조회 요청 (공개)
|
||||
*
|
||||
* 페이지네이션 파라미터의 상·하한을 게이트에서 닫아, 저장소가 음수·0·과대 per_page 를
|
||||
* 그대로 받지 않도록 한다.
|
||||
*/
|
||||
class ProductInquiryListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 불리언 쿼리 파라미터를 정규화합니다.
|
||||
*
|
||||
* 쿼리 스트링은 언제나 문자열로 도착하는데 Laravel `boolean` 규칙은 `"true"` / `"false"` 를
|
||||
* 받지 않는다. 화면이 `exclude_secret=false` 로 보내면 목록 전체가 422 로 떨어져
|
||||
* 문의 탭이 통째로 비어 보인다 (#492 7차 브라우저 실측 D-38).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->has('exclude_secret')) {
|
||||
$normalized = filter_var(
|
||||
$this->query('exclude_secret'),
|
||||
FILTER_VALIDATE_BOOLEAN,
|
||||
FILTER_NULL_ON_FAILURE
|
||||
);
|
||||
|
||||
// 해석 불가한 값은 건드리지 않는다 — null 로 바꿔 버리면 오타 파라미터가
|
||||
// 조용히 "필터 없음" 으로 통과해 게이트가 무력해진다.
|
||||
if ($normalized !== null) {
|
||||
$this->merge(['exclude_secret' => $normalized]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'exclude_secret' => ['nullable', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 마이페이지 내 문의 목록 조회 요청
|
||||
*
|
||||
* 페이지네이션 파라미터의 상·하한을 게이트에서 닫아, 저장소가 음수·0·과대 per_page 를
|
||||
* 그대로 받지 않도록 한다.
|
||||
*/
|
||||
class UserInquiryListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 전 불리언 쿼리 파라미터를 정규화합니다.
|
||||
*
|
||||
* 쿼리 스트링은 언제나 문자열로 도착하는데 Laravel `boolean` 규칙은 `"true"` / `"false"` 를
|
||||
* 받지 않는다. 정규화가 없으면 화면이 그 형태로 보내는 순간 목록이 통째로 422 가 된다
|
||||
* (#492 7차 브라우저 실측 D-38 과 같은 원인).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
protected function prepareForValidation(): void
|
||||
{
|
||||
if ($this->has('is_answered')) {
|
||||
$normalized = filter_var(
|
||||
$this->query('is_answered'),
|
||||
FILTER_VALIDATE_BOOLEAN,
|
||||
FILTER_NULL_ON_FAILURE
|
||||
);
|
||||
|
||||
// 해석 불가한 값은 건드리지 않는다 — null 로 바꿔 버리면 오타 파라미터가
|
||||
// 조용히 "필터 없음" 으로 통과해 게이트가 무력해진다.
|
||||
if ($normalized !== null) {
|
||||
$this->merge(['is_answered' => $normalized]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
'search' => ['nullable', 'string', 'max:100'],
|
||||
'is_answered' => ['nullable', 'boolean'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\User;
|
||||
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 찜 목록 조회 요청
|
||||
*
|
||||
* 페이지네이션 파라미터의 상·하한을 게이트에서 닫는다. 상한만 있던 기존 클램프는
|
||||
* per_page=0 / 비숫자에서 모델 기본값(15)으로 조용히 바뀌고 음수에서 예외가 되었다.
|
||||
*/
|
||||
class WishlistListRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
return [
|
||||
'page' => ['nullable', 'integer', 'min:1'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace Modules\Sirsoft\Ecommerce\Http\Resources;
|
||||
|
||||
use App\Http\Resources\BaseApiResource;
|
||||
use Illuminate\Http\Request;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueRecordStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
|
||||
/**
|
||||
@@ -21,16 +22,23 @@ class CouponIssueResource extends BaseApiResource
|
||||
*/
|
||||
public function toArray($request): array
|
||||
{
|
||||
// 유효기간이 지난 available 행은 저장소 필터에서 '만료'로 분류되므로,
|
||||
// 표시 상태도 같은 기준을 따라야 한다. 원시 status 만 쓰면 만료 목록에
|
||||
// "사용가능" 라벨이 붙는다.
|
||||
$displayStatus = $this->isExpired()
|
||||
? CouponIssueRecordStatus::EXPIRED
|
||||
: $this->status;
|
||||
|
||||
return [
|
||||
'id' => $this->id,
|
||||
'coupon_id' => $this->coupon_id,
|
||||
'user_id' => $this->user?->uuid,
|
||||
'coupon_code' => $this->coupon_code,
|
||||
|
||||
// 상태
|
||||
// 상태 — status 는 저장된 원시값, *_label/badge 는 유효기간을 반영한 표시값
|
||||
'status' => $this->status?->value,
|
||||
'status_label' => $this->status?->label(),
|
||||
'status_badge_color' => $this->status?->badgeColor(),
|
||||
'status_label' => $displayStatus?->label(),
|
||||
'status_badge_color' => $displayStatus?->badgeColor(),
|
||||
|
||||
// 날짜
|
||||
'issued_at' => $this->formatDateTimeStringForUser($this->issued_at),
|
||||
|
||||
@@ -133,8 +133,10 @@ class CouponIssueRepository implements CouponIssueRepositoryInterface
|
||||
{
|
||||
$now = Carbon::now();
|
||||
|
||||
// 관계는 relations: 로 넘긴다 — 쿼리에 미리 with() 하면 지연 조인 트레이트가
|
||||
// outer 에서도 지워 관계가 로드되지 않는다.
|
||||
$query = $this->model
|
||||
->with(['coupon'])
|
||||
->newQuery()
|
||||
->where('user_id', $userId);
|
||||
|
||||
// 상태별 필터링
|
||||
@@ -171,6 +173,7 @@ class CouponIssueRepository implements CouponIssueRepositoryInterface
|
||||
columns: ['*'],
|
||||
sort: [['column' => 'created_at', 'direction' => 'desc']],
|
||||
perPage: $perPage,
|
||||
relations: ['coupon'],
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ class CouponRepository implements CouponRepositoryInterface
|
||||
use ResolvesSortSpec;
|
||||
|
||||
/** 허용 정렬 컬럼 (CouponListRequest 와 동일 집합) */
|
||||
private const SORTABLE_COLUMNS = ['created_at', 'name', 'discount_value', 'issued_count'];
|
||||
private const SORTABLE_COLUMNS = ['created_at', 'name', 'discount_value', 'issued_count', 'valid_to'];
|
||||
|
||||
public function __construct(
|
||||
protected Coupon $model,
|
||||
@@ -261,7 +261,9 @@ class CouponRepository implements CouponRepositoryInterface
|
||||
->where(fn ($q) => $q->whereNull('total_quantity')->orWhereColumn('issued_count', '<', 'total_quantity'))
|
||||
->where(fn ($q) => $q->whereNull('valid_to')->orWhere('valid_to', '>=', now()))
|
||||
->with(['includedProducts', 'excludedProducts', 'includedCategories', 'excludedCategories'])
|
||||
->orderBy('created_at', 'desc');
|
||||
// 정렬 마지막의 기본키는 전순서 보장용이다 (일괄 등록된 쿠폰의 created_at 동률 대비)
|
||||
->orderBy('created_at', 'desc')
|
||||
->orderBy('id', 'desc');
|
||||
|
||||
if ($perPage !== null) {
|
||||
// audit:allow repository-paginate-column-pruning reason: 다운로드 가능 쿠폰 "정의" 목록 —
|
||||
@@ -314,15 +316,16 @@ class CouponRepository implements CouponRepositoryInterface
|
||||
}
|
||||
|
||||
// 혜택금액 범위 필터
|
||||
if (! empty($filters['min_benefit_amount'])) {
|
||||
// 0 은 유효한 경계값이다. empty() 로 거르면 0 이 "미입력"이 되어 필터가 무시된다.
|
||||
if (isset($filters['min_benefit_amount']) && $filters['min_benefit_amount'] !== '') {
|
||||
$query->where('discount_value', '>=', $filters['min_benefit_amount']);
|
||||
}
|
||||
if (! empty($filters['max_benefit_amount'])) {
|
||||
if (isset($filters['max_benefit_amount']) && $filters['max_benefit_amount'] !== '') {
|
||||
$query->where('discount_value', '<=', $filters['max_benefit_amount']);
|
||||
}
|
||||
|
||||
// 최소주문금액 필터
|
||||
if (! empty($filters['min_order_amount'])) {
|
||||
// 최소주문금액 필터 (0 = 최소주문금액 제한 없는 쿠폰까지 포함하는 유효 경계)
|
||||
if (isset($filters['min_order_amount']) && $filters['min_order_amount'] !== '') {
|
||||
$query->where('min_order_amount', '>=', $filters['min_order_amount']);
|
||||
}
|
||||
|
||||
|
||||
+48
-26
@@ -185,10 +185,10 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
->where('exp.type', MileageTransactionTypeEnum::EXPIRED->value)
|
||||
->whereColumn('exp.source_transaction_id', "{$table}.id");
|
||||
|
||||
$query = MileageTransaction::query()
|
||||
->with(['user', 'grantedByUser', 'order'])
|
||||
->addSelect('*')
|
||||
->addSelect(['expired_amount' => $expiredAmount]);
|
||||
// 관계·집계·정렬은 쿼리에 붙이지 않는다 — 지연 조인 계약상 여기에는 필터/where 만 둔다.
|
||||
// 관계는 relations: 인자로, 소멸합 집계는 outerUsing 으로 outer 에서만 붙인다
|
||||
// (inner 에 두면 건너뛸 행 전체에 상관 서브쿼리가 돌아 깊은 OFFSET 비용이 그대로 남는다).
|
||||
$query = MileageTransaction::query();
|
||||
|
||||
if (! empty($filters['user_id'])) {
|
||||
$query->where('user_id', $filters['user_id']);
|
||||
@@ -203,12 +203,15 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
$query->where('currency', $filters['currency']);
|
||||
}
|
||||
|
||||
// 기간 필터 — 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());
|
||||
}
|
||||
|
||||
// 검색: search_field 별 대상 컬럼/관계 분기 (member/member_id/email/order)
|
||||
@@ -242,12 +245,23 @@ 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);
|
||||
//
|
||||
// columns 를 ['*'] 로 두는 이유: 목록 응답(MileageTransactionResource)이 금액·잔액·
|
||||
// 만료·메모·연결 주문까지 거의 모든 컬럼을 그대로 노출해 뺄 컬럼이 없다. 이 목록의
|
||||
// 이득은 컬럼 프루닝이 아니라 "넓은 컬럼을 읽는 행 수를 이번 페이지로 고정" 하는 쪽이다.
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
columns: ['*'],
|
||||
sort: $this->sortSpec($filters['sort'] ?? 'created_at_desc'),
|
||||
perPage: $perPage,
|
||||
relations: ['user', 'grantedByUser', 'order'],
|
||||
// 소멸합 집계는 결과 집합을 좁히지 않으므로 outer 에서만 실행한다.
|
||||
// `addSelect('*')` 를 함께 부르는 이유: outer 의 select 목록이 한 번 설정되면
|
||||
// `get(['*'])` 가 그것을 보존하므로, 명시하지 않으면 본 컬럼이 통째로 빠진다.
|
||||
outerUsing: fn (Builder $outer) => $outer
|
||||
->addSelect('*')
|
||||
->addSelect(['expired_amount' => $expiredAmount]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -258,23 +272,31 @@ class MileageTransactionRepository implements MileageTransactionRepositoryInterf
|
||||
*/
|
||||
protected function applySort($query, string $sort): void
|
||||
{
|
||||
switch ($sort) {
|
||||
case 'created_at_asc':
|
||||
$query->orderBy('created_at', 'asc')->orderBy('id', 'asc');
|
||||
break;
|
||||
case 'amount_desc':
|
||||
$query->orderByDesc('amount')->orderByDesc('id');
|
||||
break;
|
||||
case 'amount_asc':
|
||||
$query->orderBy('amount', 'asc')->orderBy('id', 'asc');
|
||||
break;
|
||||
case 'created_at_desc':
|
||||
default:
|
||||
$query->orderByDesc('created_at')->orderByDesc('id');
|
||||
break;
|
||||
foreach ($this->sortSpec($sort) as $spec) {
|
||||
$query->orderBy($spec['column'], $spec['direction']);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 정렬 슬러그를 정렬 스펙으로 해석합니다.
|
||||
*
|
||||
* 지연 조인은 정렬이 적용되지 않은 쿼리와 정렬 스펙을 따로 받으므로, 쿼리에 직접
|
||||
* `orderBy` 를 붙이는 대신 스펙을 돌려준다. 선택지가 닫힌 슬러그 집합이라 요청 값이
|
||||
* 그대로 컬럼명으로 새지 않는다.
|
||||
*
|
||||
* @param string $sort 정렬 슬러그
|
||||
* @return array<int, array{column: string, direction: string}> 정렬 스펙
|
||||
*/
|
||||
protected function sortSpec(string $sort): array
|
||||
{
|
||||
return match ($sort) {
|
||||
'created_at_asc' => [['column' => 'created_at', 'direction' => 'asc'], ['column' => 'id', 'direction' => 'asc']],
|
||||
'amount_desc' => [['column' => 'amount', 'direction' => 'desc'], ['column' => 'id', 'direction' => 'desc']],
|
||||
'amount_asc' => [['column' => 'amount', 'direction' => 'asc'], ['column' => 'id', 'direction' => 'asc']],
|
||||
default => [['column' => 'created_at', 'direction' => 'desc'], ['column' => 'id', 'direction' => 'desc']],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
|
||||
@@ -7,6 +7,7 @@ use App\Models\ActivityLog;
|
||||
use App\Models\User;
|
||||
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
||||
use App\Repositories\Concerns\ResolvesSortSpec;
|
||||
use App\Repositories\Concerns\SortsByRelatedColumn;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -27,6 +28,7 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
{
|
||||
use PaginatesWithDeferredJoin;
|
||||
use ResolvesSortSpec;
|
||||
use SortsByRelatedColumn;
|
||||
|
||||
/**
|
||||
* 주문 목록이 실제로 사용하는 컬럼
|
||||
@@ -68,6 +70,16 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
* 요청 값을 그대로 orderBy 에 넘기면 없는 컬럼으로 SQL 오류가 나거나 인덱스 없는 넓은
|
||||
* 컬럼 정렬을 강제할 수 있다.
|
||||
*
|
||||
* 이 목록은 OrderListRequest 의 `sort_by` `in:` 규칙(ordered_at·paid_at·total_amount)
|
||||
* 보다 넓다. 그 규칙은 `HookManager::applyFilters` 로 확장에 열려 있어 확장이 정렬
|
||||
* 컬럼을 늘릴 수 있고, 그때 이 목록이 더 좁으면 게이트를 통과한 정렬이 조용히 기본
|
||||
* 정렬로 되돌아간다. 게이트보다 좁게 두지 않는다
|
||||
* (service-repository.md "정렬 컬럼 화이트리스트").
|
||||
*
|
||||
* 다만 created_at·total_shipping_amount·total_paid_amount 는 인덱스가 없어, 확장이
|
||||
* 게이트를 넓혀 이 컬럼으로 정렬시키면 지연 조인의 inner 도 전체 스캔이 된다.
|
||||
* 그 경우 인덱스를 함께 추가해야 한다.
|
||||
*
|
||||
* @var array<int, string>
|
||||
*/
|
||||
private const SORTABLE_COLUMNS = [
|
||||
@@ -82,6 +94,23 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
'created_at',
|
||||
];
|
||||
|
||||
/**
|
||||
* 관계 테이블 컬럼 기준 허용 정렬 (`SortsByRelatedColumn`)
|
||||
*
|
||||
* 발송일은 주문이 아니라 배송 테이블에 있고 한 주문에 배송 행이 여러 건일 수 있다.
|
||||
* 상관 서브쿼리로 정렬하므로 원 행 수가 바뀌지 않아 총 건수·페이지 경계가 유지된다.
|
||||
* `ecommerce_order_shippings(order_id, shipped_at)` 복합 인덱스가 전제다.
|
||||
*
|
||||
* @var array<string, array{model: class-string, foreign_key: string, column: string}>
|
||||
*/
|
||||
private const RELATED_SORTABLE_COLUMNS = [
|
||||
'shipped_at' => [
|
||||
'model' => OrderShipping::class,
|
||||
'foreign_key' => 'order_id',
|
||||
'column' => 'shipped_at',
|
||||
],
|
||||
];
|
||||
|
||||
public function __construct(
|
||||
protected Order $model
|
||||
) {}
|
||||
@@ -299,10 +328,12 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
}
|
||||
|
||||
// 금액 범위 필터
|
||||
if (! empty($filters['min_amount'])) {
|
||||
// 0 은 유효한 경계값이다(예: 결제금액 0원 주문만). empty() 로 거르면 0 이 "미입력"으로
|
||||
// 취급돼 필터가 통째로 무시된다 — min_stock/max_stock 과 같은 판정식을 쓴다.
|
||||
if (isset($filters['min_amount']) && $filters['min_amount'] !== '') {
|
||||
$query->where('total_amount', '>=', (float) $filters['min_amount']);
|
||||
}
|
||||
if (! empty($filters['max_amount'])) {
|
||||
if (isset($filters['max_amount']) && $filters['max_amount'] !== '') {
|
||||
$query->where('total_amount', '<=', (float) $filters['max_amount']);
|
||||
}
|
||||
|
||||
@@ -317,10 +348,11 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
}
|
||||
|
||||
// 배송비 범위 필터
|
||||
if (! empty($filters['min_shipping_amount'])) {
|
||||
// 0 은 유효한 경계값이다(무료배송 주문만 보기). empty() 로 거르면 무시된다.
|
||||
if (isset($filters['min_shipping_amount']) && $filters['min_shipping_amount'] !== '') {
|
||||
$query->where('total_shipping_amount', '>=', (float) $filters['min_shipping_amount']);
|
||||
}
|
||||
if (! empty($filters['max_shipping_amount'])) {
|
||||
if (isset($filters['max_shipping_amount']) && $filters['max_shipping_amount'] !== '') {
|
||||
$query->where('total_shipping_amount', '<=', (float) $filters['max_shipping_amount']);
|
||||
}
|
||||
|
||||
@@ -339,8 +371,15 @@ class OrderRepository implements OrderRepositoryInterface
|
||||
$query->whereIn('order_device', $devices);
|
||||
}
|
||||
|
||||
// 정렬 — 요청 값은 허용 목록으로만 해석한다
|
||||
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'ordered_at');
|
||||
// 정렬 — 요청 값은 허용 목록으로만 해석한다.
|
||||
// 발송일(shipped_at)은 배송 테이블에 있어 상관 서브쿼리 정렬로 해석된다.
|
||||
$sort = $this->resolveSortSpecWithRelated(
|
||||
$filters,
|
||||
self::SORTABLE_COLUMNS,
|
||||
self::RELATED_SORTABLE_COLUMNS,
|
||||
$this->model,
|
||||
'ordered_at',
|
||||
);
|
||||
|
||||
return $this->paginateWithDeferredJoin(
|
||||
query: $query,
|
||||
|
||||
@@ -36,6 +36,8 @@ class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
return $this->model->newQuery()
|
||||
->where('product_id', $productId)
|
||||
->orderBy('created_at', 'desc')
|
||||
// 전순서 보장 — created_at 동률의 순서가 호출마다 달라지지 않도록
|
||||
->orderBy('id', 'desc')
|
||||
->get();
|
||||
}
|
||||
|
||||
@@ -47,6 +49,8 @@ class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
return $this->model->newQuery()
|
||||
->where('product_id', $productId)
|
||||
->orderBy('created_at', 'desc')
|
||||
// 전순서 보장 — 같은 초에 등록된 문의가 페이지 경계에서 뒤섞이지 않도록
|
||||
->orderBy('id', 'desc')
|
||||
// audit:allow repository-paginate-column-pruning reason: 상품 1건에 종속된 문의 목록 —
|
||||
// where(product_id) 로 이미 좁혀져 OFFSET 이 깊어질 수 없고, 목록이 본문을 그대로 쓴다
|
||||
->paginate($perPage);
|
||||
@@ -71,7 +75,9 @@ class ProductInquiryRepository implements ProductInquiryRepositoryInterface
|
||||
$query = $this->model->newQuery()
|
||||
->with(['product'])
|
||||
->where('user_id', $userId)
|
||||
->orderBy('created_at', 'desc');
|
||||
// 전순서 보장 — created_at 동률에서 페이지 경계 흔들림 방지
|
||||
->orderBy('created_at', 'desc')
|
||||
->orderBy('id', 'desc');
|
||||
|
||||
// 답변 여부 필터
|
||||
if (isset($filters['is_answered']) && $filters['is_answered'] !== '') {
|
||||
|
||||
@@ -453,10 +453,11 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
}
|
||||
|
||||
// 가격 범위 필터 (소수 통화 대응 — float 비교)
|
||||
if (! empty($filters['min_price'])) {
|
||||
// 0 은 유효한 경계값이다(무료 상품만 보기). empty() 로 거르면 필터가 무시된다.
|
||||
if (isset($filters['min_price']) && $filters['min_price'] !== '') {
|
||||
$query->where('selling_price', '>=', (float) $filters['min_price']);
|
||||
}
|
||||
if (! empty($filters['max_price'])) {
|
||||
if (isset($filters['max_price']) && $filters['max_price'] !== '') {
|
||||
$query->where('selling_price', '<=', (float) $filters['max_price']);
|
||||
}
|
||||
|
||||
@@ -574,6 +575,8 @@ 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)
|
||||
// 전순서 보장 — 정렬 컬럼(등록일/판매량 등)이 비고유라 페이지 경계가 흔들릴 수 있다
|
||||
->orderBy('id', $direction === 'asc' ? 'asc' : 'desc')
|
||||
// audit:allow repository-paginate-column-pruning reason: 통합검색 —
|
||||
// whereIn(id, $matchedIds) 로 FULLTEXT 매칭 ID 집합에 먼저 한정되므로 스캔 대상이
|
||||
// 상품 전체가 아니라 매칭 건수로 묶인다(OFFSET 이 훑는 범위도 그 안). 지연 조인의
|
||||
@@ -691,10 +694,11 @@ class ProductRepository implements ProductRepositoryInterface
|
||||
if (! empty($filters['price_type'])) {
|
||||
$priceField = $filters['price_type'];
|
||||
|
||||
if (! empty($filters['min_price'])) {
|
||||
// 0 은 유효한 경계값 — empty() 판정 금지 (min_stock/max_stock 과 동일 규칙)
|
||||
if (isset($filters['min_price']) && $filters['min_price'] !== '') {
|
||||
$query->where($priceField, '>=', (float) $filters['min_price']);
|
||||
}
|
||||
if (! empty($filters['max_price'])) {
|
||||
if (isset($filters['max_price']) && $filters['max_price'] !== '') {
|
||||
$query->where($priceField, '<=', (float) $filters['max_price']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,8 +37,9 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
*/
|
||||
public function getListWithFilters(array $filters, int $perPage = 20): LengthAwarePaginator
|
||||
{
|
||||
$query = $this->model->newQuery()
|
||||
->with(['user', 'product', 'images', 'orderOption.order', 'replyAdmin']);
|
||||
// 관계는 아래 relations: 인자로만 넘긴다 — 여기서 with() 해도 지연 조인 트레이트가
|
||||
// 지우므로 실제로 로드되지 않는다(중복 선언은 계약을 오해하게 만든다).
|
||||
$query = $this->model->newQuery();
|
||||
|
||||
// 검색 키워드
|
||||
if (! empty($filters['search_keyword'])) {
|
||||
@@ -134,8 +135,8 @@ class ProductReviewRepository implements ProductReviewRepositoryInterface
|
||||
*/
|
||||
public function findByProduct(int $productId, array $filters = [], int $perPage = 10): LengthAwarePaginator
|
||||
{
|
||||
// 관계는 아래 relations: 인자로만 넘긴다 (위 getListWithFilters 와 같은 이유)
|
||||
$query = $this->model->newQuery()
|
||||
->with(['user', 'images'])
|
||||
->where('product_id', $productId)
|
||||
->where('status', ReviewStatus::VISIBLE->value);
|
||||
|
||||
|
||||
@@ -57,8 +57,13 @@ class ProductWishlistRepository implements ProductWishlistRepositoryInterface
|
||||
{
|
||||
return $this->model
|
||||
->where('user_id', $userId)
|
||||
// 상품이 소프트 삭제되면 eager load 결과가 null 이 되어 카드가 렌더 실패한다.
|
||||
// 목록에서 아예 제외해 "빈 셀 0" 을 성립시킨다 (찜 행 자체는 보존).
|
||||
->whereHas('product')
|
||||
->with(['product.brand', 'product.categories', 'product.activeLabelAssignments.label'])
|
||||
->orderByDesc('created_at')
|
||||
// 전순서 보장 — 한 번에 여러 건을 담았을 때의 created_at 동률 대비
|
||||
->orderByDesc('id')
|
||||
// audit:allow repository-paginate-column-pruning reason: 사용자 1명에 종속된 찜 목록 —
|
||||
// where(user_id) 로 이미 좁혀지고, 피벗 성격의 테이블이라 넓은 컬럼이 없다
|
||||
->paginate($perPage);
|
||||
|
||||
@@ -922,6 +922,13 @@ class UserMileageService
|
||||
$firstSource ??= $lot->id;
|
||||
}
|
||||
|
||||
// 지급(adminEarn)은 description 을 채우는데 차감·사용은 비워 두면
|
||||
// 회원 마일리지 내역의 「내용」 열이 음수 행에서만 공백이 된다.
|
||||
// 활동 로그와 같은 키를 써서 지급/차감 표기를 대칭으로 맞춘다.
|
||||
$descriptionKey = $type === MileageTransactionTypeEnum::ADMIN_DEDUCT
|
||||
? 'sirsoft-ecommerce::activity_log.description.mileage_admin_deduct'
|
||||
: 'sirsoft-ecommerce::activity_log.description.mileage_use';
|
||||
|
||||
$tx = $this->ledger->createTransaction(array_merge([
|
||||
'user_id' => $userId,
|
||||
'currency' => $currency,
|
||||
@@ -930,6 +937,7 @@ class UserMileageService
|
||||
'remaining_amount' => 0,
|
||||
'balance_after' => $this->ledger->getBalanceByCurrency($userId, $currency),
|
||||
'source_transaction_id' => $firstSource,
|
||||
'description' => __($descriptionKey, ['amount' => $amount]),
|
||||
], $extra));
|
||||
|
||||
$this->cache->recalculateForUser($userId, $currency);
|
||||
|
||||
@@ -1213,6 +1213,8 @@ return [
|
||||
'reply_deleted' => 'Reply has been deleted.',
|
||||
'reply_delete_failed' => 'Failed to delete reply.',
|
||||
'reply_not_found' => 'Reply not found.',
|
||||
// 서비스가 던진 사유를 그대로 덧붙여, 실패 원인을 서버 기록 없이도 알 수 있게 한다
|
||||
'operation_failed_reason' => ':reason',
|
||||
],
|
||||
|
||||
// User addresses
|
||||
|
||||
@@ -1202,6 +1202,8 @@ return [
|
||||
'reply_deleted' => '답변이 삭제되었습니다.',
|
||||
'reply_delete_failed' => '답변 삭제에 실패했습니다.',
|
||||
'reply_not_found' => '답변을 찾을 수 없습니다.',
|
||||
// 서비스가 던진 사유를 그대로 덧붙여, 실패 원인을 서버 기록 없이도 알 수 있게 한다
|
||||
'operation_failed_reason' => ':reason',
|
||||
],
|
||||
|
||||
// 사용자 배송지
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Admin;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderShipping;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\OrderRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 주문 목록 "발송일" 정렬 회귀 테스트 (#492 D-19).
|
||||
*
|
||||
* 화면은 "최근 발송순 / 오래된 발송순" 정렬 옵션을 제공하는데 `shipped_at` 은 주문이 아니라
|
||||
* 배송 테이블(`ecommerce_order_shippings`)의 컬럼이다. 게이트가 이 값을 막고 있어 옵션을
|
||||
* 고르면 422 가 나고 목록은 그대로 남아 정렬이 적용된 것처럼 보였다.
|
||||
*
|
||||
* 관계 테이블 컬럼 정렬은 `SortsByRelatedColumn` 의 상관 서브쿼리로 해석한다. 이 테스트가
|
||||
* 지키는 불변식은 셋이다.
|
||||
*
|
||||
* 1. 주문별 **가장 늦은/이른** 발송일 기준으로 정렬된다
|
||||
* 2. 배송 행이 여러 건이어도 총 건수가 부풀지 않는다 (1:N 조인 금지)
|
||||
* 3. 발송 이력이 없는 주문도 목록에 남는다 (INNER JOIN 금지)
|
||||
*
|
||||
* 부하 설계: 픽스처를 **한 벌만** 만들고 한 메서드에서 세 불변식을 모두 단언한다. 사용자는
|
||||
* 1명을 재사용하고(팩토리 기본값은 주문마다 User 를 새로 만든다), 배송 행 6건은 INSERT 1회로
|
||||
* 심는다. 케이스마다 픽스처를 다시 만들면 같은 주문·배송을 반복해서 심게 된다.
|
||||
*/
|
||||
class OrderShippedAtSortTest extends ModuleTestCase
|
||||
{
|
||||
/**
|
||||
* 주문번호 → 배송 행의 발송일시(사이트 저장값) 목록.
|
||||
*
|
||||
* SORT-NONE 은 배송 이력이 없는 주문이다 — INNER JOIN 으로 좁혀지면 목록에서 사라진다.
|
||||
*/
|
||||
private const SHIPMENTS = [
|
||||
'SORT-A' => ['2026-07-05 10:00:00', '2026-07-20 10:00:00'],
|
||||
'SORT-B' => ['2026-07-10 10:00:00'],
|
||||
'SORT-C' => ['2026-07-01 10:00:00', '2026-07-15 10:00:00', '2026-07-08 10:00:00'],
|
||||
'SORT-NONE' => [],
|
||||
];
|
||||
|
||||
/**
|
||||
* 주문 4건과 배송 6건을 최소 쿼리로 심습니다.
|
||||
*
|
||||
* 주문은 팩토리를 쓰되 사용자를 1명으로 고정하고(기본값은 주문마다 User 생성),
|
||||
* 배송 행은 모델 이벤트가 필요 없으므로 쿼리 빌더로 한 번에 넣는다.
|
||||
*/
|
||||
private function seedOrders(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$shippingRows = [];
|
||||
|
||||
foreach (self::SHIPMENTS as $orderNumber => $shippedAts) {
|
||||
$order = Order::factory()->create([
|
||||
'user_id' => $user->id,
|
||||
'order_number' => $orderNumber,
|
||||
'ordered_at' => '2026-07-01 00:00:00',
|
||||
]);
|
||||
|
||||
if ($shippedAts === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 배송 행은 주문 옵션을 FK 로 요구한다. 옵션 자체는 정렬 판정과 무관하므로
|
||||
// 주문당 1건만 만들고 그 주문의 배송 행이 공유한다.
|
||||
$option = OrderOption::factory()->create(['order_id' => $order->id]);
|
||||
|
||||
foreach ($shippedAts as $index => $shippedAt) {
|
||||
$shippingRows[] = [
|
||||
'order_id' => $order->id,
|
||||
'order_option_id' => $option->id,
|
||||
'shipping_type' => 'delivery',
|
||||
'shipping_status' => 'shipped',
|
||||
'tracking_number' => $orderNumber.'-'.$index,
|
||||
'shipped_at' => $shippedAt,
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
DB::table((new OrderShipping)->getTable())->insert($shippingRows);
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 조회 결과의 주문번호 순서를 반환합니다.
|
||||
*
|
||||
* @param string $direction 정렬 방향 (asc|desc)
|
||||
* @return array{numbers: array<int, string>, total: int} 주문번호 순서와 총 건수
|
||||
*/
|
||||
private function listSortedByShippedAt(string $direction): array
|
||||
{
|
||||
$paginator = app(OrderRepositoryInterface::class)
|
||||
->getListWithFilters(['sort_by' => 'shipped_at', 'sort_order' => $direction], 20);
|
||||
|
||||
return [
|
||||
'numbers' => array_map(fn ($row) => $row->order_number, $paginator->items()),
|
||||
'total' => $paginator->total(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 발송 이력이 있는 주문만 남긴 순서를 반환합니다.
|
||||
*
|
||||
* 발송 이력이 없는 주문의 `NULL` 정렬 위치는 DB 마다 다르므로(선행/후행) 순서 판정에서
|
||||
* 제외한다 — 존재 여부는 별도로 단언한다 (데이터베이스 독립성 원칙).
|
||||
*
|
||||
* @param array<int, string> $numbers 주문번호 순서
|
||||
* @return array<int, string> 발송 이력이 있는 주문번호 순서
|
||||
*/
|
||||
private function withShipmentsOnly(array $numbers): array
|
||||
{
|
||||
return array_values(array_filter($numbers, fn ($n) => self::SHIPMENTS[$n] !== []));
|
||||
}
|
||||
|
||||
/**
|
||||
* 관계 테이블 컬럼(발송일) 정렬의 세 불변식을 함께 검증한다.
|
||||
*/
|
||||
public function test_발송일_정렬은_집계기준_정확하고_총건수와_미발송주문을_보존한다(): void
|
||||
{
|
||||
$this->seedOrders();
|
||||
|
||||
$desc = $this->listSortedByShippedAt('desc');
|
||||
$asc = $this->listSortedByShippedAt('asc');
|
||||
|
||||
// (1) 최근 발송순 — 주문별 가장 늦은 발송일 A(07-20) > C(07-15) > B(07-10)
|
||||
$this->assertSame(
|
||||
['SORT-A', 'SORT-C', 'SORT-B'],
|
||||
$this->withShipmentsOnly($desc['numbers']),
|
||||
'주문별 최신 발송일 기준 내림차순이어야 합니다.'
|
||||
);
|
||||
|
||||
// (1) 오래된 발송순 — 주문별 가장 이른 발송일 C(07-01) < A(07-05) < B(07-10)
|
||||
$this->assertSame(
|
||||
['SORT-C', 'SORT-A', 'SORT-B'],
|
||||
$this->withShipmentsOnly($asc['numbers']),
|
||||
'주문별 최초 발송일 기준 오름차순이어야 합니다.'
|
||||
);
|
||||
|
||||
// (2) 배송 행이 6건이어도 주문은 4건 — 총 건수가 늘면 1:N 조인으로 원 행이 부푼 것
|
||||
$this->assertSame(4, $desc['total'], '배송 행 수만큼 총 건수가 부풀면 안 됩니다.');
|
||||
$this->assertCount(4, $desc['numbers'], '페이지에 실린 행 수도 주문 수와 같아야 합니다.');
|
||||
|
||||
// (3) 발송 이력이 없는 주문이 빠지면 INNER JOIN 으로 좁혀진 것
|
||||
$this->assertContains('SORT-NONE', $desc['numbers'], '미발송 주문이 내림차순 목록에서 사라졌습니다.');
|
||||
$this->assertContains('SORT-NONE', $asc['numbers'], '미발송 주문이 오름차순 목록에서 사라졌습니다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 화면이 제공하는 발송일 정렬 옵션이 게이트에서 422 가 되지 않아야 한다.
|
||||
*/
|
||||
public function test_발송일_정렬_요청이_422가_아니다(): void
|
||||
{
|
||||
$admin = $this->createAdminUser(['sirsoft-ecommerce.orders.read']);
|
||||
|
||||
$this->actingAs($admin, 'sanctum')
|
||||
->getJson('/api/modules/sirsoft-ecommerce/admin/orders?sort_by=shipped_at&sort_order=desc&per_page=20')
|
||||
->assertOk();
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Http\Controllers;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductWishlist;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 목록 조회 페이지네이션 게이트 회귀 테스트 (#492 6차)
|
||||
*
|
||||
* 상한만 있고 하한이 없던 목록 엔드포인트에서 per_page=0 / 음수 / 비숫자가
|
||||
* 500 이 되거나 모델 기본값으로 조용히 바뀌었고, 과대값은 테이블 전량을 반환했다.
|
||||
* 게이트를 되돌리면 이 테스트가 실패한다.
|
||||
*/
|
||||
class ListPaginationGuardTest extends ModuleTestCase
|
||||
{
|
||||
/**
|
||||
* 찜 목록: per_page 경계값이 전부 422 로 거부되는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_wishlist_rejects_out_of_range_per_page(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
|
||||
foreach (['0', '-5', 'abc', '99999'] as $value) {
|
||||
$this->actingAs($user)
|
||||
->getJson('/api/modules/sirsoft-ecommerce/wishlist?per_page='.$value)
|
||||
->assertStatus(422);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 찜 목록: 허용 범위 per_page 는 그대로 적용되는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_wishlist_accepts_in_range_per_page(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
$products = Product::factory()->count(3)->create();
|
||||
|
||||
foreach ($products as $product) {
|
||||
ProductWishlist::create([
|
||||
'user_id' => $user->id,
|
||||
'product_id' => $product->id,
|
||||
]);
|
||||
}
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->getJson('/api/modules/sirsoft-ecommerce/wishlist?per_page=2')
|
||||
->assertOk();
|
||||
|
||||
$this->assertSame(2, $response->json('data.pagination.per_page'));
|
||||
$this->assertSame(3, $response->json('data.pagination.total'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 문의 목록(공개): per_page 경계값이 전부 422 로 거부되는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_product_inquiry_list_rejects_out_of_range_per_page(): void
|
||||
{
|
||||
$product = Product::factory()->create();
|
||||
|
||||
foreach (['0', '-5', 'abc', '99999'] as $value) {
|
||||
$this->getJson(
|
||||
'/api/modules/sirsoft-ecommerce/products/'.$product->product_code.'/inquiries?per_page='.$value
|
||||
)->assertStatus(422);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 마이페이지 내 문의 목록: per_page 경계값이 전부 422 로 거부되는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_user_inquiry_list_rejects_out_of_range_per_page(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
|
||||
foreach (['0', '-5', 'abc', '99999'] as $value) {
|
||||
$this->actingAs($user)
|
||||
->getJson('/api/modules/sirsoft-ecommerce/user/inquiries?per_page='.$value)
|
||||
->assertStatus(422);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 문의 목록(공개): 쿼리 스트링의 불리언 표기 4종을 모두 받아들이는지 검증합니다.
|
||||
*
|
||||
* 쿼리는 언제나 문자열로 도착하므로 `boolean` 규칙만 두면 화면이 보내는
|
||||
* `exclude_secret=false` 에서 목록 전체가 422 가 되고 문의 탭이 비어 보인다 (#492 7차 D-38).
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_product_inquiry_list_accepts_boolean_query_spellings(): void
|
||||
{
|
||||
$product = Product::factory()->create();
|
||||
|
||||
foreach (['true', 'false', '1', '0'] as $value) {
|
||||
$this->getJson(
|
||||
'/api/modules/sirsoft-ecommerce/products/'.$product->product_code
|
||||
.'/inquiries?per_page=10&exclude_secret='.$value
|
||||
)->assertOk();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 문의 목록(공개): 불리언으로 해석할 수 없는 값은 여전히 거부되는지 검증합니다.
|
||||
*
|
||||
* 정규화가 게이트를 통째로 무력화하지 않아야 한다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_product_inquiry_list_rejects_non_boolean_exclude_secret(): void
|
||||
{
|
||||
$product = Product::factory()->create();
|
||||
|
||||
$this->getJson(
|
||||
'/api/modules/sirsoft-ecommerce/products/'.$product->product_code
|
||||
.'/inquiries?exclude_secret=maybe'
|
||||
)->assertStatus(422);
|
||||
}
|
||||
|
||||
/**
|
||||
* 마이페이지 내 문의 목록: 쿼리 스트링의 불리언 표기 4종을 모두 받아들이는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_user_inquiry_list_accepts_boolean_query_spellings(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
|
||||
foreach (['true', 'false', '1', '0'] as $value) {
|
||||
$this->actingAs($user)
|
||||
->getJson('/api/modules/sirsoft-ecommerce/user/inquiries?is_answered='.$value)
|
||||
->assertOk();
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -70,6 +70,35 @@ class UserAddressUpdatePresenceValidationTest extends ModuleTestCase
|
||||
->assertJsonValidationErrors(['zipcode']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 우편번호만 유효한 값으로 바꾸는 수정은 통과합니다.
|
||||
*
|
||||
* 비우기(`''`)는 위 test_update_blanking_zipcode_only_fails 가 막지만, 그 반대 방향인
|
||||
* "우편번호만 새 값으로 교체" 는 별개 경로다. 결과 상태 판정이 페이로드에 없는 필드를
|
||||
* 기존 레코드로 메우지 못하면 이 정상 수정도 422 가 되어 부분 수정이 깨진다.
|
||||
*/
|
||||
public function test_update_zipcode_only_passes(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$address = UserAddress::factory()->create([
|
||||
'user_id' => $user->id,
|
||||
'zipcode' => '06236',
|
||||
'address' => '서울시 강남구 테헤란로 100',
|
||||
]);
|
||||
|
||||
$response = $this->actingAs($user)
|
||||
->putJson("{$this->baseUrl}/{$address->id}", ['zipcode' => '13529']);
|
||||
|
||||
$response->assertStatus(200);
|
||||
|
||||
$this->assertSame('13529', $address->fresh()->zipcode, '변경한 우편번호가 저장되어야 한다');
|
||||
$this->assertSame(
|
||||
'서울시 강남구 테헤란로 100',
|
||||
$address->fresh()->address,
|
||||
'전송하지 않은 주소는 기존 값이 보존되어야 한다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 도로명 주소만 바꾸는 수정은 기존 우편번호를 근거로 통과합니다.
|
||||
*/
|
||||
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Seeders;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Listeners\ActivityLogDescriptionResolver;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* 활동 로그 description 치환자 정합성 테스트.
|
||||
*
|
||||
* 템플릿의 `:option_id` 같은 치환자는 (기록 지점이 넘긴 description_params) +
|
||||
* (필터 훅 `core.activity_log.filter_description_params` 이 보강한 값) 으로 전부 채워져야 한다.
|
||||
* 하나라도 비면 화면에 치환자 원문이 그대로 찍힌다 — 오류 없이 조용히 잘못 보인다.
|
||||
*
|
||||
* 대상은 하드코딩하지 않고 시더 소스에서 (키, 파라미터명) 쌍을 **도출**한다.
|
||||
* 시더에 새 로그 유형이 추가되면 이 테스트가 자동으로 그것까지 검사한다.
|
||||
*/
|
||||
class ActivityLogDescriptionParamsTest extends ModuleTestCase
|
||||
{
|
||||
/**
|
||||
* 시더 소스에서 (lang 키, description_params 키 목록) 쌍을 도출합니다.
|
||||
*
|
||||
* @return array<int, array{key: string, params: array<int, string>, line: int}>
|
||||
*/
|
||||
private function declaredLogShapes(): array
|
||||
{
|
||||
$file = dirname(__DIR__, 3).'/database/seeders/ActivityLogSampleSeeder.php';
|
||||
|
||||
$this->assertFileExists($file, '이커머스 활동 로그 샘플 시더가 있어야 합니다.');
|
||||
|
||||
$source = file_get_contents($file);
|
||||
$shapes = [];
|
||||
|
||||
// ['action' => '...', 'key' => 'xxx', ... 'params' => fn (...) => ['a' => ..., 'b' => ...]
|
||||
preg_match_all("/'key'\s*=>\s*'([a-z0-9_]+)'/i", $source, $keys, PREG_OFFSET_CAPTURE);
|
||||
|
||||
foreach ($keys[1] as $match) {
|
||||
[$key, $offset] = $match;
|
||||
|
||||
$paramsPos = strpos($source, "'params'", $offset);
|
||||
|
||||
if ($paramsPos === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 다음 'key' 선언보다 뒤에 있으면 이 항목의 params 가 아니다 (params 미선언 항목)
|
||||
$nextKey = strpos($source, "'key'", $offset + 1);
|
||||
|
||||
if ($nextKey !== false && $paramsPos > $nextKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$open = strpos($source, '[', $paramsPos);
|
||||
|
||||
if ($open === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$depth = 0;
|
||||
$end = null;
|
||||
|
||||
for ($p = $open; $p < strlen($source); $p++) {
|
||||
if ($source[$p] === '[') {
|
||||
$depth++;
|
||||
} elseif ($source[$p] === ']') {
|
||||
$depth--;
|
||||
|
||||
if ($depth === 0) {
|
||||
$end = $p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($end === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
preg_match_all("/'([a-z0-9_]+)'\s*=>/i", substr($source, $open, $end - $open), $names);
|
||||
|
||||
$shapes[] = [
|
||||
'key' => $key,
|
||||
'params' => $names[1],
|
||||
'line' => substr_count(substr($source, 0, $offset), "\n") + 1,
|
||||
];
|
||||
}
|
||||
|
||||
return $shapes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 시더가 만드는 모든 로그의 설명이 치환자를 남기지 않는지 검증합니다.
|
||||
*
|
||||
* 렌더 경로는 모델 접근자와 동일하게 필터 훅을 태운다 — 훅이 ID → 이름으로
|
||||
* 보강해 주는 키(coupon_id → coupon_name 등)를 결함으로 오판하지 않기 위해서다.
|
||||
*/
|
||||
#[Test]
|
||||
public function seeded_activity_log_descriptions_leave_no_placeholder(): void
|
||||
{
|
||||
$shapes = $this->declaredLogShapes();
|
||||
|
||||
$this->assertNotEmpty($shapes, '시더에서 로그 형태를 도출하지 못했습니다(파서 회귀).');
|
||||
|
||||
$unresolved = [];
|
||||
|
||||
foreach ($shapes as $shape) {
|
||||
$langKey = 'sirsoft-ecommerce::activity_log.description.'.$shape['key'];
|
||||
$template = __($langKey);
|
||||
|
||||
// 시더 배열의 'key' 가 description 키가 아닌 경우(다른 용도)는 건너뛴다
|
||||
if ($template === $langKey) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (preg_match('/:[a-zA-Z_]/', $template) !== 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$params = array_fill_keys($shape['params'], '1');
|
||||
|
||||
// 훅 체인 전체(applyFilters)를 태우면 다른 모듈의 리스너까지 해석되어
|
||||
// 이 모듈 테스트 컨텍스트에서 바인딩이 없는 의존성으로 터진다.
|
||||
// 검증 대상은 "이커머스 시더 + 이커머스 리졸버" 조합이므로 그 리스너만 직접 호출한다.
|
||||
$params = app(ActivityLogDescriptionResolver::class)
|
||||
->resolveDescriptionParams($params, $langKey, []);
|
||||
|
||||
$rendered = __($langKey, $params);
|
||||
|
||||
if (preg_match('/:([a-zA-Z_][a-zA-Z0-9_]*)/', $rendered, $m) === 1) {
|
||||
$unresolved[] = sprintf(
|
||||
'%s (시더 %d행) → "%s" — 치환자 :%s 미충족 (전달: %s)',
|
||||
$shape['key'],
|
||||
$shape['line'],
|
||||
$rendered,
|
||||
$m[1],
|
||||
implode(', ', $shape['params']) ?: '없음'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertSame(
|
||||
[],
|
||||
$unresolved,
|
||||
"샘플 활동 로그 설명에 치환자가 그대로 남습니다:\n ".implode("\n ", $unresolved)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,15 @@ use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Seeders\Sample\EcommerceUserProfileSeeder;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Seeders\Sample\OrderSeeder;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponDiscountType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueCondition;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueMethod;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponTargetType;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\DeliveryMemoPresetEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Cart;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Coupon;
|
||||
use Modules\Sirsoft\Ecommerce\Models\CouponIssue;
|
||||
use Modules\Sirsoft\Ecommerce\Models\EcommerceUserProfile;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderAddress;
|
||||
@@ -271,6 +278,53 @@ class SeederConsistencyTest extends ModuleTestCase
|
||||
$this->assertEquals((int) $fresh->unit_price, (int) $mc[$base], 'base 통화 금액은 unit_price 와 동일해야 합니다(오환산 없음).');
|
||||
}
|
||||
|
||||
/**
|
||||
* OrderSeeder 의 쿠폰 보충 발급이 쿠폰의 발급수(issued_count)까지 함께 올리는지 검증합니다.
|
||||
*
|
||||
* 보충 발급은 발급 이력 행을 직접 만들기 때문에, 카운터를 올리지 않으면
|
||||
* 쿠폰 목록의 "발급수" 컬럼과 발급 이력 모달의 "총 N건" 이 영구히 어긋난다.
|
||||
*/
|
||||
public function test_replenished_coupon_issue_increments_issued_count(): void
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
$other = User::factory()->create();
|
||||
|
||||
$coupon = Coupon::create([
|
||||
'name' => ['ko' => '보충 발급 검증 쿠폰', 'en' => 'Replenish Test Coupon'],
|
||||
'target_type' => CouponTargetType::ORDER_AMOUNT,
|
||||
'discount_type' => CouponDiscountType::FIXED,
|
||||
'discount_value' => 1000,
|
||||
'issue_method' => CouponIssueMethod::DIRECT,
|
||||
'issue_condition' => CouponIssueCondition::MANUAL,
|
||||
'issued_count' => 0,
|
||||
]);
|
||||
|
||||
$seeder = new OrderSeeder;
|
||||
$seeder->setCommand($this->mockSeederCommand());
|
||||
|
||||
// 주문 생성 중 소진된 쿠폰 내역을 주입 (동일 조합 중복은 1건으로 접힌다)
|
||||
$records = new \ReflectionProperty(OrderSeeder::class, 'usedCouponRecords');
|
||||
$records->setAccessible(true);
|
||||
$records->setValue($seeder, [
|
||||
['user_id' => $user->id, 'coupon_id' => $coupon->id],
|
||||
['user_id' => $user->id, 'coupon_id' => $coupon->id],
|
||||
['user_id' => $other->id, 'coupon_id' => $coupon->id],
|
||||
]);
|
||||
|
||||
$replenish = new \ReflectionMethod(OrderSeeder::class, 'replenishAvailableCoupons');
|
||||
$replenish->setAccessible(true);
|
||||
$replenish->invoke($seeder);
|
||||
|
||||
$issueCount = CouponIssue::where('coupon_id', $coupon->id)->count();
|
||||
|
||||
$this->assertSame(2, $issueCount, '중복 제거 후 회원 2명분 보충 발급이 생성되어야 합니다.');
|
||||
$this->assertSame(
|
||||
$issueCount,
|
||||
(int) $coupon->fresh()->issued_count,
|
||||
'보충 발급 건수만큼 쿠폰 발급수(issued_count)가 올라가야 합니다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 시더 콘솔 출력을 흡수하는 mock command 를 반환합니다.
|
||||
*/
|
||||
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Services;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\DTO\MileageAdminDeductDto;
|
||||
use Modules\Sirsoft\Ecommerce\DTO\MileageAdminEarnDto;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\CouponIssueRecordStatus;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\CouponIssueResource;
|
||||
use Modules\Sirsoft\Ecommerce\Models\CouponIssue;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductWishlist;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductWishlistRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Services\UserMileageService;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 목록 표시 정합성 회귀 테스트 (#492 6차)
|
||||
*
|
||||
* 브라우저 실측에서 "행은 나오는데 칸이 비거나 상태가 틀린" 세 지점을 고정한다.
|
||||
* - 찜 목록에 소프트 삭제된 상품 행이 남아 카드 렌더가 실패했다
|
||||
* - 유효기간이 지난 쿠폰이 "사용가능" 라벨로 표시됐다
|
||||
* - 마일리지 사용·차감 거래의 내용(description)이 비어 있었다
|
||||
*/
|
||||
class ListDisplayIntegrityTest extends ModuleTestCase
|
||||
{
|
||||
/**
|
||||
* 소프트 삭제된 상품의 찜 행이 목록에서 빠지는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_wishlist_excludes_soft_deleted_products(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
$products = Product::factory()->count(3)->create();
|
||||
|
||||
foreach ($products as $product) {
|
||||
ProductWishlist::create([
|
||||
'user_id' => $user->id,
|
||||
'product_id' => $product->id,
|
||||
]);
|
||||
}
|
||||
|
||||
$repository = app(ProductWishlistRepositoryInterface::class);
|
||||
|
||||
$this->assertSame(3, $repository->getByUser($user->id, 20)->total());
|
||||
|
||||
$products->first()->delete();
|
||||
|
||||
$paginator = $repository->getByUser($user->id, 20);
|
||||
|
||||
$this->assertSame(2, $paginator->total(), '소프트 삭제된 상품의 찜 행이 목록에 남아 있습니다.');
|
||||
foreach ($paginator->items() as $item) {
|
||||
$this->assertNotNull($item->product, '상품이 없는 찜 행이 목록에 포함됐습니다.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효기간이 지난 쿠폰이 만료 라벨로 표시되는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_expired_coupon_issue_is_labelled_as_expired(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
|
||||
$issue = new CouponIssue([
|
||||
'user_id' => $user->id,
|
||||
'status' => CouponIssueRecordStatus::AVAILABLE,
|
||||
'expired_at' => now()->subDay(),
|
||||
]);
|
||||
|
||||
$payload = (new CouponIssueResource($issue))->toArray(request());
|
||||
|
||||
$this->assertTrue($payload['is_expired']);
|
||||
$this->assertSame('available', $payload['status'], '저장된 원시 상태는 그대로 노출되어야 합니다.');
|
||||
$this->assertSame(
|
||||
CouponIssueRecordStatus::EXPIRED->label(),
|
||||
$payload['status_label'],
|
||||
'유효기간이 지난 쿠폰이 사용가능으로 표시됩니다.'
|
||||
);
|
||||
$this->assertSame(CouponIssueRecordStatus::EXPIRED->badgeColor(), $payload['status_badge_color']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효기간이 남은 쿠폰은 원래 라벨을 유지하는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_active_coupon_issue_keeps_available_label(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
|
||||
$issue = new CouponIssue([
|
||||
'user_id' => $user->id,
|
||||
'status' => CouponIssueRecordStatus::AVAILABLE,
|
||||
'expired_at' => now()->addDay(),
|
||||
]);
|
||||
|
||||
$payload = (new CouponIssueResource($issue))->toArray(request());
|
||||
|
||||
$this->assertFalse($payload['is_expired']);
|
||||
$this->assertSame(CouponIssueRecordStatus::AVAILABLE->label(), $payload['status_label']);
|
||||
}
|
||||
|
||||
/**
|
||||
* 관리자 차감 거래에 내용(description)이 기록되는지 검증합니다.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function test_admin_deduct_records_description(): void
|
||||
{
|
||||
$user = $this->createUser();
|
||||
$service = app(UserMileageService::class);
|
||||
|
||||
$service->adminEarn($user->id, new MileageAdminEarnDto(
|
||||
amount: 5000,
|
||||
currency: 'KRW',
|
||||
grantedBy: $user->id,
|
||||
));
|
||||
|
||||
$deduct = $service->adminDeduct($user->id, new MileageAdminDeductDto(
|
||||
amount: 1200,
|
||||
currency: 'KRW',
|
||||
grantedBy: $user->id,
|
||||
));
|
||||
|
||||
$this->assertNotEmpty(
|
||||
$deduct->description,
|
||||
'차감 거래의 내용이 비어 있어 회원 마일리지 내역의 「내용」 칸이 공백이 됩니다.'
|
||||
);
|
||||
$this->assertSame(
|
||||
__('sirsoft-ecommerce::activity_log.description.mileage_admin_deduct', ['amount' => 1200]),
|
||||
$deduct->description
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Benchmark;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Module;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use Tests\Support\Concerns\AssertsListIndexCoverage;
|
||||
|
||||
/**
|
||||
* 이커머스 모듈 목록 프로파일의 색인 커버리지 검사
|
||||
*
|
||||
* 모듈 테이블은 이 스위트에서만 마이그레이션되므로, 코어 스위트에 몰면 테이블이 없어
|
||||
* 건너뛰고 초록인 채 미검사가 된다. 모듈 프로파일은 반드시 자기 스위트에서 검사한다.
|
||||
*
|
||||
* @scenario case=list_index_coverage
|
||||
*
|
||||
* @effects list_profiles_declare_matching_index
|
||||
*/
|
||||
class ListIndexCoverageTest extends ModuleTestCase
|
||||
{
|
||||
use AssertsListIndexCoverage;
|
||||
|
||||
public function test_module_list_profiles_have_matching_indexes(): void
|
||||
{
|
||||
$this->assertListIndexCoverageForExtension(new Module);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Layouts;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use Tests\Support\Concerns\AssertsLayoutSortOptionGateParity;
|
||||
|
||||
/**
|
||||
* 화면 정렬 옵션 ↔ 게이트 허용 집합 회귀 가드 — 이커머스 모듈 (#492 D-19).
|
||||
*
|
||||
* 실제로 이 모듈의 두 화면이 이 형태로 깨져 있었다.
|
||||
*
|
||||
* - 쿠폰 목록 "유효기간 임박순/여유순" (`valid_to`)
|
||||
* - 주문 목록 "최근 발송순/오래된 발송순" (`shipped_at`)
|
||||
*
|
||||
* 옵션을 고르면 422 가 나고 목록은 직전 결과 그대로 남아, 정렬이 적용된 것처럼 보였다.
|
||||
*
|
||||
* 코어 스위트가 아니라 **모듈 스위트**에 두는 이유: 모듈 라우트는 모듈이 활성일 때만 등록된다.
|
||||
* 코어 스위트에서는 `/api/modules/sirsoft-ecommerce/...` 엔드포인트가 라우트에 닿지 않아
|
||||
* 검사가 성립하지 않는다(그 상태로 두면 초록인 채 아무것도 보지 않는다).
|
||||
*/
|
||||
class LayoutSortOptionGateParityTest extends ModuleTestCase
|
||||
{
|
||||
use AssertsLayoutSortOptionGateParity;
|
||||
|
||||
/**
|
||||
* 이커머스 레이아웃의 정렬 옵션은 게이트 허용 집합의 부분집합이어야 한다.
|
||||
*/
|
||||
public function test_이커머스_화면_정렬옵션은_게이트_허용집합의_부분집합이다(): void
|
||||
{
|
||||
$this->assertLayoutSortOptionsWithinGate([
|
||||
dirname(__DIR__, 3).'/resources/layouts',
|
||||
]);
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Repositories;
|
||||
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Group;
|
||||
|
||||
/**
|
||||
* 수치 범위 필터의 0 경계 회귀 가드 (#492 브라우저 실측).
|
||||
*
|
||||
* `! empty($filters['max_shipping_amount'])` 처럼 판정하면 0 이 "미입력"으로 취급돼
|
||||
* 필터가 통째로 무시된다. 실측에서 "배송비 0원(무료배송) 주문만 보기" 가 전체 100건을
|
||||
* 돌려줬고, 1 을 넣어야 47건이 나왔다.
|
||||
*
|
||||
* 소스 판정식을 직접 검사한다 — 데이터에 의존하지 않아 어떤 시드에서도 성립하고,
|
||||
* 새 범위 필터가 추가돼도 같은 규칙을 강제한다.
|
||||
*/
|
||||
#[Group('ecommerce')]
|
||||
class NumericRangeFilterZeroBoundaryTest extends ModuleTestCase
|
||||
{
|
||||
/**
|
||||
* 0 이 유효 경계값인 수치 범위 필터 키 목록.
|
||||
*
|
||||
* @return array<string, array{0: string, 1: array<int, string>}>
|
||||
*/
|
||||
public static function rangeFilterProvider(): array
|
||||
{
|
||||
$base = dirname(__DIR__, 3).'/src/Repositories/';
|
||||
|
||||
return [
|
||||
'주문 금액·배송비 범위' => [
|
||||
$base.'OrderRepository.php',
|
||||
['min_amount', 'max_amount', 'min_shipping_amount', 'max_shipping_amount'],
|
||||
],
|
||||
'상품 가격·재고 범위' => [
|
||||
$base.'ProductRepository.php',
|
||||
['min_price', 'max_price', 'min_stock', 'max_stock'],
|
||||
],
|
||||
'쿠폰 혜택·주문금액 범위' => [
|
||||
$base.'CouponRepository.php',
|
||||
['min_benefit_amount', 'max_benefit_amount', 'min_order_amount'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string> $keys 검사할 필터 키 목록
|
||||
*/
|
||||
#[DataProvider('rangeFilterProvider')]
|
||||
public function test_수치_범위_필터는_empty_판정으로_0을_버리지_않는다(string $file, array $keys): void
|
||||
{
|
||||
$this->assertFileExists($file);
|
||||
$source = file_get_contents($file);
|
||||
|
||||
foreach ($keys as $key) {
|
||||
$pattern = "/!\s*empty\(\s*\\\$filters\[\s*'".preg_quote($key, '/')."'\s*\]\s*\)/";
|
||||
|
||||
$this->assertDoesNotMatchRegularExpression(
|
||||
$pattern,
|
||||
$source,
|
||||
sprintf(
|
||||
"%s 의 '%s' 필터가 empty() 로 판정되고 있습니다. 0 이 유효 경계값이므로 "
|
||||
."isset(\$filters['%s']) && \$filters['%s'] !== '' 형태를 사용해야 합니다.",
|
||||
basename($file), $key, $key, $key
|
||||
)
|
||||
);
|
||||
|
||||
// 필터 키가 실제로 사용되고는 있는지 (오탈자로 조용히 사라지는 것 방지)
|
||||
$this->assertStringContainsString(
|
||||
"'".$key."'",
|
||||
$source,
|
||||
sprintf('%s 에서 %s 필터 키를 찾지 못했습니다.', basename($file), $key)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Repositories;
|
||||
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\CouponListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ExtraFeeTemplateListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\OrderListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ProductListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\ShippingPolicyListRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\CouponRepository;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\ExtraFeeTemplateRepository;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\OrderRepository;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\ProductRepository;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\ShippingPolicyRepository;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\Attributes\Group;
|
||||
use ReflectionClass;
|
||||
|
||||
/**
|
||||
* 정렬 허용 컬럼의 포함관계 회귀 가드 (이커머스).
|
||||
*
|
||||
* 목록 정렬은 두 곳에서 제한된다 — 요청을 차단하는 FormRequest(게이트)와
|
||||
* ResolvesSortSpec 이 해석하는 Repository 의 닫힌 집합(저장소).
|
||||
*
|
||||
* 불변식은 **게이트 ⊆ 저장소** 다 (docs/backend/service-repository.md).
|
||||
* 저장소가 게이트보다 좁으면 검증을 통과한 정렬이 조용히 기본 정렬로 되돌아간다.
|
||||
* 저장소가 더 넓은 것은 의도된 여유다 — 게이트가 훅으로 확장에 열려 있기 때문이다.
|
||||
*/
|
||||
#[Group('ecommerce')]
|
||||
class SortWhitelistGateParityTest extends ModuleTestCase
|
||||
{
|
||||
/**
|
||||
* Repository 상수 ↔ FormRequest 규칙 쌍 목록.
|
||||
*
|
||||
* @return array<string, array{0: string, 1: string, 2: string}>
|
||||
*/
|
||||
public static function surfaceProvider(): array
|
||||
{
|
||||
return [
|
||||
'주문 목록' => [
|
||||
OrderRepository::class,
|
||||
OrderListRequest::class,
|
||||
'SORTABLE_COLUMNS',
|
||||
],
|
||||
'상품 목록' => [
|
||||
ProductRepository::class,
|
||||
ProductListRequest::class,
|
||||
'ADMIN_SORTABLE_COLUMNS',
|
||||
],
|
||||
'추가배송비 템플릿' => [
|
||||
ExtraFeeTemplateRepository::class,
|
||||
ExtraFeeTemplateListRequest::class,
|
||||
'SORTABLE_COLUMNS',
|
||||
],
|
||||
'배송정책 목록' => [
|
||||
ShippingPolicyRepository::class,
|
||||
ShippingPolicyListRequest::class,
|
||||
'SORTABLE_COLUMNS',
|
||||
],
|
||||
'쿠폰 목록' => [
|
||||
CouponRepository::class,
|
||||
CouponListRequest::class,
|
||||
'SORTABLE_COLUMNS',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
#[DataProvider('surfaceProvider')]
|
||||
public function test_게이트가_허용한_정렬은_저장소도_허용한다(
|
||||
string $repositoryClass,
|
||||
string $requestClass,
|
||||
string $constantName
|
||||
): void {
|
||||
$reflection = new ReflectionClass($repositoryClass);
|
||||
|
||||
$repoColumns = $reflection->getConstant($constantName);
|
||||
$this->assertIsArray($repoColumns, "{$repositoryClass}::{$constantName} 상수를 찾지 못했습니다.");
|
||||
|
||||
// 관계 테이블 컬럼 기준 정렬(SortsByRelatedColumn)도 저장소가 허용하는 정렬이다.
|
||||
// 맵의 **키**가 요청 sort_by 값이므로 원 테이블 컬럼 목록과 합쳐서 대조한다.
|
||||
$repoColumns = array_values($repoColumns);
|
||||
$related = $reflection->getConstant('RELATED_SORTABLE_COLUMNS');
|
||||
|
||||
if (is_array($related)) {
|
||||
$repoColumns = array_merge($repoColumns, array_keys($related));
|
||||
}
|
||||
|
||||
$gateColumns = $this->readGateSortColumns($requestClass);
|
||||
$this->assertNotEmpty($gateColumns, "{$requestClass} 에서 sort_by 허용 목록을 찾지 못했습니다.");
|
||||
|
||||
$missing = array_values(array_diff($gateColumns, $repoColumns));
|
||||
|
||||
$this->assertSame(
|
||||
[],
|
||||
$missing,
|
||||
sprintf(
|
||||
'게이트가 통과시키는 정렬 컬럼을 저장소가 허용하지 않습니다 — 그 정렬은 조용히 '
|
||||
."기본 정렬로 되돌아갑니다.\n 누락: %s\n 저장소: %s\n 게이트: %s",
|
||||
implode(',', $missing),
|
||||
implode(',', array_values($repoColumns)),
|
||||
implode(',', $gateColumns)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* FormRequest 소스에서 sort_by 허용 목록을 읽습니다.
|
||||
*
|
||||
* @return array<int, string> 정렬 허용 컬럼 목록
|
||||
*/
|
||||
private function readGateSortColumns(string $class): array
|
||||
{
|
||||
$source = file_get_contents((new ReflectionClass($class))->getFileName());
|
||||
|
||||
if (preg_match("/'sort_by'\s*=>\s*'[^']*\bin:([^'|]+)/", $source, $m)) {
|
||||
return $this->splitColumns($m[1]);
|
||||
}
|
||||
|
||||
if (preg_match("/'sort_by'\s*=>\s*\[[^\]]*'in:([^']+)'/", $source, $m)) {
|
||||
return $this->splitColumns($m[1]);
|
||||
}
|
||||
|
||||
if (preg_match("/'sort_by'\s*=>\s*\[.*?Rule::in\(\s*\[(.*?)\]/s", $source, $m)) {
|
||||
return $this->splitColumns(str_replace("'", '', $m[1]));
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 쉼표 구분 컬럼 문자열을 배열로 변환합니다.
|
||||
*
|
||||
* @return array<int, string> 정리된 컬럼 목록
|
||||
*/
|
||||
private function splitColumns(string $raw): array
|
||||
{
|
||||
return array_values(array_filter(array_map('trim', explode(',', $raw))));
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,11 @@ use App\Extension\AbstractUpgradeStep;
|
||||
* 쓰기 지점이 부분취소 재계산 1곳뿐이라 부분취소를 겪은 주문만 값이 정상화되고
|
||||
* 나머지는 영구 0 이었다. 0 인 주문만 채우고 이미 정상화된 값은 건드리지 않는다.
|
||||
*
|
||||
* 함께 목록 조회 성능용 인덱스를 기존 사이트에 반영한다 — 상품 리뷰 정렬 인덱스(02)와
|
||||
* 주문 목록 "발송일" 정렬용 복합 인덱스(04). 마이그레이션만 추가하면 신규 설치에만
|
||||
* 반영되므로 업그레이드 시점에 동일 인덱스를 적용한다. 데이터가 많은 쇼핑몰에서는
|
||||
* ALTER TABLE 이 수 분 걸리며 그동안 해당 테이블 쓰기가 대기한다.
|
||||
*
|
||||
* 모든 비즈니스 로직은 data/1.0.5/migrations/ 로 격리(AbstractUpgradeStep 규약).
|
||||
*
|
||||
* @upgrade-path A
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
<?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\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* 마일리지 사용·차감 거래의 비어 있는 내용(description)을 채웁니다.
|
||||
*
|
||||
* 적립 거래는 생성 시 description 을 기록했지만 사용·차감 거래는 기록하지 않아,
|
||||
* 회원 마일리지 내역의 「내용」 칸이 음수 행에서만 공백이었습니다. 생성 경로는
|
||||
* 수정했으나 이미 쌓인 행은 그대로 비어 있으므로 여기서 채웁니다.
|
||||
*
|
||||
* 금액은 저장된 음수 amount 의 절대값을 쓰고, 문구는 활동 로그와 같은 다국어 키를 씁니다.
|
||||
*
|
||||
* idempotent: description 이 NULL 이거나 빈 문자열인 행만 갱신하므로 재실행해도 안전합니다.
|
||||
* V-1 안전: Facades\DB/Schema 만 사용하며 모델·서비스에 의존하지 않습니다.
|
||||
*/
|
||||
class BackfillMileageConsumptionDescriptions implements DataMigration
|
||||
{
|
||||
private const TABLE = 'ecommerce_mileage_transactions';
|
||||
|
||||
/** @var array<string, string> 거래 유형 → 다국어 키 */
|
||||
private const DESCRIPTION_KEYS = [
|
||||
'admin_deduct' => 'sirsoft-ecommerce::activity_log.description.mileage_admin_deduct',
|
||||
'order_use' => 'sirsoft-ecommerce::activity_log.description.mileage_use',
|
||||
];
|
||||
|
||||
/**
|
||||
* 마이그레이션 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 마이그레이션 이름
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return 'BackfillMileageConsumptionDescriptions';
|
||||
}
|
||||
|
||||
/**
|
||||
* 비어 있는 사용·차감 거래 내용을 채웁니다.
|
||||
*
|
||||
* @param UpgradeContext $context 업그레이드 컨텍스트
|
||||
* @return void
|
||||
*/
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
if (! Schema::hasTable(self::TABLE)) {
|
||||
$context->logger->info('[ecommerce:1.0.5] 마일리지 거래 테이블 부재 — 내용 백필 스킵');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$updated = 0;
|
||||
|
||||
foreach (self::DESCRIPTION_KEYS as $type => $key) {
|
||||
DB::table(self::TABLE)
|
||||
->where('type', $type)
|
||||
->where(function ($query) {
|
||||
$query->whereNull('description')->orWhere('description', '');
|
||||
})
|
||||
->orderBy('id')
|
||||
->chunkById(500, function ($rows) use ($key, &$updated) {
|
||||
foreach ($rows as $row) {
|
||||
DB::table(self::TABLE)
|
||||
->where('id', $row->id)
|
||||
->update([
|
||||
'description' => __($key, ['amount' => abs((float) $row->amount)]),
|
||||
]);
|
||||
$updated++;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$context->logger->info("[ecommerce:1.0.5] 마일리지 사용·차감 내용 백필 완료: {$updated}건");
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* 주문 목록 "발송일" 정렬용 복합 인덱스를 추가합니다.
|
||||
*
|
||||
* 주문 목록은 배송 테이블의 `shipped_at` 을 상관 서브쿼리로 읽어 정렬합니다. 주문 1건마다
|
||||
* 서브쿼리가 한 번씩 실행되므로 `(order_id, shipped_at)` 복합 인덱스가 없으면 주문 수만큼
|
||||
* 배송 테이블을 스캔합니다. 기존 단일 인덱스 `order_id` 만으로는 정렬 컬럼이 인덱스에 없어
|
||||
* 매번 행을 읽고 정렬해야 합니다.
|
||||
*
|
||||
* 신규 설치는 마이그레이션이 처리하지만 기존 사이트에는 반영되지 않으므로 업그레이드 시점에
|
||||
* 동일 인덱스를 추가합니다.
|
||||
*
|
||||
* 주문이 많은 쇼핑몰에서는 ALTER TABLE 이 수 분 걸릴 수 있고 그동안 배송 정보 쓰기가
|
||||
* 대기합니다. 진행 상황을 로그로 남깁니다.
|
||||
*
|
||||
* idempotent: 이미 존재하는 인덱스는 건너뜁니다. V-1 안전: Facades\Schema 만 사용합니다.
|
||||
*/
|
||||
class AddOrderShippingSortIndex implements DataMigration
|
||||
{
|
||||
private const TABLE = 'ecommerce_order_shippings';
|
||||
|
||||
private const INDEX_NAME = 'ecommerce_order_shippings_order_id_shipped_at_index';
|
||||
|
||||
/** @var array<int, string> */
|
||||
private const INDEX_COLUMNS = ['order_id', 'shipped_at'];
|
||||
|
||||
/**
|
||||
* 마이그레이션 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 마이그레이션 이름
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return 'AddOrderShippingSortIndex';
|
||||
}
|
||||
|
||||
/**
|
||||
* 발송일 정렬 인덱스를 추가합니다.
|
||||
*
|
||||
* @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');
|
||||
|
||||
if (in_array(self::INDEX_NAME, $existing, true)) {
|
||||
$context->logger->info('[ecommerce:1.0.5] 이미 존재하는 인덱스 — 스킵: '.self::INDEX_NAME);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$context->logger->info('[ecommerce:1.0.5] 발송일 정렬 인덱스 추가 시작: '.self::INDEX_NAME.' (주문이 많으면 수 분 걸릴 수 있고 그동안 배송 정보 쓰기가 대기합니다)');
|
||||
|
||||
Schema::table(self::TABLE, function ($table) {
|
||||
$table->index(self::INDEX_COLUMNS, self::INDEX_NAME);
|
||||
});
|
||||
|
||||
$context->logger->info('[ecommerce:1.0.5] 발송일 정렬 인덱스 추가 완료: '.self::INDEX_NAME);
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
<?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;
|
||||
|
||||
/**
|
||||
* 이커머스 목록의 정렬 색인을 추가·교체합니다.
|
||||
*
|
||||
* 주문·상품·상품문의 목록은 정렬 순서를 덮는 색인이 없어 뒤쪽 페이지가 테이블 전체를 훑었고,
|
||||
* 상품후기·쿠폰 발급이력은 색인이 정렬 컬럼에서 끝나 같은 시각 구간에 추가 정렬 작업이
|
||||
* 남았습니다.
|
||||
*
|
||||
* 신규 설치는 마이그레이션이 처리하지만 기존 사이트에는 반영되지 않으므로 업그레이드
|
||||
* 시점에 같은 색인을 적용합니다.
|
||||
*
|
||||
* 데이터가 많은 쇼핑몰에서는 색인마다 수 분 걸릴 수 있고 그동안 해당 테이블 쓰기가
|
||||
* 대기합니다. 새 색인을 먼저 만들고 기존 색인을 나중에 지우므로, 중간에 중단되어도 조회가
|
||||
* 색인 없이 남는 구간은 없습니다.
|
||||
*
|
||||
* idempotent: 이미 적용된 대상은 건너뜁니다. V-1 안전: Facades\Schema 만 사용합니다.
|
||||
*/
|
||||
class AddListSortIndexes implements DataMigration
|
||||
{
|
||||
/**
|
||||
* 대상 [테이블 => [신규 색인명, 컬럼, 교체 대상 기존 색인명(없으면 null)]]
|
||||
*
|
||||
* @var array<string, array{0: string, 1: array<int, string>, 2: string|null}>
|
||||
*/
|
||||
private const TARGETS = [
|
||||
'ecommerce_orders' => ['idx_orders_deleted_ordered_id', ['deleted_at', 'ordered_at', 'id'], null],
|
||||
'ecommerce_products' => ['idx_products_deleted_created_id', ['deleted_at', 'created_at', 'id'], null],
|
||||
'ecommerce_product_inquiries' => ['idx_inquiries_created_id', ['created_at', 'id'], null],
|
||||
'ecommerce_product_reviews' => ['idx_reviews_deleted_created_id', ['deleted_at', 'created_at', 'id'], 'idx_reviews_deleted_created'],
|
||||
'ecommerce_promotion_coupon_issues' => ['idx_coupon_issues_issued_id', ['issued_at', 'id'], 'idx_issued_at'],
|
||||
];
|
||||
|
||||
/**
|
||||
* 마이그레이션 식별자를 반환합니다.
|
||||
*
|
||||
* @return string 마이그레이션 이름
|
||||
*/
|
||||
public function name(): string
|
||||
{
|
||||
return 'AddListSortIndexes';
|
||||
}
|
||||
|
||||
/**
|
||||
* 목록 정렬 색인을 적용합니다.
|
||||
*
|
||||
* @param UpgradeContext $context 업그레이드 컨텍스트
|
||||
*/
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
foreach (self::TARGETS as $table => [$newIndex, $columns, $oldIndex]) {
|
||||
if (! Schema::hasTable($table)) {
|
||||
$context->logger->info("[ecommerce:1.0.5] 테이블 부재 — 색인 적용 스킵: {$table}");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$existing = array_column(Schema::getIndexes($table), 'name');
|
||||
|
||||
if (in_array($newIndex, $existing, true)) {
|
||||
$context->logger->info("[ecommerce:1.0.5] 이미 적용된 색인 — 스킵: {$newIndex}");
|
||||
} else {
|
||||
$context->logger->info("[ecommerce:1.0.5] 목록 정렬 색인 적용 시작: {$table} (데이터가 많으면 수 분 걸릴 수 있고 그동안 해당 테이블 쓰기가 대기합니다)");
|
||||
|
||||
Schema::table($table, function ($blueprint) use ($columns, $newIndex) {
|
||||
$blueprint->index($columns, $newIndex);
|
||||
});
|
||||
|
||||
$context->logger->info("[ecommerce:1.0.5] 색인 적용 완료: {$newIndex}");
|
||||
}
|
||||
|
||||
// 기존 색인은 새 색인의 좌측 프리픽스라 남겨 두면 쓰기 비용만 늘어난다.
|
||||
// 반드시 새 색인 생성 이후에 지운다.
|
||||
if ($oldIndex !== null && in_array($oldIndex, $existing, true)) {
|
||||
Schema::table($table, function ($blueprint) use ($oldIndex) {
|
||||
$blueprint->dropIndex($oldIndex);
|
||||
});
|
||||
|
||||
$context->logger->info("[ecommerce:1.0.5] 상위집합에 포함된 기존 색인 제거: {$oldIndex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,9 @@
|
||||
- 다른 페이지의 주소로 특정 페이지의 이전 버전 내용을 열람할 수 있던 문제를 수정했습니다.
|
||||
- 다른 페이지에 속한 버전으로 복원을 시도하면 "복원에 실패했습니다" 라는 서버 오류가 나던 문제를 수정했습니다. 이제 열람과 동일하게 "찾을 수 없음" 으로 안내합니다.
|
||||
- 관리자 목록에서 검색·필터·정렬을 바꿀 때 표가 다시 그려지는 동안 로딩 표시가 나오지 않던 문제를 수정했습니다. 응답이 늦으면 아무 반응이 없는 것처럼 보여 같은 조작을 반복하게 되던 상황이 사라집니다.
|
||||
- 통합검색에서 페이지 제목으로 찾을 수 없던 문제를 수정했습니다. 한국어·영어 어느 쪽 제목으로도, 제목의 일부만 입력해도 검색됩니다.
|
||||
- 통합검색의 페이지 결과에서 같은 시각에 등록된 페이지가 여러 건일 때 목록 순서가 흔들리던 문제를 수정했습니다.
|
||||
- 페이지 관리 목록에서 뒤쪽 페이지를 보던 중 정렬을 바꾸면 이전 페이지 번호에 그대로 머물러 엉뚱한 구간이 보이던 문제를 수정했습니다. 이제 정렬을 바꾸면 첫 페이지부터 보여줍니다.
|
||||
|
||||
## [1.0.1] - 2026-07-08
|
||||
|
||||
|
||||
Loaded 100 of 276 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user