fix(core,board,ecommerce,page): 중첩 리소스 스코프·계층 무결성 결함 12건 일괄 수정
중첩 라우트의 상위 리소스 ID 를 조회 스코프에 반영하지 않아 A 의 경로로 B 의 하위 리소스를 읽거나 변경할 수 있었다. 방어 위치를 Repository where 절(SSoT)로 통일하고 컨트롤러 사후 비교에 의존하지 않게 했다. 같은 리소스의 형제 엔드포인트가 서로 다른 강도로 검증하던 부분도 맞췄다. 계층 리소스는 자기 자신·자손을 부모로 지정하는 순환을 검증 계층에서 차단하고, 검증을 우회하는 경로(시더/훅/오염 데이터)를 위해 path 재귀에 방문 ID 가드를 뒀다. 설정값이 정하는 깊이 상한을 Service 가 리터럴로 재클램프하던 부분을 제거해 게시판 설정이 실제로 적용되게 했다. 쓰기 경로는 validated 기준으로 좁혀 FormRequest 미정의 필드가 fillable 로 새지 않게 했다. 기존 오염 데이터는 업그레이드 스텝이 정리한다(삭제 없이 최상위로 이동). 재발 방지로 audit 룰 3종을 추가하고, 규정 문서와 트러블슈팅 사례를 함께 갱신했다. 공개 이슈: gnuboard/g7
This commit is contained in:
1 parent
9dda22f8e4
commit
abb40ad210
74 files changed
+3880
-192
No files matched your search
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* 카테고리 조작 실패 예외
|
||||
*
|
||||
* 카테고리를 찾을 수 없거나, 하위 카테고리·연결 상품이 있어 삭제할 수 없는 경우에 사용합니다.
|
||||
* 컨트롤러의 기존 catch (\Exception) 흐름에서 400 응답으로 처리됩니다.
|
||||
*/
|
||||
class CategoryOperationException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* CategoryOperationException 생성자
|
||||
*
|
||||
* @param string $messageKey 다국어 메시지 키 (sirsoft-ecommerce::exceptions.*)
|
||||
* @param array<string, mixed> $replace 메시지 치환 파라미터
|
||||
*/
|
||||
public function __construct(string $messageKey, array $replace = [])
|
||||
{
|
||||
parent::__construct(__($messageKey, $replace));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Exceptions;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
/**
|
||||
* 하위 리소스가 요청 경로의 상위 리소스에 속하지 않을 때 발생하는 예외
|
||||
*
|
||||
* 주문 옵션이 다른 주문에 속하거나, 상품 이미지가 다른 상품에 속하는 등
|
||||
* 중첩 리소스의 소유권이 어긋난 경우에 사용합니다.
|
||||
* 컨트롤러의 기존 catch (\Exception) 흐름에서 400 응답으로 처리됩니다.
|
||||
*/
|
||||
class ResourceScopeMismatchException extends RuntimeException
|
||||
{
|
||||
/**
|
||||
* ResourceScopeMismatchException 생성자
|
||||
*
|
||||
* @param string $messageKey 다국어 메시지 키 (sirsoft-ecommerce::exceptions.*)
|
||||
*/
|
||||
public function __construct(string $messageKey)
|
||||
{
|
||||
parent::__construct(__($messageKey));
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,10 @@ use Exception;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\PaymentAmountMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ResourceScopeMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkChangeOrderOptionStatusRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\BulkUpdateOrdersRequest;
|
||||
use Modules\Sirsoft\Ecommerce\Http\Requests\Admin\CancelOrderRequest;
|
||||
@@ -221,6 +223,7 @@ class OrderController extends AdminBaseController
|
||||
$result = $this->orderOptionService->bulkChangeStatusWithQuantity(
|
||||
$validated['items'],
|
||||
$newStatus,
|
||||
$order->id,
|
||||
$metadata
|
||||
);
|
||||
|
||||
@@ -235,6 +238,15 @@ class OrderController extends AdminBaseController
|
||||
'messages.orders.option_status_change_failed',
|
||||
422
|
||||
);
|
||||
} catch (ResourceScopeMismatchException $e) {
|
||||
// 상위 주문 스코프 불일치는 잘못된 요청이다. FormRequest 가 1차로 422 를 내지만,
|
||||
// 훅·내부 호출로 Service 2차 방어가 트립한 경우에도 500 이 아닌 400 으로 응답해
|
||||
// 같은 모듈의 ProductController::setThumbnail 과 계약을 일치시킨다.
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
'messages.orders.option_status_change_failed',
|
||||
400
|
||||
);
|
||||
} catch (Exception $e) {
|
||||
return ResponseHelper::moduleError(
|
||||
'sirsoft-ecommerce',
|
||||
|
||||
+8
-1
@@ -32,9 +32,16 @@ class BulkChangeOrderOptionStatusRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
// 경로의 주문에 속한 옵션만 허용 (교차 주문 옵션 변경 차단)
|
||||
$orderId = $this->route('order')?->id;
|
||||
|
||||
return [
|
||||
'items' => ['required', 'array', 'min:1'],
|
||||
'items.*.option_id' => ['required', 'integer', Rule::exists(OrderOption::class, 'id')],
|
||||
'items.*.option_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists(OrderOption::class, 'id')->where('order_id', $orderId),
|
||||
],
|
||||
'items.*.quantity' => ['required', 'integer', 'min:1'],
|
||||
'status' => ['required', 'string', Rule::in(OrderStatusEnum::values())],
|
||||
'carrier_id' => ['nullable', 'integer', Rule::exists(ShippingCarrier::class, 'id')],
|
||||
|
||||
+9
-4
@@ -8,6 +8,7 @@ use App\Rules\TranslatableField;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Rules\NotCircularCategoryParent;
|
||||
|
||||
/**
|
||||
* 카테고리 생성 요청
|
||||
@@ -18,6 +19,8 @@ class CreateCategoryRequest extends FormRequest
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 권한 검증 결과 (항상 true)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -43,14 +46,16 @@ class CreateCategoryRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 필드별 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
$rules = [
|
||||
'name' => ['required', 'array', new LocaleRequiredTranslatable(maxLength: 100)],
|
||||
'description' => ['nullable', 'array', new TranslatableField()],
|
||||
'parent_id' => ['nullable', Rule::exists(Category::class, 'id')],
|
||||
'description' => ['nullable', 'array', new TranslatableField],
|
||||
// 생성 시에는 자기 자신이 아직 없어 순환이 불가하나, 수정 요청과 규칙 구성을
|
||||
// 동일하게 유지해 두 엔드포인트의 검증 강도가 갈라지는 것을 막는다.
|
||||
'parent_id' => ['nullable', Rule::exists(Category::class, 'id'), new NotCircularCategoryParent],
|
||||
'slug' => [
|
||||
'required',
|
||||
'string',
|
||||
@@ -71,7 +76,7 @@ class CreateCategoryRequest extends FormRequest
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, string> 규칙별 다국어 에러 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+37
-2
@@ -5,7 +5,9 @@ namespace Modules\Sirsoft\Ecommerce\Http\Requests\Admin;
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Rules\NotCircularCategoryParent;
|
||||
|
||||
/**
|
||||
* 카테고리 순서 변경 요청
|
||||
@@ -20,6 +22,8 @@ class ReorderCategoriesRequest extends FormRequest
|
||||
{
|
||||
/**
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* @return bool 권한 검증 결과 (항상 true)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -29,7 +33,7 @@ class ReorderCategoriesRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 필드별 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -46,10 +50,41 @@ class ReorderCategoriesRequest extends FormRequest
|
||||
return HookManager::applyFilters('sirsoft-ecommerce.category.reorder_validation_rules', $rules, $this);
|
||||
}
|
||||
|
||||
/**
|
||||
* 추가 검증 — 자식으로 지정된 카테고리가 대상 부모의 조상이면 순환이 된다.
|
||||
*
|
||||
* 개별 이동 단위로 현재 DB 상태와 대조한다. 한 요청 안의 여러 이동이 누적되어 만들어지는
|
||||
* 순환은 CategoryService 의 방문 ID 가드가 최종 방어한다.
|
||||
*
|
||||
* @param Validator $validator 검증기
|
||||
*/
|
||||
public function withValidator($validator): void
|
||||
{
|
||||
$validator->after(function ($validator) {
|
||||
foreach ((array) $this->input('child_menus', []) as $parentId => $children) {
|
||||
foreach ((array) $children as $index => $child) {
|
||||
$childId = $child['id'] ?? null;
|
||||
|
||||
if ($childId === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attribute = "child_menus.{$parentId}.{$index}.id";
|
||||
|
||||
(new NotCircularCategoryParent((int) $childId))->validate(
|
||||
$attribute,
|
||||
(int) $parentId,
|
||||
fn (string $message) => $validator->errors()->add($attribute, $message)
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, string> 규칙별 다국어 에러 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
|
||||
+12
-5
@@ -8,6 +8,7 @@ use App\Rules\TranslatableField;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Rules\NotCircularCategoryParent;
|
||||
|
||||
/**
|
||||
* 카테고리 수정 요청
|
||||
@@ -18,6 +19,8 @@ class UpdateCategoryRequest extends FormRequest
|
||||
* 사용자가 이 요청을 수행할 권한이 있는지 확인
|
||||
*
|
||||
* 권한 체크는 라우트의 permission 미들웨어에서 수행됩니다.
|
||||
*
|
||||
* @return bool 권한 검증 결과 (항상 true)
|
||||
*/
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -43,7 +46,7 @@ class UpdateCategoryRequest extends FormRequest
|
||||
/**
|
||||
* 요청에 적용할 검증 규칙
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, mixed> 필드별 검증 규칙
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
@@ -51,8 +54,12 @@ class UpdateCategoryRequest extends FormRequest
|
||||
|
||||
$rules = [
|
||||
'name' => ['required', 'array', new LocaleRequiredTranslatable(maxLength: 100)],
|
||||
'description' => ['nullable', 'array', new TranslatableField()],
|
||||
'parent_id' => ['nullable', Rule::exists(Category::class, 'id')],
|
||||
'description' => ['nullable', 'array', new TranslatableField],
|
||||
'parent_id' => [
|
||||
'nullable',
|
||||
Rule::exists(Category::class, 'id'),
|
||||
new NotCircularCategoryParent($categoryId !== null ? (int) $categoryId : null),
|
||||
],
|
||||
'slug' => [
|
||||
'required',
|
||||
'string',
|
||||
@@ -73,7 +80,7 @@ class UpdateCategoryRequest extends FormRequest
|
||||
/**
|
||||
* 검증 오류 메시지 커스터마이징
|
||||
*
|
||||
* @return array
|
||||
* @return array<string, string> 규칙별 다국어 에러 메시지
|
||||
*/
|
||||
public function messages(): array
|
||||
{
|
||||
@@ -85,4 +92,4 @@ class UpdateCategoryRequest extends FormRequest
|
||||
'parent_id.exists' => __('sirsoft-ecommerce::validation.category.parent_not_found'),
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Rules;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
|
||||
/**
|
||||
* 카테고리 순환 참조를 방지하는 검증 규칙
|
||||
*
|
||||
* 카테고리를 이동할 때 자기 자신 또는 자신의 자손(descendant)을 부모로 지정하는 것을 막습니다.
|
||||
* 순환이 만들어지면 path 재계산 재귀가 종료되지 않아 요청이 실패하고, 해당 노드가 트리에서
|
||||
* 사라져 관리자 화면으로 복구할 수 없게 됩니다.
|
||||
*
|
||||
* 자손 판정은 머티리얼라이즈드 path 컬럼의 prefix 매칭(쿼리 1회)으로 수행하며,
|
||||
* path 가 비어 있는 레거시 행에 대비해 parent_id 재귀 fallback 을 둡니다.
|
||||
*/
|
||||
class NotCircularCategoryParent implements ValidationRule
|
||||
{
|
||||
/**
|
||||
* NotCircularCategoryParent 생성자
|
||||
*
|
||||
* @param int|null $categoryId 이동하려는 카테고리 ID (생성 시 null → 자기참조 불가하므로 통과)
|
||||
*/
|
||||
public function __construct(
|
||||
private ?int $categoryId = null
|
||||
) {}
|
||||
|
||||
/**
|
||||
* 검증을 수행합니다.
|
||||
*
|
||||
* @param string $attribute 검증 대상 속성명
|
||||
* @param mixed $value 검증 대상 값 (새 부모 ID)
|
||||
* @param Closure $fail 실패 콜백
|
||||
*/
|
||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||
{
|
||||
// 최상위로 이동 → 순환 없음
|
||||
if ($value === null || $value === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 신규 생성 → 자기 자신이 아직 없으므로 순환 불가
|
||||
if ($this->categoryId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$newParentId = (int) $value;
|
||||
|
||||
if ($newParentId === $this->categoryId) {
|
||||
$fail(__('sirsoft-ecommerce::validation.category.parent_id.self'));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->isDescendant($newParentId)) {
|
||||
$fail(__('sirsoft-ecommerce::validation.category.parent_id.circular'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 지정한 카테고리가 이동 대상의 자손인지 판정합니다.
|
||||
*
|
||||
* @param int $candidateId 새 부모 후보 카테고리 ID
|
||||
* @return bool 자손이면 true
|
||||
*/
|
||||
private function isDescendant(int $candidateId): bool
|
||||
{
|
||||
$self = Category::find($this->categoryId);
|
||||
|
||||
if (! $self) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// path 가 채워져 있으면 prefix 매칭 1회로 판정
|
||||
if (! empty($self->path)) {
|
||||
return Category::where('id', $candidateId)
|
||||
->where('path', 'like', $self->path.'/%')
|
||||
->exists();
|
||||
}
|
||||
|
||||
// path 가 비어 있는 레거시 행 — parent_id 를 거슬러 올라가며 판정
|
||||
return $this->hasAncestor($candidateId, $this->categoryId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 후보 카테고리의 조상 중에 대상 ID 가 있는지 확인합니다.
|
||||
*
|
||||
* @param int $candidateId 탐색 시작 카테고리 ID
|
||||
* @param int $ancestorId 찾으려는 조상 ID
|
||||
* @return bool 조상에 포함되면 true
|
||||
*/
|
||||
private function hasAncestor(int $candidateId, int $ancestorId): bool
|
||||
{
|
||||
$visited = [];
|
||||
$currentId = $candidateId;
|
||||
|
||||
while ($currentId !== null && ! isset($visited[$currentId])) {
|
||||
$visited[$currentId] = true;
|
||||
|
||||
$parentId = Category::where('id', $currentId)->value('parent_id');
|
||||
|
||||
if ($parentId === null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((int) $parentId === $ancestorId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$currentId = (int) $parentId;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ namespace Modules\Sirsoft\Ecommerce\Services;
|
||||
use App\Extension\HookManager;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\CategoryOperationException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Category;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CategoryImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\CategoryRepositoryInterface;
|
||||
@@ -22,8 +24,8 @@ class CategoryService
|
||||
/**
|
||||
* 계층형 카테고리 목록 조회
|
||||
*
|
||||
* @param array $filters 필터 조건
|
||||
* @return Collection
|
||||
* @param array $filters 필터 조건
|
||||
* @return Collection 계층 구조가 적용된 카테고리 컬렉션
|
||||
*/
|
||||
public function getHierarchicalCategories(array $filters = []): Collection
|
||||
{
|
||||
@@ -34,9 +36,9 @@ class CategoryService
|
||||
$filters = HookManager::applyFilters('sirsoft-ecommerce.category.filter_list_query', $filters);
|
||||
|
||||
// hierarchical 플래그가 true이면 전체 트리 구조 반환
|
||||
if (!empty($filters['hierarchical'])) {
|
||||
if (! empty($filters['hierarchical'])) {
|
||||
$categories = Category::getTree(null, $filters['is_active'] ?? false);
|
||||
} elseif (!empty($filters['flat'])) {
|
||||
} elseif (! empty($filters['flat'])) {
|
||||
// flat 플래그가 true이면 평면 리스트 반환 (TagInput 등에 사용)
|
||||
$categories = $this->repository->getFlatList($filters, ['images']);
|
||||
} else {
|
||||
@@ -57,7 +59,7 @@ class CategoryService
|
||||
*
|
||||
* 프론트엔드 사용자 페이지에서 카테고리 필터에 사용합니다.
|
||||
*
|
||||
* @return Collection
|
||||
* @return Collection 활성 카테고리로만 구성된 공개 트리
|
||||
*/
|
||||
public function getPublicCategoryTree(): Collection
|
||||
{
|
||||
@@ -75,8 +77,8 @@ class CategoryService
|
||||
/**
|
||||
* slug로 공개 카테고리 조회 (활성 카테고리만)
|
||||
*
|
||||
* @param string $slug 카테고리 slug
|
||||
* @return Category|null
|
||||
* @param string $slug 카테고리 slug
|
||||
* @return Category|null 활성 카테고리 또는 null (비활성·미존재)
|
||||
*/
|
||||
public function getPublicCategoryBySlug(string $slug): ?Category
|
||||
{
|
||||
@@ -104,8 +106,8 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 상세 조회
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category|null
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category|null 카테고리 모델 또는 null (미존재)
|
||||
*/
|
||||
public function getCategory(int $id): ?Category
|
||||
{
|
||||
@@ -132,8 +134,8 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 생성
|
||||
*
|
||||
* @param array $data 카테고리 데이터
|
||||
* @return Category
|
||||
* @param array $data 카테고리 데이터
|
||||
* @return Category 생성된 카테고리 모델
|
||||
*/
|
||||
public function createCategory(array $data): Category
|
||||
{
|
||||
@@ -150,7 +152,7 @@ class CategoryService
|
||||
$data['path'] = $depthAndPath['path'];
|
||||
|
||||
// sort_order가 없으면 자동 계산
|
||||
if (!isset($data['sort_order'])) {
|
||||
if (! isset($data['sort_order'])) {
|
||||
$data['sort_order'] = $this->repository->getNextSortOrder($data['parent_id'] ?? null);
|
||||
}
|
||||
|
||||
@@ -162,7 +164,7 @@ class CategoryService
|
||||
$this->updatePath($category);
|
||||
|
||||
// 이미지 처리 (temp_key 방식)
|
||||
if (!empty($data['temp_key'])) {
|
||||
if (! empty($data['temp_key'])) {
|
||||
$this->imageRepository->linkTempImages($data['temp_key'], $category->id);
|
||||
}
|
||||
|
||||
@@ -178,16 +180,16 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 수정
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @param array $data 수정할 데이터
|
||||
* @return Category
|
||||
* @param int $id 카테고리 ID
|
||||
* @param array $data 수정할 데이터
|
||||
* @return Category 수정된 카테고리 모델
|
||||
*/
|
||||
public function updateCategory(int $id, array $data): Category
|
||||
{
|
||||
$category = $this->repository->findById($id);
|
||||
|
||||
if (!$category) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]));
|
||||
if (! $category) {
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]);
|
||||
}
|
||||
|
||||
// Before 훅
|
||||
@@ -201,7 +203,8 @@ class CategoryService
|
||||
|
||||
$category = DB::transaction(function () use ($category, $data) {
|
||||
// parent_id가 변경되었으면 depth/path 재계산
|
||||
if (isset($data['parent_id']) && $data['parent_id'] !== $category->parent_id) {
|
||||
// 루트로 이동(parent_id = null)도 변경이므로 array_key_exists 사용 (isset 은 null 을 미설정으로 취급)
|
||||
if (array_key_exists('parent_id', $data) && $data['parent_id'] !== $category->parent_id) {
|
||||
$depthAndPath = $this->calculateDepthAndPath($data['parent_id']);
|
||||
$data['depth'] = $depthAndPath['depth'];
|
||||
$data['path'] = $depthAndPath['path'];
|
||||
@@ -211,15 +214,15 @@ class CategoryService
|
||||
$categoryData = collect($data)->except(['temp_key'])->toArray();
|
||||
$category = $this->repository->update($category->id, $categoryData);
|
||||
|
||||
// path 업데이트 (parent_id 변경 시)
|
||||
if (isset($data['parent_id'])) {
|
||||
// path 업데이트 (parent_id 변경 시 — 루트 이동 포함)
|
||||
if (array_key_exists('parent_id', $data)) {
|
||||
$this->updatePath($category);
|
||||
// 하위 카테고리들의 path도 재계산
|
||||
$this->updateDescendantsPaths($category);
|
||||
}
|
||||
|
||||
// 이미지 처리
|
||||
if (!empty($data['temp_key'])) {
|
||||
if (! empty($data['temp_key'])) {
|
||||
$this->imageRepository->linkTempImages($data['temp_key'], $category->id);
|
||||
}
|
||||
|
||||
@@ -235,33 +238,34 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 삭제
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @param int $id 카테고리 ID
|
||||
* @return array 삭제 결과 정보
|
||||
* @throws \Exception
|
||||
*
|
||||
* @throws CategoryOperationException 카테고리 미존재 또는 삭제 불가 조건
|
||||
*/
|
||||
public function deleteCategory(int $id): array
|
||||
{
|
||||
$category = $this->repository->findById($id);
|
||||
|
||||
if (!$category) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]));
|
||||
if (! $category) {
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]);
|
||||
}
|
||||
|
||||
// 하위 카테고리 확인
|
||||
if ($this->repository->hasChildren($id)) {
|
||||
$childrenCount = $category->children()->count();
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_has_children', [
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_has_children', [
|
||||
'category_id' => $id,
|
||||
'count' => $childrenCount,
|
||||
]));
|
||||
]);
|
||||
}
|
||||
|
||||
// 연결된 상품 수 확인 - 상품이 있으면 삭제 차단
|
||||
$productsCount = $this->repository->getProductCount($id);
|
||||
if ($productsCount > 0) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_has_products', [
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_has_products', [
|
||||
'count' => $productsCount,
|
||||
]));
|
||||
]);
|
||||
}
|
||||
|
||||
// Before 훅
|
||||
@@ -286,7 +290,7 @@ class CategoryService
|
||||
/**
|
||||
* depth와 Materialized Path를 계산합니다.
|
||||
*
|
||||
* @param int|null $parentId 부모 카테고리 ID
|
||||
* @param int|null $parentId 부모 카테고리 ID
|
||||
* @return array ['depth' => int, 'path' => string]
|
||||
*/
|
||||
private function calculateDepthAndPath(?int $parentId): array
|
||||
@@ -297,7 +301,7 @@ class CategoryService
|
||||
|
||||
$parent = $this->repository->findById($parentId);
|
||||
|
||||
if (!$parent) {
|
||||
if (! $parent) {
|
||||
return ['depth' => 0, 'path' => ''];
|
||||
}
|
||||
|
||||
@@ -309,9 +313,6 @@ class CategoryService
|
||||
|
||||
/**
|
||||
* 카테고리의 path를 업데이트합니다 (ID 포함).
|
||||
*
|
||||
* @param Category $category
|
||||
* @return void
|
||||
*/
|
||||
private function updatePath(Category $category): void
|
||||
{
|
||||
@@ -329,39 +330,52 @@ class CategoryService
|
||||
/**
|
||||
* 하위 카테고리들의 path를 재계산합니다 (재귀).
|
||||
*
|
||||
* @param Category $category
|
||||
* @return void
|
||||
* 검증(NotCircularCategoryParent)을 우회한 경로(시더/훅/기존 오염 데이터)에서
|
||||
* 순환 참조가 남아 있어도 무한 재귀 대신 유한 실패로 끝나도록 방문 ID 를 추적한다.
|
||||
*
|
||||
* @param Category $category 기준 카테고리
|
||||
* @param array<int, bool> $visited 방문한 카테고리 ID 집합 (재귀 내부 전달용)
|
||||
*/
|
||||
private function updateDescendantsPaths(Category $category): void
|
||||
private function updateDescendantsPaths(Category $category, array $visited = []): void
|
||||
{
|
||||
$children = $category->children;
|
||||
$visited[$category->id] = true;
|
||||
|
||||
foreach ($category->children as $child) {
|
||||
if (isset($visited[$child->id])) {
|
||||
Log::warning('[sirsoft-ecommerce] 카테고리 순환 참조 감지 — path 재계산 중단', [
|
||||
'category_id' => $category->id,
|
||||
'child_id' => $child->id,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($children as $child) {
|
||||
$this->updatePath($child);
|
||||
$this->updateDescendantsPaths($child); // 재귀 호출
|
||||
$this->updateDescendantsPaths($child, $visited);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 카테고리 상태 토글
|
||||
*
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category
|
||||
* @throws \Exception
|
||||
* @param int $id 카테고리 ID
|
||||
* @return Category 상태가 토글된 카테고리 모델
|
||||
*
|
||||
* @throws CategoryOperationException 카테고리 미존재 또는 삭제 불가 조건
|
||||
*/
|
||||
public function toggleStatus(int $id): Category
|
||||
{
|
||||
$category = $this->repository->findById($id);
|
||||
|
||||
if (!$category) {
|
||||
throw new \Exception(__('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]));
|
||||
if (! $category) {
|
||||
throw new CategoryOperationException('sirsoft-ecommerce::exceptions.category_not_found', ['category_id' => $id]);
|
||||
}
|
||||
|
||||
// Before 훅
|
||||
HookManager::doAction('sirsoft-ecommerce.category.before_toggle_status', $category);
|
||||
|
||||
$category = $this->repository->update($id, [
|
||||
'is_active' => !$category->is_active,
|
||||
'is_active' => ! $category->is_active,
|
||||
]);
|
||||
|
||||
// After 훅
|
||||
@@ -373,8 +387,7 @@ class CategoryService
|
||||
/**
|
||||
* 카테고리 순서 변경
|
||||
*
|
||||
* @param array $orders 순서 변경 데이터 [['id' => 1, 'parent_id' => null, 'sort_order' => 0], ...]
|
||||
* @return void
|
||||
* @param array $orders 순서 변경 데이터 [['id' => 1, 'parent_id' => null, 'sort_order' => 0], ...]
|
||||
*/
|
||||
public function reorder(array $orders): void
|
||||
{
|
||||
@@ -384,7 +397,7 @@ class CategoryService
|
||||
DB::transaction(function () use ($orders) {
|
||||
foreach ($orders as $order) {
|
||||
$category = $this->repository->findById($order['id']);
|
||||
if (!$category) {
|
||||
if (! $category) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use Modules\Sirsoft\Ecommerce\Enums\OrderOptionSourceTypeEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\OrderStatusEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\PaymentMethodEnum;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\OrderProcessingException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ResourceScopeMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\Order;
|
||||
use Modules\Sirsoft\Ecommerce\Models\OrderOption;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\MileageTransactionRepositoryInterface;
|
||||
@@ -295,18 +296,26 @@ class OrderOptionService
|
||||
*
|
||||
* @param array $items [{option_id, quantity}] 변경 대상
|
||||
* @param OrderStatusEnum $newStatus 변경할 상태
|
||||
* @param int $orderId 상위 주문 ID (옵션 소속 검증에 사용)
|
||||
* @param array $metadata 추가 정보
|
||||
* @return array 변경 결과
|
||||
*
|
||||
* @throws ResourceScopeMismatchException 옵션이 상위 주문에 속하지 않는 경우
|
||||
*/
|
||||
public function bulkChangeStatusWithQuantity(
|
||||
array $items,
|
||||
OrderStatusEnum $newStatus,
|
||||
int $orderId,
|
||||
array $metadata = []
|
||||
): array {
|
||||
// 스냅샷 캡처 (ChangeDetector용)
|
||||
$optionIds = collect($items)->pluck('option_id')->filter()->unique()->toArray();
|
||||
$snapshots = $this->orderOptionRepository->getSnapshotsByIds($optionIds);
|
||||
|
||||
// 상위 주문 스코프 2차 방어 — FormRequest 를 우회한 내부/훅 호출도 차단.
|
||||
// 선택 파라미터로 두면 신규 호출처가 빠뜨렸을 때 방어가 조용히 꺼지므로 필수로 받는다.
|
||||
$this->assertOptionsBelongToOrder($optionIds, $orderId);
|
||||
|
||||
// 결제완료(payment_complete) 목표 전이 시 본인인증(IDV) 정책 가드 (A8 / N4).
|
||||
// 관리자 주문상세 "주문상태 변경"(옵션 일괄변경)이 결제완료로 부모 주문을 전이시키는,
|
||||
// 실무에서 가장 흔한 결제승인 경로다. OrderService::update / bulkUpdate 와 동일하게
|
||||
@@ -351,8 +360,8 @@ class OrderOptionService
|
||||
|
||||
// 부모 주문 상태 동기화
|
||||
$orderIds = $this->orderOptionRepository->getOrderIdsByOptionIds($optionIds);
|
||||
foreach ($orderIds as $orderId) {
|
||||
$this->syncParentOrderStatus($orderId);
|
||||
foreach ($orderIds as $parentOrderId) {
|
||||
$this->syncParentOrderStatus($parentOrderId);
|
||||
}
|
||||
|
||||
// after 훅 (스냅샷 전달)
|
||||
@@ -365,6 +374,29 @@ class OrderOptionService
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* 주어진 옵션들이 모두 지정 주문에 속하는지 검증합니다.
|
||||
*
|
||||
* @param array<int, int> $optionIds 검증할 주문 옵션 ID 목록
|
||||
* @param int $orderId 상위 주문 ID
|
||||
*
|
||||
* @throws ResourceScopeMismatchException 하나라도 다른 주문에 속하는 경우
|
||||
*/
|
||||
private function assertOptionsBelongToOrder(array $optionIds, int $orderId): void
|
||||
{
|
||||
if ($optionIds === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$orderIds = $this->orderOptionRepository->getOrderIdsByOptionIds($optionIds);
|
||||
|
||||
foreach ($orderIds as $foundOrderId) {
|
||||
if ((int) $foundOrderId !== $orderId) {
|
||||
throw new ResourceScopeMismatchException('sirsoft-ecommerce::exceptions.order_option_not_in_order');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 옵션 금액 필드를 캡처합니다.
|
||||
*
|
||||
|
||||
@@ -11,6 +11,7 @@ use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
use Modules\Sirsoft\Ecommerce\Enums\ProductImageCollection;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ProductImageUploadLimitException;
|
||||
use Modules\Sirsoft\Ecommerce\Exceptions\ResourceScopeMismatchException;
|
||||
use Modules\Sirsoft\Ecommerce\Models\ProductImage;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductImageRepositoryInterface;
|
||||
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ProductRepositoryInterface;
|
||||
@@ -306,11 +307,19 @@ class ProductImageService
|
||||
* @param int $productId 상품 ID
|
||||
* @param int $imageId 이미지 ID
|
||||
* @return bool 성공 여부
|
||||
*
|
||||
* @throws ResourceScopeMismatchException 이미지가 해당 상품에 속하지 않는 경우
|
||||
*/
|
||||
public function setThumbnail(int $productId, int $imageId): bool
|
||||
{
|
||||
// 기존 대표 이미지 해제
|
||||
$images = $this->repository->getByProductId($productId);
|
||||
|
||||
// 대상 이미지가 이 상품에 속하는지 먼저 확인 (교차 상품 오염 차단)
|
||||
if ($images->firstWhere('id', $imageId) === null) {
|
||||
throw new ResourceScopeMismatchException('sirsoft-ecommerce::exceptions.product_image_not_in_product');
|
||||
}
|
||||
|
||||
// 기존 대표 이미지 해제
|
||||
foreach ($images as $image) {
|
||||
if ($image->is_thumbnail) {
|
||||
$this->repository->update($image->id, ['is_thumbnail' => false]);
|
||||
|
||||
@@ -60,6 +60,8 @@ return [
|
||||
'order_already_cancelled' => 'This order has already been cancelled.',
|
||||
'order_already_paid' => 'This order has already been paid.',
|
||||
'order_option_not_found' => 'Order option not found.',
|
||||
'order_option_not_in_order' => 'This order option does not belong to the specified order.',
|
||||
'product_image_not_in_product' => 'This image does not belong to the specified product.',
|
||||
'order_option_already_cancelled' => 'This order option has already been cancelled.',
|
||||
'order_option_already_confirmed' => 'This order option has already been confirmed.',
|
||||
'order_option_cannot_confirm' => 'Cannot confirm purchase in current status.',
|
||||
|
||||
@@ -454,6 +454,10 @@ return [
|
||||
'slug_unique' => 'This slug is already in use.',
|
||||
'slug_format' => 'The slug must start with a lowercase letter and contain only lowercase letters, numbers, and hyphens (-).',
|
||||
'parent_not_found' => 'Parent category not found.',
|
||||
'parent_id' => [
|
||||
'self' => 'A category cannot be its own parent.',
|
||||
'circular' => 'A descendant category cannot be set as the parent.',
|
||||
],
|
||||
],
|
||||
|
||||
// Product image validation messages
|
||||
|
||||
@@ -60,6 +60,8 @@ return [
|
||||
'order_already_cancelled' => '이미 취소된 주문입니다.',
|
||||
'order_already_paid' => '이미 결제가 완료된 주문입니다.',
|
||||
'order_option_not_found' => '주문 옵션을 찾을 수 없습니다.',
|
||||
'order_option_not_in_order' => '해당 주문에 속하지 않는 주문 옵션입니다.',
|
||||
'product_image_not_in_product' => '해당 상품에 속하지 않는 이미지입니다.',
|
||||
'order_option_already_cancelled' => '이미 취소된 주문 옵션입니다.',
|
||||
'order_option_already_confirmed' => '이미 구매확정된 주문 옵션입니다.',
|
||||
'order_option_cannot_confirm' => '현재 상태에서는 구매확정할 수 없습니다.',
|
||||
|
||||
@@ -454,6 +454,10 @@ return [
|
||||
'slug_unique' => '이미 사용중인 슬러그입니다.',
|
||||
'slug_format' => '슬러그는 영문 소문자로 시작해야 하며, 영문 소문자/숫자/하이픈(-)만 사용 가능합니다.',
|
||||
'parent_not_found' => '상위 카테고리를 찾을 수 없습니다.',
|
||||
'parent_id' => [
|
||||
'self' => '자기 자신을 상위 카테고리로 지정할 수 없습니다.',
|
||||
'circular' => '하위 카테고리를 상위 카테고리로 지정할 수 없습니다.',
|
||||
],
|
||||
],
|
||||
|
||||
// 상품 이미지 검증 메시지
|
||||
|
||||
Reference in new issue
Block a user