v7.0.0-beta.4 release

This commit is contained in:
HeuJung committed 2026-05-11 11:29:41 +09:00
1 parent 05db17887d
commit 1db039ff34
1545 files changed
+136783 -11634

No files matched your search

+54 -5
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\ActivityLogType;
use App\Extension\ExtensionManager;
use App\Extension\HookManager;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
@@ -155,31 +156,79 @@ class ActivityLog extends Model
/**
* 액션 라벨을 반환합니다.
*
* 3단계 조회: 전체 키 → 마지막 세그먼트 → raw 문자열 fallback
* 5단계 조회: 모듈 lang 전체 키 → 모듈 lang 마지막 세그먼트
* → 코어 lang 전체 키 → 코어 lang 마지막 세그먼트 → raw 문자열 fallback
*
* 모듈/플러그인 origin 라벨은 자체 lang 파일에서 우선 조회되어 G7 의 영역 분리
* 설계 의도와 일치합니다. 모듈 lang 미정의 시 코어 lang fallback (하위 호환).
*
* Origin 식별 우선순위:
* 1) loggable_type FQCN (가장 정확)
* 2) properties.extension_origin (loggable 없는 케이스 — 호출 시점 trait 자동 주입)
*
* @return string
*/
public function getActionLabelAttribute(): string
{
// 1단계: 전체 액션 키 (예: activity_log.action.user.create)
$namespace = $this->resolveOriginNamespace();
$lastSegment = last(explode('.', $this->action));
if ($namespace !== null) {
// 1단계: 모듈 lang 의 전체 액션 키
$moduleFullKey = "{$namespace}::activity_log.action.{$this->action}";
$translated = __($moduleFullKey);
if ($translated !== $moduleFullKey) {
return $translated;
}
// 2단계: 모듈 lang 의 마지막 세그먼트
$moduleSegmentKey = "{$namespace}::activity_log.action.{$lastSegment}";
$translated = __($moduleSegmentKey);
if ($translated !== $moduleSegmentKey) {
return $translated;
}
}
// 3단계: 코어 lang 의 전체 액션 키
$fullKey = "activity_log.action.{$this->action}";
$translated = __($fullKey);
if ($translated !== $fullKey) {
return $translated;
}
// 2단계: 마지막 세그먼트만 (예: activity_log.action.create)
$lastSegment = last(explode('.', $this->action));
// 4단계: 코어 lang 의 마지막 세그먼트
$segmentKey = "activity_log.action.{$lastSegment}";
$translated = __($segmentKey);
if ($translated !== $segmentKey) {
return $translated;
}
// 3단계: raw action 문자열 fallback
// 5단계: raw action 문자열 fallback
return $this->action;
}
/**
* 본 활동 로그의 origin 모듈/플러그인 lang 네임스페이스를 추론합니다.
*
* @return string|null 모듈/플러그인 식별자 (네임스페이스), 코어 origin 또는 미해석 시 null
*/
protected function resolveOriginNamespace(): ?string
{
if ($this->loggable_type !== null) {
$resolved = ExtensionManager::resolveExtensionByFqcn($this->loggable_type);
if ($resolved !== null) {
return $resolved;
}
}
$origin = $this->properties['extension_origin'] ?? null;
if (is_string($origin) && $origin !== '') {
return $origin;
}
return null;
}
/**
* 행위자 이름을 반환합니다.
*
+150 -4
View File
@@ -15,15 +15,20 @@ use Illuminate\Database\Eloquent\Model;
* use HasUserOverrides;
*
* protected array $trackableFields = ['subject', 'body', 'is_active'];
*
* // 다국어 JSON 컬럼은 sub-key dot-path 단위 보존
* protected array $translatableTrackableFields = ['subject', 'body'];
* }
* ```
*
* 동작:
* - 사용자가 trackable 필드를 수정 → user_overrides 에 자동 기록
* - 일반 컬럼: `['is_active']` (컬럼명)
* - 다국어 JSON 컬럼: `['name.ko']` (사용자가 ko 만 수정한 경우 sub-key 단위)
* - 사용자 경로가 Eloquent 인스턴스 `->update()`, `->save()` 또는 mass update
* `Model::where(...)->update()` 중 어느 것이든 **모두 자동 추적**
* (mass update 는 커스텀 Builder 가 per-row 로 분해하여 `updating` 이벤트 발화)
* - 시더/업그레이드 스텝에서 syncFromUpgrade() 호출 → 기록된 필드 보존
* 다국어 컬럼은 보존 대상 locale 만 이전 값 유지, 나머지 locale 은 신규 값으로 갱신
*
* 컨테이너 플래그 `user_overrides.seeding` 으로 시더/사용자 컨텍스트를 구분합니다.
*
@@ -31,6 +36,7 @@ use Illuminate\Database\Eloquent\Model;
* `DB::table('...')->update(...)` (Eloquent 우회) 사용을 권장합니다.
*
* @since 7.0.0-beta.2
* @since 7.0.0-beta.4 다국어 JSON 컬럼 sub-key dot-path 단위 보존 (translatableTrackableFields)
*/
trait HasUserOverrides
{
@@ -57,9 +63,25 @@ trait HasUserOverrides
$userOverrides = $model->user_overrides ?? [];
$original = $userOverrides;
$translatable = $model->getTranslatableTrackableFields();
foreach ($model->getTrackableFields() as $field) {
if ($model->isDirty($field) && ! in_array($field, $userOverrides, true)) {
if (! $model->isDirty($field)) {
continue;
}
if (in_array($field, $translatable, true)) {
$userOverrides = $model->mergeTranslatableOverrides(
$userOverrides,
$field,
$model->getOriginal($field),
$model->getAttribute($field),
);
continue;
}
if (! in_array($field, $userOverrides, true)) {
$userOverrides[] = $field;
}
}
@@ -82,6 +104,52 @@ trait HasUserOverrides
return property_exists($this, 'trackableFields') ? $this->trackableFields : [];
}
/**
* 다국어 JSON 컬럼인 trackable 필드 목록을 반환합니다.
*
* 모델에서 `protected array $translatableTrackableFields = [...]` 로 오버라이드합니다.
* 여기 등록된 필드는 sub-key dot-path 단위로 user_overrides 에 기록되며
* (예: `['name.ko', 'name.en']`), syncFromUpgrade 시 sub-key 단위로 보존됩니다.
*
* trackableFields 와의 관계: translatableTrackableFields ⊂ trackableFields 이어야 합니다.
*
* @return array<int, string>
*/
public function getTranslatableTrackableFields(): array
{
return property_exists($this, 'translatableTrackableFields') ? $this->translatableTrackableFields : [];
}
/**
* 다국어 필드 변경 비교 후 user_overrides 에 dot-path 항목을 누적 추가합니다.
*
* @param array<int, string> $userOverrides 현재 user_overrides 배열
* @param string $field 컬럼명 (예: 'name')
* @param mixed $original 변경 전 컬럼 값 (array 또는 null)
* @param mixed $current 변경 후 컬럼 값 (array 또는 null)
* @return array<int, string> 갱신된 user_overrides 배열
*/
protected function mergeTranslatableOverrides(array $userOverrides, string $field, mixed $original, mixed $current): array
{
$originalArr = is_array($original) ? $original : [];
$currentArr = is_array($current) ? $current : [];
$allLocales = array_unique(array_merge(array_keys($originalArr), array_keys($currentArr)));
foreach ($allLocales as $locale) {
$before = $originalArr[$locale] ?? null;
$after = $currentArr[$locale] ?? null;
if ($before === $after) {
continue;
}
$entry = "{$field}.{$locale}";
if (! in_array($entry, $userOverrides, true)) {
$userOverrides[] = $entry;
}
}
return $userOverrides;
}
/**
* 현재 모델 상태와 신규 입력 값을 비교하여 user_overrides 에 추가될 필드 집합을 계산합니다.
*
@@ -95,12 +163,28 @@ trait HasUserOverrides
public function calculateUserOverridesFor(array $incomingAttributes): array
{
$current = $this->user_overrides ?? [];
$translatable = $this->getTranslatableTrackableFields();
foreach ($this->getTrackableFields() as $field) {
if (! array_key_exists($field, $incomingAttributes)) {
continue;
}
$incoming = $incomingAttributes[$field];
if (in_array($field, $translatable, true)) {
$incomingArr = $this->normalizeTranslatableValue($incoming);
if ($incomingArr === null) {
if ($this->{$field} != $incoming && ! in_array($field, $current, true)) {
$current[] = $field;
}
continue;
}
$current = $this->mergeTranslatableOverrides($current, $field, $this->{$field}, $incomingArr);
continue;
}
if ($this->{$field} != $incoming && ! in_array($field, $current, true)) {
$current[] = $field;
}
@@ -109,10 +193,35 @@ trait HasUserOverrides
return $current;
}
/**
* 다국어 값으로 정규화 — array 이면 그대로, JSON 문자열이면 디코드, 그 외 null.
*
* @param mixed $value
* @return array<string, mixed>|null
*/
protected function normalizeTranslatableValue(mixed $value): ?array
{
if (is_array($value)) {
return $value;
}
if (is_string($value) && $value !== '') {
$decoded = json_decode($value, true);
if (is_array($decoded)) {
return $decoded;
}
}
return null;
}
/**
* 업그레이드 스텝/시더에서 호출 — user_overrides 보존하며 갱신합니다.
*
* trackable 필드 + user_overrides 에 등록된 필드는 갱신을 건너뜁니다.
* 일반 trackable 필드: user_overrides 에 컬럼명이 있으면 갱신 SKIP.
* 다국어 trackable 필드 (translatableTrackableFields): sub-key 단위 머지.
* - user_overrides 에 `field.{locale}` 이 있으면 해당 locale 키만 기존 값 유지
* - 나머지 locale 키는 신규 값으로 갱신 (활성 언어팩 자동 동기화)
* - 호환성: user_overrides 에 컬럼명(`field`) 만 있는 legacy row 는 컬럼 전체 보존 (기존 동작)
*
* @param array<string, mixed> $newAttributes 시더 정의 값
*/
@@ -120,12 +229,49 @@ trait HasUserOverrides
{
$userOverrides = $this->user_overrides ?? [];
$trackable = $this->getTrackableFields();
$translatable = $this->getTranslatableTrackableFields();
$updateData = [];
foreach ($newAttributes as $field => $value) {
if (in_array($field, $trackable, true) && in_array($field, $userOverrides, true)) {
$isTrackable = in_array($field, $trackable, true);
$isTranslatable = in_array($field, $translatable, true);
// legacy 컬럼명 보존 (전체 컬럼 갱신 SKIP)
if ($isTrackable && in_array($field, $userOverrides, true)) {
continue;
}
if ($isTranslatable) {
$newArr = $this->normalizeTranslatableValue($value);
if ($newArr === null) {
$updateData[$field] = $value;
continue;
}
$currentArr = $this->normalizeTranslatableValue($this->getAttribute($field)) ?? [];
$merged = $newArr;
foreach ($newArr as $locale => $newVal) {
$entry = "{$field}.{$locale}";
if (in_array($entry, $userOverrides, true) && array_key_exists($locale, $currentArr)) {
$merged[$locale] = $currentArr[$locale];
}
}
// 신규 값에 누락된 locale 키 중 사용자가 보존한 키는 유지
foreach ($currentArr as $locale => $currentVal) {
if (array_key_exists($locale, $merged)) {
continue;
}
if (in_array("{$field}.{$locale}", $userOverrides, true)) {
$merged[$locale] = $currentVal;
}
}
$updateData[$field] = $merged;
continue;
}
$updateData[$field] = $value;
}
@@ -0,0 +1,128 @@
<?php
namespace App\Models\Concerns;
use Illuminate\Database\Eloquent\Builder;
/**
* IDV(본인인증) 메시지 템플릿 컨텐츠 Trait.
*
* IdentityMessageTemplate 모델에서 사용하는 casts, 스코프, 다국어 헬퍼,
* 변수 치환 메서드를 제공합니다. 알림 시스템(NotificationContentBehavior)과
* 완전히 분리된 IDV 전용 트레이트입니다.
*/
trait IdentityMessageContentBehavior
{
/**
* 공통 casts 초기화.
*
* @return void
*/
public function initializeIdentityMessageContentBehavior(): void
{
$this->mergeCasts([
'subject' => 'array',
'body' => 'array',
'is_active' => 'boolean',
'is_default' => 'boolean',
]);
}
/**
* 활성 템플릿만 조회합니다.
*
* @param Builder $query
* @return Builder
*/
public function scopeActive(Builder $query): Builder
{
return $query->where('is_active', true);
}
/**
* 특정 채널의 템플릿을 조회합니다.
*
* @param Builder $query
* @param string $channel
* @return Builder
*/
public function scopeByChannel(Builder $query, string $channel): Builder
{
return $query->where('channel', $channel);
}
/**
* 현재 로케일의 제목을 반환합니다.
*
* @param string|null $locale
* @return string
*/
public function getLocalizedSubject(?string $locale = null): string
{
$locale = $locale ?? app()->getLocale();
$subject = $this->subject ?? [];
return $subject[$locale] ?? $subject['ko'] ?? $subject['en'] ?? '';
}
/**
* 현재 로케일의 본문을 반환합니다.
*
* @param string|null $locale
* @return string
*/
public function getLocalizedBody(?string $locale = null): string
{
$locale = $locale ?? app()->getLocale();
$body = $this->body ?? [];
return $body[$locale] ?? $body['ko'] ?? $body['en'] ?? '';
}
/**
* 변수를 치환하여 제목과 본문을 반환합니다.
*
* {key} 형식의 변수를 실제 값으로 치환합니다.
*
* @param array $data key => value 변수 맵
* @param string|null $locale
* @return array{subject: string, body: string}
*/
public function replaceVariables(array $data, ?string $locale = null): array
{
$subject = $this->getLocalizedSubject($locale);
$body = $this->getLocalizedBody($locale);
$replacements = [];
foreach ($data as $key => $value) {
if ($value === null || is_array($value) || is_object($value)) {
continue;
}
$replacements['{'.$key.'}'] = (string) $value;
}
return [
'subject' => strtr($subject, $replacements),
'body' => strtr($body, $replacements),
];
}
/**
* 단일 문자열의 변수를 치환합니다.
*
* @param string $template
* @param array $data
* @return string
*/
public function replaceVariablesInString(string $template, array $data): string
{
$replacements = [];
foreach ($data as $key => $value) {
if (is_string($value) || is_numeric($value)) {
$replacements['{'.$key.'}'] = (string) $value;
}
}
return strtr($template, $replacements);
}
}
@@ -60,7 +60,7 @@ trait NotificationContentBehavior
$locale = $locale ?? app()->getLocale();
$subject = $this->subject ?? [];
return $subject[$locale] ?? $subject['ko'] ?? $subject['en'] ?? '';
return $subject[$locale] ?? $subject[config('app.fallback_locale', 'ko')] ?? '';
}
/**
@@ -74,7 +74,7 @@ trait NotificationContentBehavior
$locale = $locale ?? app()->getLocale();
$body = $this->body ?? [];
return $body[$locale] ?? $body['ko'] ?? $body['en'] ?? '';
return $body[$locale] ?? $body[config('app.fallback_locale', 'ko')] ?? '';
}
/**
+213
View File
@@ -0,0 +1,213 @@
<?php
namespace App\Models;
use App\Enums\IdentityMessageScopeType;
use App\Models\Concerns\HasUserOverrides;
use App\Services\IdentityMessageDefinitionService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* 본인인증 메시지 정의 모델.
*
* 알림 시스템(NotificationDefinition)과 분리된 IDV 전용 메시지 템플릿 시스템의 정의 레코드.
* (provider_id, scope_type, scope_value) 매트릭스로 식별.
*/
class IdentityMessageDefinition extends Model
{
use HasFactory, HasUserOverrides;
/** @deprecated 7.0.0-beta.5 — IdentityMessageScopeType enum 사용 */
public const SCOPE_PROVIDER_DEFAULT = 'provider_default';
/** @deprecated 7.0.0-beta.5 — IdentityMessageScopeType enum 사용 */
public const SCOPE_PURPOSE = 'purpose';
/** @deprecated 7.0.0-beta.5 — IdentityMessageScopeType enum 사용 */
public const SCOPE_POLICY = 'policy';
/**
* 사용자 수정 보존 대상 필드.
*
* @var array<int, string>
*/
protected array $trackableFields = ['name', 'is_active'];
/**
* 다국어 JSON 컬럼 — sub-key dot-path 단위 user_overrides 보존.
*
* @var array<int, string>
*/
protected array $translatableTrackableFields = ['name'];
/**
* 활동 로그 추적 필드.
*
* @var array<string, array<string, string>>
*/
public static array $activityLogFields = [
'name' => ['label_key' => 'activity_log.fields.name', 'type' => 'text'],
'channels' => ['label_key' => 'activity_log.fields.channels', 'type' => 'text'],
'is_active' => ['label_key' => 'activity_log.fields.is_active', 'type' => 'boolean'],
];
/**
* @var string
*/
protected $table = 'identity_message_definitions';
/**
* @var array<string, string>
*/
protected $attributes = [
'channels' => '["mail"]',
'variables' => '[]',
'scope_value' => '',
];
/**
* @var array<int, string>
*/
protected $fillable = [
'provider_id',
'scope_type',
'scope_value',
'name',
'description',
'channels',
'variables',
'extension_type',
'extension_identifier',
'is_active',
'is_default',
'user_overrides',
];
/**
* 모델 이벤트 등록 — 모든 변경 시 정의 캐시 자동 삭제.
*/
protected static function booted(): void
{
$invalidate = function () {
try {
app(IdentityMessageDefinitionService::class)->invalidateAllCache();
} catch (\Throwable) {
// 테스트/마이그레이션 환경에서 서비스 미등록 시 무시
}
};
static::saved($invalidate);
static::deleted($invalidate);
}
/**
* 캐스팅 정의.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'name' => 'array',
'description' => 'array',
'channels' => 'array',
'variables' => 'array',
'scope_type' => IdentityMessageScopeType::class,
'is_active' => 'boolean',
'is_default' => 'boolean',
'user_overrides' => 'array',
];
}
/**
* 메시지 템플릿 관계.
*
* @return HasMany
*/
public function templates(): HasMany
{
return $this->hasMany(IdentityMessageTemplate::class, 'definition_id');
}
/**
* 활성 정의만 조회.
*
* @param Builder $query
* @return Builder
*/
public function scopeActive(Builder $query): Builder
{
return $query->where('is_active', true);
}
/**
* 특정 프로바이더 정의 조회.
*
* @param Builder $query
* @param string $providerId
* @return Builder
*/
public function scopeByProvider(Builder $query, string $providerId): Builder
{
return $query->where('provider_id', $providerId);
}
/**
* 특정 scope 정의 조회.
*
* @param Builder $query
* @param string $scopeType
* @param string|null $scopeValue
* @return Builder
*/
public function scopeByScope(Builder $query, string $scopeType, ?string $scopeValue = null): Builder
{
return $query->where('scope_type', $scopeType)
->where('scope_value', $scopeValue ?? '');
}
/**
* 특정 확장 정의 조회.
*
* @param Builder $query
* @param string $extensionType
* @param string $extensionIdentifier
* @return Builder
*/
public function scopeByExtension(Builder $query, string $extensionType, string $extensionIdentifier): Builder
{
return $query->where('extension_type', $extensionType)
->where('extension_identifier', $extensionIdentifier);
}
/**
* 현재 로케일의 이름 반환.
*
* @param string|null $locale
* @return string
*/
public function getLocalizedName(?string $locale = null): string
{
$locale = $locale ?? app()->getLocale();
$name = $this->name ?? [];
return $name[$locale] ?? $name['ko'] ?? $name['en'] ?? '';
}
/**
* 현재 로케일의 설명 반환.
*
* @param string|null $locale
* @return string
*/
public function getLocalizedDescription(?string $locale = null): string
{
$locale = $locale ?? app()->getLocale();
$description = $this->description ?? [];
return $description[$locale] ?? $description['ko'] ?? $description['en'] ?? '';
}
}
+114
View File
@@ -0,0 +1,114 @@
<?php
namespace App\Models;
use App\Models\Concerns\HasUserOverrides;
use App\Models\Concerns\IdentityMessageContentBehavior;
use App\Services\IdentityMessageDefinitionService;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* 본인인증 메시지 템플릿 모델.
*
* 정의(IdentityMessageDefinition) 1건 × 채널 N개 구조. 다국어 subject/body + 활성 토글
* + user_overrides 보존을 제공합니다. NotificationTemplate 와 분리된 IDV 전용 모델.
*/
class IdentityMessageTemplate extends Model
{
use HasFactory, HasUserOverrides, IdentityMessageContentBehavior;
/**
* 사용자 수정 보존 대상 필드.
*
* @var array<int, string>
*/
protected array $trackableFields = [
'subject',
'body',
'is_active',
];
/**
* 활동 로그 추적 필드.
*
* @var array<string, array<string, string>>
*/
public static array $activityLogFields = [
'subject' => ['label_key' => 'activity_log.fields.subject', 'type' => 'text'],
'body' => ['label_key' => 'activity_log.fields.body', 'type' => 'text'],
'is_active' => ['label_key' => 'activity_log.fields.is_active', 'type' => 'boolean'],
];
/**
* @var string
*/
protected $table = 'identity_message_templates';
/**
* @var array<int, string>
*/
protected $fillable = [
'definition_id',
'channel',
'subject',
'body',
'is_active',
'is_default',
'user_overrides',
'updated_by',
];
/**
* 모델 이벤트 등록 — 변경 시 정의/템플릿 캐시 자동 삭제.
*/
protected static function booted(): void
{
$invalidate = function () {
try {
app(IdentityMessageDefinitionService::class)->invalidateAllCache();
} catch (\Throwable) {
// 테스트/마이그레이션 환경에서 서비스 미등록 시 무시
}
};
static::saved($invalidate);
static::deleted($invalidate);
}
/**
* 캐스팅 정의.
*
* IdentityMessageContentBehavior trait 가 subject/body/is_active/is_default 를 처리하므로
* 여기서는 user_overrides 만 추가합니다.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'user_overrides' => 'array',
];
}
/**
* 메시지 정의 관계.
*
* @return BelongsTo
*/
public function definition(): BelongsTo
{
return $this->belongsTo(IdentityMessageDefinition::class, 'definition_id');
}
/**
* 수정자 관계.
*
* @return BelongsTo
*/
public function updater(): BelongsTo
{
return $this->belongsTo(User::class, 'updated_by');
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
namespace App\Models;
use App\Enums\IdentityPolicyAppliesTo;
use App\Enums\IdentityPolicyFailMode;
use App\Enums\IdentityPolicyScope;
use App\Enums\IdentityPolicySourceType;
use App\Models\Concerns\HasUserOverrides;
use Illuminate\Database\Eloquent\Model;
/**
* 본인인증 정책 모델.
*
* scope(route/hook/custom) x target(라우트명/훅명/커스텀키) 매칭으로
* 특정 지점에 IDV 를 강제합니다. 선언형(Seeder) + 운영자 편집(user_overrides 보존) 혼합 관리.
*
* @since 7.0.0-beta.4
*
* @property int $id
* @property string $key
* @property string $scope
* @property string $target
* @property string $purpose
* @property string|null $provider_id
* @property int $grace_minutes
* @property bool $enabled
* @property int $priority
* @property array|null $conditions
* @property string $source_type
* @property string $source_identifier
* @property string $applies_to
* @property string $fail_mode
* @property array|null $user_overrides
*/
class IdentityPolicy extends Model
{
use HasUserOverrides;
protected $table = 'identity_policies';
protected $fillable = [
'key',
'scope',
'target',
'purpose',
'provider_id',
'grace_minutes',
'enabled',
'priority',
'conditions',
'source_type',
'source_identifier',
'applies_to',
'fail_mode',
'user_overrides',
];
/**
* ActivityLog 추적 필드 — 관리자 CRUD 대상 전체를 감사 대상으로.
*/
protected array $activityLogFields = [
'key', 'scope', 'target', 'purpose', 'provider_id',
'grace_minutes', 'enabled', 'priority', 'applies_to', 'fail_mode',
];
/**
* HasUserOverrides — 운영자가 수정 가능한 필드.
* Seeder 재실행 시 user_overrides 에 기록된 필드는 운영자 수정값을 보존한다.
*/
protected array $trackableFields = [
'enabled', 'grace_minutes', 'provider_id', 'fail_mode', 'conditions',
];
protected function casts(): array
{
return [
'enabled' => 'boolean',
'grace_minutes' => 'integer',
'priority' => 'integer',
'scope' => IdentityPolicyScope::class,
'fail_mode' => IdentityPolicyFailMode::class,
'applies_to' => IdentityPolicyAppliesTo::class,
'source_type' => IdentityPolicySourceType::class,
'conditions' => 'array',
'user_overrides' => 'array',
];
}
/**
* Route scope 자동 매핑 캐시 키 — Repository::getRouteScopeIndex 가 사용.
* 정책 CRUD 시 saved/deleted 이벤트로 즉시 invalidate 되어 다음 요청부터 새 정책 반영.
*
* 캐시 백엔드는 CoreCacheDriver(접두사 g7:core:) 를 통해 G7 표준 격리 적용.
*/
public const ROUTE_SCOPE_CACHE_KEY = 'identity_policies.route_scope_index';
/**
* 캐시 무효화 태그 — Repository::getRouteScopeIndex 가 같은 태그로 등록하므로
* flushTags 한 번에 일괄 정리됨 (단일 키 forget 보다 향후 다중 캐시 키 확장에 안전).
*/
public const ROUTE_SCOPE_CACHE_TAG = 'identity_policy';
protected static function booted(): void
{
static::saved(static::flushRouteScopeCache(...));
static::deleted(static::flushRouteScopeCache(...));
}
public static function flushRouteScopeCache(): void
{
$cache = app(\App\Contracts\Extension\CacheInterface::class);
if ($cache->supportsTags()) {
$cache->flushTags([self::ROUTE_SCOPE_CACHE_TAG]);
return;
}
$cache->forget(self::ROUTE_SCOPE_CACHE_KEY);
}
}
+112
View File
@@ -0,0 +1,112 @@
<?php
namespace App\Models;
use App\Enums\IdentityOriginType;
use App\Enums\IdentityVerificationStatus;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* 본인인증 Challenge 감사 로그.
*
* Challenge 생명주기 전체(발송/재시도/검증/만료/취소/정책 위반)를 기록하는 append-only 테이블.
* activity_logs 와 역할을 분리 — 이쪽은 기술 이벤트 감사, activity_logs 는 사용자 관점 서사.
*
* @since 7.0.0-beta.4
*
* @property string $id
* @property string $provider_id
* @property string $purpose
* @property string $channel
* @property int|null $user_id
* @property string $target_hash
* @property string $status
* @property string|null $render_hint
* @property int $attempts
* @property int $max_attempts
* @property string|null $ip_address
* @property string|null $user_agent
* @property string|null $origin_type
* @property string|null $origin_identifier
* @property string|null $origin_policy_key
* @property array|null $properties
* @property array|null $metadata
* @property string|null $verification_token
* @property \Carbon\Carbon|null $expires_at
* @property \Carbon\Carbon|null $verified_at
* @property \Carbon\Carbon|null $consumed_at
*/
class IdentityVerificationLog extends Model
{
use HasUuids;
public const STATUS_REQUESTED = 'requested';
public const STATUS_SENT = 'sent';
public const STATUS_VERIFIED = 'verified';
public const STATUS_FAILED = 'failed';
public const STATUS_EXPIRED = 'expired';
public const STATUS_CANCELLED = 'cancelled';
public const STATUS_POLICY_VIOLATION_LOGGED = 'policy_violation_logged';
protected $table = 'identity_verification_logs';
public $incrementing = false;
protected $keyType = 'string';
protected $fillable = [
'id',
'provider_id',
'purpose',
'channel',
'user_id',
'target_hash',
'status',
'render_hint',
'attempts',
'max_attempts',
'ip_address',
'user_agent',
'origin_type',
'origin_identifier',
'origin_policy_key',
'properties',
'metadata',
'verification_token',
'expires_at',
'verified_at',
'consumed_at',
];
protected function casts(): array
{
return [
'attempts' => 'integer',
'max_attempts' => 'integer',
'status' => IdentityVerificationStatus::class,
'origin_type' => IdentityOriginType::class,
'properties' => 'array',
'metadata' => 'array',
'expires_at' => 'datetime',
'verified_at' => 'datetime',
'consumed_at' => 'datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function isExpired(): bool
{
return $this->expires_at !== null && $this->expires_at->isPast();
}
public function isVerified(): bool
{
return $this->status === IdentityVerificationStatus::Verified;
}
}
+248
View File
@@ -0,0 +1,248 @@
<?php
namespace App\Models;
use App\Enums\LanguagePackOrigin;
use App\Enums\LanguagePackScope;
use App\Enums\LanguagePackStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* 언어팩 모델.
*
* 슬롯(scope, target_identifier, locale) 단위로 여러 벤더의 언어팩이 공존할 수 있으며,
* 슬롯당 active 상태는 1개만 허용됩니다 (DB functional unique index).
*
* @property int $id
* @property string $identifier
* @property string $vendor
* @property string $scope
* @property string|null $target_identifier
* @property string $locale
* @property string $locale_name
* @property string $locale_native_name
* @property string $text_direction
* @property string $version
* @property string|null $latest_version
* @property string|null $target_version_constraint
* @property bool $target_version_mismatch
* @property string|null $license
* @property array<string, string>|null $description
* @property string $status
* @property bool $is_protected
* @property array<string, mixed> $manifest
* @property string|null $source_type
* @property string|null $source_url
* @property int|null $installed_by
* @property \Illuminate\Support\Carbon|null $installed_at
* @property \Illuminate\Support\Carbon|null $activated_at
*/
class LanguagePack extends Model
{
use HasFactory;
/**
* 테이블명.
*
* @var string
*/
protected $table = 'language_packs';
/**
* 기본키.
*
* @var string
*/
protected $primaryKey = 'id';
/**
* 타임스탬프 사용 여부.
*
* @var bool
*/
public $timestamps = true;
/**
* 대량 할당 허용 컬럼.
*
* @var array<int, string>
*/
protected $fillable = [
'identifier',
'vendor',
'scope',
'target_identifier',
'locale',
'locale_name',
'locale_native_name',
'text_direction',
'version',
'latest_version',
'target_version_constraint',
'target_version_mismatch',
'license',
'description',
'status',
'is_protected',
'manifest',
'source_type',
'source_url',
'installed_by',
'installed_at',
'activated_at',
];
/**
* 캐스팅 정의.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'description' => 'array',
'manifest' => 'array',
'is_protected' => 'boolean',
'target_version_mismatch' => 'boolean',
'installed_at' => 'datetime',
'activated_at' => 'datetime',
];
}
/**
* 설치자(User) 와의 관계를 정의합니다.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function installer(): BelongsTo
{
return $this->belongsTo(User::class, 'installed_by');
}
/**
* 활성 상태 여부를 확인합니다.
*
* @return bool 활성 여부
*/
public function isActive(): bool
{
return $this->status === LanguagePackStatus::Active->value;
}
/**
* 코어 스코프 여부를 확인합니다.
*
* @return bool 코어 여부
*/
public function isCoreScope(): bool
{
return $this->scope === LanguagePackScope::Core->value;
}
/**
* 번들 (수정 보호) 언어팩 여부를 확인합니다.
*
* @return bool 번들 여부
*/
public function isProtected(): bool
{
return (bool) $this->is_protected;
}
/**
* UI 출처(origin) 분류를 반환합니다.
*
* `source_type` 컬럼을 3그룹(built_in / bundled / user_installed) 으로 매핑한 값.
* 가상 미설치 번들 행도 source_type=bundled 이므로 동일 매핑.
*
* @return string|null origin 값 (source_type 누락 시 null)
*/
public function getOriginAttribute(): ?string
{
return LanguagePackOrigin::fromSourceTypeValue($this->source_type)?->value;
}
/**
* 슬롯 키를 반환합니다 ({scope}|{target_identifier}|{locale}).
*
* @return string 슬롯 키
*/
public function slotKey(): string
{
return sprintf(
'%s|%s|%s',
$this->scope,
$this->target_identifier ?? '',
$this->locale
);
}
/**
* 활성 언어팩만 조회하는 스코프.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeActive(Builder $query): Builder
{
return $query->where('status', LanguagePackStatus::Active->value);
}
/**
* 특정 스코프 언어팩만 조회하는 스코프.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $scope 스코프 문자열
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeOfScope(Builder $query, string $scope): Builder
{
return $query->where('scope', $scope);
}
/**
* 특정 슬롯의 언어팩만 조회하는 스코프.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string $scope 스코프 문자열
* @param string|null $targetIdentifier 대상 확장 식별자
* @param string $locale 로케일
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeForSlot(
Builder $query,
string $scope,
?string $targetIdentifier,
string $locale
): Builder {
return $query
->where('scope', $scope)
->where('target_identifier', $targetIdentifier)
->where('locale', $locale);
}
/**
* 활성 디렉토리 절대 경로를 반환합니다.
*
* source_type=bundled_with_extension 인 가상 레코드는 확장 디렉토리 경로를 반환하고,
* 그 외에는 lang-packs/{identifier}/ 경로를 반환합니다.
*
* @return string 디렉토리 절대 경로
*/
public function resolveDirectory(): string
{
if ($this->source_type === 'bundled_with_extension' && $this->source_url) {
return base_path($this->source_url);
}
// uninstalled 가상 행(미설치 번들)은 활성 디렉토리가 없으므로 _bundled 원본을 가리킴
if ($this->status === LanguagePackStatus::Uninstalled->value) {
return base_path('lang-packs/_bundled/'.$this->identifier);
}
return base_path('lang-packs/'.$this->identifier);
}
}
+7
View File
@@ -36,6 +36,13 @@ class Menu extends Model
*/
protected array $trackableFields = ['name', 'icon', 'order', 'url'];
/**
* 다국어 JSON 컬럼 — sub-key dot-path 단위 user_overrides 보존.
*
* @var array<int, string>
*/
protected array $translatableTrackableFields = ['name'];
/** @var array<string, array> 활동 로그 추적 필드 */
public static array $activityLogFields = [
'url' => ['label_key' => 'activity_log.fields.url', 'type' => 'text'],
+6
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Enums\DeactivationReason;
use App\Enums\ExtensionStatus;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -39,6 +40,9 @@ class Module extends Model
'version',
'latest_version',
'status',
'deactivated_reason',
'deactivated_at',
'incompatible_required_version',
'update_available',
'description',
'github_url',
@@ -63,6 +67,8 @@ class Module extends Model
'metadata' => 'array',
'is_active' => 'boolean',
'update_available' => 'boolean',
'deactivated_reason' => DeactivationReason::class,
'deactivated_at' => 'datetime',
];
}
+9 -2
View File
@@ -20,6 +20,13 @@ class NotificationDefinition extends Model
*/
protected array $trackableFields = ['name', 'is_active'];
/**
* 다국어 JSON 컬럼 — sub-key dot-path 단위 user_overrides 보존.
*
* @var array<int, string>
*/
protected array $translatableTrackableFields = ['name'];
/**
* 모델 이벤트 등록 — 모든 변경 시 알림 정의 캐시 자동 삭제.
*/
@@ -158,7 +165,7 @@ class NotificationDefinition extends Model
$locale = $locale ?? app()->getLocale();
$name = $this->name ?? [];
return $name[$locale] ?? $name['ko'] ?? $name['en'] ?? '';
return $name[$locale] ?? $name[config('app.fallback_locale', 'ko')] ?? '';
}
/**
@@ -172,6 +179,6 @@ class NotificationDefinition extends Model
$locale = $locale ?? app()->getLocale();
$description = $this->description ?? [];
return $description[$locale] ?? $description['ko'] ?? $description['en'] ?? '';
return $description[$locale] ?? $description[config('app.fallback_locale', 'ko')] ?? '';
}
}
+13
View File
@@ -49,6 +49,19 @@ class Permission extends Model
'owner_key',
];
/**
* 속성 기본값
*
* type 컬럼은 마이그레이션에서 NOT NULL 이지만 default 가 없어
* create 시 명시 제공 없을 경우 DB 레벨 에러 발생. 대다수 권한이 admin 이므로
* 모델 레벨 default 를 `admin` 으로 지정하여 호출부 누락을 방어.
*
* @var array<string, mixed>
*/
protected $attributes = [
'type' => 'admin',
];
/**
* 속성 캐스팅
*
+6
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Enums\DeactivationReason;
use App\Enums\ExtensionStatus;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -40,6 +41,9 @@ class Plugin extends Model
'latest_version',
'description',
'status',
'deactivated_reason',
'deactivated_at',
'incompatible_required_version',
'update_available',
'hooks',
'github_url',
@@ -62,6 +66,8 @@ class Plugin extends Model
'hooks' => 'array',
'metadata' => 'array',
'update_available' => 'boolean',
'deactivated_reason' => DeactivationReason::class,
'deactivated_at' => 'datetime',
];
}
+10
View File
@@ -30,6 +30,16 @@ class Role extends Model
*/
protected array $trackableFields = ['name', 'description'];
/**
* 다국어 JSON 컬럼 — sub-key dot-path 단위로 user_overrides 보존.
*
* 사용자가 ko 라벨만 수정하면 user_overrides=['name.ko'] 로 기록되어
* 언어팩 활성/시더 재실행 시 ja/en 키는 자동 동기화 가능.
*
* @var array<int, string>
*/
protected array $translatableTrackableFields = ['name', 'description'];
/** @var array<string, array> 활동 로그 추적 필드 */
public static array $activityLogFields = [
'identifier' => ['label_key' => 'activity_log.fields.identifier', 'type' => 'text'],
+6
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Enums\DeactivationReason;
use App\Enums\ExtensionStatus;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -32,6 +33,9 @@ class Template extends Model
'update_available',
'type',
'status',
'deactivated_reason',
'deactivated_at',
'incompatible_required_version',
'description',
'user_modified_at',
'github_url',
@@ -54,6 +58,8 @@ class Template extends Model
'metadata' => 'array',
'user_modified_at' => 'datetime',
'update_available' => 'boolean',
'deactivated_reason' => DeactivationReason::class,
'deactivated_at' => 'datetime',
];
}
+13
View File
@@ -100,6 +100,14 @@ class User extends Authenticatable
'last_login_at',
'withdrawn_at',
'blocked_at',
'identity_verified_at',
'identity_verified_provider',
'identity_verified_purpose_last',
'identity_hash',
'mobile_verified_at',
'failed_login_attempts',
'locked_until',
'last_failed_login_at',
];
/**
@@ -126,7 +134,12 @@ class User extends Authenticatable
'last_login_at' => 'datetime',
'withdrawn_at' => 'datetime',
'blocked_at' => 'datetime',
'identity_verified_at' => 'datetime',
'mobile_verified_at' => 'datetime',
'is_super' => 'boolean',
'failed_login_attempts' => 'integer',
'locked_until' => 'datetime',
'last_failed_login_at' => 'datetime',
];
}