목록이 뒤쪽 페이지로 갈수록 느려지는 원인은 건너뛰는 행의 넓은 컬럼까지 읽는 것이었다. 지연 조인(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인당 사용 제한 부분 수정 차단도 함께 수정.
254 lines
6.9 KiB
PHP
254 lines
6.9 KiB
PHP
<?php
|
|
|
|
namespace Modules\Sirsoft\Ecommerce\Repositories;
|
|
|
|
use App\Repositories\Concerns\PaginatesWithDeferredJoin;
|
|
use App\Repositories\Concerns\ResolvesSortSpec;
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Database\Eloquent\Collection;
|
|
use Modules\Sirsoft\Ecommerce\Models\ExtraFeeTemplate;
|
|
use Modules\Sirsoft\Ecommerce\Repositories\Contracts\ExtraFeeTemplateRepositoryInterface;
|
|
|
|
/**
|
|
* 추가배송비 템플릿 Repository 구현체
|
|
*/
|
|
class ExtraFeeTemplateRepository implements ExtraFeeTemplateRepositoryInterface
|
|
{
|
|
use PaginatesWithDeferredJoin;
|
|
use ResolvesSortSpec;
|
|
|
|
/** 허용 정렬 컬럼 (ExtraFeeTemplate::scopeOrderByField 와 동일 집합) */
|
|
private const SORTABLE_COLUMNS = ['id', 'zipcode', 'fee', 'region', 'is_active', 'created_at', 'updated_at'];
|
|
|
|
public function __construct(
|
|
protected ExtraFeeTemplate $model
|
|
) {}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function find(int $id): ?ExtraFeeTemplate
|
|
{
|
|
return $this->model->find($id);
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function findByZipcode(string $zipcode): ?ExtraFeeTemplate
|
|
{
|
|
return $this->model->where('zipcode', $zipcode)->first();
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function getListWithFilters(array $filters, int $perPage = 20): LengthAwarePaginator
|
|
{
|
|
$query = $this->model->newQuery();
|
|
|
|
// 검색어 (우편번호 또는 지역명)
|
|
if (! empty($filters['search'])) {
|
|
$query->search($filters['search']);
|
|
}
|
|
|
|
// 지역 필터
|
|
if (! empty($filters['region'])) {
|
|
$query->inRegion($filters['region']);
|
|
}
|
|
|
|
// 사용여부 필터
|
|
if (isset($filters['is_active']) && $filters['is_active'] !== '') {
|
|
$isActive = filter_var($filters['is_active'], FILTER_VALIDATE_BOOLEAN);
|
|
$query->where('is_active', $isActive);
|
|
}
|
|
|
|
// 정렬 (모델 scopeOrderByField 와 동일한 허용 집합)
|
|
$sort = $this->resolveSortSpec($filters, self::SORTABLE_COLUMNS, 'zipcode', 'asc');
|
|
|
|
// 지연 조인: 우편번호 단위 행이라 건수가 커질 수 있고 description(text)이 있어
|
|
// OFFSET 이 훑는 구간에서 넓은 컬럼까지 읽힌다. inner 는 id 만 훑는다.
|
|
return $this->paginateWithDeferredJoin(
|
|
query: $query,
|
|
columns: ['*'],
|
|
sort: $sort,
|
|
perPage: $perPage,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function create(array $data): ExtraFeeTemplate
|
|
{
|
|
$data['created_by'] = auth()->id();
|
|
|
|
return $this->model->create($data);
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function update(ExtraFeeTemplate $template, array $data): ExtraFeeTemplate
|
|
{
|
|
$data['updated_by'] = auth()->id();
|
|
$template->update($data);
|
|
|
|
return $template->fresh();
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function delete(ExtraFeeTemplate $template): bool
|
|
{
|
|
return $template->delete();
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function toggleActive(ExtraFeeTemplate $template): ExtraFeeTemplate
|
|
{
|
|
$template->update([
|
|
'is_active' => ! $template->is_active,
|
|
'updated_by' => auth()->id(),
|
|
]);
|
|
|
|
return $template->fresh();
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function bulkDelete(array $ids): int
|
|
{
|
|
return $this->model->whereIn('id', $ids)->delete();
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function bulkToggleActive(array $ids, bool $isActive): int
|
|
{
|
|
return $this->model
|
|
->whereIn('id', $ids)
|
|
->update([
|
|
'is_active' => $isActive,
|
|
'updated_by' => auth()->id(),
|
|
'updated_at' => now(),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function getActiveList(): Collection
|
|
{
|
|
return $this->model
|
|
->active()
|
|
->orderBy('zipcode')
|
|
->get();
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function getAllAsExtraFeeSettings(): array
|
|
{
|
|
return $this->model
|
|
->active()
|
|
->orderBy('zipcode')
|
|
->get()
|
|
->map(fn ($template) => $template->toExtraFeeSetting())
|
|
->toArray();
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function bulkCreate(array $items): int
|
|
{
|
|
$userId = auth()->id();
|
|
$now = now();
|
|
$count = 0;
|
|
|
|
// Batch insert for performance
|
|
$chunks = array_chunk($items, 100);
|
|
|
|
foreach ($chunks as $chunk) {
|
|
$records = array_map(function ($item) use ($userId, $now) {
|
|
return [
|
|
'zipcode' => $item['zipcode'],
|
|
'fee' => $item['fee'] ?? 0,
|
|
'region' => $item['region'] ?? null,
|
|
'description' => $item['description'] ?? null,
|
|
'is_active' => $item['is_active'] ?? true,
|
|
'created_by' => $userId,
|
|
'created_at' => $now,
|
|
'updated_at' => $now,
|
|
];
|
|
}, $chunk);
|
|
|
|
// upsert: 우편번호 중복 시 업데이트
|
|
$this->model->upsert(
|
|
$records,
|
|
['zipcode'],
|
|
['fee', 'region', 'description', 'is_active', 'updated_by', 'updated_at']
|
|
);
|
|
|
|
$count += count($chunk);
|
|
}
|
|
|
|
return $count;
|
|
}
|
|
|
|
/**
|
|
* {@inheritDoc}
|
|
*/
|
|
public function getStatisticsByRegion(): array
|
|
{
|
|
$total = $this->model->count();
|
|
$active = $this->model->where('is_active', true)->count();
|
|
$inactive = $this->model->where('is_active', false)->count();
|
|
|
|
// 지역별 통계
|
|
$regionStats = $this->model
|
|
->selectRaw('region, COUNT(*) as count, AVG(fee) as avg_fee, MIN(fee) as min_fee, MAX(fee) as max_fee')
|
|
->whereNotNull('region')
|
|
->groupBy('region')
|
|
->orderBy('region')
|
|
->get()
|
|
->map(fn ($row) => [
|
|
'region' => $row->region,
|
|
'count' => $row->count,
|
|
'avg_fee' => round($row->avg_fee, 2),
|
|
'min_fee' => $row->min_fee,
|
|
'max_fee' => $row->max_fee,
|
|
])
|
|
->toArray();
|
|
|
|
return [
|
|
'total' => $total,
|
|
'active' => $active,
|
|
'inactive' => $inactive,
|
|
'by_region' => $regionStats,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* ID 목록으로 조회하고 ID 키 맵으로 반환합니다 (bulk activity log lookup).
|
|
*
|
|
* @param array<int, int> $ids ID 목록
|
|
* @return Collection
|
|
*/
|
|
public function findByIdsKeyed(array $ids): Collection
|
|
{
|
|
if (empty($ids)) {
|
|
return new Collection;
|
|
}
|
|
|
|
return ExtraFeeTemplate::whereIn('id', $ids)->get()->keyBy('id');
|
|
}
|
|
}
|