feat: 사용자 관리 기능 및 MNG 문서 추가

- MNG_CRITICAL_RULES.md: DB 마이그레이션 금지 등 핵심 규칙
- UserController: 사용자 CRUD API 엔드포인트
- StoreUserRequest, UpdateUserRequest: 사용자 검증
- 사용자 관리 뷰: index, create, edit, table
- 시스템 관리 메뉴 UI 개선 (테이블 헤더 스타일)
- docs/INDEX.md: CRITICAL_RULES 링크 추가
This commit is contained in:
2025-11-24 18:49:02 +09:00
parent 74ee0f5f5a
commit 0c86b390ad
16 changed files with 1141 additions and 26 deletions

View File

@@ -0,0 +1,143 @@
<?php
namespace App\Http\Controllers\Api\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function __construct(
private readonly UserService $userService
) {}
/**
* 사용자 목록 조회
*/
public function index(Request $request): JsonResponse
{
$users = $this->userService->getUsers(
$request->all(),
$request->integer('per_page', 15)
);
// HTMX 요청인 경우 HTML 반환
if ($request->header('HX-Request')) {
$html = view('users.partials.table', compact('users'))->render();
return response()->json(['html' => $html]);
}
// 일반 API 요청인 경우 JSON 반환
return response()->json([
'success' => true,
'data' => $users->items(),
'meta' => [
'current_page' => $users->currentPage(),
'last_page' => $users->lastPage(),
'per_page' => $users->perPage(),
'total' => $users->total(),
],
]);
}
/**
* 사용자 상세 조회
*/
public function show(int $id): JsonResponse
{
$user = $this->userService->getUserById($id);
if (!$user) {
return response()->json([
'success' => false,
'message' => '사용자를 찾을 수 없습니다.',
], 404);
}
return response()->json([
'success' => true,
'data' => $user,
]);
}
/**
* 사용자 생성
*/
public function store(StoreUserRequest $request): JsonResponse
{
try {
$user = $this->userService->createUser($request->validated());
return response()->json([
'success' => true,
'message' => '사용자가 생성되었습니다.',
'data' => $user,
'redirect' => route('users.index'),
], 201);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => '사용자 생성에 실패했습니다: ' . $e->getMessage(),
], 500);
}
}
/**
* 사용자 수정
*/
public function update(UpdateUserRequest $request, int $id): JsonResponse
{
try {
$result = $this->userService->updateUser($id, $request->validated());
if (!$result) {
return response()->json([
'success' => false,
'message' => '사용자를 찾을 수 없습니다.',
], 404);
}
return response()->json([
'success' => true,
'message' => '사용자가 수정되었습니다.',
'redirect' => route('users.index'),
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => '사용자 수정에 실패했습니다: ' . $e->getMessage(),
], 500);
}
}
/**
* 사용자 삭제
*/
public function destroy(int $id): JsonResponse
{
try {
$result = $this->userService->deleteUser($id);
if (!$result) {
return response()->json([
'success' => false,
'message' => '사용자를 찾을 수 없습니다.',
], 404);
}
return response()->json([
'success' => true,
'message' => '사용자가 삭제되었습니다.',
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => '사용자 삭제에 실패했습니다: ' . $e->getMessage(),
], 500);
}
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace App\Http\Controllers;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\View\View;
class UserController extends Controller
{
public function __construct(
private readonly UserService $userService
) {}
/**
* 사용자 목록 페이지
*/
public function index(Request $request): View
{
return view('users.index');
}
/**
* 사용자 생성 페이지
*/
public function create(): View
{
return view('users.create');
}
/**
* 사용자 수정 페이지
*/
public function edit(int $id): View
{
$user = $this->userService->getUserById($id);
if (!$user) {
abort(404, '사용자를 찾을 수 없습니다.');
}
return view('users.edit', compact('user'));
}
}

View File

@@ -0,0 +1,71 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'user_id' => 'nullable|string|max:50|unique:users,user_id',
'name' => 'required|string|max:100',
'email' => 'required|email|max:255|unique:users,email',
'phone' => 'nullable|string|max:20',
'password' => 'required|string|min:8|confirmed',
'role' => 'nullable|string|max:50',
'is_active' => 'nullable|boolean',
'is_super_admin' => 'nullable|boolean',
];
}
/**
* Get custom attributes for validator errors.
*
* @return array<string, string>
*/
public function attributes(): array
{
return [
'user_id' => '사용자 ID',
'name' => '이름',
'email' => '이메일',
'phone' => '연락처',
'password' => '비밀번호',
'password_confirmation' => '비밀번호 확인',
'role' => '역할',
'is_active' => '활성 상태',
'is_super_admin' => '슈퍼 관리자',
];
}
/**
* Get custom messages for validator errors.
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'email.unique' => '이미 사용 중인 이메일입니다.',
'user_id.unique' => '이미 사용 중인 사용자 ID입니다.',
'password.confirmed' => '비밀번호가 일치하지 않습니다.',
'password.min' => '비밀번호는 최소 8자 이상이어야 합니다.',
];
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
$userId = $this->route('id');
return [
'user_id' => [
'nullable',
'string',
'max:50',
Rule::unique('users', 'user_id')->ignore($userId),
],
'name' => 'required|string|max:100',
'email' => [
'required',
'email',
'max:255',
Rule::unique('users', 'email')->ignore($userId),
],
'phone' => 'nullable|string|max:20',
'password' => 'nullable|string|min:8|confirmed',
'role' => 'nullable|string|max:50',
'is_active' => 'nullable|boolean',
'is_super_admin' => 'nullable|boolean',
];
}
/**
* Get custom attributes for validator errors.
*
* @return array<string, string>
*/
public function attributes(): array
{
return [
'user_id' => '사용자 ID',
'name' => '이름',
'email' => '이메일',
'phone' => '연락처',
'password' => '비밀번호',
'password_confirmation' => '비밀번호 확인',
'role' => '역할',
'is_active' => '활성 상태',
'is_super_admin' => '슈퍼 관리자',
];
}
/**
* Get custom messages for validator errors.
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'email.unique' => '이미 사용 중인 이메일입니다.',
'user_id.unique' => '이미 사용 중인 사용자 ID입니다.',
'password.confirmed' => '비밀번호가 일치하지 않습니다.',
'password.min' => '비밀번호는 최소 8자 이상이어야 합니다.',
];
}
}

View File

@@ -67,6 +67,7 @@ ### 현재 진행 상황
-**Phase 6**: BOM/카테고리 관리
### 프로젝트 문서
- **[🚨 MNG_CRITICAL_RULES.md](./MNG_CRITICAL_RULES.md)** - 절대 위반 금지 규칙 (필독!)
- **[CURRENT_WORKS.md](../CURRENT_WORKS.md)** - 현재 작업 진행 상황
- **[MIGRATION_PLAN.md](./MIGRATION_PLAN.md)** - Admin → MNG 마이그레이션 계획 (Phase 4)
- **[claudedocs/mng/MNG_PROJECT_PLAN.md](../../claudedocs/mng/MNG_PROJECT_PLAN.md)** - 전체 프로젝트 계획

234
docs/MNG_CRITICAL_RULES.md Normal file
View File

@@ -0,0 +1,234 @@
# MNG 프로젝트 Critical Rules
> 🚨 **절대 위반하지 말아야 할 규칙들**
**작성일**: 2025-11-24
**목적**: 반복되는 실수 방지 및 프로젝트 정책 명확화
---
## 🚫 절대 금지 사항
### 1. DB 마이그레이션 금지
**규칙:**
- ❌ mng/에서는 **절대로** 마이그레이션 파일 생성 금지
- ❌ 기존 테이블 구조 변경 금지
- ✅ 모델 관계 정의만 가능
- ✅ 필요 시 api/에 마이그레이션 요청
**이유:**
- mng/는 api/의 DB를 **읽기 전용**으로 사용
- DB 스키마는 **api/에서만** 관리
- 여러 저장소(api, admin, mng)가 동일 DB 공유
**예외:**
- `admin_*` 접두사 테이블만 mng/에서 생성 가능 (mng 전용 기능용)
- 그래도 가능하면 api/에 요청 권장
**실수 사례:**
```php
// ❌ 잘못된 예: mng/에서 users 테이블 수정 시도
Schema::table('users', function (Blueprint $table) {
$table->foreignId('tenant_id')->comment('테넌트 ID');
});
// ✅ 올바른 예: User 모델에 관계만 정의
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Tenant::class, 'user_tenants');
}
```
---
### 2. 기존 테이블은 재사용만
**재사용 테이블:**
- `users` - 사용자 계정
- `tenants` - 테넌트 (회사)
- `user_tenants` - 사용자-테넌트 관계 (pivot)
- `roles` - 역할
- `departments` - 부서
- `permissions` - 권한
- `products`, `materials`, `categories` 등 모든 비즈니스 테이블
**작업 방법:**
1. **모델 복사**: admin/app/Models → mng/app/Models
2. **Filament 코드 제거**: form(), table() 등 제거
3. **관계만 유지**: belongsTo, hasMany, belongsToMany
4. **Traits 적용**: BelongsToTenant (필요 시), SoftDeletes
---
### 3. Multi-tenant 아키텍처 이해
**user_tenants pivot 테이블 구조:**
```
user_tenants:
├── user_id (FK → users)
├── tenant_id (FK → tenants)
├── is_active (활성 여부)
├── is_default (기본 테넌트)
├── joined_at (가입일)
└── left_at (탈퇴일)
```
**관계 정의:**
```php
// User 모델
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Tenant::class, 'user_tenants')
->withTimestamps()
->withPivot(['is_active', 'is_default', 'joined_at', 'left_at']);
}
// Tenant 모델
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class, 'user_tenants');
}
```
**세션 기반 테넌트 선택:**
- `session('selected_tenant_id')` - 현재 선택된 테넌트
- `currentTenant()` 헬퍼 메서드 사용 권장
---
### 4. BelongsToTenant Trait 사용 주의
**언제 사용하지 말아야 하나:**
-`users` 테이블 - user_tenants pivot 사용
-`tenants` 테이블 - 테넌트 자체
- ❌ 다대다 관계 테이블
**언제 사용해야 하나:**
-`roles` - tenant_id 컬럼 있음
-`departments` - tenant_id 컬럼 있음
-`products` - tenant_id 컬럼 있음
**판단 기준:**
- 테이블에 직접 `tenant_id` 컬럼이 있으면 → BelongsToTenant 사용
- pivot 테이블로 관계가 맺어지면 → belongsToMany 관계만 정의
---
### 5. Service-First 패턴 엄수
**규칙:**
- ✅ 비즈니스 로직은 **Service 클래스**에만
- ✅ Controller는 FormRequest + Service 호출만
- ✅ Model은 관계와 accessor만
**잘못된 예:**
```php
// ❌ Controller에 로직
public function store(Request $request)
{
$user = User::create($request->all());
$user->tenant_id = session('selected_tenant_id');
$user->save();
}
```
**올바른 예:**
```php
// ✅ Service에 로직
class UserService
{
public function createUser(array $data): User
{
// 비즈니스 로직
return User::create($data);
}
}
// Controller는 호출만
public function store(StoreUserRequest $request, UserService $service)
{
$user = $service->createUser($request->validated());
return response()->json(['success' => true]);
}
```
---
### 6. FormRequest 필수 사용
**규칙:**
- ❌ Controller에서 `$request->validate()` 금지
- ✅ 모든 검증은 FormRequest 클래스로
**예:**
```php
// ✅ StoreUserRequest.php
class StoreUserRequest extends FormRequest
{
public function rules(): array
{
return [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
];
}
}
// ✅ Controller
public function store(StoreUserRequest $request)
{
// $request->validated() 만 Service에 전달
}
```
---
## 📋 작업 전 체크리스트
### DB 작업 시:
```
□ mng/에서 작업 중인가? → 마이그레이션 금지!
□ 기존 테이블 수정인가? → api/에 요청!
□ 새 테이블인가? → admin_* 접두사 OR api/에 요청!
□ 관계만 추가인가? → OK, 모델만 수정
```
### 모델 작업 시:
```
□ tenant_id 컬럼 있는가? → BelongsToTenant trait
□ pivot 테이블 사용하는가? → belongsToMany 관계만
□ 비즈니스 로직 있는가? → Service로 이동!
```
### Controller 작업 시:
```
□ FormRequest 생성했는가?
□ Service 클래스 생성했는가?
□ Controller는 호출만 하는가?
```
---
## 🔗 관련 문서
- **[INDEX.md](./INDEX.md)** - MNG 프로젝트 개요
- **[MIGRATION_PLAN.md](./MIGRATION_PLAN.md)** - Admin → MNG 마이그레이션
- **[DEV_PROCESS.md](../../claudedocs/mng/DEV_PROCESS.md)** - 개발 프로세스
- **[database-schema.md](../../docs/specs/database-schema.md)** - DB 스키마
- **[api-rules.md](../../docs/reference/api-rules.md)** - API 개발 규칙
---
## 📝 실수 사례 로그
### 2025-11-24: users 테이블 마이그레이션 시도
- **문제**: mng/에서 users 테이블에 tenant_id 추가 시도
- **원인**: user_tenants pivot 테이블 존재를 간과
- **교훈**: 다대다 관계는 belongsToMany로, 마이그레이션 금지
- **해결**: User 모델에 tenants() 관계만 추가
---
**최종 업데이트**: 2025-11-24
**다음 리뷰**: 반복 실수 발생 시 업데이트

View File

@@ -1,12 +1,12 @@
<table class="w-full">
<thead class="bg-gray-50 border-b">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">부서 코드</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">부서명</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">상위 부서</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">상태</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">정렬순서</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">작업</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">부서 코드</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">부서명</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">상위 부서</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">상태</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">정렬순서</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">작업</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">

View File

@@ -33,8 +33,8 @@ class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-700 hover:bg-gray-
<!-- 사용자 관리 -->
<li>
<a href="#"
class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-700 hover:bg-gray-100">
<a href="{{ route('users.index') }}"
class="flex items-center gap-3 px-4 py-3 rounded-lg text-gray-700 hover:bg-gray-100 {{ request()->routeIs('users.*') ? 'bg-primary text-white hover:bg-primary' : '' }}">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197M13 7a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>

View File

@@ -2,12 +2,12 @@
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">역할 이름</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">설명</th>
<th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">권한 </th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">생성일</th>
<th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">액션</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">역할 이름</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">설명</th>
<th class="px-6 py-3 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider">권한 </th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">생성일</th>
<th class="px-6 py-3 text-right text-sm font-semibold text-gray-700 uppercase tracking-wider">액션</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">

View File

@@ -2,18 +2,18 @@
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">회사명</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">코드</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">상태</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">이메일</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">전화번호</th>
<th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">사용자</th>
<th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">부서</th>
<th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">메뉴</th>
<th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">역할</th>
<th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">생성일</th>
<th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">액션</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">회사명</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">코드</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">상태</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">이메일</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">전화번호</th>
<th class="px-6 py-3 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider">사용자</th>
<th class="px-6 py-3 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider">부서</th>
<th class="px-6 py-3 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider">메뉴</th>
<th class="px-6 py-3 text-center text-sm font-semibold text-gray-700 uppercase tracking-wider">역할</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">생성일</th>
<th class="px-6 py-3 text-right text-sm font-semibold text-gray-700 uppercase tracking-wider">액션</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">

View File

@@ -0,0 +1,164 @@
@extends('layouts.app')
@section('title', '사용자 생성')
@section('content')
<div class="container mx-auto max-w-4xl">
<!-- 페이지 헤더 -->
<div class="flex justify-between items-center mb-6">
<h1 class="text-2xl font-bold text-gray-800">👥 사용자 생성</h1>
<a href="{{ route('users.index') }}" class="text-gray-600 hover:text-gray-800">
목록으로
</a>
</div>
<!-- 영역 -->
<div class="bg-white rounded-lg shadow-sm p-6">
<form id="userForm"
hx-post="/api/admin/users"
hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
hx-swap="none">
<!-- 기본 정보 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">기본 정보</h2>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
사용자 ID
</label>
<input type="text" name="user_id" maxlength="50"
placeholder="선택사항"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
<p class="text-xs text-gray-500 mt-1">비워두면 자동 생성됩니다.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
이름 <span class="text-red-500">*</span>
</label>
<input type="text" name="name" required maxlength="100"
placeholder="홍길동"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
</div>
</div>
<!-- 계정 정보 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">계정 정보</h2>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
이메일 <span class="text-red-500">*</span>
</label>
<input type="email" name="email" required maxlength="255"
placeholder="user@example.com"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
연락처
</label>
<input type="text" name="phone" maxlength="20"
placeholder="010-1234-5678"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
</div>
</div>
<!-- 비밀번호 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">비밀번호</h2>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
비밀번호 <span class="text-red-500">*</span>
</label>
<input type="password" name="password" required minlength="8"
placeholder="최소 8자 이상"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
<p class="text-xs text-gray-500 mt-1">최소 8 이상 입력하세요.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
비밀번호 확인 <span class="text-red-500">*</span>
</label>
<input type="password" name="password_confirmation" required minlength="8"
placeholder="비밀번호 재입력"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
</div>
</div>
<!-- 권한 설정 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">권한 설정</h2>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">역할</label>
<input type="text" name="role" maxlength="50"
placeholder="예: 관리자, 사용자"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div class="flex items-center gap-4">
<label class="flex items-center">
<input type="checkbox" name="is_active" value="1" checked
class="h-4 w-4 text-blue-600 rounded focus:ring-2 focus:ring-blue-500">
<span class="ml-2 text-sm text-gray-700">활성 상태</span>
</label>
<label class="flex items-center">
<input type="checkbox" name="is_super_admin" value="1"
class="h-4 w-4 text-blue-600 rounded focus:ring-2 focus:ring-blue-500">
<span class="ml-2 text-sm text-gray-700">슈퍼 관리자</span>
</label>
</div>
</div>
</div>
<!-- 버튼 영역 -->
<div class="flex justify-end gap-3">
<a href="{{ route('users.index') }}"
class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
취소
</a>
<button type="submit"
class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
생성
</button>
</div>
</form>
</div>
</div>
@endsection
@push('scripts')
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>
// HTMX 응답 처리
document.body.addEventListener('htmx:afterRequest', function(event) {
if (event.detail.target.id === 'userForm') {
const response = JSON.parse(event.detail.xhr.response);
if (response.success) {
alert(response.message);
window.location.href = response.redirect;
} else {
alert('오류: ' + (response.message || '사용자 생성에 실패했습니다.'));
}
}
});
// 에러 처리
document.body.addEventListener('htmx:responseError', function(event) {
if (event.detail.xhr.status === 422) {
const errors = JSON.parse(event.detail.xhr.response).errors;
let errorMsg = '입력 오류:\n';
for (let field in errors) {
errorMsg += '- ' + errors[field].join('\n') + '\n';
}
alert(errorMsg);
} else {
alert('서버 오류가 발생했습니다.');
}
});
</script>
@endpush

View File

@@ -0,0 +1,194 @@
@extends('layouts.app')
@section('title', '사용자 수정')
@section('content')
<div class="container mx-auto max-w-4xl">
<!-- 페이지 헤더 -->
<div class="flex justify-between items-center mb-6">
<h1 class="text-2xl font-bold text-gray-800">👥 사용자 수정</h1>
<a href="{{ route('users.index') }}" class="text-gray-600 hover:text-gray-800">
목록으로
</a>
</div>
<!-- 영역 -->
<div class="bg-white rounded-lg shadow-sm p-6">
<form id="userForm"
hx-post="/api/admin/users/{{ $user->id }}"
hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
hx-swap="none">
<input type="hidden" name="_method" value="PUT">
<!-- 기본 정보 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">기본 정보</h2>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
사용자 ID
</label>
<input type="text" name="user_id" maxlength="50"
value="{{ old('user_id', $user->user_id) }}"
placeholder="선택사항"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
이름 <span class="text-red-500">*</span>
</label>
<input type="text" name="name" required maxlength="100"
value="{{ old('name', $user->name) }}"
placeholder="홍길동"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
</div>
</div>
<!-- 계정 정보 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">계정 정보</h2>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
이메일 <span class="text-red-500">*</span>
</label>
<input type="email" name="email" required maxlength="255"
value="{{ old('email', $user->email) }}"
placeholder="user@example.com"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
연락처
</label>
<input type="text" name="phone" maxlength="20"
value="{{ old('phone', $user->phone) }}"
placeholder="010-1234-5678"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
</div>
</div>
<!-- 비밀번호 변경 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">비밀번호 변경</h2>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
비밀번호
</label>
<input type="password" name="password" minlength="8"
placeholder="변경하지 않으려면 비워두세요"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
<p class="text-xs text-gray-500 mt-1">변경하지 않으려면 비워두세요.</p>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">
비밀번호 확인
</label>
<input type="password" name="password_confirmation" minlength="8"
placeholder="비밀번호 재입력"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
</div>
</div>
<!-- 권한 설정 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">권한 설정</h2>
<div class="space-y-4">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">역할</label>
<input type="text" name="role" maxlength="50"
value="{{ old('role', $user->role) }}"
placeholder="예: 관리자, 사용자"
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<div class="flex items-center gap-4">
<label class="flex items-center">
<input type="checkbox" name="is_active" value="1"
{{ old('is_active', $user->is_active) ? 'checked' : '' }}
class="h-4 w-4 text-blue-600 rounded focus:ring-2 focus:ring-blue-500">
<span class="ml-2 text-sm text-gray-700">활성 상태</span>
</label>
<label class="flex items-center">
<input type="checkbox" name="is_super_admin" value="1"
{{ old('is_super_admin', $user->is_super_admin) ? 'checked' : '' }}
class="h-4 w-4 text-blue-600 rounded focus:ring-2 focus:ring-blue-500">
<span class="ml-2 text-sm text-gray-700">슈퍼 관리자</span>
</label>
</div>
</div>
</div>
<!-- 사용자 정보 -->
<div class="mb-8">
<h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">사용자 정보</h2>
<div class="grid grid-cols-2 gap-4 text-sm">
<div>
<span class="text-gray-600">생성일:</span>
<span class="font-medium">{{ $user->created_at?->format('Y-m-d H:i') ?? '-' }}</span>
</div>
<div>
<span class="text-gray-600">수정일:</span>
<span class="font-medium">{{ $user->updated_at?->format('Y-m-d H:i') ?? '-' }}</span>
</div>
<div>
<span class="text-gray-600">마지막 로그인:</span>
<span class="font-medium">{{ $user->last_login_at?->format('Y-m-d H:i') ?? '없음' }}</span>
</div>
<div>
<span class="text-gray-600">사용자 ID:</span>
<span class="font-medium">#{{ $user->id }}</span>
</div>
</div>
</div>
<!-- 버튼 영역 -->
<div class="flex justify-end gap-3">
<a href="{{ route('users.index') }}"
class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition">
취소
</a>
<button type="submit"
class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
수정
</button>
</div>
</form>
</div>
</div>
@endsection
@push('scripts')
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>
// HTMX 응답 처리
document.body.addEventListener('htmx:afterRequest', function(event) {
if (event.detail.target.id === 'userForm') {
const response = JSON.parse(event.detail.xhr.response);
if (response.success) {
alert(response.message);
window.location.href = response.redirect;
} else {
alert('오류: ' + (response.message || '사용자 수정에 실패했습니다.'));
}
}
});
// 에러 처리
document.body.addEventListener('htmx:responseError', function(event) {
if (event.detail.xhr.status === 422) {
const errors = JSON.parse(event.detail.xhr.response).errors;
let errorMsg = '입력 오류:\n';
for (let field in errors) {
errorMsg += '- ' + errors[field].join('\n') + '\n';
}
alert(errorMsg);
} else {
alert('서버 오류가 발생했습니다.');
}
});
</script>
@endpush

View File

@@ -0,0 +1,92 @@
@extends('layouts.app')
@section('title', '사용자 관리')
@section('content')
<!-- Tenant Selector -->
@include('partials.tenant-selector')
<!-- 페이지 헤더 -->
<div class="flex justify-between items-center mt-6 mb-6">
<h1 class="text-2xl font-bold text-gray-800">👥 사용자 관리</h1>
<a href="{{ route('users.create') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition">
+ 사용자
</a>
</div>
<!-- 필터 영역 -->
<div class="bg-white rounded-lg shadow-sm p-4 mb-6">
<form id="filterForm" class="flex gap-4">
<!-- 검색 -->
<div class="flex-1">
<input type="text"
name="search"
placeholder="이름, 이메일, 연락처로 검색..."
class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
</div>
<!-- 활성 상태 필터 -->
<div class="w-48">
<select name="is_active" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
<option value="">전체 상태</option>
<option value="1">활성</option>
<option value="0">비활성</option>
</select>
</div>
<!-- 검색 버튼 -->
<button type="submit" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition">
검색
</button>
</form>
</div>
<!-- 테이블 영역 (HTMX로 로드) -->
<div id="user-table"
hx-get="/api/admin/users"
hx-trigger="load, filterSubmit from:body"
hx-include="#filterForm"
hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
class="bg-white rounded-lg shadow-sm overflow-hidden">
<!-- 로딩 스피너 -->
<div class="flex justify-center items-center p-12">
<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
</div>
</div>
@endsection
@push('scripts')
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>
// 폼 제출 시 HTMX 이벤트 트리거
document.getElementById('filterForm').addEventListener('submit', function(e) {
e.preventDefault();
htmx.trigger('#user-table', 'filterSubmit');
});
// HTMX 응답 처리
document.body.addEventListener('htmx:afterSwap', function(event) {
if (event.detail.target.id === 'user-table') {
const response = JSON.parse(event.detail.xhr.response);
if (response.html) {
event.detail.target.innerHTML = response.html;
}
}
});
// 삭제 확인
window.confirmDelete = function(id, name) {
if (confirm(`"${name}" 사용자를 삭제하시겠습니까?`)) {
htmx.ajax('DELETE', `/api/admin/users/${id}`, {
target: '#user-table',
swap: 'none',
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
}).then(() => {
htmx.trigger('#user-table', 'filterSubmit');
});
}
};
</script>
@endpush

View File

@@ -0,0 +1,71 @@
<div class="bg-white rounded-lg shadow-sm overflow-hidden">
<table class="w-full">
<thead class="bg-gray-50 border-b">
<tr>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">ID</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">이름</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">이메일</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">연락처</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">테넌트</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">상태</th>
<th class="px-6 py-3 text-left text-sm font-semibold text-gray-700 uppercase tracking-wider">작업</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
@forelse($users as $user)
<tr class="hover:bg-gray-50">
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
{{ $user->user_id ?? '-' }}
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="text-sm font-medium text-gray-900">{{ $user->name }}</div>
@if($user->is_super_admin)
<span class="text-xs text-red-600 font-semibold">슈퍼 관리자</span>
@endif
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{ $user->email }}
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{ $user->phone ?? '-' }}
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{{ $user->currentTenant()?->company_name ?? '-' }}
</td>
<td class="px-6 py-4 whitespace-nowrap">
@if($user->is_active)
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
활성
</span>
@else
<span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">
비활성
</span>
@endif
</td>
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
<a href="{{ route('users.edit', $user->id) }}" class="text-blue-600 hover:text-blue-900 mr-3">
수정
</a>
<button onclick="confirmDelete({{ $user->id }}, '{{ $user->name }}')" class="text-red-600 hover:text-red-900">
삭제
</button>
</td>
</tr>
@empty
<tr>
<td colspan="7" class="px-6 py-4 text-center text-gray-500">
사용자가 없습니다.
</td>
</tr>
@endforelse
</tbody>
</table>
</div>
<!-- 페이지네이션 -->
@include('partials.pagination', [
'paginator' => $users,
'target' => '#user-table',
'includeForm' => '#filterForm'
])

View File

@@ -3,6 +3,7 @@
use App\Http\Controllers\Api\Admin\DepartmentController;
use App\Http\Controllers\Api\Admin\RoleController;
use App\Http\Controllers\Api\Admin\TenantController;
use App\Http\Controllers\Api\Admin\UserController;
use Illuminate\Support\Facades\Route;
/*
@@ -50,4 +51,13 @@
Route::put('/{id}', [DepartmentController::class, 'update'])->name('update');
Route::delete('/{id}', [DepartmentController::class, 'destroy'])->name('destroy');
});
// 사용자 관리 API
Route::prefix('users')->name('users.')->group(function () {
Route::get('/', [UserController::class, 'index'])->name('index');
Route::post('/', [UserController::class, 'store'])->name('store');
Route::get('/{id}', [UserController::class, 'show'])->name('show');
Route::put('/{id}', [UserController::class, 'update'])->name('update');
Route::delete('/{id}', [UserController::class, 'destroy'])->name('destroy');
});
});

View File

@@ -4,6 +4,7 @@
use App\Http\Controllers\DepartmentController;
use App\Http\Controllers\RoleController;
use App\Http\Controllers\TenantController;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;
/*
@@ -50,6 +51,13 @@
Route::get('/{id}/edit', [DepartmentController::class, 'edit'])->name('edit');
});
// 사용자 관리 (Blade 화면만)
Route::prefix('users')->name('users.')->group(function () {
Route::get('/', [UserController::class, 'index'])->name('index');
Route::get('/create', [UserController::class, 'create'])->name('create');
Route::get('/{id}/edit', [UserController::class, 'edit'])->name('edit');
});
// 대시보드
Route::get('/dashboard', function () {
return view('dashboard.index');