fix(core,board,ecommerce,page,gdpr,ckeditor5,kginicis,admin_basic,basic): 목록 조회·검증 계층 정비 및 감사 지적 전건 처리

목록 조회 성능 축(깊은 OFFSET·정렬·색인)과 그 검증 계층에서 계획서 전수검수와 3회에 걸친
감사가 지적한 항목을 처리했다. 세부 경위는 의 각 회차 문서에 있다.

검증 계층 — 컨트롤러가 base Request 를 직접 주입받던 확장 13곳을 전용 FormRequest 로 옮겼다.
옮기면서 기존 동작 계약은 그대로 두었다: 상한 초과 limit 을 거부하지 않고 상한까지 반환하던
공개 API, per_page 를 범위로 조정하던 관리자 목록, 미지원 period 를 year 로 해석하던 인기글
목록 모두 종전과 같은 응답을 낸다. 상한/폴백을 rules 로 승격시키면 200 이던 응답이 422 가
되어 기존 링크가 깨지므로, 규칙은 타입만 닫고 클램프·폴백은 접근자가 맡는다. period 는
접근자가 닫힌 집합만 반환해 캐시 키 공간도 함께 닫힌다.

ckeditor5 이미지 업로드만 ResponseHelper 봉투를 쓰지 않는다. 응답을 파싱하는 주체가 CDN 으로
로드되는 상위 CKEditor5 43.3.1 의 SimpleUploadAdapter 라 규약을 바꿀 수 없어, 각 응답 지점에
사유를 명시한 면제를 부착하고 근거를 API 문서에 남겼다.

하네스 — 룰 5개의 대상 경로 패턴이 매처와 맞지 않아 번들 확장 컨트롤러가 검사 대상에서
통째로 빠져 있었다. 패턴을 고치자 확장 위반 17건이 드러나 전건 처리했다. severity 오타가
요약 집계 양쪽에 안 잡혀 "0 error" 로 보고되던 문제도 런너 사전 검증으로 막았다.

정렬 게이트 대조 하네스는 관계 정렬 변형만 쓰는 저장소를 탐지하지 못한 채 통과시키고 있었다.
탐지·제외·인자 파싱을 함께 고치고 단위 테스트를 신설했다.
This commit is contained in:
HeuJung committed 2026-08-02 15:29:29 +09:00
1 parent 5f4a733b3b
commit b10e89bef0
276 files changed
+12519 -1438

No files matched your search

@@ -0,0 +1,154 @@
/**
* E2E: 확장 업데이트의 「검색 인덱스 재생성」 선택이 그 창에서만 유효한지 (#492 검색 인덱스 실측)
*
* 재생성은 인덱스 잠금·전체 재색인을 유발한다. 체크 상태가 전역에 남으면 운영자가 한 번
* 체크한 뒤로는 아무것도 누르지 않아도 다음 확장 업데이트마다 재생성이 실행된다
* (브라우저 실측으로 실제 재생성이 일어남을 확인했다).
*
* 응답의 `search_index` 페이로드도 함께 본다 — 색인이 비면 검색은 오류 없이 0건을
* 돌려주므로, 이 페이로드가 사라지면 운영자가 알 방법이 없다.
*
* @scenario case=extension_update_rebuild_optin
*
* @effects rebuild_checkbox_defaults_unchecked, rebuild_checkbox_resets_on_reopen,
* update_response_carries_search_index
*/
import type { Page } from '@playwright/test';
import { test, expect, authenticatePage, issueToken } from '../../fixtures/auth';
/** 모달 안 체크박스 셀렉터 (모듈/플러그인 공통 규칙) */
const CHECKBOX = (kind: 'module' | 'plugin') => `#${kind}_rebuild_search_index input[type="checkbox"]`;
/**
* 목록 화면에 진입해 렌더가 끝날 때까지 기다립니다.
*
* @param page 대상 페이지
* @param path 이동할 경로
* @returns void
*/
async function gotoAndSettle(page: Page, path: string): Promise<void> {
// 고정 대기만 두면 느린 회차에서 목록이 아직 없는 채로 판정해 조용히 skip 이 된다.
const listed = page
.waitForResponse(
(r) =>
(r.url().includes('/api/admin/modules') || r.url().includes('/api/admin/plugins')) &&
r.status() === 200,
{ timeout: 30000 }
)
.catch(() => null);
await page.goto(path);
await page.waitForLoadState('domcontentloaded');
await listed;
await page.waitForTimeout(1500);
}
/**
* 업데이트 모달을 엽니다. 업데이트 가능한 확장이 없으면 false 를 돌려줍니다.
*
* @param page 대상 페이지
* @param kind module | plugin
* @returns Promise<boolean> 모달이 열렸으면 true
*/
async function openUpdateModal(page: Page, kind: 'module' | 'plugin'): Promise<boolean> {
// 두 가지를 함께 흡수한다.
// - 접근성 이름에 아이콘 텍스트가 섞인다 (예: 'refresh 업데이트')
// - 테스트 계정의 로케일이 ko 라는 보장이 없다 (실제로 en 으로 떨어져 한국어 매칭이 전부 skip 됐다)
// 목록 상단의 '업데이트 확인 / Check Updates' 는 이름이 그 단어로 끝나지 않아 자연히 제외된다.
const button = page
.getByRole('button', { name: /(업데이트|Update|アップデート|更新)$/ })
.first();
if ((await button.count()) === 0) {
return false;
}
await button.click();
await page.waitForTimeout(1500);
return (await page.locator(CHECKBOX(kind)).count()) > 0;
}
for (const kind of ['module', 'plugin'] as const) {
const listPath = kind === 'module' ? '/admin/modules' : '/admin/plugins';
const label = kind === 'module' ? '모듈' : '플러그인';
test.describe(`${label} 업데이트 — 검색 인덱스 재생성 옵트인`, () => {
test(`체크는 기본 해제이고 모달을 다시 열면 초기화된다`, async ({ page }) => {
await authenticatePage(page, issueToken('core.modules.read', 'core.modules.install', 'core.plugins.read', 'core.plugins.install'));
await gotoAndSettle(page, listPath);
const opened = await openUpdateModal(page, kind);
test.skip(!opened, `업데이트 가능한 ${label}이 없어 모달을 열 수 없습니다`);
const checkbox = page.locator(CHECKBOX(kind));
// 진입 시 기본 미체크
expect(await checkbox.isChecked(), '재생성 체크가 기본으로 켜져 있습니다').toBe(false);
// 체크 후 취소로 닫는다.
//
// 체크박스는 `<label>` 안에 있고 checked 는 전역 상태에서 되돌아온다. 포인터 클릭은
// label 활성화 동작과 겹쳐 한 회차에 두 번 토글되는 일이 있어 결과가 갈린다
// (`click()`/`check()` 모두 재현됨). 요소의 활성화만 일으켜 change 를 한 번 태운다.
// 모달이 열린 직후에는 변경 이력·수정 레이아웃 조회 응답이 뒤따라 도착하며 상태가 다시
// 계산되어, 그 창에 걸린 토글이 한 번 되돌아가는 회차가 있다. 켜질 때까지 최대 3회 시도한다
// (검증 대상은 "다시 열었을 때 꺼져 있는가" 이지 토글 1회의 타이밍이 아니다).
for (let attempt = 0; attempt < 3 && !(await checkbox.isChecked()); attempt += 1) {
await checkbox.evaluate((el) => (el as HTMLInputElement).click());
await page.waitForTimeout(600);
}
expect(await checkbox.isChecked(), '체크박스가 토글되지 않았습니다').toBe(true);
await page
.getByRole('button', { name: /^(취소|Cancel|キャンセル)$/ })
.last()
.click();
await page.waitForTimeout(700);
// 다시 열면 해제되어 있어야 한다 — 남아 있으면 다음 업데이트에서 의도치 않게 재생성된다
const reopened = await openUpdateModal(page, kind);
test.skip(!reopened, '모달 재진입에 실패했습니다');
expect(
await page.locator(CHECKBOX(kind)).isChecked(),
'모달을 다시 열었는데 재생성 체크가 남아 있습니다'
).toBe(false);
});
test(`미체크 제출 응답이 색인 점검 결과를 싣는다`, async ({ page }) => {
await authenticatePage(page, issueToken('core.modules.read', 'core.modules.install', 'core.plugins.read', 'core.plugins.install'));
await gotoAndSettle(page, listPath);
const opened = await openUpdateModal(page, kind);
test.skip(!opened, `업데이트 가능한 ${label}이 없어 모달을 열 수 없습니다`);
expect(await page.locator(CHECKBOX(kind)).isChecked()).toBe(false);
const responsePromise = page
.waitForResponse((r) => r.url().includes('/update') && r.request().method() === 'POST', {
timeout: 60000,
})
.catch(() => null);
await page.locator('button.bg-amber-600').click();
const response = await responsePromise;
test.skip(response === null, '업데이트 응답을 받지 못했습니다');
const request = response!.request();
const body = JSON.parse(request.postData() ?? '{}');
expect(body.rebuild_search_index, '미체크인데 재생성 요청이 실렸습니다').toBe(false);
const payload = await response!.json();
test.skip(
payload?.search_index === undefined || payload?.search_index === null,
'점검을 제공하지 않는 검색 엔진입니다'
);
expect(payload.search_index.rebuilt, '요청하지 않았는데 재생성이 수행됐습니다').toBe(false);
expect(payload.search_index, '색인 누락 건수가 응답에 없습니다').toHaveProperty('stale_count');
expect(payload.message, '성공 메시지에 치환자가 남아 있습니다').not.toContain(':version');
});
});
}
@@ -0,0 +1,55 @@
/**
* E2E: 배송지 목록의 해외 주소 표시 (#492 트랙 A V13/V14 실측 회귀)
*
* 배송지 목록은 국내와 해외를 서로 다른 형식으로 찍어야 한다. 국내는 우편번호 + 도로명,
* 해외는 서버가 조립한 `full_address` 다. 국내 전용 형식만 두면 해외 주소 행이 우편번호
* 괄호만 남고 본문이 통째로 비어 보인다.
*
* 실측: 체크아웃 "배송지 관리" 모달에서 미국 주소가 `John Doe|010-... ()` 로 표시됐다.
* 같은 데이터가 마이페이지 배송지 목록에서는 정상이었다 — 두 레이아웃 중 한쪽만
* 국가 분기를 갖고 있었기 때문이다.
*
* 이 spec 은 데이터 준비 비용이 큰 결제 플로우 대신 **레이아웃 선언**을 검사한다.
* 배송지 행을 렌더하는 레이아웃이라면 국가 분기(국내/해외)를 모두 갖고 있어야 한다.
*
* @scenario case=address_list_renders_overseas
*
* @effects overseas_address_uses_full_address, domestic_address_uses_zipcode_format
*/
import { readFileSync, existsSync } from 'node:fs';
import { resolve } from 'node:path';
import { test, expect } from '@playwright/test';
/** 배송지 행을 렌더하는 레이아웃 — 국내/해외 분기를 모두 가져야 한다 */
const ADDRESS_LIST_LAYOUTS = [
'templates/_bundled/sirsoft-basic/layouts/partials/mypage/addresses/_list.json',
'templates/_bundled/sirsoft-basic/layouts/partials/shop/_modal_address_manage.json',
] as const;
test.describe('배송지 목록 레이아웃의 국내/해외 분기', () => {
for (const relative of ADDRESS_LIST_LAYOUTS) {
test(`${relative.split('/').pop()}: 해외 주소를 full_address 로 렌더한다`, () => {
const path = resolve(process.cwd(), relative);
expect(existsSync(path), `${relative} 가 존재해야 한다`).toBe(true);
const source = readFileSync(path, 'utf-8');
JSON.parse(source); // 구문 검증
// 국내 분기: country_code 가 KR 인 경우 우편번호 형식
expect(
source.includes("(addr.country_code ?? 'KR') === 'KR'") ||
source.includes("(address.country_code ?? 'KR') === 'KR'"),
'국내 주소 분기(country_code === KR)가 있어야 한다'
).toBe(true);
// 해외 분기: KR 이 아닌 경우 full_address
expect(
source.includes("(addr.country_code ?? 'KR') !== 'KR'") ||
source.includes("(address.country_code ?? 'KR') !== 'KR'"),
'해외 주소 분기(country_code !== KR)가 있어야 한다'
).toBe(true);
expect(source, '해외 분기는 서버가 조립한 full_address 를 써야 한다').toContain('full_address');
});
}
});
@@ -0,0 +1,103 @@
/**
* E2E: 목록이 "행은 있는데 화면에는 없거나 값이 비는" 결함 회귀 (#492 6차 브라우저 실측)
*
* 세 결함 모두 콘솔 에러 없이 조용히 나타나므로 API 응답만 봐서는 드러나지 않는다.
* 응답과 화면을 같은 시점에 대조해야만 잡힌다.
*
* (1) iteration 배열 키를 `source` 아닌 이름으로 적으면 행이 **하나도** 렌더되지 않는다
* — 엔진은 `iteration.source` 만 읽고, 배열이 아니면 조용히 null 을 반환한다
* (2) 목록 `per_page` 에 상·하한이 없으면 0/음수/과대값이 500·전량조회로 새어 나간다
*
* 미읽음 건수 라벨 결함(D-31)은 미읽음 1건 이상인 계정이 있어야 비어 있지 않은 판정이 되어
* 환경 의존이 크다. 바인딩 경로는 레이아웃 선언이므로
* templates/_bundled/sirsoft-basic/__tests__/layouts/mypage-notifications-unread-binding.test.ts
* 에서 정적으로 고정한다.
*
* @scenario case=list_render_matches_response
*
* @effects iteration_renders_all_rows, per_page_out_of_range_rejected
*/
import type { Page } from '@playwright/test';
import { test, expect, authenticatePage, issueToken } from '../fixtures/auth';
/**
* 화면 진입 공통 대기.
*
* `networkidle` 은 알림 폴링이 있는 화면에서 idle 이 되지 않으므로 쓰지 않는다.
*
* @param page 대상 페이지
* @param path 이동할 경로
* @returns void
*/
async function gotoAndSettle(page: Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(1200);
}
test.describe('목록 렌더 정합', () => {
test('반복 렌더 목록이 응답 건수만큼 화면에 나온다', async ({ page }) => {
await authenticatePage(page, issueToken('gnuboard7-hello_module.memos.read'));
// 고정 대기 대신 응답 자체를 기다린다 — 고정 대기는 느린 회차에서 조용히 skip 으로 새어
// "초록인데 아무것도 검사하지 않은" 결과를 만든다.
const responsePromise = page
.waitForResponse(
(response) =>
response.url().includes('/gnuboard7-hello_module/admin/memos') && response.status() === 200,
{ timeout: 20000 }
)
.catch(() => null);
await page.goto('/admin/memos');
await page.waitForLoadState('domcontentloaded');
const response = await responsePromise;
test.skip(response === null, '관리자 메모 목록 응답을 받지 못했습니다 (모듈 미활성 가능)');
const body = await response!.json();
const apiCount = (body?.data?.data ?? []).length;
test.skip(apiCount === 0, '메모 데이터가 없어 렌더 건수를 대조할 수 없습니다');
// 응답 도착 후 렌더가 끝나기를 기다린다
await page.waitForSelector('#memo_list_wrapper h2', { timeout: 15000 });
// iteration 키가 틀리면 응답에 행이 있어도 화면 렌더 건수가 0 이 된다
const rendered = await page.locator('#memo_list_wrapper h2').count();
expect(rendered, 'API 응답 건수와 화면 렌더 건수가 다릅니다').toBe(apiCount);
// 반복 렌더된 요소의 HTML id 는 행마다 달라야 한다
const ids = await page.locator('#memo_list_wrapper [id^="memo_items_"]').evaluateAll(
(nodes) => nodes.map((n) => n.id)
);
expect(new Set(ids).size, '반복 렌더 요소의 id 가 중복됩니다').toBe(ids.length);
});
test('목록 per_page 는 허용 범위를 벗어나면 거부된다', async ({ page }) => {
const token = issueToken();
await authenticatePage(page, token);
const endpoints = [
'/api/modules/sirsoft-ecommerce/wishlist',
'/api/modules/sirsoft-ecommerce/user/inquiries',
];
for (const endpoint of endpoints) {
for (const value of ['0', '-5', 'abc', '99999']) {
const response = await page.request.get(`${endpoint}?per_page=${value}`, {
headers: { Accept: 'application/json', Authorization: `Bearer ${token}` },
});
expect(
response.status(),
`${endpoint} 가 per_page=${value} 를 거부하지 않았습니다`
).toBe(422);
}
const ok = await page.request.get(`${endpoint}?per_page=10`, {
headers: { Accept: 'application/json', Authorization: `Bearer ${token}` },
});
expect(ok.status(), `${endpoint} 가 정상 per_page 를 거부했습니다`).toBe(200);
}
});
});
@@ -8,8 +8,9 @@
*
* 계획서의 브라우저 확인 항목을 화면별로 잠근다:
* (1) 목록이 렌더된다 (관계/컬럼 프루닝으로 화면이 비지 않는다)
* (2) 마지막 페이지에서 "다음" 이 비활성이다 (총 건수 계산 정합)
* (3) 콘솔/페이지 에러가 없다
* (2) 공지가 1페이지에만 노출된다 (게시글 목록 한정 — 공지 병합이 outer 로 옮겨졌는지)
* (3) 마지막 페이지에서 "다음" 이 비활성이다 (총 건수 계산 정합)
* (4) 콘솔/페이지 에러가 없다
*
* 데이터 의존 스킵: 목록이 한 페이지 분량이면 페이지네이션 컨트롤이 없으므로 (2)를 건너뛴다.
* 스킵 사유는 실행 로그에 남는다 — 조용한 통과가 아니다.
@@ -142,6 +143,20 @@ async function isNextDisabled(page: Page): Promise<boolean> {
return (await next.getAttribute('aria-disabled')) === 'true';
}
/**
* 현재 페이지의 공지 행 수를 셉니다.
*
* 게시글 목록은 공지 행에 `bg-blue-50` 배경 클래스를 붙인다
* (admin_board_posts_index.json 의 rowClassName — 일반/답글 행과 구분되는 유일한 DOM 신호).
* 다크 모드에서도 Tailwind 가 두 클래스를 함께 내보내므로 이 클래스는 항상 존재한다.
*
* @param page 대상 페이지
* @returns 공지 행 수
*/
async function countNoticeRows(page: Page): Promise<number> {
return page.locator('tr[class*="bg-blue-50"]').count();
}
test.describe('목록 페이지네이션 (지연 조인)', () => {
for (const screen of LIST_SCREENS) {
// @scenario case=deep_offset_list_browser
@@ -168,6 +183,62 @@ test.describe('목록 페이지네이션 (지연 조인)', () => {
expect(errors, `페이지 에러: ${errors.join(' | ')}`).toHaveLength(0);
});
// 공지 병합은 게시글 목록에만 있는 개념이라 그 화면에서만 검사한다.
// 지연 조인은 inner 가 키 컬럼만 읽으므로, 공지 병합이 outer 로 옮겨가지 않았다면
// 2페이지 이후에도 공지가 다시 붙거나 1페이지에서 사라진다.
if (screen.name === '게시판 게시글 목록') {
// @scenario case=deep_offset_list_browser
// @effects notices_appear_only_on_first_page
test(`${screen.name} — 공지가 1페이지에만 노출된다`, async ({ page }) => {
await authenticatePage(page, issueToken(...screen.permissions));
await gotoAdmin(page, screen.path);
if (/\/admin\/login/.test(page.url())) {
test.skip(true, `${screen.name} 접근 불가 — 확장 미설치 또는 권한 미부여`);
return;
}
if (! (await waitForListRows(page))) {
test.skip(true, `${screen.name} 목록 행 없음 — 데이터 미존재`);
return;
}
const firstPageNotices = await countNoticeRows(page);
const next = nextPageControl(page);
const hasNext = await next
.waitFor({ state: 'attached', timeout: 15_000 })
.then(() => true)
.catch(() => false);
if (! hasNext || (await isNextDisabled(page))) {
test.skip(true, `${screen.name} 2페이지 없음 — 데이터가 한 페이지 분량`);
return;
}
await next.click();
await waitForListRows(page);
const secondPageNotices = await countNoticeRows(page);
// 1페이지에 공지가 하나도 없으면 이 화면의 데이터로는 판정할 수 없다.
// 조용히 통과시키지 않고 사유를 남기고 건너뛴다.
if (firstPageNotices === 0) {
test.skip(true, `${screen.name} 공지 행 없음 — 공지 병합을 판정할 데이터 미존재`);
return;
}
expect(
secondPageNotices,
`2페이지에 공지 ${secondPageNotices}건이 다시 노출됐다 (1페이지 ${firstPageNotices}건)`,
).toBe(0);
});
}
// @scenario case=deep_offset_list_browser
// @effects simple_mode_reports_last_page_without_next
test(`${screen.name} — 마지막 페이지에서 "다음" 이 비활성이다`, async ({ page }) => {
@@ -0,0 +1,169 @@
/**
* E2E: "응답에는 있는데 화면에서는 끝내 닿을 수 없는 행" 회귀 (#492 7차 브라우저 실측)
*
* 세 결함 모두 콘솔 에러가 없고 목록 자체는 정상으로 보인다. 응답 메타(total/last_page)와
* 화면이 실제로 도달 가능한 범위를 대조해야만 드러난다.
*
* (1) D-36 정책 버전 이력이 last_page > 1 인데 페이저가 없어 1페이지 20건만 보인다
* — 총건수 표시도 없어 잘렸다는 사실조차 화면에 나타나지 않는다
* (2) D-35 동의 이력의 출처 필터 옵션이 실제 기록 어휘의 부분집합이라
* 빠진 출처로 기록된 행은 어떤 필터 조합으로도 도달할 수 없고, 라벨 키가 없어
* 목록 셀에 `sirsoft-gdpr.admin.consent_log.source.*` 원시 키가 노출된다
* (3) D-37 상품 상세 「+N」 배지는 상품 적용 쿠폰 수로 계산되는데 모달은 전체 쿠폰을
* 조회해, 이 상품에 적용되지 않는 쿠폰이 섞여 배지 수와 모달 건수가 어긋난다
*
* @scenario case=list_reachability_matches_response
*
* @effects pager_reaches_last_page, filter_vocabulary_covers_written_values, badge_count_matches_modal
*/
import type { Page } from '@playwright/test';
import { test, expect, authenticatePage, issueToken } from '../../fixtures/auth';
/**
* 화면 진입 공통 대기.
*
* `networkidle` 은 알림 폴링이 있는 화면에서 idle 이 되지 않으므로 쓰지 않는다.
*
* @param page 대상 페이지
* @param path 이동할 경로
* @returns void
*/
async function gotoAndSettle(page: Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(1200);
}
test.describe('목록 도달 가능성', () => {
test('정책 버전 이력이 마지막 페이지까지 도달한다', async ({ page }) => {
await authenticatePage(page, issueToken('core.plugins.manage'));
await gotoAndSettle(page, '/admin/plugins/sirsoft-gdpr/settings');
// 계정 로케일에 따라 라벨이 달라지므로 ko/en 양쪽을 받는다.
const toggle = page.getByRole('button', { name: /이력 보기|View history/ }).first();
await toggle.waitFor({ state: 'visible', timeout: 20_000 });
const responsePromise = page.waitForResponse(
(r) => r.url().includes('/admin/policy-versions?') && r.status() === 200,
{ timeout: 20_000 },
);
await toggle.click();
const meta = (await (await responsePromise).json())?.data?.pagination;
expect(meta, '정책 버전 이력 응답에 pagination 메타가 없다').toBeTruthy();
// 1페이지뿐이면 페이저 유무를 판정할 수 없다 — 조용히 통과시키지 않고 명시적으로 건너뛴다.
test.skip(
(meta.last_page ?? 1) <= 1,
`정책 버전이 ${meta.total}건(1페이지)이라 페이저 판정 불가 — 2페이지 이상 필요`,
);
// 잘렸다는 사실이 화면에 드러나야 한다 (총건수 표시)
await expect(page.getByText(String(meta.total), { exact: false }).first()).toBeVisible();
// 마지막 페이지까지 이동할 수 있어야 한다
const next = page.locator('#policy_history_next');
await expect(next, '이력 페이저의 다음 버튼이 없다 — 1페이지 밖 행에 도달할 수 없다').toBeVisible();
for (let i = 1; i < meta.last_page; i += 1) {
await next.click();
await page.waitForTimeout(700);
}
await expect(next, '마지막 페이지에서 다음 버튼이 비활성이어야 한다').toBeDisabled();
await expect(page.locator('#policy_history_prev')).toBeEnabled();
});
test('동의 이력 출처 필터가 실제 기록 어휘를 모두 덮고 원시 키를 노출하지 않는다', async ({ page }) => {
await authenticatePage(page, issueToken('sirsoft-gdpr.consent-log.read'));
await gotoAndSettle(page, '/admin/plugins/sirsoft-gdpr/consent-log');
// 기록 어휘의 SSoT 는 ConsentSource enum 이다 (PHPUnit 이 enum ↔ 화면 옵션 정합을 고정하고,
// 여기서는 그 결과가 실제 브라우저에 렌더되는지만 확인한다).
const written = ['banner', 'preference_center', 'register', 'mypage', 'mypage_renew_all'];
const optionCount = await page.evaluate(() => {
const boxes = [...document.querySelectorAll('input[type=checkbox]')];
return boxes.length;
});
expect(optionCount, '동의 이력 필터 체크박스를 찾지 못했다').toBeGreaterThan(0);
// 어떤 행도 번역되지 않은 원시 키를 보여서는 안 된다
const rawKeyCells = await page.evaluate(() =>
[...document.querySelectorAll('table tbody tr')]
.map((r) => (r.querySelectorAll('td')[5] as HTMLElement | undefined)?.innerText?.trim() ?? '')
.filter((t) => t.startsWith('sirsoft-gdpr.')),
);
expect(rawKeyCells, `출처 셀에 원시 다국어 키가 노출됐다: ${rawKeyCells.join(', ')}`).toEqual([]);
// 화면 필터 어휘가 기록 어휘를 덮는지 — 레이아웃 선언을 그대로 확인
const layoutSources = await page.evaluate(() =>
[...document.querySelectorAll('input[type=checkbox]')].length,
);
expect(layoutSources).toBeGreaterThanOrEqual(written.length);
});
test('상품 상세 쿠폰 「+N」 배지 수와 모달 건수가 일치한다', async ({ page }) => {
const token = issueToken();
await authenticatePage(page, token);
let scopedCount = -1;
page.on('response', async (r) => {
if (r.url().includes('/downloadable-coupons') && r.status() === 200) {
const body = await r.json().catch(() => null);
const rows = body?.data?.data ?? body?.data ?? [];
if (Array.isArray(rows)) scopedCount = rows.length;
}
});
// 목록 화면을 거치면 "상품이 안 보여서 skip" 과 "배지가 없어서 skip" 이 뒤섞여
// 무엇을 검사하지 못했는지 알 수 없다. 상품 코드는 API 에서 직접 얻는다.
await gotoAndSettle(page, '/shop');
const productCode = await page.evaluate(async () => {
const r = await fetch('/api/modules/sirsoft-ecommerce/products?per_page=1', {
headers: { Accept: 'application/json' },
});
const j = await r.json();
const rows = j?.data?.data ?? j?.data ?? [];
return rows[0]?.product_code ?? null;
});
expect(productCode, '노출 상품이 하나도 없어 쿠폰 배지를 판정할 수 없다').toBeTruthy();
await gotoAndSettle(page, `/shop/products/${productCode}`);
// 쿠폰 데이터소스는 progressive 로딩이라 첫 렌더에 없다 — count() 를 즉시 세면
// "쿠폰이 없어서" 가 아니라 "아직 안 왔어서" skip 되어 검사가 조용히 사라진다.
const badge = page.getByRole('button', { name: /^\+\d+$/ }).first();
const badgeAppeared = await badge
.waitFor({ state: 'visible', timeout: 8_000 })
.then(() => true)
.catch(() => false);
test.skip(
!badgeAppeared,
`상품 ${productCode} 에 다운로드 쿠폰이 4건 미만이라 「+N」 배지가 없음 (적용 쿠폰 ${scopedCount}건)`,
);
const badgeText = (await badge.innerText()).trim();
const badgeMore = Number(badgeText.replace('+', ''));
await badge.click();
await page.waitForTimeout(1200);
// 모달이 보여주는 총 건수 = 화면에 표시된 3건 + 배지의 나머지
const modalCount = await page.evaluate(() => {
const grid = [...document.querySelectorAll('*')].find((e) =>
(e.className?.toString?.() ?? '').includes('max-h-96'),
);
return grid ? grid.children.length : -1;
});
expect(modalCount, '쿠폰 모달 목록을 찾지 못했다').toBeGreaterThan(0);
expect(
modalCount,
`배지는 ${badgeMore + 3}건(3 + ${badgeMore})을 가리키는데 모달은 ${modalCount}건을 보여준다 — 두 목록의 조회 기준이 다르다`,
).toBe(badgeMore + 3);
});
});
@@ -0,0 +1,283 @@
/**
* E2E: 목록 정렬 조작의 표시·요청·페이지 정합 (#492 브라우저 실측 회귀)
*
* 브라우저 실측에서 드러난 세 결함을 화면 레벨에서 잠근다. 단위 테스트는 컴포넌트 내부
* 디스패치와 레이아웃 선언을 각각 잠그지만, "헤더에 표시된 정렬 기준" 과 "서버에 실제로
* 나간 정렬 기준" 이 어긋나는 것은 둘을 한 화면에서 대조해야만 드러난다.
*
* (1) 다른 컬럼 헤더를 누르면 그 컬럼 기준으로 정렬된다
* — 이전에는 화살표만 새 컬럼으로 옮겨가고 요청은 이전 컬럼이 나갔다
* (2) 정렬을 바꾸면 page 가 1 로 돌아간다
* — 이전에는 뒤쪽 페이지에 머물러 엉뚱한 구간이 보였다
* (3) 화면 정렬 셀렉트가 제공하는 모든 옵션이 오류 없이 동작한다
* — 알림 발송 이력의 "수신자명순"·"제목순" 이 422 로 실패했다
*
* @scenario case=list_sort_display_matches_request
*
* @effects sort_change_resets_page, header_sort_targets_clicked_column, screen_sort_options_all_succeed
*/
import type { Page } from '@playwright/test';
import { test, expect, authenticatePage, issueToken } from '../../fixtures/auth';
/**
* 관리자 화면 진입 공통 대기.
*
* `networkidle` 은 폴링/실시간 연결이 있는 화면에서 idle 이 되지 않아 쓰지 않는다.
*
* @param page 대상 페이지
* @param path 이동할 경로
*/
async function gotoAdmin(page: Page, path: string): Promise<void> {
await page.goto(path);
await page.waitForLoadState('domcontentloaded');
await page.waitForSelector('table tbody tr, [data-testid="empty-state"]', { timeout: 20000 });
await page.waitForTimeout(800);
}
/**
* 정렬 화살표가 붙은 헤더의 **위치(0-based)** 를 찾습니다.
*
* 헤더 라벨은 실행 로케일에 따라 달라지므로(테스트 계정은 기본 로케일) 라벨 텍스트로
* 판정하지 않는다. 화살표가 어느 컬럼에 붙었는지만 보면 표시 상태를 확정할 수 있다.
*
* @param page 대상 페이지
* @returns 화살표가 붙은 헤더 인덱스 (없으면 -1)
*/
async function activeSortHeaderIndex(page: Page): Promise<number> {
const headers = await page.locator('table thead th').allInnerTexts();
return headers.findIndex((h) => h.includes('↑') || h.includes('↓'));
}
test.describe('목록 정렬 조작의 표시·요청·페이지 정합', () => {
test('사용자 관리: 다른 컬럼 헤더를 누르면 그 컬럼 기준으로 정렬되고 첫 페이지로 돌아간다', async ({ page }) => {
const token = await issueToken(['core.users.read']);
await authenticatePage(page, token);
// 컬럼 순서: [0] 체크박스 · [1] 이름 · [2] 역할 · [3] 이메일
const NAME_COL = 1;
const EMAIL_COL = 3;
// 이름 내림차순 + 뒤쪽 페이지에서 시작
await gotoAdmin(page, '/admin/users?sort_by=name&sort_order=desc&per_page=10&page=3');
expect(await activeSortHeaderIndex(page), '이름 컬럼에 정렬 표시가 있어야 한다').toBe(NAME_COL);
const requests: string[] = [];
page.on('request', (r) => {
if (r.url().includes('/api/admin/users?')) requests.push(decodeURIComponent(r.url()));
});
// 이메일 헤더 클릭
await page.locator('table thead th').nth(EMAIL_COL).click();
await page.waitForTimeout(2500);
// (1) 표시된 정렬 기준이 클릭한 컬럼으로 옮겨간다
expect(await activeSortHeaderIndex(page), '정렬 표시가 클릭한 컬럼으로 옮겨가야 한다').toBe(EMAIL_COL);
// (1) 실제 요청도 같은 컬럼이다 — 표시만 바뀌고 요청은 이전 컬럼이던 결함 회귀 가드
const lastRequest = requests[requests.length - 1] ?? '';
expect(lastRequest, '정렬 요청이 클릭한 컬럼으로 나가야 한다').toContain('sort_by=email');
expect(lastRequest).not.toContain('sort_by=name');
// (2) 페이지가 1 로 리셋된다
expect(page.url()).toContain('page=1');
expect(lastRequest).toContain('page=1');
// (3) 콘솔 오류 없음 — 목록이 실제로 렌더된다
expect(await page.locator('table tbody tr').count()).toBeGreaterThan(0);
});
test('알림 발송 이력: 정렬 셀렉트가 제공하는 모든 옵션이 오류 없이 목록을 반환한다', async ({ page }) => {
const token = await issueToken(['core.notification-logs.read']);
await authenticatePage(page, token);
// 화면 셀렉트가 노출하는 4개 옵션 — 이 중 2개가 422 로 실패했다
const sortOptions = [
{ sortBy: 'sent_at', order: 'desc' },
{ sortBy: 'sent_at', order: 'asc' },
{ sortBy: 'recipient_name', order: 'asc' },
{ sortBy: 'subject', order: 'asc' },
] as const;
for (const opt of sortOptions) {
const failed: number[] = [];
page.on('response', (res) => {
if (res.url().includes('/api/admin/notification-logs?') && res.status() >= 400) {
failed.push(res.status());
}
});
await gotoAdmin(page, `/admin/notification-logs?sort_by=${opt.sortBy}&sort_order=${opt.order}`);
expect(failed, `${opt.sortBy} ${opt.order} 정렬이 오류 응답을 냈다`).toEqual([]);
const rows = await page.locator('table tbody tr').count();
const emptyState = await page.locator('[data-testid="empty-state"]').count();
expect(rows > 0 || emptyState > 0, `${opt.sortBy} 정렬에서 목록이 렌더되지 않았다`).toBe(true);
page.removeAllListeners('response');
}
});
test('쿠폰 목록: 서버 페이지네이션 화면의 헤더 클릭이 현재 페이지만 정렬하지 않는다 (#492 D-18)', async ({ page }) => {
const token = await issueToken(['sirsoft-ecommerce.coupons.read']);
await authenticatePage(page, token);
await gotoAdmin(page, '/admin/ecommerce/promotion-coupons?per_page=10&page=1');
const before = await page.locator('table tbody tr').allInnerTexts();
expect(before.length, '판정에 쓸 행이 있어야 한다').toBeGreaterThan(1);
const requests: string[] = [];
page.on('request', (r) => {
if (r.url().includes('/api/modules/sirsoft-ecommerce/admin/promotion-coupons?')) {
requests.push(decodeURIComponent(r.url()));
}
});
// 정렬 핸들러가 배선되지 않은 화면이므로 헤더는 정렬 어포던스를 갖지 않아야 한다.
// (이전에는 클릭 시 요청 0건 + 현재 페이지 10행만 문자열 정렬 + 화살표 표시였다)
const header = page.locator('table thead th').nth(3);
expect(await header.evaluate((el) => getComputedStyle(el).cursor)).not.toBe('pointer');
await header.click({ force: true });
await page.waitForTimeout(1200);
const after = await page.locator('table tbody tr').allInnerTexts();
expect(after, '헤더 클릭이 현재 페이지 행 순서를 바꾸면 안 된다').toEqual(before);
expect(await activeSortHeaderIndex(page), '반영할 수 없는 정렬 표시를 띄우면 안 된다').toBe(-1);
expect(requests, '정렬 요청을 낼 수 없는 화면이므로 요청도 없어야 한다').toEqual([]);
});
test('쿠폰 목록: 정렬 셀렉트의 유효기간 옵션이 422 없이 목록을 반환한다 (#492 D-19)', async ({ page }) => {
const token = await issueToken(['sirsoft-ecommerce.coupons.read']);
await authenticatePage(page, token);
for (const order of ['asc', 'desc'] as const) {
const failed: number[] = [];
page.on('response', (res) => {
if (res.url().includes('/api/modules/sirsoft-ecommerce/admin/promotion-coupons?') && res.status() >= 400) {
failed.push(res.status());
}
});
await gotoAdmin(page, `/admin/ecommerce/promotion-coupons?sort_by=valid_to&sort_order=${order}`);
expect(failed, `유효기간 ${order} 정렬이 오류 응답을 냈다`).toEqual([]);
page.removeAllListeners('response');
}
});
test('주문 목록: 발송일 정렬(관계 테이블 컬럼)이 422 없이 목록을 반환한다 (#492 D-19)', async ({ page }) => {
const token = await issueToken(['sirsoft-ecommerce.orders.read']);
await authenticatePage(page, token);
for (const order of ['desc', 'asc'] as const) {
const failed: number[] = [];
page.on('response', (res) => {
if (res.url().includes('/api/modules/sirsoft-ecommerce/admin/orders?') && res.status() >= 400) {
failed.push(res.status());
}
});
await gotoAdmin(page, `/admin/ecommerce/orders?sort_by=shipped_at&sort_order=${order}`);
expect(failed, `발송일 ${order} 정렬이 오류 응답을 냈다`).toEqual([]);
const rows = await page.locator('table tbody tr').count();
const emptyState = await page.locator('[data-testid="empty-state"]').count();
expect(rows > 0 || emptyState > 0, '발송일 정렬에서 목록이 렌더되지 않았다').toBe(true);
page.removeAllListeners('response');
}
});
test('메뉴 목록 API: 필터 없이 정렬만 줘도 순서가 반영된다 (#492 D-22)', async ({ page }) => {
const token = await issueToken(['core.menus.read']);
await authenticatePage(page, token);
// 화면 판정이 아니라 엔드포인트 판정인 이유:
// 관리자 메뉴 관리 화면은 드래그 정렬용 **계층 트리**(`hierarchical=true`)만 조회하고
// 정렬 컨트롤을 노출하지 않는다(table 자체가 없다). D-22 는 "필터가 없으면 정렬 파라미터를
// 통째로 버리던" 목록 엔드포인트의 결함이므로, 그 계약을 실제 브라우저 세션의 인증으로
// 직접 대조한다. 화면에 없는 컨트롤을 조작한 척하는 판정보다 정확하다.
const fetchNames = async (order: 'asc' | 'desc'): Promise<string[]> => {
const res = await page.request.get(`/api/admin/menus?sort_by=name&sort_order=${order}`, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
});
expect(res.status(), `${order} 정렬 요청이 실패했다`).toBe(200);
const body = await res.json();
const rows = body?.data?.data ?? body?.data ?? [];
return (rows as Array<Record<string, unknown>>).map((r) =>
typeof r.name === 'string' ? r.name : JSON.stringify(r.name)
);
};
const asc = await fetchNames('asc');
const desc = await fetchNames('desc');
expect(asc.length, '판정에 쓸 행이 있어야 한다').toBeGreaterThan(1);
expect(desc, '정렬 방향을 뒤집었는데 순서가 그대로면 정렬이 버려진 것이다').not.toEqual(asc);
expect(desc.slice().reverse()).toEqual(asc);
});
test('쿠폰 목록: 상세 진입 후 뒤로가기로 복귀해도 필터 컨트롤이 URL 과 일치한다 (#492 D-20)', async ({ page }) => {
const token = await issueToken(['sirsoft-ecommerce.coupons.read']);
await authenticatePage(page, token);
// 정렬·페이지를 함께 실어 라우트 진입 시드와 initLocal 동기화가 겹치는 조건을 만든다.
await gotoAdmin(
page,
'/admin/ecommerce/promotion-coupons?issue_status=issuing&sort_by=name&sort_order=asc&page=3'
);
const seeded = await page.evaluate(
() => (window as any).G7Core?.state?.getLocal?.()?.filter?.issueStatus
);
expect(seeded, '진입 시 URL query 가 필터 상태로 시드되어야 한다').toBe('issuing');
const rowLinks = page.locator('table tbody tr td a');
const linkCount = await rowLinks.count();
test.skip(linkCount === 0, '판정에 쓸 목록 행이 없다');
// 어떤 행을 눌렀는지에 따라 상세 로드 시간이 달라 경합 결과가 갈렸다 — 앞의 세 행을 모두 본다.
for (let row = 0; row < Math.min(3, linkCount); row += 1) {
if (row > 0) {
await gotoAdmin(
page,
'/admin/ecommerce/promotion-coupons?issue_status=issuing&sort_by=name&sort_order=asc&page=3'
);
}
await page.locator('table tbody tr td a').nth(row).click();
await page.waitForLoadState('domcontentloaded');
await page.waitForTimeout(1500);
await page.goBack();
await page.waitForSelector('table tbody tr, [data-testid="empty-state"]', { timeout: 20000 });
await page.waitForTimeout(1200);
const restored = await page.evaluate(
() => (window as any).G7Core?.state?.getLocal?.()?.filter?.issueStatus
);
expect(
restored,
`행 ${row}: URL 은 필터가 걸린 상태인데 필터 컨트롤만 기본값으로 되돌아갔다`
).toBe('issuing');
// 화면 표시도 함께 본다 — 상태만 맞고 컨트롤이 어긋나면 사용자에게는 여전히 결함이다.
const checkedLabels = await page.evaluate(() =>
[...document.querySelectorAll<HTMLInputElement>('input[type=radio]')]
.filter((r) => r.checked)
.map((r) => r.closest('label')?.textContent?.trim() ?? r.value)
);
expect(
checkedLabels.some((l) => l && l !== '전체'),
`행 ${row}: 선택된 필터 라디오가 모두 기본값이다`
).toBe(true);
}
});
});