Files
Gnuboard7/app/Repositories/NotificationLogRepository.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

187 lines
6.0 KiB
PHP

<?php
namespace App\Repositories;
use App\Contracts\Repositories\NotificationLogRepositoryInterface;
use App\Enums\NotificationLogStatus;
use App\Models\NotificationLog;
use App\Models\User;
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
use App\Repositories\Concerns\ResolvesSortSpec;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
class NotificationLogRepository implements NotificationLogRepositoryInterface
{
use PaginatesWithDeferredJoin;
use ResolvesSortSpec;
/**
* 발송 이력 목록 정렬 허용 컬럼
*
* 요청 값을 그대로 orderBy 에 넘기면 없는 컬럼으로 SQL 오류가 나거나 인덱스 없는 컬럼
* 정렬을 강제할 수 있다.
*
* @var array<int, string>
*/
private const SORTABLE_COLUMNS = [
'id',
'sent_at',
'created_at',
'status',
'channel',
'notification_type',
'recipient_name',
];
/**
* 최근 발송된 알림 로그를 발송 시각 최신순으로 조회합니다 (대시보드 최근 알림).
*
* @param int $limit 조회 건수
* @return Collection<int, NotificationLog> 최근 알림 로그 컬렉션
*/
public function getRecent(int $limit): Collection
{
return NotificationLog::with(['recipientUser'])
->orderByDesc('sent_at')
->orderByDesc('id')
->limit($limit)
->get();
}
/**
* ID로 알림 로그 조회.
*
* @param int $id 알림 로그 ID
* @return NotificationLog|null 알림 로그 또는 null
*/
public function findById(int $id): ?NotificationLog
{
return NotificationLog::find($id);
}
/**
* 알림 로그 생성.
*
* @param array<string, mixed> $data 생성 데이터
* @return NotificationLog 생성된 알림 로그
*/
public function create(array $data): NotificationLog
{
return NotificationLog::create($data);
}
/**
* 알림 로그 삭제.
*
* @param NotificationLog $log 삭제 대상 알림 로그
* @return bool 삭제 성공 여부
*/
public function delete(NotificationLog $log): bool
{
return (bool) $log->delete();
}
/**
* 다건 삭제.
*
* @param array<int, int> $ids 삭제할 알림 로그 ID 목록
* @return int 삭제된 건수
*/
public function bulkDelete(array $ids): int
{
return NotificationLog::whereIn('id', $ids)->delete();
}
/**
* 페이지네이션 목록 조회.
*
* @param array<string, mixed> $filters 필터 조건
* @param int $perPage 페이지당 건수
* @param User|null $scopeUser 스코프 적용 대상 사용자 (null이면 스코프 미적용)
* @return LengthAwarePaginator 페이지네이션 결과
*/
public function getPaginated(array $filters = [], int $perPage = 20, ?User $scopeUser = null): LengthAwarePaginator
{
// 관계는 지연 조인의 outer 에서만 로드한다 (inner 는 키 컬럼만 조회한다)
$query = NotificationLog::query();
// notification-logs scope: 전달된 사용자의 권한 스코프 적용
if ($scopeUser) {
$this->applyNotificationLogScope($query, $scopeUser);
}
if (! empty($filters['sender_user_id'])) {
$query->where('sender_user_id', $filters['sender_user_id']);
}
if (! empty($filters['recipient_user_id'])) {
$query->where('recipient_user_id', $filters['recipient_user_id']);
}
if (! empty($filters['channel'])) {
$query->byChannel($filters['channel']);
}
if (! empty($filters['notification_type'])) {
$query->byNotificationType($filters['notification_type']);
}
if (! empty($filters['status'])) {
$status = NotificationLogStatus::tryFrom($filters['status']);
if ($status) {
$query->byStatus($status);
}
}
if (! empty($filters['extension_type'])) {
$query->where('extension_type', $filters['extension_type']);
}
if (! empty($filters['search'])) {
$search = $filters['search'];
$query->where(function ($q) use ($search) {
$q->where('recipient_name', 'like', "%{$search}%")
->orWhere('recipient_identifier', 'like', "%{$search}%")
->orWhere('subject', 'like', "%{$search}%")
->orWhere('notification_type', 'like', "%{$search}%");
});
}
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'sent_at');
// 목록 컬럼을 좁히지 않는 이유: 이 목록의 리소스는 렌더링된 본문(longText `body`)까지
// 그대로 노출하므로 컬럼을 빼면 응답 계약이 바뀐다. 지연 조인만으로도 본문을 읽는
// 행 수가 OFFSET 과 무관하게 이번 페이지 분량으로 고정된다.
return $this->paginateWithDeferredJoin(
query: $query,
columns: ['*'],
sort: $sort,
perPage: $perPage,
relations: ['senderUser', 'recipientUser'],
);
}
/**
* notification-logs 전용 스코프를 적용합니다.
*
* self 스코프: 본인이 발송했거나 수신한 알림 이력만 조회
*/
private function applyNotificationLogScope(Builder $query, User $user): void
{
$effectiveScope = $user->getEffectiveScopeForPermission('core.notification-logs.read');
if ($effectiveScope === null) {
return; // 전체 접근
}
if ($effectiveScope === 'self') {
$query->where(function (Builder $q) use ($user) {
$q->where('sender_user_id', $user->id)
->orWhere('recipient_user_id', $user->id);
});
}
}
}