Files
Gnuboard7/app/Repositories/ActivityLogRepository.php
T
HeuJung be9befe023 fix(core,board,ecommerce,page,gdpr,basic): 깊은 OFFSET 목록 조회 개선 및 raw/테이블명 전수 정리
목록이 뒤쪽 페이지로 갈수록 느려지는 원인은 건너뛰는 행의 넓은 컬럼까지 읽는 것이었다.
지연 조인(inner 는 키 컬럼만, outer 는 이번 페이지 행만 전체 컬럼)과 정렬 컬럼 해석을
코어 공통 트레이트로 두고 코어 8 + 확장 6 저장소에 적용했다.

감사 지적 처리:
- 그룹 쿼리의 총 건수 오산 — count 는 groupBy 를 벗기지 않아 첫 그룹의 행 수를
 총 건수로 돌려준다. getCountForPagination 으로 교정.
- audit 전수 스캔이 버퍼 한계로 한 번도 동작하지 않던 결함과, 확장 경로를 놓치던
 정규식 5건을 함께 고쳤다. 그동안 번들 확장의 위반이 보이지 않았다.

raw 20건을 빌더 표현으로 치환하고 하드코딩 테이블명 16건을 모델 유래로 바꿨다.
이 과정에서 마이페이지 「내가 댓글 단 글」 검색이 조인 별칭 충돌로 SQL 오류를 내던
결함이 해소됐다. 재발 차단용 룰 2종을 신설하고, 컬럼 프루닝 룰을 error 로 승격했다
(전역 위반 0건 — warning 으로 두면 "0 error" 판정을 통과하며 무음으로 재누적된다).

정렬 허용 목록은 FormRequest 게이트를 덮어야 한다. 좁으면 검증을 통과한 정렬이 422 도
로그도 없이 기본값으로 되돌아간다(스케줄 실행 이력의 종료시각·소요시간 정렬이 그랬다).
호출처를 스캔해 매핑 완전성까지 검사하는 계약 테스트로 전수 강제한다.

해외 배송지 결함도 함께 고쳤다 — 조회는 city/state/postal_code 로 내려주고 폼은
intl_* 로 제출하는 비대칭 때문에, 수정 시 입력칸이 비어 보이고 저장하면 기존 값이
유실됐다. 쿠폰 수정의 유효기간 미검증과 1인당 사용 제한 부분 수정 차단도 함께 수정.
2026-08-02 14:36:37 +09:00

287 lines
10 KiB
PHP

<?php
namespace App\Repositories;
use App\Contracts\Repositories\ActivityLogRepositoryInterface;
use App\Helpers\PermissionHelper;
use App\Helpers\TimezoneHelper;
use App\Models\ActivityLog;
use App\Repositories\Concerns\HasMultipleSearchFilters;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
/**
* 활동 로그 Repository
*/
class ActivityLogRepository implements ActivityLogRepositoryInterface
{
use HasMultipleSearchFilters;
use PaginatesWithDeferredJoin;
use ResolvesSortSpec;
/**
* 활동 로그 목록 정렬 허용 컬럼
*
* 요청 값을 그대로 orderBy 에 넘기면 없는 컬럼으로 SQL 오류가 나거나 인덱스 없는 컬럼
* 정렬을 강제할 수 있다.
*
* @var array<int, string>
*/
private const SORTABLE_COLUMNS = [
'id',
'created_at',
'action',
'log_type',
'user_id',
];
/**
* 특정 모델의 활동 로그를 페이지네이션하여 조회합니다.
*
* @param Model $model 대상 모델
* @param array $filters 필터 조건
* @return LengthAwarePaginator 페이지네이션된 로그 목록
*/
public function getPaginatedForModel(Model $model, array $filters = []): LengthAwarePaginator
{
$sortOrder = $this->normalizeSortDirection($filters['sort_order'] ?? null);
$query = ActivityLog::forModel($model);
if (isset($filters['action'])) {
$query->action($filters['action']);
}
if (isset($filters['user_id'])) {
$query->byUser($filters['user_id']);
}
// 컬럼을 좁히지 않는 이유는 getPaginated() 와 같다 — 리소스가 변경 내역을 그대로 노출한다
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: [['column' => 'created_at', 'direction' => $sortOrder]],
perPage: (int) ($filters['per_page'] ?? 15),
);
}
/**
* 활동 로그 목록을 페이지네이션하여 조회합니다.
*
* @param array $filters 필터 조건
* @return LengthAwarePaginator 페이지네이션된 로그 목록
*/
public function getPaginated(array $filters = []): LengthAwarePaginator
{
// 관계는 지연 조인의 outer 에서만 로드한다 (inner 는 키 컬럼만 조회한다)
$query = ActivityLog::query();
// 스코프 기반 권한 필터링 (self: 본인 로그만, role: 소유역할 로그, null: 전체)
PermissionHelper::applyPermissionScope($query, 'core.activities.read');
if (isset($filters['log_type'])) {
if (is_array($filters['log_type'])) {
$query->whereIn('log_type', $filters['log_type']);
} else {
$query->where('log_type', $filters['log_type']);
}
}
if (isset($filters['action'])) {
$query->action($filters['action']);
}
if (isset($filters['user_id'])) {
$query->byUser($filters['user_id']);
}
if (isset($filters['loggable_type'])) {
$query->where('loggable_type', $filters['loggable_type']);
}
if (isset($filters['created_by'])) {
$query->whereHas('user', function ($q) use ($filters) {
$q->where('uuid', $filters['created_by']);
});
}
if (isset($filters['search'])) {
$searchType = $filters['search_type'] ?? 'all';
$this->applyBilingualSearch($query, $filters['search'], $searchType);
}
if (isset($filters['date_from'])) {
$query->where('created_at', '>=', TimezoneHelper::fromSiteDateTime($filters['date_from']));
}
if (isset($filters['date_to'])) {
$query->where('created_at', '<=', TimezoneHelper::fromSiteDateTime($filters['date_to']));
}
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'created_at');
// 목록 컬럼을 좁히지 않는 이유: 활동 로그 리소스는 변경 내역(mediumText `changes`)과
// 부가 정보(`properties`)까지 그대로 노출하므로 컬럼을 빼면 응답 계약이 바뀐다.
// 지연 조인만으로도 이 넓은 컬럼들을 읽는 행 수가 이번 페이지 분량으로 고정된다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: $sort,
perPage: (int) ($filters['per_page'] ?? 15),
relations: ['user:id,uuid,name,email'],
);
}
/**
* 양방향(한글/영어) 검색을 적용합니다.
*
* action/description 필드는 영어 키를 저장하므로,
* 검색어가 번역된 라벨과 일치하는 원본 키도 함께 검색합니다.
*
* @param Builder $query 쿼리 빌더
* @param string $search 검색어
* @param string $searchType 검색 유형 (all, action, description, ip_address)
*/
private function applyBilingualSearch($query, string $search, string $searchType): void
{
$query->where(function ($q) use ($search, $searchType) {
$searchLower = mb_strtolower($search);
if ($searchType === 'action' || $searchType === 'all') {
// 영어 원문 검색
$q->orWhere('action', 'LIKE', "%{$search}%");
// 번역된 라벨로 원본 action 값 역추적
$matchingActions = $this->findActionsByTranslatedLabel($searchLower);
if (! empty($matchingActions)) {
$q->orWhereIn('action', $matchingActions);
}
}
if ($searchType === 'description' || $searchType === 'all') {
// 영어 원문 검색
$q->orWhere('description_key', 'LIKE', "%{$search}%");
// 번역된 설명으로 원본 description_key 역추적
$matchingKeys = $this->findDescriptionKeysByTranslatedText($searchLower);
if (! empty($matchingKeys)) {
$q->orWhereIn('description_key', $matchingKeys);
}
}
if ($searchType === 'ip_address' || $searchType === 'all') {
$q->orWhere('ip_address', 'LIKE', "%{$search}%");
}
});
}
/**
* 번역된 액션 라벨로 원본 action 값을 역추적합니다.
*
* @param string $searchLower 소문자 검색어
* @return array<string> 일치하는 action 값 목록
*/
private function findActionsByTranslatedLabel(string $searchLower): array
{
$distinctActions = ActivityLog::distinct()->pluck('action')->toArray();
$matching = [];
foreach ($distinctActions as $action) {
// 전체 키 번역 (activity_log.action.user.create)
$fullKey = "activity_log.action.{$action}";
$translated = __($fullKey);
if ($translated !== $fullKey && str_contains(mb_strtolower($translated), $searchLower)) {
$matching[] = $action;
continue;
}
// 마지막 세그먼트 번역 (activity_log.action.create)
$lastSegment = last(explode('.', $action));
$segmentKey = "activity_log.action.{$lastSegment}";
$translated = __($segmentKey);
if ($translated !== $segmentKey && str_contains(mb_strtolower($translated), $searchLower)) {
$matching[] = $action;
}
}
return $matching;
}
/**
* 번역된 설명 텍스트로 원본 description_key를 역추적합니다.
*
* @param string $searchLower 소문자 검색어
* @return array<string> 일치하는 description_key 목록
*/
private function findDescriptionKeysByTranslatedText(string $searchLower): array
{
$distinctKeys = ActivityLog::distinct()->pluck('description_key')->filter()->toArray();
$matching = [];
foreach ($distinctKeys as $key) {
$translated = __($key);
if ($translated !== $key && str_contains(mb_strtolower($translated), $searchLower)) {
$matching[] = $key;
}
}
return $matching;
}
/**
* 활동 로그를 삭제합니다.
*
* @param int $id 삭제할 활동 로그 ID
* @return bool 삭제 성공 여부
*/
public function delete(int $id): bool
{
return ActivityLog::where('id', $id)->delete() > 0;
}
/**
* 여러 활동 로그를 일괄 삭제합니다.
*
* @param array<int> $ids 삭제할 활동 로그 ID 목록
* @return int 삭제된 건수
*/
public function deleteMany(array $ids): int
{
return ActivityLog::whereIn('id', $ids)->delete();
}
/**
* 최근 활동 로그를 스코프 권한 적용하여 조회합니다.
*
* @param string $permission 권한 식별자
* @param int $limit 조회할 활동 수
* @return Collection 활동 로그 컬렉션
*/
public function getRecent(string $permission, int $limit = 5): Collection
{
$query = ActivityLog::query()->with('user:id,uuid,name,email');
// 스코프 기반 권한 필터링 (self: 본인 활동만, role: 소유역할 활동, null: 전체)
PermissionHelper::applyPermissionScope($query, $permission);
return $query->latest()
->limit($limit)
->get();
}
/**
* 사용자 삭제 시 해당 사용자의 모든 activity_logs.user_id 컬럼을 NULL 로 익명화합니다.
*
* @param int $userId 익명화 대상 사용자 ID
* @return int 익명화된 row 수
*/
public function anonymizeUserId(int $userId): int
{
return ActivityLog::where('user_id', $userId)->update(['user_id' => null]);
}
}