diff --git a/CURRENT_WORKS.md b/CURRENT_WORKS.md index 1a94954..6cb2e7c 100644 --- a/CURRENT_WORKS.md +++ b/CURRENT_WORKS.md @@ -1,5 +1,235 @@ # SAM API 저장소 작업 현황 +## 2025-10-13 (일) - ClientGroup 및 Pricing API 완성 (오후) + +### 주요 작업 +- **ClientGroup API 전체 구현**: 고객 그룹 관리를 위한 완전한 REST API 구축 +- **Pricing API 전체 구현**: 가격 이력 관리 및 가격 조회 API 구축 +- **Swagger 문서 작성**: ClientGroup, Pricing API의 완전한 OpenAPI 3.0 문서 생성 +- **l5-swagger 재생성**: 모든 API 문서를 Swagger UI에서 확인 가능하도록 재생성 + +### 추가된 파일: +- `app/Services/ClientGroupService.php` - 고객 그룹 관리 서비스 (CRUD + toggle) +- `app/Http/Controllers/Api/V1/ClientGroupController.php` - 고객 그룹 컨트롤러 +- `app/Http/Controllers/Api/V1/PricingController.php` - 가격 이력 컨트롤러 +- `app/Swagger/v1/ClientGroupApi.php` - ClientGroup Swagger 문서 +- `app/Swagger/v1/PricingApi.php` - Pricing Swagger 문서 + +### 수정된 파일: +- `routes/api.php` - ClientGroup 및 Pricing 라우트 등록 + +### 작업 내용: + +#### 1. ClientGroupService 구현 +**핵심 기능:** +- `index()` - 페이지네이션 목록 조회 (검색, 활성 여부 필터링) +- `show($id)` - 단건 조회 +- `store($params)` - 생성 (group_code 중복 검사) +- `update($id, $params)` - 수정 (중복 검사) +- `destroy($id)` - Soft Delete +- `toggle($id)` - 활성/비활성 상태 토글 + +**검증 규칙:** +```php +- group_code: required|string|max:30 +- group_name: required|string|max:100 +- price_rate: required|numeric|min:0|max:99.9999 +- is_active: nullable|boolean +``` + +**에러 처리:** +- 중복 코드: `__('error.duplicate_code')` +- 데이터 없음: `NotFoundHttpException` +- 검증 실패: `BadRequestHttpException` + +#### 2. ClientGroupController 구현 +**표준 RESTful 패턴:** +```php +- GET /api/v1/client-groups → index() +- POST /api/v1/client-groups → store() +- GET /api/v1/client-groups/{id} → show() +- PUT /api/v1/client-groups/{id} → update() +- DELETE /api/v1/client-groups/{id} → destroy() +- PATCH /api/v1/client-groups/{id}/toggle → toggle() +``` + +**공통 특징:** +- ApiResponse::handle() 래퍼 사용 +- i18n 메시지 키 사용 (__('message.xxx')) +- Service DI를 통한 비즈니스 로직 분리 + +#### 3. PricingController 구현 +**특화된 엔드포인트:** +```php +- GET /api/v1/pricing → index() (가격 이력 목록) +- GET /api/v1/pricing/show → show() (단일 항목 가격 조회) +- POST /api/v1/pricing/bulk → bulk() (여러 항목 일괄 조회) +- POST /api/v1/pricing/upsert → upsert() (등록/수정) +- DELETE /api/v1/pricing/{id} → destroy() (삭제) +``` + +**가격 조회 파라미터:** +- `item_type`: PRODUCT | MATERIAL (필수) +- `item_id`: 항목 ID (필수) +- `client_id`: 고객 ID (선택, 그룹별 가격 조회) +- `date`: 기준일 (선택, 미지정 시 오늘) + +**일괄 조회 요청:** +```json +{ + "items": [ + {"item_type": "PRODUCT", "item_id": 1}, + {"item_type": "MATERIAL", "item_id": 5} + ], + "client_id": 10, + "date": "2025-10-13" +} +``` + +#### 4. ClientGroupApi.php Swagger 문서 +**스키마 구성:** +- `ClientGroup` - 모델 스키마 (전체 필드) +- `ClientGroupPagination` - 페이지네이션 응답 +- `ClientGroupCreateRequest` - 생성 요청 (required 필드) +- `ClientGroupUpdateRequest` - 수정 요청 (optional 필드) + +**엔드포인트 문서:** +- 각 엔드포인트별 파라미터, 요청/응답 예시 +- 에러 응답 (401, 404, 400) 정의 +- Security: ApiKeyAuth + BearerAuth + +#### 5. PricingApi.php Swagger 문서 +**스키마 구성:** +- `PriceHistory` - 가격 이력 모델 +- `PriceHistoryPagination` - 목록 응답 +- `PriceUpsertRequest` - 등록/수정 요청 +- `PriceQueryResult` - 단일 조회 결과 (price, price_history_id, client_group_id, warning) +- `BulkPriceQueryRequest` - 일괄 조회 요청 +- `BulkPriceQueryResult` - 일괄 조회 결과 (prices[], warnings[]) + +**특수 스키마:** +```php +// 단일 항목 가격 조회 결과 +PriceQueryResult { + price: 50000.00, + price_history_id: 1, + client_group_id: 1, + warning: "가격을 찾을 수 없습니다" // nullable +} + +// 일괄 조회 결과 +BulkPriceQueryResult { + prices: [ + {item_type: "PRODUCT", item_id: 1, price: 50000, ...}, + {item_type: "MATERIAL", item_id: 5, price: null, ...} + ], + warnings: ["MATERIAL(5): 가격을 찾을 수 없습니다"] +} +``` + +#### 6. Routes 등록 +**ClientGroups 라우트:** +```php +Route::prefix('client-groups')->group(function () { + Route::get ('', [ClientGroupController::class, 'index']); + Route::post ('', [ClientGroupController::class, 'store']); + Route::get ('/{id}', [ClientGroupController::class, 'show'])->whereNumber('id'); + Route::put ('/{id}', [ClientGroupController::class, 'update'])->whereNumber('id'); + Route::delete('/{id}', [ClientGroupController::class, 'destroy'])->whereNumber('id'); + Route::patch ('/{id}/toggle', [ClientGroupController::class, 'toggle'])->whereNumber('id'); +}); +``` + +**Pricing 라우트:** +```php +Route::prefix('pricing')->group(function () { + Route::get ('', [PricingController::class, 'index']); + Route::get ('/show', [PricingController::class, 'show']); + Route::post ('/bulk', [PricingController::class, 'bulk']); + Route::post ('/upsert', [PricingController::class, 'upsert']); + Route::delete('/{id}', [PricingController::class, 'destroy'])->whereNumber('id'); +}); +``` + +#### 7. Swagger 재생성 및 검증 +```bash +# Swagger JSON 재생성 +php artisan l5-swagger:generate + +# 검증 결과 +✅ ClientGroup 태그 확인됨 +✅ Pricing 태그 확인됨 +✅ 11개 엔드포인트 모두 포함: + - /api/v1/client-groups (6개) + - /api/v1/pricing (5개) +``` + +### 사용한 도구: +- **기본 Claude 도구**: Read, Write, Edit, Bash, TodoWrite +- **MCP 서버**: 사용하지 않음 (표준 CRUD 구현) +- **SuperClaude 페르소나**: 사용하지 않음 (기존 패턴 따름) + +### 아키텍처 준수 사항: +✅ **SAM API Development Rules 준수:** +- Service-First 아키텍처 (비즈니스 로직은 Service에) +- Controller는 DI + ApiResponse::handle()만 사용 +- i18n 메시지 키 사용 (__('message.xxx')) +- Validator 사용 (Service 내에서) +- BelongsToTenant 멀티테넌트 스코프 +- SoftDeletes 적용 +- 감사 컬럼 (created_by, updated_by) 포함 + +✅ **Swagger 문서 표준:** +- Controller와 분리된 별도 파일 +- 파일 위치: `app/Swagger/v1/` +- 파일명: `{Resource}Api.php` +- 빈 메서드에 @OA 어노테이션 +- ApiResponse, ErrorResponse 재사용 + +### API 엔드포인트 요약: + +#### ClientGroup API (6개) +| 메서드 | 경로 | 설명 | +|--------|------|------| +| GET | /api/v1/client-groups | 목록 조회 (페이지네이션, 검색) | +| POST | /api/v1/client-groups | 고객 그룹 생성 | +| GET | /api/v1/client-groups/{id} | 단건 조회 | +| PUT | /api/v1/client-groups/{id} | 수정 | +| DELETE | /api/v1/client-groups/{id} | 삭제 (soft) | +| PATCH | /api/v1/client-groups/{id}/toggle | 활성/비활성 토글 | + +#### Pricing API (5개) +| 메서드 | 경로 | 설명 | +|--------|------|------| +| GET | /api/v1/pricing | 가격 이력 목록 (필터링) | +| GET | /api/v1/pricing/show | 단일 항목 가격 조회 | +| POST | /api/v1/pricing/bulk | 여러 항목 일괄 조회 | +| POST | /api/v1/pricing/upsert | 가격 등록/수정 | +| DELETE | /api/v1/pricing/{id} | 가격 이력 삭제 | + +### Swagger UI 접근: +- URL: `http://localhost:8000/api-docs/index.html` +- ClientGroup 섹션: 6개 엔드포인트 +- Pricing 섹션: 5개 엔드포인트 +- Try it out 기능으로 즉시 테스트 가능 + +### 완료된 향후 작업 (오전 작업 기준): +- [x] 가격 관리 API 엔드포인트 추가 (CRUD) ✅ +- [x] Swagger 문서 작성 (가격 관련 API) ✅ +- [x] 고객 그룹 관리 API 엔드포인트 추가 ✅ + +### 신규 향후 작업: +- [ ] API 엔드포인트 실제 테스트 (Postman/Swagger UI) +- [ ] Frontend 가격 관리 화면 구현 +- [ ] Frontend 고객 그룹 관리 화면 구현 +- [ ] 가격 일괄 업로드 기능 추가 +- [ ] 단위 테스트 작성 + +### Git 커밋 준비: +- 다음 커밋 예정: `feat: ClientGroup 및 Pricing API 완성 및 Swagger 문서 작성` + +--- + ## 2025-10-13 (일) - 고객그룹별 차등 가격 시스템 구축 ### 주요 작업 diff --git a/app/Http/Controllers/Api/V1/ClientGroupController.php b/app/Http/Controllers/Api/V1/ClientGroupController.php new file mode 100644 index 0000000..bfd0d46 --- /dev/null +++ b/app/Http/Controllers/Api/V1/ClientGroupController.php @@ -0,0 +1,72 @@ +service = $service; + } + + public function index(Request $request) + { + return ApiResponse::handle(function () use ($request) { + $data = $this->service->index($request->all()); + + return ['data' => $data, 'message' => __('message.fetched')]; + }); + } + + public function show(int $id) + { + return ApiResponse::handle(function () use ($id) { + $data = $this->service->show($id); + + return ['data' => $data, 'message' => __('message.fetched')]; + }); + } + + public function store(Request $request) + { + return ApiResponse::handle(function () use ($request) { + $data = $this->service->store($request->all()); + + return ['data' => $data, 'message' => __('message.created')]; + }); + } + + public function update(Request $request, int $id) + { + return ApiResponse::handle(function () use ($request, $id) { + $data = $this->service->update($id, $request->all()); + + return ['data' => $data, 'message' => __('message.updated')]; + }); + } + + public function destroy(int $id) + { + return ApiResponse::handle(function () use ($id) { + $this->service->destroy($id); + + return ['data' => null, 'message' => __('message.deleted')]; + }); + } + + public function toggle(int $id) + { + return ApiResponse::handle(function () use ($id) { + $data = $this->service->toggle($id); + + return ['data' => $data, 'message' => __('message.updated')]; + }); + } +} \ No newline at end of file diff --git a/app/Http/Controllers/Api/V1/PricingController.php b/app/Http/Controllers/Api/V1/PricingController.php new file mode 100644 index 0000000..f4f7a5e --- /dev/null +++ b/app/Http/Controllers/Api/V1/PricingController.php @@ -0,0 +1,96 @@ +service = $service; + } + + /** + * 가격 이력 목록 조회 + */ + public function index(Request $request) + { + return ApiResponse::handle(function () use ($request) { + $filters = $request->only([ + 'item_type_code', + 'item_id', + 'price_type_code', + 'client_group_id', + 'date', + ]); + $perPage = (int) ($request->input('size') ?? 15); + + $data = $this->service->listPrices($filters, $perPage); + + return ['data' => $data, 'message' => __('message.fetched')]; + }); + } + + /** + * 단일 항목 가격 조회 + */ + public function show(Request $request) + { + return ApiResponse::handle(function () use ($request) { + $itemType = $request->input('item_type'); // PRODUCT | MATERIAL + $itemId = (int) $request->input('item_id'); + $clientId = $request->input('client_id') ? (int) $request->input('client_id') : null; + $date = $request->input('date') ?? null; + + $result = $this->service->getItemPrice($itemType, $itemId, $clientId, $date); + + return ['data' => $result, 'message' => __('message.fetched')]; + }); + } + + /** + * 여러 항목 일괄 가격 조회 + */ + public function bulk(Request $request) + { + return ApiResponse::handle(function () use ($request) { + $items = $request->input('items'); // [['item_type' => 'PRODUCT', 'item_id' => 1], ...] + $clientId = $request->input('client_id') ? (int) $request->input('client_id') : null; + $date = $request->input('date') ?? null; + + $result = $this->service->getBulkItemPrices($items, $clientId, $date); + + return ['data' => $result, 'message' => __('message.fetched')]; + }); + } + + /** + * 가격 등록/수정 + */ + public function upsert(Request $request) + { + return ApiResponse::handle(function () use ($request) { + $data = $this->service->upsertPrice($request->all()); + + return ['data' => $data, 'message' => __('message.created')]; + }); + } + + /** + * 가격 삭제 + */ + public function destroy(int $id) + { + return ApiResponse::handle(function () use ($id) { + $this->service->deletePrice($id); + + return ['data' => null, 'message' => __('message.deleted')]; + }); + } +} \ No newline at end of file diff --git a/app/Services/ClientGroupService.php b/app/Services/ClientGroupService.php new file mode 100644 index 0000000..c165a41 --- /dev/null +++ b/app/Services/ClientGroupService.php @@ -0,0 +1,167 @@ +tenantId(); + + $page = (int) ($params['page'] ?? 1); + $size = (int) ($params['size'] ?? 20); + $q = trim((string) ($params['q'] ?? '')); + $onlyActive = $params['only_active'] ?? null; + + $query = ClientGroup::query()->where('tenant_id', $tenantId); + + if ($q !== '') { + $query->where(function ($qq) use ($q) { + $qq->where('group_name', 'like', "%{$q}%") + ->orWhere('group_code', 'like', "%{$q}%"); + }); + } + + if ($onlyActive !== null) { + $query->where('is_active', $onlyActive ? 1 : 0); + } + + $query->orderBy('group_code')->orderBy('id'); + + return $query->paginate($size, ['*'], 'page', $page); + } + + /** 단건 */ + public function show(int $id) + { + $tenantId = $this->tenantId(); + $group = ClientGroup::where('tenant_id', $tenantId)->find($id); + if (! $group) { + throw new NotFoundHttpException(__('error.not_found')); + } + + return $group; + } + + /** 생성 */ + public function store(array $params) + { + $tenantId = $this->tenantId(); + $uid = $this->apiUserId(); + + $v = Validator::make($params, [ + 'group_code' => 'required|string|max:30', + 'group_name' => 'required|string|max:100', + 'price_rate' => 'required|numeric|min:0|max:99.9999', + 'is_active' => 'nullable|boolean', + ]); + + if ($v->fails()) { + throw new BadRequestHttpException($v->errors()->first()); + } + + $data = $v->validated(); + + // group_code 중복 검사 + $exists = ClientGroup::where('tenant_id', $tenantId) + ->where('group_code', $data['group_code']) + ->exists(); + if ($exists) { + throw new BadRequestHttpException(__('error.duplicate_code')); + } + + $data['tenant_id'] = $tenantId; + $data['is_active'] = $data['is_active'] ?? 1; + $data['created_by'] = $uid; + + return ClientGroup::create($data); + } + + /** 수정 */ + public function update(int $id, array $params) + { + $tenantId = $this->tenantId(); + $uid = $this->apiUserId(); + + $group = ClientGroup::where('tenant_id', $tenantId)->find($id); + if (! $group) { + throw new NotFoundHttpException(__('error.not_found')); + } + + $v = Validator::make($params, [ + 'group_code' => 'sometimes|required|string|max:30', + 'group_name' => 'sometimes|required|string|max:100', + 'price_rate' => 'sometimes|required|numeric|min:0|max:99.9999', + 'is_active' => 'nullable|boolean', + ]); + + if ($v->fails()) { + throw new BadRequestHttpException($v->errors()->first()); + } + + $payload = $v->validated(); + + // group_code 변경 시 중복 검사 + if (isset($payload['group_code']) && $payload['group_code'] !== $group->group_code) { + $exists = ClientGroup::where('tenant_id', $tenantId) + ->where('group_code', $payload['group_code']) + ->exists(); + if ($exists) { + throw new BadRequestHttpException(__('error.duplicate_code')); + } + } + + $payload['updated_by'] = $uid; + + $group->update($payload); + + return $group->refresh(); + } + + /** 삭제 */ + public function destroy(int $id) + { + $tenantId = $this->tenantId(); + $uid = $this->apiUserId(); + + $group = ClientGroup::where('tenant_id', $tenantId)->find($id); + if (! $group) { + throw new NotFoundHttpException(__('error.not_found')); + } + + // 해당 그룹에 속한 고객이 있는지 검사 + if ($group->clients()->exists()) { + throw new BadRequestHttpException(__('error.has_clients')); + } + + $group->deleted_by = $uid; + $group->save(); + $group->delete(); + + return 'success'; + } + + /** 활성/비활성 토글 */ + public function toggle(int $id) + { + $tenantId = $this->tenantId(); + $uid = $this->apiUserId(); + + $group = ClientGroup::where('tenant_id', $tenantId)->find($id); + if (! $group) { + throw new NotFoundHttpException(__('error.not_found')); + } + + $group->is_active = $group->is_active ? 0 : 1; + $group->updated_by = $uid; + $group->save(); + + return $group->refresh(); + } +} \ No newline at end of file diff --git a/app/Swagger/v1/ClientGroupApi.php b/app/Swagger/v1/ClientGroupApi.php new file mode 100644 index 0000000..f62539f --- /dev/null +++ b/app/Swagger/v1/ClientGroupApi.php @@ -0,0 +1,176 @@ +whereNumber('id')->name('v1.clients.toggle'); // 활성/비활성 }); + // Client Groups (고객 그룹 관리) + Route::prefix('client-groups')->group(function () { + Route::get ('', [ClientGroupController::class, 'index'])->name('v1.client-groups.index'); // 목록 + Route::post ('', [ClientGroupController::class, 'store'])->name('v1.client-groups.store'); // 생성 + Route::get ('/{id}', [ClientGroupController::class, 'show'])->whereNumber('id')->name('v1.client-groups.show'); // 단건 + Route::put ('/{id}', [ClientGroupController::class, 'update'])->whereNumber('id')->name('v1.client-groups.update'); // 수정 + Route::delete('/{id}', [ClientGroupController::class, 'destroy'])->whereNumber('id')->name('v1.client-groups.destroy'); // 삭제 + Route::patch ('/{id}/toggle', [ClientGroupController::class, 'toggle'])->whereNumber('id')->name('v1.client-groups.toggle'); // 활성/비활성 + }); + + // Pricing (가격 이력 관리) + Route::prefix('pricing')->group(function () { + Route::get ('', [PricingController::class, 'index'])->name('v1.pricing.index'); // 목록 + Route::get ('/show', [PricingController::class, 'show'])->name('v1.pricing.show'); // 단일 항목 가격 조회 + Route::post ('/bulk', [PricingController::class, 'bulk'])->name('v1.pricing.bulk'); // 여러 항목 일괄 조회 + Route::post ('/upsert', [PricingController::class, 'upsert'])->name('v1.pricing.upsert'); // 가격 등록/수정 + Route::delete('/{id}', [PricingController::class, 'destroy'])->whereNumber('id')->name('v1.pricing.destroy'); // 삭제 + }); + // Products & Materials (제품/자재 통합 관리) Route::prefix('products')->group(function (){