fix : 카테고리 API
This commit is contained in:
58
app/Http/Controllers/Api/V1/CategoryController.php
Normal file
58
app/Http/Controllers/Api/V1/CategoryController.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Api\V1;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Services\CategoryService;
|
||||
use App\Helpers\ApiResponse;
|
||||
|
||||
class CategoryController extends Controller
|
||||
{
|
||||
public function __construct(private CategoryService $service) {}
|
||||
|
||||
public function index(Request $request)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->index($request->all()), '카테고리 목록 조회');
|
||||
}
|
||||
|
||||
public function show(int $id)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->show($id), '카테고리 단건 조회');
|
||||
}
|
||||
|
||||
public function store(Request $request)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->store($request->all()), '카테고리 생성');
|
||||
}
|
||||
|
||||
public function update(int $id, Request $request)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->update($id, $request->all()), '카테고리 수정');
|
||||
}
|
||||
|
||||
public function destroy(int $id)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->destroy($id), '카테고리 삭제');
|
||||
}
|
||||
|
||||
public function toggle(int $id)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->toggle($id), '카테고리 활성/비활성 토글');
|
||||
}
|
||||
|
||||
public function move(int $id, Request $request)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->move($id, $request->all()), '카테고리 이동');
|
||||
}
|
||||
|
||||
public function reorder(Request $request)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->reorder($request->all()), '카테고리 정렬순서 일괄 변경');
|
||||
}
|
||||
|
||||
public function tree(Request $request)
|
||||
{
|
||||
return ApiResponse::handle(fn () => $this->service->tree($request->all()), '카테고리 트리 조회');
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,10 @@ class Category extends Model
|
||||
'sort_order' => 'integer',
|
||||
];
|
||||
|
||||
protected $hidden = [
|
||||
'deleted_by','deleted_at'
|
||||
];
|
||||
|
||||
// 계층
|
||||
public function parent() { return $this->belongsTo(self::class, 'parent_id'); }
|
||||
public function children() { return $this->hasMany(self::class, 'parent_id'); }
|
||||
|
||||
200
app/Services/CategoryService.php
Normal file
200
app/Services/CategoryService.php
Normal file
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\Commons\Category;
|
||||
use Illuminate\Support\Facades\Validator;
|
||||
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class CategoryService extends Service
|
||||
{
|
||||
/** 목록(검색/페이징) */
|
||||
public function index(array $params)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
|
||||
$page = (int)($params['page'] ?? 1);
|
||||
$size = (int)($params['size'] ?? 20);
|
||||
$q = trim((string)($params['q'] ?? ''));
|
||||
$pid = $params['parent_id'] ?? null;
|
||||
$onlyActive = $params['only_active'] ?? null;
|
||||
|
||||
$query = Category::query()->where('tenant_id', $tenantId);
|
||||
|
||||
if ($q !== '') {
|
||||
$query->where(function ($qq) use ($q) {
|
||||
$qq->where('name', 'like', "%{$q}%")
|
||||
->orWhere('code', 'like', "%{$q}%");
|
||||
});
|
||||
}
|
||||
if ($pid !== null) {
|
||||
$query->where('parent_id', (int)$pid);
|
||||
}
|
||||
if ($onlyActive !== null) {
|
||||
$query->where('is_active', (int)!!$onlyActive);
|
||||
}
|
||||
|
||||
$query->orderBy('parent_id')->orderBy('sort_order')->orderBy('id');
|
||||
|
||||
return $query->paginate($size, ['*'], 'page', $page);
|
||||
}
|
||||
|
||||
/** 단건 */
|
||||
public function show(int $id)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$cat = Category::where('tenant_id', $tenantId)->find($id);
|
||||
if (!$cat) throw new NotFoundHttpException(__('error.not_found'));
|
||||
return $cat;
|
||||
}
|
||||
|
||||
/** 생성 */
|
||||
public function store(array $params)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$uid = $this->apiUserId();
|
||||
|
||||
$v = Validator::make($params, [
|
||||
'parent_id' => 'nullable|integer|min:1',
|
||||
'code' => 'nullable|string|max:50',
|
||||
'name' => 'required|string|max:100',
|
||||
'description'=> 'nullable|string|max:255',
|
||||
'is_active' => 'nullable|boolean',
|
||||
'sort_order' => 'nullable|integer|min:0',
|
||||
]);
|
||||
if ($v->fails()) throw new BadRequestHttpException($v->errors()->first());
|
||||
|
||||
$data = $v->validated();
|
||||
$data['tenant_id'] = $tenantId;
|
||||
$data['created_by'] = $uid;
|
||||
$data['is_active'] = (int)($data['is_active'] ?? 1);
|
||||
$data['sort_order'] = $data['sort_order'] ?? 0;
|
||||
|
||||
return Category::create($data);
|
||||
}
|
||||
|
||||
/** 수정 */
|
||||
public function update(int $id, array $params)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$uid = $this->apiUserId();
|
||||
|
||||
$cat = Category::where('tenant_id', $tenantId)->find($id);
|
||||
if (!$cat) throw new NotFoundHttpException(__('error.not_found'));
|
||||
|
||||
$v = Validator::make($params, [
|
||||
'parent_id' => 'nullable|integer|min:1',
|
||||
'code' => 'nullable|string|max:50',
|
||||
'name' => 'sometimes|required|string|max:100',
|
||||
'description'=> 'nullable|string|max:255',
|
||||
'is_active' => 'nullable|boolean',
|
||||
'sort_order' => 'nullable|integer|min:0',
|
||||
]);
|
||||
if ($v->fails()) throw new BadRequestHttpException($v->errors()->first());
|
||||
|
||||
$payload = $v->validated();
|
||||
$payload['updated_by'] = $uid;
|
||||
|
||||
$cat->update($payload);
|
||||
return $cat->refresh();
|
||||
}
|
||||
|
||||
/** 삭제(soft) */
|
||||
public function destroy(int $id)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$uid = $this->apiUserId();
|
||||
|
||||
$cat = Category::where('tenant_id', $tenantId)->find($id);
|
||||
if (!$cat) throw new NotFoundHttpException(__('error.not_found'));
|
||||
|
||||
// (옵션) 하위 존재 검사
|
||||
$hasChild = Category::where('tenant_id', $tenantId)->where('parent_id', $id)->exists();
|
||||
if ($hasChild) throw new BadRequestHttpException(__('error.child_exists'));
|
||||
|
||||
$cat->deleted_by = $uid;
|
||||
$cat->save();
|
||||
$cat->delete();
|
||||
|
||||
return 'success';
|
||||
}
|
||||
|
||||
/** 활성/비활성 토글 */
|
||||
public function toggle(int $id)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$cat = Category::where('tenant_id', $tenantId)->find($id);
|
||||
if (!$cat) throw new NotFoundHttpException(__('error.not_found'));
|
||||
|
||||
$cat->is_active = $cat->is_active ? 0 : 1;
|
||||
$cat->save();
|
||||
return $cat->refresh();
|
||||
}
|
||||
|
||||
/** 부모/순서 이동 */
|
||||
public function move(int $id, array $params)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$v = Validator::make($params, [
|
||||
'parent_id' => 'nullable|integer|min:1',
|
||||
'sort_order' => 'nullable|integer|min:0',
|
||||
]);
|
||||
if ($v->fails()) throw new BadRequestHttpException($v->errors()->first());
|
||||
|
||||
$cat = Category::where('tenant_id', $tenantId)->find($id);
|
||||
if (!$cat) throw new NotFoundHttpException(__('error.not_found'));
|
||||
|
||||
$payload = $v->validated();
|
||||
$cat->update($payload);
|
||||
return $cat->refresh();
|
||||
}
|
||||
|
||||
/** 정렬순서 일괄 변경: [{id, sort_order}] */
|
||||
public function reorder(array $params)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$items = $params['items'] ?? null;
|
||||
if (!is_array($items) || empty($items)) {
|
||||
throw new BadRequestHttpException(__('validation.required', ['attribute' => 'items']));
|
||||
}
|
||||
foreach ($items as $row) {
|
||||
if (!isset($row['id'])) continue;
|
||||
Category::where('tenant_id', $tenantId)
|
||||
->where('id', (int)$row['id'])
|
||||
->update(['sort_order' => (int)($row['sort_order'] ?? 0)]);
|
||||
}
|
||||
return 'success';
|
||||
}
|
||||
|
||||
/** 트리 조회 (parent_id=null 기준 전체) */
|
||||
public function tree(array $params)
|
||||
{
|
||||
$tenantId = $this->tenantId();
|
||||
$onlyActive = (bool)($params['only_active'] ?? false);
|
||||
|
||||
$q = Category::where('tenant_id', $tenantId)
|
||||
->when($onlyActive, fn($qq) => $qq->where('is_active', 1))
|
||||
->orderBy('parent_id')->orderBy('sort_order')->orderBy('id')
|
||||
->get(['id','parent_id','code','name','is_active','sort_order']);
|
||||
|
||||
$byParent = [];
|
||||
foreach ($q as $c) { $byParent[$c->parent_id ?? 0][] = $c; }
|
||||
|
||||
$build = function($pid) use (&$build, &$byParent) {
|
||||
$nodes = $byParent[$pid] ?? [];
|
||||
return array_map(function($n) use ($build) {
|
||||
return [
|
||||
'id' => $n->id,
|
||||
'code' => $n->code,
|
||||
'name' => $n->name,
|
||||
'is_active' => (int)$n->is_active,
|
||||
'sort_order' => (int)$n->sort_order,
|
||||
'children' => $build($n->id),
|
||||
];
|
||||
}, $nodes);
|
||||
};
|
||||
|
||||
return $build(0);
|
||||
}
|
||||
}
|
||||
252
app/Swagger/v1/CategoryApi.php
Normal file
252
app/Swagger/v1/CategoryApi.php
Normal file
@@ -0,0 +1,252 @@
|
||||
<?php
|
||||
|
||||
namespace App\Swagger\v1;
|
||||
|
||||
/**
|
||||
* @OA\Tag(name="Category", description="카테고리 관리")
|
||||
*
|
||||
* @OA\Schema(
|
||||
* schema="Category",
|
||||
* type="object",
|
||||
* required={"id","name"},
|
||||
* @OA\Property(property="id", type="integer", example=12),
|
||||
* @OA\Property(property="tenant_id", type="integer", example=1),
|
||||
* @OA\Property(property="parent_id", type="integer", nullable=true, example=null),
|
||||
* @OA\Property(property="code", type="string", nullable=true, example="ELC"),
|
||||
* @OA\Property(property="name", type="string", example="전자"),
|
||||
* @OA\Property(property="description", type="string", nullable=true, example=null),
|
||||
* @OA\Property(property="is_active", type="integer", example=1),
|
||||
* @OA\Property(property="sort_order", type="integer", example=10),
|
||||
* @OA\Property(property="created_at", type="string", example="2025-08-22 10:00:00"),
|
||||
* @OA\Property(property="updated_at", type="string", example="2025-08-22 10:10:00")
|
||||
* )
|
||||
*
|
||||
* @OA\Schema(
|
||||
* schema="CategoryPagination",
|
||||
* type="object",
|
||||
* @OA\Property(property="current_page", type="integer", example=1),
|
||||
* @OA\Property(
|
||||
* property="data",
|
||||
* type="array",
|
||||
* @OA\Items(ref="#/components/schemas/Category")
|
||||
* ),
|
||||
* @OA\Property(property="first_page_url", type="string", example="/api/v1/categories?page=1"),
|
||||
* @OA\Property(property="from", type="integer", example=1),
|
||||
* @OA\Property(property="last_page", type="integer", example=3),
|
||||
* @OA\Property(property="last_page_url", type="string", example="/api/v1/categories?page=3"),
|
||||
* @OA\Property(
|
||||
* property="links",
|
||||
* type="array",
|
||||
* @OA\Items(type="object",
|
||||
* @OA\Property(property="url", type="string", nullable=true, example=null),
|
||||
* @OA\Property(property="label", type="string", example="« Previous"),
|
||||
* @OA\Property(property="active", type="boolean", example=false)
|
||||
* )
|
||||
* ),
|
||||
* @OA\Property(property="next_page_url", type="string", nullable=true, example="/api/v1/categories?page=2"),
|
||||
* @OA\Property(property="path", type="string", example="/api/v1/categories"),
|
||||
* @OA\Property(property="per_page", type="integer", example=20),
|
||||
* @OA\Property(property="prev_page_url", type="string", nullable=true, example=null),
|
||||
* @OA\Property(property="to", type="integer", example=20),
|
||||
* @OA\Property(property="total", type="integer", example=60)
|
||||
* )
|
||||
*
|
||||
* @OA\Schema(
|
||||
* schema="CategoryCreateRequest",
|
||||
* type="object",
|
||||
* required={"name"},
|
||||
* @OA\Property(property="parent_id", type="integer", nullable=true),
|
||||
* @OA\Property(property="code", type="string", nullable=true, maxLength=50),
|
||||
* @OA\Property(property="name", type="string", maxLength=100),
|
||||
* @OA\Property(property="description", type="string", nullable=true, maxLength=255),
|
||||
* @OA\Property(property="is_active", type="boolean", example=true),
|
||||
* @OA\Property(property="sort_order", type="integer", example=0)
|
||||
* )
|
||||
*
|
||||
* @OA\Schema(
|
||||
* schema="CategoryUpdateRequest",
|
||||
* type="object",
|
||||
* @OA\Property(property="parent_id", type="integer", nullable=true),
|
||||
* @OA\Property(property="code", type="string", nullable=true, maxLength=50),
|
||||
* @OA\Property(property="name", type="string", maxLength=100),
|
||||
* @OA\Property(property="description", type="string", nullable=true, maxLength=255),
|
||||
* @OA\Property(property="is_active", type="boolean"),
|
||||
* @OA\Property(property="sort_order", type="integer")
|
||||
* )
|
||||
*
|
||||
* @OA\Schema(
|
||||
* schema="CategoryTreeNode",
|
||||
* type="object",
|
||||
* @OA\Property(property="id", type="integer", example=1),
|
||||
* @OA\Property(property="code", type="string", nullable=true, example="ELC"),
|
||||
* @OA\Property(property="name", type="string", example="전자"),
|
||||
* @OA\Property(property="is_active", type="integer", example=1),
|
||||
* @OA\Property(property="sort_order", type="integer", example=0),
|
||||
* @OA\Property(property="children", type="array", @OA\Items(ref="#/components/schemas/CategoryTreeNode"))
|
||||
* )
|
||||
*/
|
||||
class CategoryApi
|
||||
{
|
||||
/**
|
||||
* @OA\Get(
|
||||
* path="/api/v1/categories",
|
||||
* tags={"Category"},
|
||||
* summary="카테고리 목록",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\Parameter(name="page", in="query", @OA\Schema(type="integer", example=1)),
|
||||
* @OA\Parameter(name="size", in="query", @OA\Schema(type="integer", example=20)),
|
||||
* @OA\Parameter(name="q", in="query", description="코드/이름 검색", @OA\Schema(type="string")),
|
||||
* @OA\Parameter(name="parent_id", in="query", @OA\Schema(type="integer", nullable=true)),
|
||||
* @OA\Parameter(name="only_active", in="query", @OA\Schema(type="boolean")),
|
||||
* @OA\Response(response=200, description="조회 성공",
|
||||
* @OA\JsonContent(allOf={
|
||||
* @OA\Schema(ref="#/components/schemas/ApiResponse"),
|
||||
* @OA\Schema(@OA\Property(property="data", ref="#/components/schemas/CategoryPagination"))
|
||||
* })
|
||||
* ),
|
||||
* @OA\Response(response=401, description="인증 실패", @OA\JsonContent(ref="#/components/schemas/ErrorResponse"))
|
||||
* )
|
||||
*/
|
||||
public function index() {}
|
||||
|
||||
/**
|
||||
* @OA\Get(
|
||||
* path="/api/v1/categories/{id}",
|
||||
* tags={"Category"},
|
||||
* summary="카테고리 단건 조회",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
* @OA\Response(response=200, description="조회 성공",
|
||||
* @OA\JsonContent(allOf={
|
||||
* @OA\Schema(ref="#/components/schemas/ApiResponse"),
|
||||
* @OA\Schema(@OA\Property(property="data", ref="#/components/schemas/Category"))
|
||||
* })
|
||||
* ),
|
||||
* @OA\Response(response=404, description="데이터 없음", @OA\JsonContent(ref="#/components/schemas/ErrorResponse"))
|
||||
* )
|
||||
*/
|
||||
public function show() {}
|
||||
|
||||
/**
|
||||
* @OA\Post(
|
||||
* path="/api/v1/categories",
|
||||
* tags={"Category"},
|
||||
* summary="카테고리 생성",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\RequestBody(required=true, @OA\JsonContent(ref="#/components/schemas/CategoryCreateRequest")),
|
||||
* @OA\Response(response=200, description="생성 성공",
|
||||
* @OA\JsonContent(allOf={
|
||||
* @OA\Schema(ref="#/components/schemas/ApiResponse"),
|
||||
* @OA\Schema(@OA\Property(property="data", ref="#/components/schemas/Category"))
|
||||
* })
|
||||
* ),
|
||||
* @OA\Response(response=400, description="검증 실패", @OA\JsonContent(ref="#/components/schemas/ErrorResponse"))
|
||||
* )
|
||||
*/
|
||||
public function store() {}
|
||||
|
||||
/**
|
||||
* @OA\Patch(
|
||||
* path="/api/v1/categories/{id}",
|
||||
* tags={"Category"},
|
||||
* summary="카테고리 수정",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
* @OA\RequestBody(required=true, @OA\JsonContent(ref="#/components/schemas/CategoryUpdateRequest")),
|
||||
* @OA\Response(response=200, description="수정 성공",
|
||||
* @OA\JsonContent(allOf={
|
||||
* @OA\Schema(ref="#/components/schemas/ApiResponse"),
|
||||
* @OA\Schema(@OA\Property(property="data", ref="#/components/schemas/Category"))
|
||||
* })
|
||||
* )
|
||||
* )
|
||||
*/
|
||||
public function update() {}
|
||||
|
||||
/**
|
||||
* @OA\Delete(
|
||||
* path="/api/v1/categories/{id}",
|
||||
* tags={"Category"},
|
||||
* summary="카테고리 삭제(soft)",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
* @OA\Response(response=200, description="삭제 성공", @OA\JsonContent(ref="#/components/schemas/ApiResponse"))
|
||||
* )
|
||||
*/
|
||||
public function destroy() {}
|
||||
|
||||
/**
|
||||
* @OA\Post(
|
||||
* path="/api/v1/categories/{id}/toggle",
|
||||
* tags={"Category"},
|
||||
* summary="활성/비활성 토글",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
* @OA\Response(response=200, description="변경 성공",
|
||||
* @OA\JsonContent(allOf={
|
||||
* @OA\Schema(ref="#/components/schemas/ApiResponse"),
|
||||
* @OA\Schema(@OA\Property(property="data", ref="#/components/schemas/Category"))
|
||||
* })
|
||||
* )
|
||||
* )
|
||||
*/
|
||||
public function toggle() {}
|
||||
|
||||
/**
|
||||
* @OA\Patch(
|
||||
* path="/api/v1/categories/{id}/move",
|
||||
* tags={"Category"},
|
||||
* summary="부모/순서 이동",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\Parameter(name="id", in="path", required=true, @OA\Schema(type="integer")),
|
||||
* @OA\RequestBody(required=true, @OA\JsonContent(
|
||||
* type="object",
|
||||
* @OA\Property(property="parent_id", type="integer", nullable=true),
|
||||
* @OA\Property(property="sort_order", type="integer", nullable=true)
|
||||
* )),
|
||||
* @OA\Response(response=200, description="이동 성공",
|
||||
* @OA\JsonContent(allOf={
|
||||
* @OA\Schema(ref="#/components/schemas/ApiResponse"),
|
||||
* @OA\Schema(@OA\Property(property="data", ref="#/components/schemas/Category"))
|
||||
* })
|
||||
* )
|
||||
* )
|
||||
*/
|
||||
public function move() {}
|
||||
|
||||
/**
|
||||
* @OA\Post(
|
||||
* path="/api/v1/categories/reorder",
|
||||
* tags={"Category"},
|
||||
* summary="정렬순서 일괄 변경",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\RequestBody(required=true, @OA\JsonContent(
|
||||
* type="object",
|
||||
* @OA\Property(property="items", type="array", @OA\Items(
|
||||
* type="object",
|
||||
* @OA\Property(property="id", type="integer", example=1),
|
||||
* @OA\Property(property="sort_order", type="integer", example=10)
|
||||
* ))
|
||||
* )),
|
||||
* @OA\Response(response=200, description="저장 성공", @OA\JsonContent(ref="#/components/schemas/ApiResponse"))
|
||||
* )
|
||||
*/
|
||||
public function reorder() {}
|
||||
|
||||
/**
|
||||
* @OA\Get(
|
||||
* path="/api/v1/categories/tree",
|
||||
* tags={"Category"},
|
||||
* summary="카테고리 트리",
|
||||
* security={{"ApiKeyAuth":{}},{"BearerAuth":{}}},
|
||||
* @OA\Parameter(name="only_active", in="query", @OA\Schema(type="boolean")),
|
||||
* @OA\Response(response=200, description="조회 성공",
|
||||
* @OA\JsonContent(allOf={
|
||||
* @OA\Schema(ref="#/components/schemas/ApiResponse"),
|
||||
* @OA\Schema(@OA\Property(property="data", type="array", @OA\Items(ref="#/components/schemas/CategoryTreeNode")))
|
||||
* })
|
||||
* )
|
||||
* )
|
||||
*/
|
||||
public function tree() {}
|
||||
}
|
||||
Reference in New Issue
Block a user