Files
sam-api/app/Models/Tenants/Department.php
권혁성 189b38c936 feat: Auditable 트레이트 구현 및 97개 모델 적용
- Auditable 트레이트 신규 생성 (bootAuditable 패턴)
  - creating: created_by/updated_by 자동 채우기
  - updating: updated_by 자동 채우기
  - deleting: deleted_by 채우기 + saveQuietly()
  - created/updated/deleted: audit_logs 자동 기록
- 기존 AuditLogger 패턴과 동일한 try/catch 조용한 실패
- 변경된 필드만 before/after 기록 (updated 이벤트)
- auditExclude 프로퍼티로 모델별 제외 필드 설정 가능
- 제외 대상: Attendance, StockTransaction, TodayIssue 등 고빈도/시스템 모델

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-29 15:33:54 +09:00

82 lines
2.4 KiB
PHP

<?php
namespace App\Models\Tenants;
use App\Models\Members\User;
use App\Models\Permissions\PermissionOverride;
use App\Models\Tenants\Pivots\DepartmentUser;
use App\Traits\Auditable;
use App\Traits\BelongsToTenant;
use App\Traits\ModelTrait;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Spatie\Permission\Traits\HasRoles;
class Department extends Model
{
use Auditable, BelongsToTenant, HasRoles, ModelTrait, SoftDeletes; // 부서도 권한/역할을 가짐
protected $table = 'departments';
protected $guarded = ['id'];
protected $casts = [
'tenant_id' => 'int',
'parent_id' => 'int',
'is_active' => 'bool',
'sort_order' => 'int',
];
protected $hidden = [
'deleted_by', 'deleted_at',
];
// 스파티 가드명(프로젝트 설정에 맞게 조정)
protected string $guard_name = 'web';
/** 상위/하위 부서 */
public function parent(): BelongsTo
{
return $this->belongsTo(self::class, 'parent_id');
}
public function children()
{
return $this->hasMany(self::class, 'parent_id');
}
/** 부서-사용자 N:N (추가 컬럼 포함 Pivot) */
public function users()
{
return $this->belongsToMany(User::class, 'department_user')
->using(DepartmentUser::class)
->wherePivotNull('deleted_at')
->withTimestamps()
->withPivot(['tenant_id', 'is_primary', 'joined_at', 'left_at']);
}
/** 부서의 권한 오버라이드(DENY/임시허용) */
public function permissionOverrides(): MorphMany
{
return $this->morphMany(PermissionOverride::class, 'model');
}
/** 부서-사용자 매핑 로우들(피벗 테이블의 레코드들) */
public function departmentUsers()
{
return $this->hasMany(DepartmentUser::class, 'department_id');
}
/** 부서 소속 사원 (tenant_user_profiles 기반) */
public function employees(): HasMany
{
// Department가 이미 BelongsToTenant로 필터링되므로
// department_id 연결만으로 테넌트 격리됨
return $this->hasMany(TenantUserProfile::class, 'department_id')
->where('employee_status', 'active');
}
}