Files
sam-api/app/Services/ItemMaster/ItemFieldService.php
hskwon efa2a84d2c feat(item-master): 잠금 기능 추가 및 FK 레거시 코드 정리
## 잠금 기능 (Lock Feature)
- entity_relationships 테이블에 is_locked, locked_by, locked_at 컬럼 추가
- EntityRelationship 모델에 잠금 관련 헬퍼 메서드 추가
- LockCheckTrait 생성 (destroy 시 잠금 체크 공통 로직)
- 각 Service의 destroy() 메서드에 잠금 체크 적용
- API 응답에 is_locked 필드 포함
- 한국어 에러 메시지 추가

## FK 레거시 코드 정리
- ItemMasterSeeder: entity_relationships 기반으로 전환
- ItemPage 모델: FK 기반 sections() 관계 제거
- ItemSectionService: clone() 메서드 FK 제거
- SectionTemplateService: page_id 컬럼 참조 제거
- EntityRelationship::link() 파라미터 순서 통일

## 기타
- Swagger 스키마에 is_locked 속성 추가
- 프론트엔드 가이드 문서 추가
2025-11-27 15:51:00 +09:00

266 lines
8.9 KiB
PHP

<?php
namespace App\Services\ItemMaster;
use App\Models\ItemMaster\EntityRelationship;
use App\Models\ItemMaster\ItemField;
use App\Services\Service;
use App\Traits\LockCheckTrait;
use Illuminate\Database\Eloquent\Collection;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ItemFieldService extends Service
{
use LockCheckTrait;
/**
* 모든 필드 목록 조회
*
* GET /api/v1/item-master/fields
*/
public function index(): Collection
{
$tenantId = $this->tenantId();
return ItemField::where('tenant_id', $tenantId)
->orderBy('created_at', 'desc')
->get();
}
/**
* 독립 필드 생성 (섹션 연결 없음)
*
* POST /api/v1/item-master/fields
*/
public function storeIndependent(array $data): ItemField
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
$field = ItemField::create([
'tenant_id' => $tenantId,
'group_id' => $data['group_id'] ?? 1,
'field_name' => $data['field_name'],
'field_type' => $data['field_type'],
'order_no' => 0,
'is_required' => $data['is_required'] ?? false,
'default_value' => $data['default_value'] ?? null,
'placeholder' => $data['placeholder'] ?? null,
'display_condition' => $data['display_condition'] ?? null,
'validation_rules' => $data['validation_rules'] ?? null,
'options' => $data['options'] ?? null,
'properties' => $data['properties'] ?? null,
'category' => $data['category'] ?? null,
'description' => $data['description'] ?? null,
'is_common' => $data['is_common'] ?? false,
'created_by' => $userId,
]);
return $field;
}
/**
* 필드 복제
*
* POST /api/v1/item-master/fields/{id}/clone
*/
public function clone(int $id): ItemField
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
$original = ItemField::where('tenant_id', $tenantId)
->where('id', $id)
->first();
if (! $original) {
throw new NotFoundHttpException(__('error.field_not_found'));
}
$cloned = ItemField::create([
'tenant_id' => $tenantId,
'group_id' => $original->group_id,
'field_name' => $original->field_name.' (복사본)',
'field_type' => $original->field_type,
'order_no' => 0,
'is_required' => $original->is_required,
'default_value' => $original->default_value,
'placeholder' => $original->placeholder,
'display_condition' => $original->display_condition,
'validation_rules' => $original->validation_rules,
'options' => $original->options,
'properties' => $original->properties,
'category' => $original->category,
'description' => $original->description,
'is_common' => $original->is_common,
'created_by' => $userId,
]);
return $cloned;
}
/**
* 필드 사용처 조회 (어떤 섹션/페이지에 연결되어 있는지)
*
* GET /api/v1/item-master/fields/{id}/usage
*/
public function getUsage(int $id): array
{
$tenantId = $this->tenantId();
$field = ItemField::where('tenant_id', $tenantId)
->where('id', $id)
->first();
if (! $field) {
throw new NotFoundHttpException(__('error.field_not_found'));
}
// entity_relationships 기반 연결
$linkedSections = $field->linkedSections()->get();
$linkedPages = $field->linkedPages()->get();
return [
'field_id' => $id,
'linked_sections' => $linkedSections,
'linked_pages' => $linkedPages,
'total_usage_count' => $linkedSections->count() + $linkedPages->count(),
];
}
/**
* 필드 생성 및 섹션에 연결
*/
public function store(int $sectionId, array $data): ItemField
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
// order_no 자동 계산 (해당 섹션에 연결된 마지막 필드 + 1)
$maxOrder = EntityRelationship::where('parent_type', EntityRelationship::TYPE_SECTION)
->where('parent_id', $sectionId)
->where('child_type', EntityRelationship::TYPE_FIELD)
->max('order_no');
// 필드 생성
$field = ItemField::create([
'tenant_id' => $tenantId,
'group_id' => $data['group_id'] ?? 1,
'field_name' => $data['field_name'],
'field_type' => $data['field_type'],
'order_no' => ($maxOrder ?? -1) + 1,
'is_required' => $data['is_required'] ?? false,
'default_value' => $data['default_value'] ?? null,
'placeholder' => $data['placeholder'] ?? null,
'display_condition' => $data['display_condition'] ?? null,
'validation_rules' => $data['validation_rules'] ?? null,
'options' => $data['options'] ?? null,
'properties' => $data['properties'] ?? null,
'created_by' => $userId,
]);
// 섹션-필드 관계 생성
EntityRelationship::link(
EntityRelationship::TYPE_SECTION,
$sectionId,
EntityRelationship::TYPE_FIELD,
$field->id,
$tenantId,
$data['group_id'] ?? 1,
($maxOrder ?? -1) + 1
);
return $field;
}
/**
* 필드 수정
*/
public function update(int $id, array $data): ItemField
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
$field = ItemField::where('tenant_id', $tenantId)
->where('id', $id)
->first();
if (! $field) {
throw new NotFoundHttpException(__('error.not_found'));
}
$field->update([
'field_name' => $data['field_name'] ?? $field->field_name,
'field_type' => $data['field_type'] ?? $field->field_type,
'is_required' => $data['is_required'] ?? $field->is_required,
'default_value' => $data['default_value'] ?? $field->default_value,
'placeholder' => $data['placeholder'] ?? $field->placeholder,
'display_condition' => $data['display_condition'] ?? $field->display_condition,
'validation_rules' => $data['validation_rules'] ?? $field->validation_rules,
'options' => $data['options'] ?? $field->options,
'properties' => $data['properties'] ?? $field->properties,
'category' => $data['category'] ?? $field->category,
'description' => $data['description'] ?? $field->description,
'is_common' => $data['is_common'] ?? $field->is_common,
'updated_by' => $userId,
]);
return $field;
}
/**
* 필드 삭제 (Soft Delete)
*
* 독립 엔티티 아키텍처: 필드 삭제 시 모든 부모 관계도 해제
*/
public function destroy(int $id): void
{
$tenantId = $this->tenantId();
$userId = $this->apiUserId();
$field = ItemField::where('tenant_id', $tenantId)
->where('id', $id)
->first();
if (! $field) {
throw new NotFoundHttpException(__('error.not_found'));
}
// 잠금 체크: 이 필드가 잠금된 연결로 보호되고 있는지 확인
$this->checkCanDelete(EntityRelationship::TYPE_FIELD, $id);
// 1. entity_relationships에서 이 필드의 모든 부모 관계 해제
// (section→field, page→field 관계에서 이 필드 제거)
// 주의: 잠금된 연결이 있으면 위에서 예외 발생
EntityRelationship::where('child_type', EntityRelationship::TYPE_FIELD)
->where('child_id', $id)
->where('is_locked', false)
->delete();
// 2. 필드 Soft Delete
$field->update(['deleted_by' => $userId]);
$field->delete();
}
/**
* 필드 순서 변경 (entity_relationships 기반)
*
* @param array $items [['id' => 1, 'order_no' => 0], ['id' => 2, 'order_no' => 1], ...]
*/
public function reorder(int $sectionId, array $items): void
{
foreach ($items as $item) {
// entity_relationships에서 순서 업데이트
EntityRelationship::where('parent_type', EntityRelationship::TYPE_SECTION)
->where('parent_id', $sectionId)
->where('child_type', EntityRelationship::TYPE_FIELD)
->where('child_id', $item['id'])
->update(['order_no' => $item['order_no']]);
// 필드 자체의 order_no도 동기화
ItemField::where('id', $item['id'])
->update(['order_no' => $item['order_no']]);
}
}
}