fix(core,basic,ecommerce): 쇼핑 화면 호출 통합 원복·검색 주소 승계·라우트 캐시 갱신 및 상한값 설정 저장 정합
합의되지 않은 구조 변경을 되돌리고, 계획서 전수조사에서 드러난 결함을 처리했다. 쇼핑 화면 호출 통합(F4)은 API 쿼리 튜닝이 아니라 화면 구조 변경이라 원복했다. 레이아웃 9개를 develop 상태로 복원하고 전용 엔드포인트·컨트롤러·문서·테스트를 걷어냈다. 되돌리면 함께 사라지는 비-F4 수정 둘(페이저 has_more_pages 판정 3곳, Icon 크기 클래스 23줄)은 재적용했다. 성능 개선분은 전부 잔존한다. 통합검색 화면 상태를 전역 상태에서 URL 쿼리로 옮겼다. 종전에는 탭·필터·정렬·페이지가 주소에 없어 새로고침·뒤로가기에서 초기화되고 결과를 공유할 수도 없었다. 화면은 정상으로 보이고 콘솔 에러도 없어 코드만으로는 드러나지 않는 형태였다. 확장이 라우트를 추가해도 라우트 캐시가 걸린 사이트에서는 그 주소가 404 가 되던 구멍을 막았다. 훅 캐시와 달리 라우트 캐시에는 스캔 폴백이 없어 예외도 경고도 남지 않는다. 같은 문제를 이미 푼 ConfigCacheHelper 를 미러링해 갱신 지점을 한 곳으로 모았고, 코어 업데이트가 캐시를 비우기만 하고 되살리지 않던 문제도 함께 고쳤다. 상품·페이지 검색이 커서 판정에 페이지 번호를 넘기지 않아, 커서 없이 깊은 페이지를 지목한 딥링크가 조용히 1 페이지를 돌려주던 결함을 고쳤다. 호출 지점을 손으로 열거하는 대신 저장소를 훑는 패리티 테스트로 다음 도메인의 재발을 막는다. 환경설정 고급 탭의 목록 상한값이 저장되지 않던 결함을 고쳤다. 화면·검증·읽기는 모두 있었는데 저장 시 카테고리 분류표가 손으로 열거돼 있어 그 값만 버려지고 있었다. 분류표를 설정 정의에서 도출하도록 바꿔 다음 카테고리가 합류해도 같은 일이 생기지 않게 했다. 범위를 벗어난 값의 안내에 내부 식별자가 노출되던 것도 함께 정리했다. 언어팩 재설치가 활성 팩을 자기 자신과의 슬롯 충돌로 오인해 강등하던 회귀와, CLI 설치가 HTTP 권한 컨텍스트 없이 자동 활성화되는지를 고정하는 테스트를 함께 담았다.
This commit is contained in:
1 parent
0d1105abfc
commit
7b859d4200
74 files changed
+2443
-1520
No files matched your search
@@ -3,6 +3,7 @@
|
||||
namespace Modules\Sirsoft\Board\Tests\Feature;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Board\Models\Comment;
|
||||
use Modules\Sirsoft\Board\Models\Post;
|
||||
use Modules\Sirsoft\Board\Tests\BoardTestCase;
|
||||
use Tests\Concerns\CountsQueries;
|
||||
@@ -122,4 +123,46 @@ class PostDetailQueryCountRegressionTest extends BoardTestCase
|
||||
'게시글 상세에서 게시판 테이블 SELECT 가 '.$boardSelects.'회 — 이미 조회한 게시판을 다시 찾고 있다.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 딸린 데이터가 늘어도 상세 화면의 쿼리 수가 늘지 않는지 확인
|
||||
*
|
||||
* 앞의 두 단언은 "같은 행을 두 번 읽지 않는다" 만 본다. 그것만으로는 댓글처럼
|
||||
* 개수가 변하는 자식 데이터에 항목별 쿼리가 붙는 형태를 잡지 못한다 — 그 형태는
|
||||
* 글 행을 한 번만 읽으면서도 댓글 수만큼 쿼리를 낸다.
|
||||
*
|
||||
* 그래서 댓글을 3배로 늘려 놓고 같은 화면을 다시 재, 쿼리 수가 그대로인지 본다.
|
||||
*
|
||||
* @effects post_detail_query_count_does_not_grow_with_comment_count
|
||||
*/
|
||||
public function test_query_count_does_not_grow_with_comment_count(): void
|
||||
{
|
||||
$seedComments = function (int $count, string $prefix): void {
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
Comment::create([
|
||||
'board_id' => $this->board->id,
|
||||
'post_id' => $this->post->id,
|
||||
'content' => $prefix.' '.$i,
|
||||
'author_name' => '댓글쓴이',
|
||||
'ip_address' => '127.0.0.1',
|
||||
]);
|
||||
}
|
||||
};
|
||||
|
||||
$seedComments(3, '초기');
|
||||
|
||||
// 모집단 확인 — 상세 응답이 댓글을 싣지 않게 되면 아래 단언은 "댓글을 늘려도
|
||||
// 쿼리가 안 는다" 를 아무 근거 없이 통과시킨다. 댓글을 실제로 읽는지 먼저 고정한다.
|
||||
$commentReads = array_filter(
|
||||
$this->captureDetailQueries(),
|
||||
fn (string $sql) => str_contains($sql, '`'.DB::getTablePrefix().'board_comments`')
|
||||
);
|
||||
$this->assertNotEmpty($commentReads, '상세 응답이 댓글을 조회하지 않는다 — 측정 전제가 무너졌다');
|
||||
|
||||
$this->assertQueryCountStableAsDataGrows(
|
||||
measure: fn () => $this->captureDetailQueries(),
|
||||
grow: fn () => $seedComments(9, '추가'),
|
||||
context: '게시글 상세(댓글 3건 → 12건)'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,8 +34,6 @@
|
||||
- 마이페이지 주문내역 조회가 기본으로 주문마다 주문상품 전체를 내려주지 않습니다. 기본 응답에는 대표 상품 1건과 전체 개수만 실리며, 주문상품을 전부 나열하는 마이페이지 화면은 전량을 함께 요청하므로 보이는 내용은 종전과 동일합니다. 주문내역 조회를 직접 사용하는 외부 연동에서 상품 전체가 필요하면 주소 뒤에 `?with_items=1` 을 붙이면 됩니다. (#76 @jordy-bitree 님께서 제보해주셨습니다.)
|
||||
- 통합 검색의 상품 결과를 최신순·가격순으로 볼 때 이어보기 방식으로 뒤쪽 페이지를 이동할 수 있습니다. 결과가 많아도 페이지를 넘길수록 느려지지 않습니다.
|
||||
- 분류 단건 조회가 화면에서 쓰지 않는 상품 수·하위 분류 수 집계를 기본으로 계산하지 않도록 바꿨습니다. 분류 순서 변경처럼 그 값을 읽지 않는 작업이 빨라집니다.
|
||||
- 쇼핑 첫 화면이 분류·상품목록·최근 본·인기·신상품을 각각 따로 요청하던 것을 한 번에 받도록 바꿨습니다. 화면에 보이는 내용은 동일하며 첫 화면이 뜨는 속도가 빨라집니다.
|
||||
- 상품 분류 화면도 같은 방식으로 바꿨습니다. 예전에는 분류 정보·분류 목록·상품 목록을 각각 요청했고 그중 분류 목록은 화면에서 쓰지 않았습니다. 이제 한 번의 요청으로 필요한 것만 받습니다. 없는 분류 주소로 들어오면 빈 화면 대신 없는 페이지로 처리됩니다.
|
||||
- 상품 목록의 판매량 정렬과 인기 상품 조회 방식을 개선했습니다. 예전에는 순서를 정하기 위해 전체 상품의 판매량을 매번 계산했지만, 이제 미리 묶어 둔 집계를 사용합니다. 상품이 많을수록 차이가 큽니다.
|
||||
- 상품 목록의 리뷰 개수·평점도 같은 방식으로 한 번에 집계합니다. 예전에는 상품 한 건마다 리뷰 표를 두 번씩 훑었습니다.
|
||||
- 주문·마일리지·쿠폰 발급내역·리뷰·1:1 문의 목록도 총 건수가 아주 많으면 "N건 이상" 으로 표시합니다. 페이지 이동은 끝까지 열려 있습니다.
|
||||
@@ -43,6 +41,7 @@
|
||||
- 플러그인으로 다른 검색엔진을 연결하면 상품·쿠폰·브랜드 검색에도 그 엔진이 적용됩니다. 이전에는 연결한 엔진과 무관하게 기본 방식으로만 검색됐습니다.
|
||||
- 상품 검색 결과의 총 건수가 아주 많으면 "N건 이상" 으로 표시하고, 다음 페이지 이동은 끝까지 열어 둡니다. 마지막 페이지로 바로 뛰는 버튼만 이때 감춰집니다.
|
||||
- 기간으로 걸러 보는 목록(주문·쿠폰)의 날짜 조건을 색인을 활용하는 방식으로 바꿨습니다.
|
||||
- 주문 상세에서 여러 옵션의 상태를 한꺼번에 바꿀 때, 대상 옵션을 한 번에 조회하도록 바꿨습니다. 예전에는 항목마다 같은 옵션을 다시 읽었고, 결제완료로 바꿀 때는 주문과 결제수단까지 주문 수만큼 되풀이해 읽었습니다. 한 번에 처리하는 항목이 많을수록 차이가 큽니다.
|
||||
- 주문 관리 화면 상단의 통계를 짧게 저장해 두고 재사용합니다. 주문이 바뀌면 즉시 새로 계산됩니다.
|
||||
- 상품 대량 수정(가격·재고)이 상품 수만큼 저장을 반복하던 것을 한 번에 처리하도록 바꿨습니다.
|
||||
- 결제 진행과 비회원 장바구니 병합에서 항목마다 반복하던 조회를 한 번에 처리하도록 바꿨습니다. 장바구니에 담긴 상품이 많을수록 차이가 큽니다.
|
||||
@@ -134,6 +133,7 @@
|
||||
- 해외 배송지를 수정하면 도시·주·우편번호가 안내 없이 비워지던 문제를 수정했습니다. 이번 수정에서 다시 입력하지 않은 항목은 저장된 값이 그대로 유지됩니다. (#78 @glitter-gim 님께서 제보해주셨습니다.)
|
||||
- 관리자 목록에서 기록이 아주 많아 총 건수를 끝까지 세지 못하면 "1페이지뿐" 으로 표시되어 뒤쪽 페이지를 볼 수 없던 문제를 수정했습니다. 주문·상품·마일리지·쿠폰·쿠폰 발급 이력·상품 리뷰·배송 정책·활동 이력 목록이 해당하며, 마지막 페이지로 바로 뛰는 버튼만 감춰지고 이전·다음 이동은 그대로 동작합니다.
|
||||
- 쿠폰 사용조건의 상품 검색에서 결과가 많을 때 목록 끝까지 스크롤해도 다음 묶음이 더 불러와지지 않던 문제를 수정했습니다.
|
||||
|
||||
## [1.0.4] - 2026-07-16
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -39,7 +39,6 @@
|
||||
| [shipping-carriers.md](shipping-carriers.md) | `shipping-carriers` | 7 |
|
||||
| [shipping-country.md](shipping-country.md) | `shipping-country` | 2 |
|
||||
| [shipping-policies.md](shipping-policies.md) | `shipping-policies` | 11 |
|
||||
| [storefront.md](storefront.md) | `storefront` | 1 |
|
||||
| [users.md](users.md) | `users` | 2 |
|
||||
| [wishlist.md](wishlist.md) | `wishlist` | 3 |
|
||||
|
||||
|
||||
@@ -16,6 +16,20 @@
|
||||
|
||||
---
|
||||
|
||||
## 목록 응답의 총 건수와 페이지 이동
|
||||
|
||||
상품 목록(관리자·공개 양쪽)은 총 건수를 상한까지만 셉니다. 상한을 넘으면 응답의
|
||||
`pagination` 에 정확도가 함께 실립니다 — `total_relation` 이 `at_least`, `total_is_exact`
|
||||
가 `false`, `result_cap` 이 적용된 상한값입니다. 이때 `last_page` 는 `null` 이고,
|
||||
`has_more_pages` 는 그대로 정확하므로 마지막 페이지 점프만 감춰지고 다음 페이지 이동은
|
||||
끝까지 열려 있습니다. 상한 이하이면 종전과 동일하게 `total` 이 정확한 값이고
|
||||
`total_relation` 은 `exact` 입니다.
|
||||
|
||||
같은 규약이 이 모듈의 다른 목록 응답(주문·쿠폰·마일리지·문의·리뷰 등)에도 적용됩니다.
|
||||
상세 규약은 [pagination.md](../../../../../docs/backend/pagination.md) 를 참고하세요.
|
||||
|
||||
---
|
||||
|
||||
|
||||
### GET /api/modules/sirsoft-ecommerce/admin/products
|
||||
<!-- @generated:start:api.modules.sirsoft-ecommerce.admin.products.index -->
|
||||
|
||||
@@ -1,138 +0,0 @@
|
||||
# Storefront API 레퍼런스
|
||||
|
||||
> **소유**: module `sirsoft-ecommerce` · 쇼핑 첫 화면이 필요한 데이터를 한 번에 돌려주는 통합 엔드포인트입니다.
|
||||
|
||||
---
|
||||
|
||||
## TL;DR (5초 요약)
|
||||
|
||||
```text
|
||||
1. GET /api/modules/sirsoft-ecommerce/storefront — 분류·상품목록·최근본·인기·신상품 한 번에 (`category_slug` 지정 시 그 분류의 상세까지)
|
||||
2. 각 묶음의 응답 형태는 개별 엔드포인트와 완전히 동일 (조립 위치만 서버로 이동)
|
||||
3. 개별 엔드포인트도 그대로 남아 다른 화면에서 계속 사용
|
||||
4. products 묶음은 총 건수 정확도 메타(total_relation / total_is_exact / result_cap) 포함
|
||||
5. 진열 묶음 개수를 0 으로 주면 그 묶음은 조회하지 않음
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 왜 통합 엔드포인트인가
|
||||
|
||||
쇼핑 첫 화면은 분류·상품 목록·최근 본·인기·신상품 다섯 묶음을 한 화면에 함께 그립니다.
|
||||
이를 각각의 엔드포인트로 부르면 화면 하나에 요청이 다섯 번 나가고, 그 다섯 번이 전부 같은
|
||||
부팅(라우팅·미들웨어·권한 판정·설정 적재)을 되풀이합니다.
|
||||
|
||||
각 묶음의 응답 형태(리소스 계약)는 개별 엔드포인트와 같습니다 — 옮긴 것은 조립 위치뿐이므로,
|
||||
개별 엔드포인트를 쓰는 다른 화면은 영향을 받지 않습니다.
|
||||
|
||||
분류 화면도 같은 이유로 이 엔드포인트를 씁니다. 종전에는 분류 상세·분류 트리·상품 목록으로
|
||||
요청이 세 번 나갔고, 그중 분류 트리는 그 화면의 어떤 표현식도 읽지 않는 낭비였습니다.
|
||||
`category_slug` 를 주면 `category` 묶음에 그 분류의 상세가 함께 담겨 요청 한 번으로 끝납니다.
|
||||
|
||||
---
|
||||
|
||||
### GET /api/modules/sirsoft-ecommerce/storefront
|
||||
|
||||
- **라우트명**: `api.modules.sirsoft-ecommerce.storefront.index`
|
||||
- **컨트롤러**: `Modules\Sirsoft\Ecommerce\Http\Controllers\Public\StorefrontController@index`
|
||||
- **인증/권한**: `optional.sanctum` (선택적 인증: 회원/비회원 모두 접근) + `permission:sirsoft-ecommerce.user-products.read`
|
||||
|
||||
**요청 파라미터**
|
||||
|
||||
| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| category_id | query | integer | 아니오 | — | 상품 목록 묶음의 카테고리 필터 (category 식별자) |
|
||||
| category_slug | query | string | 아니오 | max 100 | 상품 목록 묶음의 카테고리 필터 (URL 친화 식별자). **지정하면 `category` 묶음에 그 분류의 상세가 함께 담깁니다** — 없는 분류면 404 |
|
||||
| brand_id | query | integer | 아니오 | — | 상품 목록 묶음의 브랜드 필터 |
|
||||
| search | query | string | 아니오 | max 200 | 상품 목록 묶음의 검색어 |
|
||||
| sort | query | string | 아니오 | `latest`, `sales`, `price_asc`, `price_desc` | 상품 목록 묶음의 정렬 기준 |
|
||||
| min_price | query | integer | 아니오 | min 0 | 판매가 하한 |
|
||||
| max_price | query | integer | 아니오 | min 0 | 판매가 상한 |
|
||||
| per_page | query | integer | 아니오 | min 1, max 100 | 상품 목록 묶음의 페이지당 항목 수 |
|
||||
| page | query | integer | 아니오 | min 1 | 상품 목록 묶음의 페이지 번호 |
|
||||
| popular_limit | query | integer | 아니오 | min 0, max 50 | 인기 상품 개수 (0 이면 조회하지 않음, 미지정 시 8) |
|
||||
| new_limit | query | integer | 아니오 | min 0, max 50 | 신상품 개수 (0 이면 조회하지 않음, 미지정 시 8) |
|
||||
| recent_ids | query | string | 아니오 | max 500 | 최근 본 상품 ID 목록 (쉼표 구분, 비면 조회하지 않음) |
|
||||
|
||||
> 이 엔드포인트는 확장이 파라미터를 추가할 수 있습니다 (`sirsoft-ecommerce.product.public_storefront_validation_rules`, `sirsoft-ecommerce.product.public_storefront_validation_messages`).
|
||||
|
||||
**요청 예시**
|
||||
|
||||
```http
|
||||
GET /api/modules/sirsoft-ecommerce/storefront?page=1&per_page=12&sort=latest&popular_limit=8&new_limit=8&recent_ids=12%2C34 HTTP/1.1
|
||||
Host: api.example.com
|
||||
Accept: application/json
|
||||
Authorization: Bearer {YOUR_TOKEN} (optional.sanctum: 비회원은 헤더 생략 가능)
|
||||
```
|
||||
|
||||
**응답 필드** (`data` 내부)
|
||||
|
||||
| 필드 | 타입 | 용도/설명 |
|
||||
| --- | --- | --- |
|
||||
| category | object\|null | 지금 보고 있는 분류의 상세. `GET /categories/{slug}` 의 `data` 와 동일한 형태. `category_slug` 를 주지 않으면 `null` |
|
||||
| categories | array | 공개 카테고리 트리. `GET /categories` 의 `data` 와 동일한 형태 |
|
||||
| products | object | 상품 목록. `GET /products` 의 `data` 와 동일한 형태 (`data[]` + `pagination`) |
|
||||
| recent_products | array | 최근 본 상품. `GET /products/recent` 의 `data` 와 동일한 형태 (`recent_ids` 가 비면 `[]`) |
|
||||
| popular_products | array | 인기 상품. `GET /products/popular` 의 `data` 와 동일한 형태 (`popular_limit=0` 이면 `[]`) |
|
||||
| new_products | array | 신상품. `GET /products/new` 의 `data` 와 동일한 형태 (`new_limit=0` 이면 `[]`) |
|
||||
|
||||
`products.pagination` 은 표준 페이지네이션 메타에 총 건수 정확도가 더해진 형태입니다.
|
||||
|
||||
| 필드 | 타입 | 용도/설명 |
|
||||
| --- | --- | --- |
|
||||
| current_page | integer | 현재 페이지 번호 |
|
||||
| per_page | integer | 페이지당 항목 수 |
|
||||
| from / to | integer\|null | 현재 페이지의 첫/마지막 행 번호 |
|
||||
| has_more_pages | boolean | 다음 페이지 존재 여부 (총 건수를 몰라도 정확) |
|
||||
| total | integer | 총 건수 (상한 초과 시 상한값 = 하한 보증) |
|
||||
| last_page | integer\|null | 마지막 페이지 번호. **총 건수가 부정확하면 `null`** |
|
||||
| total_relation | string | `exact` 또는 `at_least` |
|
||||
| total_is_exact | boolean | 총 건수가 정확한지 여부 |
|
||||
| result_cap | integer\|null | 총 건수 집계에 적용된 상한 (무제한이면 `null`) |
|
||||
|
||||
> 총 건수 상한과 페이지 이동의 관계는 [pagination.md](../../../../../docs/backend/pagination.md) 참조.
|
||||
|
||||
**응답 예시**
|
||||
|
||||
```http
|
||||
HTTP/1.1 200
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "상품 목록을 조회했습니다.",
|
||||
"data": {
|
||||
"category": null,
|
||||
"categories": [],
|
||||
"products": {
|
||||
"data": [],
|
||||
"pagination": {
|
||||
"current_page": 1,
|
||||
"per_page": 12,
|
||||
"from": null,
|
||||
"to": null,
|
||||
"has_more_pages": false,
|
||||
"total": 0,
|
||||
"last_page": 1,
|
||||
"total_relation": "exact",
|
||||
"total_is_exact": true,
|
||||
"result_cap": 10000
|
||||
}
|
||||
},
|
||||
"recent_products": [],
|
||||
"popular_products": [],
|
||||
"new_products": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**오류 응답**
|
||||
|
||||
| 상태 | 상황 |
|
||||
| --- | --- |
|
||||
| 404 | `category_slug` 가 가리키는 분류가 없거나 비활성 (200 + 빈 목록으로 내보내면 검색엔진이 없는 주소를 정상 페이지로 수집합니다) |
|
||||
| 401 | 비회원에게 `sirsoft-ecommerce.user-products.read` 권한이 없음 |
|
||||
| 403 | 인증 사용자에게 해당 권한이 없음 |
|
||||
| 422 | 파라미터 검증 실패 (범위를 벗어난 `popular_limit` 등) |
|
||||
| 500 | 조회 중 예외 — 응답 형태는 개별 상품 엔드포인트와 동일 |
|
||||
-181
@@ -1,181 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Controllers\Public;
|
||||
|
||||
use App\Helpers\ResponseHelper;
|
||||
use App\Http\Controllers\Api\Base\PublicBaseController;
|
||||
use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Public\PublicStorefrontRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\ProductListResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\PublicCategoryDetailResource;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\PublicCategoryResource;
|
||||
use Modules\Sirsoft\Ecommerce\Services\CategoryService;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductService;
|
||||
|
||||
/**
|
||||
* 쇼핑 첫 화면 통합 조회 컨트롤러
|
||||
*
|
||||
* 쇼핑 첫 화면은 분류·상품 목록·최근 본·인기·신상품 다섯 묶음을 한 화면에 함께 그린다.
|
||||
* 이를 각각의 엔드포인트로 부르면 화면 하나에 요청이 다섯 번 나가고, 그 다섯 번이 전부
|
||||
* 같은 부팅(라우팅·미들웨어·권한 판정·설정 적재)을 되풀이한다.
|
||||
*
|
||||
* 각 묶음의 응답 형태(리소스 계약)는 개별 엔드포인트와 완전히 같다 — 옮긴 것은 조립
|
||||
* 위치뿐이므로, 개별 엔드포인트도 그대로 남아 다른 화면에서 계속 쓰인다.
|
||||
*/
|
||||
class StorefrontController extends PublicBaseController
|
||||
{
|
||||
public function __construct(
|
||||
private ProductService $productService,
|
||||
private CategoryService $categoryService
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 쇼핑 첫 화면에 필요한 데이터를 한 번에 조회합니다.
|
||||
*
|
||||
* @param PublicStorefrontRequest $request 요청 데이터
|
||||
* @return JsonResponse 분류·상품 목록·최근 본·인기·신상품을 담은 JSON 응답
|
||||
*/
|
||||
public function index(PublicStorefrontRequest $request): JsonResponse
|
||||
{
|
||||
try {
|
||||
$this->logApiUsage('storefront.index');
|
||||
|
||||
$validated = $request->validated();
|
||||
|
||||
$category = $this->resolveFocusedCategory($validated);
|
||||
|
||||
if ($category === false) {
|
||||
return ResponseHelper::notFound(
|
||||
'messages.categories.not_found',
|
||||
[],
|
||||
'sirsoft-ecommerce'
|
||||
);
|
||||
}
|
||||
|
||||
return ResponseHelper::moduleSuccess(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.fetch_success',
|
||||
[
|
||||
'category' => $category,
|
||||
'categories' => PublicCategoryResource::collection(
|
||||
$this->categoryService->getPublicCategoryTree()
|
||||
)->resolve(),
|
||||
'products' => $this->resolveProductList($request, $validated),
|
||||
'recent_products' => $this->resolveRecentProducts($validated),
|
||||
'popular_products' => $this->resolveDisplayGroup(
|
||||
(int) ($validated['popular_limit'] ?? 8),
|
||||
fn (int $limit) => $this->productService->getPopularProducts($limit)
|
||||
),
|
||||
'new_products' => $this->resolveDisplayGroup(
|
||||
(int) ($validated['new_limit'] ?? 8),
|
||||
fn (int $limit) => $this->productService->getNewProducts($limit)
|
||||
),
|
||||
]
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.products.fetch_failed',
|
||||
500
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 상품 목록 묶음을 조립합니다.
|
||||
*
|
||||
* 개별 상품 목록 엔드포인트와 같은 컬렉션을 쓰므로 페이지네이션 메타까지 형태가 같습니다.
|
||||
*
|
||||
* @param PublicStorefrontRequest $request 요청 객체
|
||||
* @param array<string, mixed> $validated 검증된 입력
|
||||
* @return array<string, mixed> 상품 목록 응답 데이터
|
||||
*/
|
||||
private function resolveProductList(PublicStorefrontRequest $request, array $validated): array
|
||||
{
|
||||
$listKeys = ['category_id', 'category_slug', 'brand_id', 'search', 'sort', 'min_price', 'max_price'];
|
||||
$filters = array_filter(
|
||||
$validated,
|
||||
fn ($value, $key) => in_array($key, $listKeys, true) && $value !== null && $value !== '',
|
||||
ARRAY_FILTER_USE_BOTH
|
||||
);
|
||||
|
||||
$perPage = (int) ($validated['per_page'] ?? 20);
|
||||
$collection = new ProductCollection($this->productService->getPublicList($filters, $perPage));
|
||||
|
||||
return $collection->toArray($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* 특정 분류 화면이 필요로 하는 단건 분류를 조립합니다.
|
||||
*
|
||||
* 분류 화면은 "지금 보고 있는 분류" 하나와 전체 분류 트리, 그 분류의 상품 목록을 함께
|
||||
* 그린다. 단건 분류를 여기서 함께 돌려주면 그 화면도 요청 한 번으로 끝난다.
|
||||
* `category_slug` 가 없으면(쇼핑 첫 화면) 조회하지 않는다.
|
||||
*
|
||||
* 응답 형태는 단건 분류 엔드포인트와 같은 리소스를 써서 완전히 일치시킨다 —
|
||||
* 옮긴 것은 조립 위치뿐이므로 화면 바인딩이 그대로 동작해야 한다.
|
||||
*
|
||||
* 반환값이 false 면 "분류를 지정했는데 그런 분류가 없다" 는 뜻이다. 이 경우 호출자가
|
||||
* 404 로 끊는다 — 200 으로 빈 화면을 내보내면 검색엔진이 존재하지 않는 분류 주소를
|
||||
* 정상 페이지로 수집한다.
|
||||
*
|
||||
* @param array<string, mixed> $validated 검증된 입력
|
||||
* @return array<string, mixed>|null|false 분류 응답 데이터 / 미지정 시 null / 대상 없음 시 false
|
||||
*/
|
||||
private function resolveFocusedCategory(array $validated): array|null|false
|
||||
{
|
||||
$slug = trim((string) ($validated['category_slug'] ?? ''));
|
||||
|
||||
if ($slug === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$category = $this->categoryService->getPublicCategoryBySlug($slug);
|
||||
|
||||
return $category ? (new PublicCategoryDetailResource($category))->resolve() : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 본 상품 묶음을 조립합니다.
|
||||
*
|
||||
* 최근 본 상품은 클라이언트가 보관한 ID 목록으로만 정해지므로, 비어 있으면 조회하지 않습니다.
|
||||
*
|
||||
* @param array<string, mixed> $validated 검증된 입력
|
||||
* @return array<int, mixed> 상품 목록 (없으면 빈 배열)
|
||||
*/
|
||||
private function resolveRecentProducts(array $validated): array
|
||||
{
|
||||
$ids = array_values(array_filter(array_map(
|
||||
'intval',
|
||||
explode(',', (string) ($validated['recent_ids'] ?? ''))
|
||||
)));
|
||||
|
||||
if (empty($ids)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return ProductListResource::collection(
|
||||
$this->productService->getProductsByIds($ids)
|
||||
)->resolve();
|
||||
}
|
||||
|
||||
/**
|
||||
* 진열 묶음(인기·신상품)을 조립합니다.
|
||||
*
|
||||
* 개수가 0 이면 그 묶음을 쓰지 않겠다는 뜻이므로 조회하지 않습니다.
|
||||
*
|
||||
* @param int $limit 조회 개수
|
||||
* @param callable $resolver 상품 조회 클로저
|
||||
* @return array<int, mixed> 상품 목록 (없으면 빈 배열)
|
||||
*/
|
||||
private function resolveDisplayGroup(int $limit, callable $resolver): array
|
||||
{
|
||||
if ($limit <= 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return ProductListResource::collection($resolver($limit))->resolve();
|
||||
}
|
||||
}
|
||||
-85
@@ -1,85 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Http\Requests\Public;
|
||||
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
|
||||
/**
|
||||
* 쇼핑 첫 화면 통합 조회 요청 (공개)
|
||||
*
|
||||
* 상품 목록 필터에 더해 진열 묶음(인기/신상품/최근 본)의 개수와 최근 본 상품 ID 를 받습니다.
|
||||
* 개별 엔드포인트가 각각 쓰던 규칙을 그대로 합친 것이므로, 같은 값이면 같은 결과가 나옵니다.
|
||||
*/
|
||||
class PublicStorefrontRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 권한 확인
|
||||
*
|
||||
* @return bool 항상 true (권한은 미들웨어 체인이 담당)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 유효성 검사 규칙
|
||||
*
|
||||
* @return array 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
// 상품 목록 필터 (PublicProductListRequest 와 동일)
|
||||
'category_id' => ['nullable', 'integer'],
|
||||
'category_slug' => ['nullable', 'string', 'max:100'],
|
||||
'brand_id' => ['nullable', 'integer'],
|
||||
'search' => ['nullable', 'string', 'max:200'],
|
||||
'sort' => ['nullable', 'string', 'in:latest,sales,price_asc,price_desc'],
|
||||
'min_price' => ['nullable', 'integer', 'min:0'],
|
||||
'max_price' => ['nullable', 'integer', 'min:0'],
|
||||
'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
|
||||
|
||||
// 진열 묶음
|
||||
'popular_limit' => ['nullable', 'integer', 'min:0', 'max:50'],
|
||||
'new_limit' => ['nullable', 'integer', 'min:0', 'max:50'],
|
||||
'recent_ids' => ['nullable', 'string', 'max:500'],
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.product.public_storefront_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 에러 메시지 정의
|
||||
*
|
||||
* @return array<string, string> 검증 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
$messages = [
|
||||
'category_id.integer' => __('sirsoft-ecommerce::validation.public_product.category_id.integer'),
|
||||
'category_slug.string' => __('sirsoft-ecommerce::validation.public_product.category_slug.string'),
|
||||
'category_slug.max' => __('sirsoft-ecommerce::validation.public_product.category_slug.max'),
|
||||
'brand_id.integer' => __('sirsoft-ecommerce::validation.public_product.brand_id.integer'),
|
||||
'search.string' => __('sirsoft-ecommerce::validation.public_product.search.string'),
|
||||
'search.max' => __('sirsoft-ecommerce::validation.public_product.search.max'),
|
||||
'sort.in' => __('sirsoft-ecommerce::validation.public_product.sort.in'),
|
||||
'min_price.integer' => __('sirsoft-ecommerce::validation.public_product.min_price.integer'),
|
||||
'min_price.min' => __('sirsoft-ecommerce::validation.public_product.min_price.min'),
|
||||
'max_price.integer' => __('sirsoft-ecommerce::validation.public_product.max_price.integer'),
|
||||
'max_price.min' => __('sirsoft-ecommerce::validation.public_product.max_price.min'),
|
||||
'per_page.integer' => __('sirsoft-ecommerce::validation.public_product.per_page.integer'),
|
||||
'per_page.min' => __('sirsoft-ecommerce::validation.public_product.per_page.min'),
|
||||
'per_page.max' => __('sirsoft-ecommerce::validation.public_product.per_page.max'),
|
||||
'popular_limit.integer' => __('sirsoft-ecommerce::validation.public_product.limit.integer'),
|
||||
'popular_limit.max' => __('sirsoft-ecommerce::validation.public_product.limit.max'),
|
||||
'new_limit.integer' => __('sirsoft-ecommerce::validation.public_product.limit.integer'),
|
||||
'new_limit.max' => __('sirsoft-ecommerce::validation.public_product.limit.max'),
|
||||
'recent_ids.string' => __('sirsoft-ecommerce::validation.public_product.ids.string'),
|
||||
'recent_ids.max' => __('sirsoft-ecommerce::validation.public_product.ids.max'),
|
||||
];
|
||||
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.product.public_storefront_validation_messages', $messages, $this);
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,9 @@ namespace Modules\Sirsoft\Ecommerce\Listeners;
|
||||
|
||||
use App\Contracts\Extension\HookListenerInterface;
|
||||
use App\Enums\TotalRelation;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use App\Search\SearchCategoryPayload;
|
||||
use App\Support\Query\BoundedCount;
|
||||
use App\Helpers\PermissionHelper;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Resources\Traits\HasMultiCurrencyPrices;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductService;
|
||||
@@ -141,7 +141,9 @@ class SearchProductsListener implements HookListenerInterface
|
||||
->map(fn ($product) => $this->formatProductResult($product, $q))
|
||||
->toArray();
|
||||
|
||||
// 커서를 받았고 그 정렬을 커서로 처리할 수 있으면 키셋으로 응답한다.
|
||||
// 그 정렬을 커서로 처리할 수 있으면 키셋으로 응답한다. 페이지 번호를 함께 넘기는
|
||||
// 이유는 커서 없이 깊은 페이지를 직접 지목한 딥링크를 코어가 가려내야 하기
|
||||
// 때문이다 — 넘기지 않으면 기본값 1 이 적용돼 그 링크가 첫 페이지로 되돌아간다.
|
||||
// 전체 탭은 미리보기 몇 건뿐이라 깊은 페이지가 없어 대상이 아니다.
|
||||
$cursorPage = $isAllTab
|
||||
? null
|
||||
@@ -150,7 +152,8 @@ class SearchProductsListener implements HookListenerInterface
|
||||
$sort,
|
||||
$categoryId,
|
||||
$fetchPerPage,
|
||||
$context['cursor'] ?? null
|
||||
$context['cursor'] ?? null,
|
||||
(int) $page
|
||||
);
|
||||
|
||||
if ($cursorPage !== null) {
|
||||
|
||||
@@ -342,9 +342,20 @@ class OrderOptionService
|
||||
$changedCount = 0;
|
||||
$splitCount = 0;
|
||||
|
||||
DB::transaction(function () use ($items, $newStatus, $metadata, &$results, &$changedCount, &$splitCount) {
|
||||
// 대상 옵션을 1회 일괄 조회해 재사용한다 (항목마다 같은 행을 다시 읽지 않는다).
|
||||
// 같은 옵션이 두 번 이상 실린 요청은 앞선 변경이 이미 DB 에 반영된 뒤이므로
|
||||
// 적재본이 낡는다 — 그 경우에만 그 항목을 다시 읽어 종전 동작을 유지한다.
|
||||
$prefetchedOptions = $this->orderOptionRepository->findByIdsKeyed($optionIds);
|
||||
|
||||
DB::transaction(function () use ($items, $newStatus, $metadata, $prefetchedOptions, &$results, &$changedCount, &$splitCount) {
|
||||
$consumed = [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
$option = $this->orderOptionRepository->findOrFail($item['option_id']);
|
||||
$optionId = $item['option_id'];
|
||||
$option = isset($consumed[$optionId])
|
||||
? $this->orderOptionRepository->findOrFail($optionId)
|
||||
: ($prefetchedOptions->get($optionId) ?? $this->orderOptionRepository->findOrFail($optionId));
|
||||
$consumed[$optionId] = true;
|
||||
|
||||
$result = $this->changeStatusWithQuantity(
|
||||
$option,
|
||||
@@ -639,8 +650,12 @@ class OrderOptionService
|
||||
{
|
||||
$orderIds = $this->orderOptionRepository->getOrderIdsByOptionIds($optionIds);
|
||||
|
||||
// 주문과 결제수단을 1회 일괄 조회한다. 주문마다 조회하면 결제수단 지연 로드까지
|
||||
// 따라붙어 대상 주문 수만큼 쿼리가 두 배로 늘어난다.
|
||||
$orders = $this->orderRepository->findByIdsWithRelationsKeyed($orderIds, ['payment']);
|
||||
|
||||
foreach ($orderIds as $orderId) {
|
||||
$order = $this->orderRepository->find($orderId);
|
||||
$order = $orders->get($orderId);
|
||||
if (! $order) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -6,9 +6,9 @@ use App\Extension\HookManager;
|
||||
use App\Search\SearchPagePolicy;
|
||||
use App\Support\Query\BoundedCount;
|
||||
use App\Support\Query\BoundedPage;
|
||||
use Illuminate\Pagination\CursorPaginator;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Pagination\CursorPaginator;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\SequenceType;
|
||||
@@ -1849,7 +1849,7 @@ class ProductService
|
||||
* @param int|null $categoryId 카테고리 필터
|
||||
* @param int $offset 오프셋
|
||||
* @param int $limit 조회할 최대 항목 수
|
||||
* @return array{total: int, items: Collection}
|
||||
* @return BoundedPage 페이지 결과 (총 건수 정확도 포함)
|
||||
*/
|
||||
public function searchByKeyword(string $keyword, string $sort = 'latest', ?int $categoryId = null, int $offset = 0, int $limit = 10): BoundedPage
|
||||
{
|
||||
@@ -1869,6 +1869,7 @@ class ProductService
|
||||
* @param int|null $categoryId 카테고리 필터
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @param string|null $cursor 인코딩된 커서 (첫 페이지면 null)
|
||||
* @param int $page 요청 페이지 번호 (커서 없이 깊은 페이지를 지목했는지 판정용)
|
||||
* @return CursorPaginator|null 커서 페이지 결과 (커서 적용 불가 시 null)
|
||||
*/
|
||||
public function searchByKeywordWithCursor(
|
||||
@@ -1876,11 +1877,12 @@ class ProductService
|
||||
string $sort = 'latest',
|
||||
?int $categoryId = null,
|
||||
int $perPage = 10,
|
||||
?string $cursor = null
|
||||
?string $cursor = null,
|
||||
int $page = 1
|
||||
): ?CursorPaginator {
|
||||
$sortKeys = SearchPagePolicy::sortKeys($sort, self::SEARCH_SORT_MAP);
|
||||
|
||||
if (! SearchPagePolicy::usesCursor($cursor, $sortKeys, self::SEARCH_CURSOR_COLUMNS)) {
|
||||
if (! SearchPagePolicy::usesCursor($cursor, $sortKeys, self::SEARCH_CURSOR_COLUMNS, $page)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -33,7 +33,6 @@ use Modules\Sirsoft\Ecommerce\Http\Controllers\Public\ProductImageController;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\Public\ProductInquiryController as PublicProductInquiryController;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\Public\ProductReviewController as PublicProductReviewController;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\Public\PublicCouponController;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\Public\StorefrontController;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\Public\WishlistController;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\Shop\PaymentConfigController;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Controllers\User\OrderController as UserOrderController;
|
||||
@@ -74,13 +73,6 @@ Route::prefix('categories')->group(function () {
|
||||
->name('categories.show');
|
||||
});
|
||||
|
||||
// 쇼핑 첫 화면 통합 조회 API
|
||||
// GET /api/modules/sirsoft-ecommerce/storefront - 분류·상품목록·최근본·인기·신상품 한 번에 조회
|
||||
// (각 묶음의 응답 형태는 개별 엔드포인트와 동일 — 조립 위치만 서버로 옮긴 것)
|
||||
Route::get('storefront', [StorefrontController::class, 'index'])
|
||||
->middleware(['optional.sanctum', 'permission:user,sirsoft-ecommerce.user-products.read'])
|
||||
->name('storefront.index');
|
||||
|
||||
// 공개 상품 API
|
||||
// GET /api/modules/sirsoft-ecommerce/products - 공개 상품 목록 조회
|
||||
// GET /api/modules/sirsoft-ecommerce/products/popular - 인기 상품 조회
|
||||
|
||||
-66
@@ -5,10 +5,6 @@ namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Performance;
|
||||
// 테스트 베이스 클래스 수동 require (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use App\Enums\PermissionType;
|
||||
use App\Models\Permission;
|
||||
use App\Models\Role;
|
||||
use App\Models\User;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
@@ -109,68 +105,6 @@ class ListQueryCountRegressionTest extends ModuleTestCase
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 쇼핑 첫 화면(storefront): 상품 수가 늘어도 쿼리 수가 늘지 않는지 확인
|
||||
*
|
||||
* 이 엔드포인트는 분류·상품·최근·인기·신상품 5묶음을 한 응답으로 합친다. 묶음마다
|
||||
* 관계가 달려 있어 어느 한 묶음이 관계 eager load 를 놓치면 그 자리에서 N+1 이 된다.
|
||||
* 응답을 통째로 재야 그 사실이 드러난다.
|
||||
*
|
||||
* @effects storefront_query_count_stable
|
||||
*/
|
||||
public function test_storefront_query_count_is_stable(): void
|
||||
{
|
||||
$this->seedProducts(5, 'SHOP-A');
|
||||
|
||||
// storefront 는 `permission:user,sirsoft-ecommerce.user-products.read` 로 가드된다.
|
||||
// 시드된 'user' 역할에 그 권한이 붙어 있는지는 앞선 테스트가 무엇을 했는지에 따라
|
||||
// 달라지므로(단독 실행은 통과, 연속 실행은 403), 전용 역할에 권한을 직접 부여한다.
|
||||
$this->actingAs($this->userWithProductReadPermission(), 'sanctum');
|
||||
|
||||
$this->assertQueryCountStableAsDataGrows(
|
||||
measure: function () {
|
||||
// 카테고리 트리 캐시가 살아 있으면 두 번째 측정이 그만큼 적게 나와
|
||||
// 판정이 무의미해진다. 매 측정 조건을 같게 맞춘다.
|
||||
Category::flushTreeCache();
|
||||
|
||||
$response = $this->getJson('/api/modules/sirsoft-ecommerce/storefront');
|
||||
$response->assertOk();
|
||||
},
|
||||
grow: fn () => $this->seedProducts(10, 'SHOP-B'),
|
||||
context: '쇼핑 첫 화면(storefront)',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 공개 상품 조회 권한을 가진 사용자를 만듭니다.
|
||||
*
|
||||
* 전용 역할에 권한을 직접 붙여, 시드된 공용 역할의 상태에 의존하지 않게 한다.
|
||||
*
|
||||
* @return User 권한을 가진 사용자
|
||||
*/
|
||||
private function userWithProductReadPermission(): User
|
||||
{
|
||||
$user = User::factory()->create();
|
||||
|
||||
$role = Role::create([
|
||||
'identifier' => 'storefront-probe-'.$user->id,
|
||||
'name' => ['ko' => '진열 조회 테스트', 'en' => 'Storefront Probe'],
|
||||
]);
|
||||
|
||||
$permission = Permission::firstOrCreate(
|
||||
['identifier' => 'sirsoft-ecommerce.user-products.read'],
|
||||
[
|
||||
'name' => ['ko' => '공개 상품 조회', 'en' => 'Read public products'],
|
||||
'type' => PermissionType::User,
|
||||
]
|
||||
);
|
||||
|
||||
$role->permissions()->syncWithoutDetaching([$permission->id]);
|
||||
$user->roles()->attach($role->id);
|
||||
|
||||
return User::findOrFail($user->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리를 계층으로 만듭니다 (루트 1 + 자식 N-1).
|
||||
*
|
||||
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Performance;
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderOptionFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Database\Factories\OrderPaymentFactory;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Services\OrderOptionService;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use Tests\Concerns\CountsQueries;
|
||||
|
||||
/**
|
||||
* 주문 옵션 일괄 처리의 쿼리 수 회귀 테스트 (#519 E3)
|
||||
*
|
||||
* 일괄 상태 변경은 항목마다 옵션을 다시 조회했고, 결제완료 전이 가드는 주문마다
|
||||
* 다시 조회한 뒤 결제수단을 지연 로드했다. 둘 다 대상이 늘수록 조회가 함께 늘어난다.
|
||||
*
|
||||
* 전체 쿼리 수로는 재지 않는다 — 상태 UPDATE 는 항목마다 나는 것이 정상이라
|
||||
* 총량은 어차피 항목 수에 비례한다. 여기서 고정하는 것은 **쓰기 직전에 같은 행을
|
||||
* 한 건씩 다시 읽던 조회**이므로, 그 단일 행 조회의 형태를 직접 센다.
|
||||
*/
|
||||
class OrderOptionBulkQueryCountRegressionTest extends ModuleTestCase
|
||||
{
|
||||
use CountsQueries;
|
||||
|
||||
private OrderOptionService $service;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
$this->service = app(OrderOptionService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제완료 상태의 주문과 옵션 N건을 만든다.
|
||||
*
|
||||
* @param int $optionCount 생성할 옵션 수
|
||||
* @return Order 생성된 주문
|
||||
*/
|
||||
private function makeOrderWithOptions(int $optionCount): Order
|
||||
{
|
||||
$order = OrderFactory::new()->create([
|
||||
'order_status' => OrderStatusEnum::PAYMENT_COMPLETE,
|
||||
]);
|
||||
|
||||
for ($i = 0; $i < $optionCount; $i++) {
|
||||
OrderOptionFactory::new()->forOrder($order)->create([
|
||||
'option_status' => OrderStatusEnum::PAYMENT_COMPLETE,
|
||||
'quantity' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
return $order->fresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* 주문의 전 옵션을 대상으로 하는 일괄 변경 요청 페이로드를 만든다.
|
||||
*
|
||||
* @param Order $order 대상 주문
|
||||
* @return array<int, array{option_id: int, quantity: int}> 변경 항목 배열
|
||||
*/
|
||||
private function itemsFor(Order $order): array
|
||||
{
|
||||
return $order->options->map(fn ($option) => [
|
||||
'option_id' => $option->id,
|
||||
'quantity' => (int) $option->quantity,
|
||||
])->values()->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 기본키 단일 행 조회(`where ...id = ? limit 1`)의 건수를 센다.
|
||||
*
|
||||
* @param array<int, string> $queries 실행된 SQL 목록
|
||||
* @param string $table 대상 테이블 이름 조각
|
||||
* @return int 단일 행 조회 건수
|
||||
*/
|
||||
private function countSingleRowLookups(array $queries, string $table): int
|
||||
{
|
||||
$pattern = '/^select .* from \S*'.preg_quote($table, '/').'\S* where \S*"?id"?\S* = \? limit 1$/i';
|
||||
|
||||
return count(array_filter(
|
||||
$queries,
|
||||
fn (string $sql) => (bool) preg_match($pattern, str_replace('`', '"', $sql))
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 일괄 상태 변경이 대상 옵션을 1회 일괄 조회해 재사용한다.
|
||||
*
|
||||
* 총 단일 행 조회 수로는 재지 않는다 — 옵션 단위 훅(`order_option.after_status_change`)이
|
||||
* 항목마다 발화하고 그 구독자들이 자기 대상을 읽으므로, 총량은 어느 구현에서든 항목 수에
|
||||
* 비례한다. 그 비례는 훅 설계상 정상이고 E3 의 대상이 아니다.
|
||||
*
|
||||
* E3 가 없앤 것은 **변경 대상을 확정하는 단계**에서 항목마다 같은 행을 한 건씩 다시 읽던
|
||||
* 조회다. 그래서 "첫 쓰기 이전에 단일 행 조회가 없고, 대상이 일괄 조회로 확정된다"는
|
||||
* 구조를 직접 고정한다. 루프 안에 단건 조회가 되살아나면 첫 항목의 조회가 첫 UPDATE 를
|
||||
* 앞서므로 이 단언이 깨진다.
|
||||
*
|
||||
* @scenario operation=bulk_change_with_quantity, item_count=6, target_status=shipping
|
||||
*
|
||||
* @effects bulk_change_resolves_targets_in_one_batched_query
|
||||
*/
|
||||
public function test_bulk_change_resolves_targets_in_one_batched_query(): void
|
||||
{
|
||||
$order = $this->makeOrderWithOptions(6);
|
||||
$items = $this->itemsFor($order);
|
||||
|
||||
$queries = $this->captureQueries(function () use ($items, $order) {
|
||||
$this->service->bulkChangeStatusWithQuantity(
|
||||
$items,
|
||||
OrderStatusEnum::SHIPPING,
|
||||
$order->id
|
||||
);
|
||||
});
|
||||
|
||||
$firstWriteAt = $this->indexOfFirstWrite($queries, 'order_options');
|
||||
$this->assertNotNull($firstWriteAt, '옵션 상태 UPDATE 가 실행되지 않았다 — 측정 전제가 무너졌다');
|
||||
|
||||
$beforeWrite = array_slice($queries, 0, $firstWriteAt);
|
||||
|
||||
$lookupsBeforeWrite = $this->countSingleRowLookups($beforeWrite, 'order_options');
|
||||
$this->assertSame(
|
||||
0,
|
||||
$lookupsBeforeWrite,
|
||||
"변경 대상을 확정하기 전에 옵션을 단건으로 {$lookupsBeforeWrite}회 조회했다. "
|
||||
.'항목마다 옵션을 다시 읽고 있다 — 대상 옵션을 1회 일괄 조회해 재사용한다'
|
||||
);
|
||||
|
||||
$batched = array_filter(
|
||||
$beforeWrite,
|
||||
fn (string $sql) => (bool) preg_match('/^select \* from \S*order_options\S* where \S*id\S* in \(/i', str_replace('`', '"', $sql))
|
||||
);
|
||||
$this->assertNotEmpty(
|
||||
$batched,
|
||||
'대상 옵션을 일괄 조회(`where id in (...)`)한 흔적이 없다 — 1회 일괄 조회로 확정해야 한다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 대상 테이블에 대한 첫 쓰기(UPDATE) 위치를 찾는다.
|
||||
*
|
||||
* @param array<int, string> $queries 실행된 SQL 목록
|
||||
* @param string $table 대상 테이블 이름 조각
|
||||
* @return int|null 첫 UPDATE 의 인덱스 (없으면 null)
|
||||
*/
|
||||
private function indexOfFirstWrite(array $queries, string $table): ?int
|
||||
{
|
||||
foreach ($queries as $index => $sql) {
|
||||
if (preg_match('/^update \S*'.preg_quote($table, '/').'\S*/i', str_replace('`', '"', $sql))) {
|
||||
return $index;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 결제완료 전이 가드가 주문마다 다시 읽지 않는다.
|
||||
*
|
||||
* 옵션 일괄변경은 단일 주문 범위지만, 가드는 옵션에서 주문을 역산하므로
|
||||
* 여러 주문에 걸친 내부/훅 호출에서 주문마다 조회 + 결제수단 지연 로드가 발생했다.
|
||||
*
|
||||
* @scenario operation=enforce_payment_complete_idv, order_count=1_vs_3, target_status=payment_complete
|
||||
*
|
||||
* @effects payment_complete_guard_query_count_does_not_grow_with_order_count
|
||||
*/
|
||||
public function test_payment_complete_guard_query_count_does_not_grow_with_order_count(): void
|
||||
{
|
||||
$single = $this->makeGuardTargets(1);
|
||||
$multiple = $this->makeGuardTargets(3);
|
||||
|
||||
$singleQueries = $this->countQueries(fn () => $this->invokeGuard($single));
|
||||
$multipleQueries = $this->countQueries(fn () => $this->invokeGuard($multiple));
|
||||
|
||||
$this->assertLessThanOrEqual(
|
||||
$singleQueries,
|
||||
$multipleQueries,
|
||||
"결제완료 가드의 쿼리 수가 주문 수에 비례한다 (1주문={$singleQueries} / 3주문={$multipleQueries}). "
|
||||
.'주문마다 다시 조회하고 결제수단을 지연 로드하고 있다 — 결제 관계까지 1회 일괄 조회한다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 가드 대상 옵션 ID 집합을 만든다 (주문마다 옵션 1건 + 결제 1건).
|
||||
*
|
||||
* @param int $orderCount 생성할 주문 수
|
||||
* @return array<int, int> 옵션 ID 배열
|
||||
*/
|
||||
private function makeGuardTargets(int $orderCount): array
|
||||
{
|
||||
$optionIds = [];
|
||||
|
||||
for ($i = 0; $i < $orderCount; $i++) {
|
||||
$order = OrderFactory::new()->create([
|
||||
'order_status' => OrderStatusEnum::PENDING_PAYMENT,
|
||||
]);
|
||||
OrderPaymentFactory::new()->create(['order_id' => $order->id]);
|
||||
$optionIds[] = OrderOptionFactory::new()->forOrder($order)->create([
|
||||
'option_status' => OrderStatusEnum::PENDING_PAYMENT,
|
||||
'quantity' => 1,
|
||||
])->id;
|
||||
}
|
||||
|
||||
return $optionIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* private 가드 메서드를 직접 호출한다.
|
||||
*
|
||||
* @param array<int, int> $optionIds 대상 옵션 ID 배열
|
||||
*/
|
||||
private function invokeGuard(array $optionIds): void
|
||||
{
|
||||
$method = new \ReflectionMethod($this->service, 'enforcePaymentCompleteIdv');
|
||||
$method->invoke($this->service, $optionIds);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Performance;
|
||||
|
||||
// 테스트 베이스 클래스 수동 require (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../../ModuleTestCase.php';
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Models\Product;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use Tests\Concerns\CountsQueries;
|
||||
|
||||
/**
|
||||
* 쇼핑 첫 화면 구성 조회의 쿼리 수 회귀 테스트 (#519)
|
||||
*
|
||||
* 쇼핑 첫 화면은 분류·상품 목록·최근 본·인기·신상품 다섯 조각으로 그려진다. 각 조각은
|
||||
* 독립 엔드포인트라 어느 하나에 N+1 이 들어와도 나머지는 멀쩡하고, 화면도 정상으로 보인다.
|
||||
* 응답 형태를 보는 테스트로는 드러나지 않으므로 **조각마다** 쿼리 수를 따로 센다.
|
||||
*
|
||||
* 특정 시점의 쿼리 수를 숫자로 박아 두면 관계 하나만 추가해도 깨져 유지되지 않는다.
|
||||
* 대신 **행 수를 늘려도 쿼리 수가 늘지 않는다** 를 단언한다 — 그것이 N+1 의 정의다.
|
||||
*
|
||||
* @scenario case=list_query_count
|
||||
*
|
||||
* @effects shop_home_popular_query_count_stable,
|
||||
* shop_home_new_query_count_stable,
|
||||
* shop_home_recent_query_count_stable
|
||||
*/
|
||||
class ShopHomeQueryCountRegressionTest extends ModuleTestCase
|
||||
{
|
||||
use CountsQueries;
|
||||
|
||||
/**
|
||||
* 진열 중인 상품을 원하는 수만큼 만듭니다.
|
||||
*
|
||||
* @param int $count 생성할 수
|
||||
* @param string $prefix 상품 코드 접두
|
||||
* @return array<int, int> 생성된 상품 ID 목록
|
||||
*/
|
||||
private function seedProducts(int $count, string $prefix): array
|
||||
{
|
||||
$ids = [];
|
||||
|
||||
for ($i = 0; $i < $count; $i++) {
|
||||
$ids[] = Product::create([
|
||||
'product_code' => $prefix.'-'.$i,
|
||||
'name' => ['ko' => '상품 '.$prefix.$i],
|
||||
'selling_price' => 1000 + $i,
|
||||
'stock_quantity' => 10,
|
||||
'sales_status' => 'on_sale',
|
||||
'display_status' => 'visible',
|
||||
])->id;
|
||||
}
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* 인기 상품 섹션: 상품 수가 늘어도 쿼리 수가 늘지 않는지 확인
|
||||
*
|
||||
* 판매량 집계가 상품마다 상관 서브쿼리로 나가면 여기서 드러난다.
|
||||
*
|
||||
* @effects shop_home_popular_query_count_stable
|
||||
*/
|
||||
public function test_popular_section_query_count_is_stable(): void
|
||||
{
|
||||
$repository = app(ProductRepositoryInterface::class);
|
||||
$this->seedProducts(5, 'HOME-POP-A');
|
||||
|
||||
$this->assertQueryCountStableAsDataGrows(
|
||||
measure: fn () => $repository->getPopularProducts(10),
|
||||
grow: fn () => $this->seedProducts(10, 'HOME-POP-B'),
|
||||
context: '쇼핑 첫 화면 인기 상품',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 신상품 섹션: 상품 수가 늘어도 쿼리 수가 늘지 않는지 확인
|
||||
*
|
||||
* @effects shop_home_new_query_count_stable
|
||||
*/
|
||||
public function test_new_section_query_count_is_stable(): void
|
||||
{
|
||||
$repository = app(ProductRepositoryInterface::class);
|
||||
$this->seedProducts(5, 'HOME-NEW-A');
|
||||
|
||||
$this->assertQueryCountStableAsDataGrows(
|
||||
measure: fn () => $repository->getNewProducts(10),
|
||||
grow: fn () => $this->seedProducts(10, 'HOME-NEW-B'),
|
||||
context: '쇼핑 첫 화면 신상품',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 최근 본 상품 섹션: 지목한 상품 수가 늘어도 쿼리 수가 늘지 않는지 확인
|
||||
*
|
||||
* 이 섹션은 화면이 보관한 ID 목록으로 조회한다. ID 마다 단건 조회가 나가면
|
||||
* 목록이 길어질수록 쿼리가 그만큼 늘어난다.
|
||||
*
|
||||
* @effects shop_home_recent_query_count_stable
|
||||
*/
|
||||
public function test_recent_section_query_count_is_stable(): void
|
||||
{
|
||||
$repository = app(ProductRepositoryInterface::class);
|
||||
$ids = $this->seedProducts(5, 'HOME-RECENT-A');
|
||||
|
||||
// measure 와 grow 가 같은 목록을 봐야 한다. 화살표 함수는 정의 시점 값을 붙잡으므로
|
||||
// 참조로 받지 않으면 두 번째 측정이 늘어나기 전 목록을 다시 재게 된다.
|
||||
$this->assertQueryCountStableAsDataGrows(
|
||||
measure: function () use ($repository, &$ids) {
|
||||
return $repository->findByIds($ids);
|
||||
},
|
||||
grow: function () use (&$ids) {
|
||||
$ids = array_merge($ids, $this->seedProducts(10, 'HOME-RECENT-B'));
|
||||
},
|
||||
context: '쇼핑 첫 화면 최근 본 상품',
|
||||
);
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature\Search;
|
||||
|
||||
use App\Search\SearchPagePolicy;
|
||||
use Modules\Sirsoft\Ecommerce\Services\ProductService;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 상품 검색의 커서 딥링크 회귀 테스트 (#519)
|
||||
*
|
||||
* 커서 판정은 코어({@see SearchPagePolicy})가 소유하지만, 그 판정에 페이지
|
||||
* 번호가 도달하지 않으면 규칙이 무력해진다. 기본값 1 이 적용돼 **모든 요청이 첫 페이지로
|
||||
* 판정**되고, `?page=3` 딥링크가 조용히 1 페이지를 돌려준다.
|
||||
*
|
||||
* 응답은 200 이고 형태도 정상이라 기능 테스트로는 드러나지 않는다. 어느 경로를 타는지
|
||||
* 자체를 단언해야 회귀가 잡힌다.
|
||||
*
|
||||
* @scenario case=search_cursor_page_propagation
|
||||
*
|
||||
* @effects search_deep_page_link_keeps_offset,
|
||||
* search_first_page_starts_cursor
|
||||
*/
|
||||
class ProductSearchCursorDeepLinkTest extends ModuleTestCase
|
||||
{
|
||||
private ProductService $productService;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->productService = app(ProductService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커서 없이 깊은 페이지를 지목한 요청이 offset 을 유지하는지 확인
|
||||
*
|
||||
* 커서로 바꿔 버리면 링크가 가리키던 자리를 잃고 첫 페이지가 열린다.
|
||||
*
|
||||
* @effects search_deep_page_link_keeps_offset
|
||||
*/
|
||||
public function test_deep_page_without_cursor_stays_on_offset(): void
|
||||
{
|
||||
// Given/When: 커서 없이 3 페이지를 직접 지목한 최신순 검색
|
||||
$result = $this->productService->searchByKeywordWithCursor(
|
||||
keyword: '커서키워드',
|
||||
sort: 'latest',
|
||||
categoryId: null,
|
||||
perPage: 10,
|
||||
cursor: null,
|
||||
page: 3
|
||||
);
|
||||
|
||||
// Then: 커서 경로를 타지 않는다 (호출자가 offset 경로로 내려간다)
|
||||
$this->assertNull(
|
||||
$result,
|
||||
'커서 없이 깊은 페이지를 지목한 요청은 offset 을 유지해야 한다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 첫 페이지는 커서가 없어도 커서 경로로 시작하는지 확인
|
||||
*
|
||||
* 서버는 커서 모드에서만 다음 커서를 내보낸다. 첫 페이지를 offset 으로 처리하면
|
||||
* 첫 커서가 만들어질 자리가 없어 화면이 영원히 offset 에 머문다.
|
||||
*
|
||||
* @effects search_first_page_starts_cursor
|
||||
*/
|
||||
public function test_first_page_starts_cursor_mode(): void
|
||||
{
|
||||
// Given/When: 커서 없는 1 페이지 최신순 검색
|
||||
$result = $this->productService->searchByKeywordWithCursor(
|
||||
keyword: '커서키워드',
|
||||
sort: 'latest',
|
||||
categoryId: null,
|
||||
perPage: 10,
|
||||
cursor: null,
|
||||
page: 1
|
||||
);
|
||||
|
||||
// Then: 커서 페이지네이터를 돌려준다
|
||||
$this->assertNotNull($result, '첫 페이지는 커서 시작점으로 읽어야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 관련도순은 페이지 번호와 무관하게 offset 을 유지하는지 확인
|
||||
*
|
||||
* 계산값(`_ft_score`) 정렬은 WHERE 경계로 쓸 수 없다.
|
||||
*
|
||||
* @effects search_deep_page_link_keeps_offset
|
||||
*/
|
||||
public function test_relevance_sort_never_uses_cursor(): void
|
||||
{
|
||||
foreach ([1, 3] as $page) {
|
||||
$this->assertNull(
|
||||
$this->productService->searchByKeywordWithCursor(
|
||||
keyword: '커서키워드',
|
||||
sort: 'relevance',
|
||||
categoryId: null,
|
||||
perPage: 10,
|
||||
cursor: null,
|
||||
page: $page
|
||||
),
|
||||
$page.' 페이지 관련도순은 커서를 쓸 수 없어야 한다'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Feature;
|
||||
|
||||
// 테스트 베이스 클래스 수동 require (autoload 전에 로드 필요)
|
||||
require_once __DIR__.'/../ModuleTestCase.php';
|
||||
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
use PHPUnit\Framework\Attributes\Test;
|
||||
|
||||
/**
|
||||
* 통합 조회의 단건 분류 응답 계약 테스트 (#519 F4)
|
||||
*
|
||||
* 분류 화면은 종전에 분류·분류트리·상품목록으로 요청을 세 번 냈다. 이를 통합 조회 하나로
|
||||
* 합치면서 단건 분류를 응답에 얹었다. 옮긴 것은 조립 위치뿐이므로, **개별 엔드포인트와
|
||||
* 같은 리소스·같은 키 집합**이어야 한다. 리소스가 어긋나면 화면 표현식이 조용히 빈 값을
|
||||
* 읽어 제목·설명·하위분류·이미지가 예외 없이 사라진다.
|
||||
*
|
||||
* @scenario case=storefront_category_contract
|
||||
*
|
||||
* @effects storefront_category_matches_single_endpoint,
|
||||
* storefront_without_slug_omits_category,
|
||||
* storefront_unknown_slug_returns_not_found
|
||||
*/
|
||||
class StorefrontCategoryContractTest extends ModuleTestCase
|
||||
{
|
||||
private Category $category;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->category = Category::create([
|
||||
'name' => ['ko' => '통합조회 분류'],
|
||||
'slug' => 'storefront-contract',
|
||||
'depth' => 0,
|
||||
'sort_order' => 1,
|
||||
'is_active' => true,
|
||||
'path' => '',
|
||||
]);
|
||||
|
||||
$this->category->update(['path' => (string) $this->category->id]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 통합 조회의 분류가 단건 엔드포인트와 같은 키 집합이어야 함
|
||||
*
|
||||
* @effects storefront_category_matches_single_endpoint
|
||||
*/
|
||||
#[Test]
|
||||
public function storefront_category_matches_single_endpoint(): void
|
||||
{
|
||||
$single = $this->getJson('/api/modules/sirsoft-ecommerce/categories/'.$this->category->slug);
|
||||
$single->assertOk();
|
||||
|
||||
$combined = $this->getJson(
|
||||
'/api/modules/sirsoft-ecommerce/storefront?category_slug='.$this->category->slug
|
||||
);
|
||||
$combined->assertOk();
|
||||
|
||||
$expected = $single->json('data');
|
||||
$actual = $combined->json('data.category');
|
||||
|
||||
$this->assertIsArray($actual, '통합 조회 응답에 분류가 없다 — 분류 화면이 제목조차 못 그린다.');
|
||||
|
||||
$missing = array_diff(array_keys($expected), array_keys($actual));
|
||||
$this->assertSame(
|
||||
[],
|
||||
$missing,
|
||||
'단건 엔드포인트에는 있고 통합 조회에는 없는 필드: '.implode(', ', $missing)
|
||||
);
|
||||
|
||||
$this->assertSame($expected, $actual, '같은 분류인데 두 경로의 응답이 다르다.');
|
||||
}
|
||||
|
||||
/**
|
||||
* 분류를 지정하지 않으면 분류 키가 비어야 함 (쇼핑 첫 화면 경로)
|
||||
*
|
||||
* @effects storefront_without_slug_omits_category
|
||||
*/
|
||||
#[Test]
|
||||
public function storefront_without_slug_omits_category(): void
|
||||
{
|
||||
$response = $this->getJson('/api/modules/sirsoft-ecommerce/storefront');
|
||||
|
||||
$response->assertOk();
|
||||
$this->assertNull($response->json('data.category'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 없는 분류를 가리키면 404 여야 함
|
||||
*
|
||||
* 200 으로 빈 화면을 내보내면 검색엔진이 존재하지 않는 분류 주소를 정상 페이지로 수집한다.
|
||||
*
|
||||
* @effects storefront_unknown_slug_returns_not_found
|
||||
*/
|
||||
#[Test]
|
||||
public function storefront_unknown_slug_returns_not_found(): void
|
||||
{
|
||||
$response = $this->getJson(
|
||||
'/api/modules/sirsoft-ecommerce/storefront?category_slug=no-such-category'
|
||||
);
|
||||
|
||||
$response->assertNotFound();
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,8 @@
|
||||
- 페이지 목록을 뒤쪽 페이지에서도 빠르게 열 수 있도록 조회 방식을 바꿨습니다. 예전에는 페이지가 뒤로 갈수록 건너뛰는 항목의 본문까지 함께 읽어 느려졌지만, 이제 현재 페이지의 항목만 본문을 읽습니다. 화면에 보이는 내용은 이전과 동일합니다. (#74 @jiwonpapa 님께서 제보해주셨습니다.)
|
||||
- 관리자 페이지 목록을 열 때 페이지 본문을 데이터베이스에서 읽지 않습니다. 목록은 제목·주소·발행 여부만 쓰는데 본문까지 함께 읽고 있었습니다. 본문이 긴 페이지가 많은 사이트일수록 목록을 여는 속도와 서버 메모리 사용이 개선되며, 화면에 보이는 내용은 이전과 동일합니다. (#76 @jordy-bitree 님께서 제보해주셨습니다.)
|
||||
- 발행 페이지 목록과 통합검색의 페이지 탭 정렬에 필요한 색인을 추가했습니다. 기존 사이트도 업데이트 시 자동으로 반영됩니다.
|
||||
- 페이지 검색이 조건에 맞는 페이지 전체를 읽어 온 뒤 화면에 보일 만큼만 잘라 내던 방식을 바꿨습니다. 이제 필요한 페이지 분량만 조회하므로, 페이지가 많은 사이트에서 검색이 빨라지고 메모리 사용량이 줄어듭니다.
|
||||
- 검색 결과가 아주 많으면 총 건수를 "N건 이상" 으로 표시하고, 다음 페이지 이동은 끝까지 열어 둡니다.
|
||||
- 페이지 검색 탭의 배지 숫자도 세지 못한 건수를 정확한 것처럼 표시하지 않습니다. 배지를 표시하지 않는 화면에서는 그 숫자를 세는 작업 자체를 건너뜁니다.
|
||||
- 관리자 페이지 목록의 총 건수도 일정 규모까지만 정확히 세고 그보다 많으면 "N건 이상" 으로 표시합니다. 페이지 이동은 끝까지 열려 있습니다.
|
||||
- 개선된 사이트맵 생성 기능을 사용하기 위해 이 모듈은 이제 코어 7.0.6 이상이 필요합니다.
|
||||
@@ -39,13 +41,7 @@
|
||||
- 통합검색에서 페이지 제목으로 찾을 수 없던 문제를 수정했습니다. 한국어·영어 어느 쪽 제목으로도, 제목의 일부만 입력해도 검색됩니다.
|
||||
- 통합검색의 페이지 결과에서 같은 시각에 등록된 페이지가 여러 건일 때 목록 순서가 흔들리던 문제를 수정했습니다.
|
||||
- 페이지 관리 목록에서 뒤쪽 페이지를 보던 중 정렬을 바꾸면 이전 페이지 번호에 그대로 머물러 엉뚱한 구간이 보이던 문제를 수정했습니다. 이제 정렬을 바꾸면 첫 페이지부터 보여줍니다.
|
||||
|
||||
- 페이지 관리 목록에서 페이지가 아주 많아 총 건수를 끝까지 세지 못하면 "1페이지뿐" 으로 표시되어 뒤쪽 페이지를 볼 수 없던 문제를 수정했습니다.
|
||||
### Changed
|
||||
|
||||
- 페이지 검색이 조건에 맞는 페이지 전체를 읽어 온 뒤 화면에 보일 만큼만 잘라 내던 방식을 바꿨습니다. 이제 필요한 페이지 분량만 조회하므로, 페이지가 많은 사이트에서 검색이 빨라지고 메모리 사용량이 줄어듭니다.
|
||||
- 검색 결과가 아주 많으면 총 건수를 "N건 이상" 으로 표시하고, 다음 페이지 이동은 끝까지 열어 둡니다.
|
||||
- 발행 페이지 목록의 정렬 색인을 추가했습니다. 기존 사이트도 업데이트 시 자동으로 반영됩니다.
|
||||
|
||||
## [1.0.1] - 2026-07-08
|
||||
|
||||
|
||||
@@ -130,9 +130,11 @@ class SearchPagesListener implements HookListenerInterface
|
||||
|
||||
// 커서를 받았고 그 정렬을 커서로 처리할 수 있으면 키셋으로 응답한다.
|
||||
// 전체 탭은 미리보기 몇 건뿐이라 깊은 페이지가 없어 대상이 아니다.
|
||||
// 페이지 번호를 함께 넘겨 커서 없이 깊은 페이지를 지목한 딥링크를 코어가 가려내게
|
||||
// 한다 — 넘기지 않으면 기본값 1 이 적용돼 그 링크가 첫 페이지로 되돌아간다.
|
||||
$cursorPage = $isAllTab
|
||||
? null
|
||||
: $this->pageService->searchByKeywordWithCursor($q, $sort, $perPage, $context['cursor'] ?? null);
|
||||
: $this->pageService->searchByKeywordWithCursor($q, $sort, $perPage, $context['cursor'] ?? null, $pageNumber);
|
||||
|
||||
if ($cursorPage !== null) {
|
||||
$results['pages'] = SearchCategoryPayload::fromCursor(
|
||||
|
||||
@@ -424,17 +424,19 @@ class PageService
|
||||
* @param string $sort 정렬 옵션
|
||||
* @param int $perPage 페이지당 항목 수
|
||||
* @param string|null $cursor 인코딩된 커서 (첫 페이지면 null)
|
||||
* @param int $page 요청 페이지 번호 (커서 없이 깊은 페이지를 지목했는지 판정용)
|
||||
* @return CursorPaginator|null 커서 페이지 결과 (커서 적용 불가 시 null)
|
||||
*/
|
||||
public function searchByKeywordWithCursor(
|
||||
string $keyword,
|
||||
string $sort = 'latest',
|
||||
int $perPage = 10,
|
||||
?string $cursor = null
|
||||
?string $cursor = null,
|
||||
int $page = 1
|
||||
): ?CursorPaginator {
|
||||
$sortKeys = SearchPagePolicy::sortKeys($sort, self::SEARCH_SORT_MAP);
|
||||
|
||||
if (! SearchPagePolicy::usesCursor($cursor, $sortKeys, self::SEARCH_CURSOR_COLUMNS)) {
|
||||
if (! SearchPagePolicy::usesCursor($cursor, $sortKeys, self::SEARCH_CURSOR_COLUMNS, $page)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Page\Tests\Feature\Search;
|
||||
|
||||
use App\Search\SearchPagePolicy;
|
||||
use Modules\Sirsoft\Page\Services\PageService;
|
||||
use Modules\Sirsoft\Page\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 페이지 검색의 커서 딥링크 회귀 테스트 (#519)
|
||||
*
|
||||
* 커서 판정은 코어({@see SearchPagePolicy})가 소유하지만, 그 판정에 페이지
|
||||
* 번호가 도달하지 않으면 규칙이 무력해진다. 기본값 1 이 적용돼 **모든 요청이 첫 페이지로
|
||||
* 판정**되고, `?page=3` 딥링크가 조용히 1 페이지를 돌려준다.
|
||||
*
|
||||
* 응답은 200 이고 형태도 정상이라 기능 테스트로는 드러나지 않는다.
|
||||
*
|
||||
* @scenario case=search_cursor_page_propagation
|
||||
*
|
||||
* @effects search_deep_page_link_keeps_offset,
|
||||
* search_first_page_starts_cursor
|
||||
*/
|
||||
class PageSearchCursorDeepLinkTest extends ModuleTestCase
|
||||
{
|
||||
private PageService $pageService;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->pageService = app(PageService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 커서 없이 깊은 페이지를 지목한 요청이 offset 을 유지하는지 확인
|
||||
*
|
||||
* @effects search_deep_page_link_keeps_offset
|
||||
*/
|
||||
public function test_deep_page_without_cursor_stays_on_offset(): void
|
||||
{
|
||||
// Given/When: 커서 없이 3 페이지를 직접 지목한 최신순 검색
|
||||
$result = $this->pageService->searchByKeywordWithCursor(
|
||||
keyword: '커서키워드',
|
||||
sort: 'latest',
|
||||
perPage: 10,
|
||||
cursor: null,
|
||||
page: 3
|
||||
);
|
||||
|
||||
// Then: 커서 경로를 타지 않는다
|
||||
$this->assertNull(
|
||||
$result,
|
||||
'커서 없이 깊은 페이지를 지목한 요청은 offset 을 유지해야 한다'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 첫 페이지는 커서가 없어도 커서 경로로 시작하는지 확인
|
||||
*
|
||||
* @effects search_first_page_starts_cursor
|
||||
*/
|
||||
public function test_first_page_starts_cursor_mode(): void
|
||||
{
|
||||
// Given/When: 커서 없는 1 페이지 최신순 검색
|
||||
$result = $this->pageService->searchByKeywordWithCursor(
|
||||
keyword: '커서키워드',
|
||||
sort: 'latest',
|
||||
perPage: 10,
|
||||
cursor: null,
|
||||
page: 1
|
||||
);
|
||||
|
||||
// Then: 커서 페이지네이터를 돌려준다
|
||||
$this->assertNotNull($result, '첫 페이지는 커서 시작점으로 읽어야 한다');
|
||||
}
|
||||
|
||||
/**
|
||||
* 관련도순은 페이지 번호와 무관하게 offset 을 유지하는지 확인
|
||||
*
|
||||
* @effects search_deep_page_link_keeps_offset
|
||||
*/
|
||||
public function test_relevance_sort_never_uses_cursor(): void
|
||||
{
|
||||
foreach ([1, 3] as $page) {
|
||||
$this->assertNull(
|
||||
$this->pageService->searchByKeywordWithCursor(
|
||||
keyword: '커서키워드',
|
||||
sort: 'relevance',
|
||||
perPage: 10,
|
||||
cursor: null,
|
||||
page: $page
|
||||
),
|
||||
$page.' 페이지 관련도순은 커서를 쓸 수 없어야 한다'
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user