v7.0.0 release

This commit is contained in:
HeuJung committed 2026-07-01 10:30:32 +09:00
1 parent 0e7fa04b03
commit c4ea9a6cd1
3582 files changed
+626189 -160151

No files matched your search

@@ -1,13 +1,16 @@
/**
* @file board-401-error-handling.test.tsx
* @description 게시판 목록/상세 - 비로그인 접근 시 401 errorHandling 검증 (이슈 #228 B-5)
* @description 게시판 목록/상세 - 비로그인 접근 시 401 errorHandling 검증 (이슈 #228 B-5, #413 item 28)
*
* 검증 항목:
* 1. show.json / index.json 데이터소스에 401 errorHandling이 정의되어 있는가
* 2. 401 핸들러가 sequence(toast → navigate /login?redirect=...) 방식인가
* 3. navigate params에 redirect 쿼리가 포함되어 있는가
* 2. 401 핸들러가 sequence(toast → redirectToLoginWithReturn) 방식인가
* 3. 두 번째 action 이 redirectToLoginWithReturn 핸들러인가 (custom+name 형식 금지)
* 4. auth_required가 아닌 auth_mode: "optional"이 사용되는가
* 5. 기존 403/404 핸들러가 유지되는가
*
* @scenario entry_point:board_list_401,board_show_401
* @effects redirect_preserves_pathname,login_returns_to_original_path
*/
import { describe, it, expect } from 'vitest';
@@ -52,19 +55,23 @@ describe('게시판 401 errorHandling — sequence + redirect 방식 (이슈 #22
expect(toastAction?.handler).toBe('toast');
});
it('두 번째 action이 navigate 핸들러이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.handler).toBe('navigate');
it('두 번째 action이 redirectToLoginWithReturn 핸들러이어야 한다', () => {
// 등록 키를 handler 에 직접 지정 (custom+name 형식은 디스패치가 handler 값으로만
// 조회하므로 throw 됨 — feedback_verify_full_path_not_just_evaluator).
const redirectAction = dsErrorHandling?.['401']?.actions[1];
expect(redirectAction?.handler).toBe('redirectToLoginWithReturn');
});
it('navigate path가 /login이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.path).toBe('/login');
it('두 번째 action에 name 필드 단언이 없어야 한다 (custom+name 거짓 통과 방지)', () => {
const redirectAction = dsErrorHandling?.['401']?.actions[1];
expect(redirectAction?.handler).not.toBe('custom');
expect((redirectAction as any)?.name).toBeUndefined();
});
it('navigate query에 redirect 파라미터가 없어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.query).toBeUndefined();
it('redirect 는 핸들러가 window.location 으로 캡처하므로 navigate params 가 불필요하다', () => {
// 레이아웃에 정적 redirect 표현식을 두지 않는다 (핸들러가 런타임에 캡처).
const redirectAction = dsErrorHandling?.['401']?.actions[1];
expect(redirectAction?.params).toBeUndefined();
});
it('기존 403 핸들러가 유지되어야 한다', () => {
@@ -109,19 +116,20 @@ describe('게시판 401 errorHandling — sequence + redirect 방식 (이슈 #22
expect(toastAction?.handler).toBe('toast');
});
it('두 번째 action이 navigate 핸들러이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.handler).toBe('navigate');
it('두 번째 action이 redirectToLoginWithReturn 핸들러이어야 한다', () => {
const redirectAction = dsErrorHandling?.['401']?.actions[1];
expect(redirectAction?.handler).toBe('redirectToLoginWithReturn');
});
it('navigate path가 /login이어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.path).toBe('/login');
it('두 번째 action에 name 필드 단언이 없어야 한다 (custom+name 거짓 통과 방지)', () => {
const redirectAction = dsErrorHandling?.['401']?.actions[1];
expect(redirectAction?.handler).not.toBe('custom');
expect((redirectAction as any)?.name).toBeUndefined();
});
it('navigate query에 redirect 파라미터가 없어야 한다', () => {
const navigateAction = dsErrorHandling?.['401']?.actions[1];
expect(navigateAction?.params?.query).toBeUndefined();
it('redirect 는 핸들러가 window.location 으로 캡처하므로 navigate params 가 불필요하다', () => {
const redirectAction = dsErrorHandling?.['401']?.actions[1];
expect(redirectAction?.params).toBeUndefined();
});
it('기존 403 핸들러가 유지되어야 한다', () => {
@@ -0,0 +1,169 @@
/**
* @file board-gallery-view-count-toggle.test.tsx
* @description 갤러리형 목록 - 조회수 표시 토글(show_view_count) 반영 회귀 테스트 (#413-19-4b)
*
* 배경:
* 갤러리형 목록(types/gallery/index.json)의 조회수 Span 에 show_view_count 조건이 없어,
* 환경설정에서 '조회수 표시'를 OFF 해도 갤러리형에서는 조회수가 항상 표시되던 회귀.
* basic/card 형은 동일 조건으로 정상 동작 → 갤러리에도 동일 if 조건을 추가.
*
* 검증 항목:
* 1. show_view_count !== false 일 때 조회수 표시 (true / 미설정 모두)
* 2. show_view_count === false 일 때 조회수 미표시
*
* 조건식: "{{posts?.data?.board?.settings?.show_view_count !== false}}"
* - basic/card/index.json 과 동일 (SSoT)
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ============================================================
// 테스트용 컴포넌트 정의
// ============================================================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>
{children || text}
</span>
);
const TestIcon: React.FC<{
name?: string;
size?: string;
className?: string;
}> = ({ name, size, className }) => (
<i className={className} data-icon={name} data-size={size} />
);
// ============================================================
// 컴포넌트 레지스트리 설정
// ============================================================
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'basic' } },
};
return registry;
}
// ============================================================
// 레이아웃 JSON — gallery/index.json 의 조회수 Span 구조를 반영
// ============================================================
const galleryViewCountLayoutJson = {
version: '1.0.0',
layout_name: 'board_gallery_view_count_test',
components: [
{
type: 'basic',
name: 'Div',
props: { 'data-testid': 'meta-area' },
children: [
{
type: 'basic',
name: 'Span',
if: '{{posts?.data?.board?.settings?.show_view_count !== false}}',
props: {
'data-testid': 'view-count',
className:
"flex items-center gap-0.5 {{(_local.post?.status === 'blinded' || _local.post?.deleted_at) ? 'text-gray-400' : 'text-gray-300'}}",
},
children: [
{ type: 'basic', name: 'Icon', props: { name: 'eye', size: 'xs' } },
{ type: 'basic', name: 'Span', text: '{{_local.post?.view_count ?? 0}}' },
],
},
],
},
],
};
// ============================================================
// 테스트
// ============================================================
// @scenario board-gallery-view-count
// @axes show_view_count=true show_view_count=false show_view_count=unset board_type=gallery
// @effects gallery_shows_view_count_when_true, gallery_shows_view_count_when_unset,
// gallery_hides_view_count_when_false, gallery_matches_basic_and_card_condition
describe('갤러리형 목록 - 조회수 표시 토글(show_view_count) (#413-19-4b)', () => {
let registry: ComponentRegistry;
beforeEach(() => {
registry = setupTestRegistry();
});
// @scenario show_view_count=true, board_type=gallery
// @effects gallery_shows_view_count_when_true, gallery_matches_basic_and_card_condition
it('show_view_count=true 이면 조회수가 표시된다', async () => {
const testUtils = createLayoutTest(galleryViewCountLayoutJson, {
componentRegistry: registry,
initialData: { posts: { data: { board: { settings: { show_view_count: true } } } } },
initialState: {
_local: { post: { id: 1, view_count: 123, status: 'published', deleted_at: null } },
},
});
await testUtils.render();
expect(screen.getByTestId('view-count')).toBeTruthy();
testUtils.cleanup();
});
// @scenario show_view_count=unset, board_type=gallery
// @effects gallery_shows_view_count_when_unset
it('show_view_count 미설정(undefined)이면 조회수가 표시된다 (기본 노출)', async () => {
const testUtils = createLayoutTest(galleryViewCountLayoutJson, {
componentRegistry: registry,
initialData: { posts: { data: { board: { settings: {} } } } },
initialState: {
_local: { post: { id: 2, view_count: 45, status: 'published', deleted_at: null } },
},
});
await testUtils.render();
expect(screen.getByTestId('view-count')).toBeTruthy();
testUtils.cleanup();
});
// @scenario show_view_count=false, board_type=gallery
// @effects gallery_hides_view_count_when_false, gallery_matches_basic_and_card_condition
it('show_view_count=false 이면 조회수가 표시되지 않는다 (회귀 차단)', async () => {
const testUtils = createLayoutTest(galleryViewCountLayoutJson, {
componentRegistry: registry,
initialData: { posts: { data: { board: { settings: { show_view_count: false } } } } },
initialState: {
_local: { post: { id: 3, view_count: 999, status: 'published', deleted_at: null } },
},
});
await testUtils.render();
expect(screen.queryByTestId('view-count')).toBeNull();
testUtils.cleanup();
});
});
@@ -0,0 +1,290 @@
/**
* @file board-post-navigation-list-return.test.tsx
* @description 게시판 목록 복귀 상태 보존(45-1) + 답글 상세 이전/다음 버튼 미렌더(47-4) 렌더링 회귀 테스트
*
* 검증 항목:
* 1. 행 클릭(basic/card/gallery) navigate 가 mergeQuery:true 로 현재 목록 query(category/search/page/del/filters)를
* 상세 URL 에 부착한다. (45-1)
* 2. 상세 '목록' 버튼 navigate 가 mergeQuery:true 로 상세 URL 에 실린 목록 상태를 그대로 목록으로 복귀한다. (45-1)
* 3. 답글 상세(navigation prev/next null) 에서는 이전/다음 버튼이 미렌더링된다. (47-4)
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
// ============================================================
// 테스트용 컴포넌트 정의
// ============================================================
const TestDiv: React.FC<{
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
}> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestButton: React.FC<{
type?: string;
className?: string;
children?: React.ReactNode;
'data-testid'?: string;
onClick?: () => void;
}> = ({ type, className, children, 'data-testid': testId, onClick }) => (
<button type={type as any} className={className} data-testid={testId} onClick={onClick}>
{children}
</button>
);
const TestSpan: React.FC<{
className?: string;
children?: React.ReactNode;
text?: string;
'data-testid'?: string;
}> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>
{children || text}
</span>
);
const TestIcon: React.FC<{ name?: string; size?: string }> = ({ name }) => (
<i data-icon={name} />
);
function setupTestRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Icon: { component: TestIcon, metadata: { name: 'Icon', type: 'composite' } },
};
return registry;
}
/**
* 현재 URL(window.location)을 목록/상세 상태로 설정합니다.
* navigate 핸들러의 mergeQuery 는 window.location.search 를 읽어 병합합니다.
*/
function setUrl(search: string): void {
window.history.replaceState({}, '', `/board/free${search}`);
}
// ============================================================
// 45-1: 행 클릭 → 상세 URL 에 목록 상태 부착 (mergeQuery)
// ============================================================
/**
* @scenario post_kind=original
* @effects list_return_preserves_query
*/
describe('45-1 행 클릭 시 목록 상태(query)를 상세 URL 에 부착', () => {
beforeEach(() => {
setupTestRegistry();
});
afterEach(() => {
window.history.replaceState({}, '', '/');
});
const rowClickLayout = {
version: '1.0.0',
layout_name: 'board_row_click_test',
data_sources: [],
components: [
{
comment: '행 클릭 시 현재 목록 상태를 상세 URL 에 부착 (45-1)',
type: 'basic',
name: 'Button',
props: { 'data-testid': 'row' },
actions: [
{
type: 'click',
handler: 'navigate',
params: { path: '/board/free/77', mergeQuery: true, query: {} },
},
],
text: 'row',
},
],
};
it('목록 query(category/search/page)가 상세 navigate 경로에 보존된다', async () => {
setUrl('?category=공지&search=테스트&page=2');
const testUtils = createLayoutTest(rowClickLayout);
await testUtils.render();
await testUtils.triggerAction({
type: 'click',
handler: 'navigate',
params: { path: '/board/free/77', mergeQuery: true, query: {} },
} as any);
const history = testUtils.getNavigationHistory();
expect(history.length).toBe(1);
const dest = history[0];
expect(dest.startsWith('/board/free/77')).toBe(true);
expect(dest).toContain('category=%EA%B3%B5%EC%A7%80'); // '공지' URL 인코딩
expect(dest).toContain('search=%ED%85%8C%EC%8A%A4%ED%8A%B8'); // '테스트'
expect(dest).toContain('page=2');
testUtils.cleanup();
});
it('del=1(권한자 토글)도 상세 URL 로 함께 전달된다', async () => {
setUrl('?del=1&page=3');
const testUtils = createLayoutTest(rowClickLayout);
await testUtils.render();
await testUtils.triggerAction({
type: 'click',
handler: 'navigate',
params: { path: '/board/free/77', mergeQuery: true, query: {} },
} as any);
const dest = testUtils.getNavigationHistory()[0];
expect(dest).toContain('del=1');
expect(dest).toContain('page=3');
testUtils.cleanup();
});
});
// ============================================================
// 45-1: 상세 '목록' 버튼 → 목록 상태 복귀
// ============================================================
describe("45-1 '목록' 버튼이 상세 URL 의 목록 상태를 목록으로 복귀", () => {
beforeEach(() => {
setupTestRegistry();
});
afterEach(() => {
window.history.replaceState({}, '', '/');
});
it('상세 URL 의 query 가 목록 경로로 그대로 복귀된다', async () => {
// 상세 화면 URL 에 목록 상태가 실려 있음
window.history.replaceState({}, '', '/board/free/77?category=공지&search=테스트&page=2');
const listButtonLayout = {
version: '1.0.0',
layout_name: 'board_list_button_test',
data_sources: [],
components: [
{
comment: '목록으로 버튼 (45-1)',
type: 'basic',
name: 'Button',
props: { 'data-testid': 'back-to-list' },
actions: [
{
type: 'click',
handler: 'navigate',
params: { path: '/board/free', mergeQuery: true, query: {} },
},
],
text: 'list',
},
],
};
const testUtils = createLayoutTest(listButtonLayout);
await testUtils.render();
await testUtils.triggerAction({
type: 'click',
handler: 'navigate',
params: { path: '/board/free', mergeQuery: true, query: {} },
} as any);
const dest = testUtils.getNavigationHistory()[0];
expect(dest.startsWith('/board/free?')).toBe(true);
expect(dest).toContain('category=%EA%B3%B5%EC%A7%80');
expect(dest).toContain('search=%ED%85%8C%EC%8A%A4%ED%8A%B8');
expect(dest).toContain('page=2');
testUtils.cleanup();
});
});
// ============================================================
// 47-4: 답글 상세 → 이전/다음 버튼 미렌더
// ============================================================
describe('47-4 답글 상세에서 이전/다음 버튼 미렌더', () => {
beforeEach(() => {
setupTestRegistry();
});
// _navigation.json 의 이전/다음 버튼 if 조건 구조를 그대로 재현
const navButtonsLayout = {
version: '1.0.0',
layout_name: 'board_nav_buttons_test',
data_sources: [
{
id: 'navigation',
type: 'api',
endpoint: '/api/modules/sirsoft-board/boards/free/posts/77/navigation',
method: 'GET',
auto_fetch: true,
},
],
components: [
{
type: 'basic',
name: 'Div',
children: [
{
comment: '이전글 버튼',
type: 'basic',
name: 'Button',
if: '{{navigation?.data?.prev?.id}}',
props: { 'data-testid': 'nav-prev' },
text: 'prev',
},
{
comment: '다음글 버튼',
type: 'basic',
name: 'Button',
if: '{{navigation?.data?.next?.id}}',
props: { 'data-testid': 'nav-next' },
text: 'next',
},
],
},
],
};
it('답글 상세(navigation prev/next null) → 이전/다음 버튼 모두 미렌더', async () => {
const testUtils = createLayoutTest(navButtonsLayout);
testUtils.mockApi('navigation', {
response: { data: { prev: null, next: null } },
});
await testUtils.render();
expect(screen.queryByTestId('nav-prev')).not.toBeInTheDocument();
expect(screen.queryByTestId('nav-next')).not.toBeInTheDocument();
testUtils.cleanup();
});
it('원글 상세(navigation prev/next 존재) → 이전/다음 버튼 렌더 (대조군)', async () => {
const testUtils = createLayoutTest(navButtonsLayout);
testUtils.mockApi('navigation', {
response: { data: { prev: { id: 76 }, next: { id: 78 } } },
});
await testUtils.render();
expect(screen.getByTestId('nav-prev')).toBeInTheDocument();
expect(screen.getByTestId('nav-next')).toBeInTheDocument();
testUtils.cleanup();
});
});
@@ -0,0 +1,107 @@
/**
* @file board-report-modal-feedback.test.tsx
* @description 신고 모달 - 제출 후 피드백/상태 반영 검증 (이슈 #413-60)
*
* 검수 결과(김은혜, 오류확정):
* - 증상2: 신고 성공 후 버튼이 "신고됨"으로 즉시 안 바뀜 (새로고침해야 전환)
* - 증상1: 신고 실패(409 등) 시 spinner만 잠깐, 모달 안 닫힘 + 에러 토스트 미노출 → "진행 불가"
*
* 근본 원인 / 수정:
* - 증상2: onSuccess 에 post 데이터소스 refetch 누락 → refetchDataSource(post) 추가
* - 증상1: onError 에 closeModal 누락 → "모달 닫고 토스트"(PO 결정) 로 보강
*
* 신고 모달은 게시글/댓글 공용 1파일이므로 이 단언이 양쪽을 모두 커버한다.
*/
import { describe, it, expect } from 'vitest';
import reportModal from '../../../layouts/partials/board/show/modals/_modal_report.json';
/**
* 신고 모달의 "신고하기" 제출 버튼 액션을 찾는다.
* 버튼 영역 → conditions 핸들러 → 검증 통과(then 배열) 안의 apiCall 을 반환.
*/
function findSubmitApiCall(layout: any): any {
const found: any[] = [];
function walk(node: any) {
if (!node || typeof node !== 'object') return;
if (Array.isArray(node)) {
node.forEach(walk);
return;
}
if (node.handler === 'apiCall') {
found.push(node);
}
for (const key of Object.keys(node)) {
walk(node[key]);
}
}
walk(layout);
// 신고 제출 apiCall: target 이 reportModal.apiEndpoint 인 것
return found.find(
(a) => typeof a.target === 'string' && a.target.includes('reportModal')
) ?? found[0] ?? null;
}
function asArray(x: any): any[] {
if (!x) return [];
return Array.isArray(x) ? x : [x];
}
describe('신고 모달 제출 피드백 (이슈 #413-60)', () => {
const apiCall = findSubmitApiCall(reportModal);
it('신고 제출 apiCall 액션을 찾을 수 있어야 한다', () => {
expect(apiCall).not.toBeNull();
expect(apiCall.handler).toBe('apiCall');
expect(apiCall.params?.method).toBe('POST');
});
describe('증상2 — onSuccess 에 post 데이터소스 refetch 가 포함되어야 한다', () => {
const onSuccess = asArray(apiCall?.onSuccess);
it('onSuccess 에 refetchDataSource 핸들러가 있어야 한다', () => {
const refetch = onSuccess.find((a) => a.handler === 'refetchDataSource');
expect(refetch).toBeDefined();
});
it('refetchDataSource 가 post 데이터소스를 대상으로 해야 한다 (params.dataSourceId)', () => {
const refetch = onSuccess.find((a) => a.handler === 'refetchDataSource');
expect(refetch?.params?.dataSourceId).toBe('post');
});
it('onSuccess 에 성공 토스트가 유지되어야 한다', () => {
const toast = onSuccess.find((a) => a.handler === 'toast');
expect(toast?.params?.type).toBe('success');
});
it('onSuccess 에 closeModal 이 유지되어야 한다', () => {
const close = onSuccess.find((a) => a.handler === 'closeModal');
expect(close).toBeDefined();
});
});
describe('증상1 — onError 에 모달 닫기 + 에러 토스트가 포함되어야 한다 (모달 닫고 토스트)', () => {
const onError = asArray(apiCall?.onError);
it('onError 에 reportSubmitting 리셋(setState)이 있어야 한다', () => {
const reset = onError.find(
(a) => a.handler === 'setState' && 'reportSubmitting' in (a.params ?? {})
);
expect(reset).toBeDefined();
expect(reset?.params?.reportSubmitting).toBe(false);
});
it('onError 에 에러 토스트가 있어야 한다', () => {
const toast = onError.find((a) => a.handler === 'toast');
expect(toast).toBeDefined();
expect(toast?.params?.type).toBe('error');
});
it('onError 에 closeModal 이 있어야 한다 (PO 결정: 실패 시 모달 닫고 토스트)', () => {
const close = onError.find((a) => a.handler === 'closeModal');
expect(close).toBeDefined();
});
});
});
@@ -159,9 +159,12 @@ describe('show.json - SEO meta 설정', () => {
expect(ogDesc).toContain('_seo');
});
it('structured_data.headline이 _seo 컨텍스트를 참조한다', () => {
const headline = seo.structured_data?.headline ?? '';
expect(headline).toContain('_seo');
// structured_data 는 show.json 정적 선언이 아니라 백엔드(module.php seoStructuredData)가
// 런타임에 게시글 데이터로 Article 스키마(headline=post.subject 등)를 동적 주입한다. og 는
// show.json 에 _seo 폴백을 정적 선언하지만 structured_data 는 주입 구조라 정적 키가 없는 게
// 정상이다. 편집기용 경로 메타(seoStructuredDataMeta)는 BoardModuleSeoTest 에서 검증한다.
it('structured_data 는 show.json 정적 선언 없음(백엔드 module.php 가 런타임 주입)', () => {
expect(seo.structured_data).toBeUndefined();
});
it('data_sources에 post가 정의된다', () => {
@@ -0,0 +1,78 @@
/**
* @file checkout-mileage-error-message.test.tsx
* @description 마일리지 적용 실패 토스트 메시지 바인딩 검증 (U15 후속)
*
* 배경: 보유 마일리지 초과 사용 시 백엔드는 422 + errors.{code,message}(구체 안내)를
* 내려보내는데, 프론트 onError 토스트가 상단 generic message(error.message)만 노출해
* "주문서 수정에 실패했습니다"만 보이던 결함. error.errors?.message 우선 fallback 으로 정정.
*/
import { describe, it, expect } from 'vitest';
import mileagePartial from '../../../layouts/partials/shop/_checkout_mileage.json';
/**
* JSON 트리에서 조건을 만족하는 첫 노드를 재귀 탐색한다.
*/
function findNode(obj: any, predicate: (node: any) => boolean): any | null {
if (!obj || typeof obj !== 'object') {
return null;
}
if (predicate(obj)) {
return obj;
}
for (const value of Object.values(obj)) {
if (Array.isArray(value)) {
for (const item of value) {
const found = findNode(item, predicate);
if (found) {
return found;
}
}
} else if (value && typeof value === 'object') {
const found = findNode(value, predicate);
if (found) {
return found;
}
}
}
return null;
}
describe('_checkout_mileage.json - 적용 실패 토스트 메시지 (U15)', () => {
// 마일리지 적용 apiCall(PUT /checkout) 노드
// (method 는 params.method, target 은 액션 top-level)
const applyAction = findNode(
mileagePartial,
(n) =>
n.handler === 'apiCall' &&
n.params?.method === 'PUT' &&
typeof n.target === 'string' &&
n.target.includes('/checkout')
);
it('마일리지 적용 apiCall(PUT /checkout)이 존재한다', () => {
expect(applyAction, '마일리지 적용 apiCall 이 없다').toBeTruthy();
});
it('onError 토스트가 error.errors?.message 를 우선 사용한다', () => {
const onError = applyAction.onError ?? [];
const toast = (Array.isArray(onError) ? onError : [onError]).find(
(a: any) => a.handler === 'toast'
);
expect(toast, 'onError 토스트가 없다').toBeTruthy();
// 구체 안내(errors.message) 우선, 없으면 상단 generic(message) fallback
expect(toast.params.message).toContain('error.errors?.message');
expect(toast.params.message).toContain('error.message');
});
it('onError 토스트가 generic message 만 단독 참조하지 않는다 (회귀 가드)', () => {
const onError = applyAction.onError ?? [];
const toast = (Array.isArray(onError) ? onError : [onError]).find(
(a: any) => a.handler === 'toast'
);
// "{{error.message}}" 단독이면 구체 안내가 묻힘 → 금지
expect(toast.params.message).not.toBe('{{error.message}}');
});
});
@@ -0,0 +1,297 @@
/**
* @file order-cancelled-earned-points-hidden.test.tsx
* @description U19③ — 취소 주문의 "적립 예정" 마일리지 숨김 회귀 렌더 테스트 (유저 화면 3종)
*
* 결함: total_earned_points_amount 는 취소 후에도 주문시점 스냅샷으로 양수가 보존된다
* (실 적립은 스케줄러가 option_status 기준으로 차단). 레이아웃이 `> 0` 만 검사하면
* 취소 주문에도 "적립 예정 +NNN P" 가 계속 노출된다.
*
* 정정: 노출 블록 if 에 취소/부분취소 제외 가드를 결합한다(값 보존, 표시만 숨김).
* order.data: `... > 0 && order.data.order_status !== 'cancelled' && !order.data.is_partially_cancelled`
* 목록 iteration order.*: 동일 논리 (order.* 경로)
*
* 본 테스트는 각 실제 레이아웃에서 적립예정 블록의 if 식을 추출해 그대로 렌더한다.
* 가드가 없으면 취소 데이터에서 RED, 가드가 있으면 GREEN.
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
createLayoutTest,
screen,
waitFor,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
import paymentJson from '../../../layouts/partials/mypage/orders/_payment.json';
import listJson from '../../../layouts/partials/mypage/orders/_list.json';
import orderCompleteJson from '../../../layouts/shop/order_complete.json';
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestP: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
<p className={className} data-testid={testId}>{children || text}</p>
);
const TestFragment: React.FC<any> = ({ children }) => <>{children}</>;
function findNode(node: any, predicate: (n: any) => boolean): any {
if (node == null || typeof node !== 'object') return null;
if (predicate(node)) return node;
for (const value of Object.values(node)) {
if (Array.isArray(value)) {
for (const item of value) {
const hit = findNode(item, predicate);
if (hit) return hit;
}
} else if (value && typeof value === 'object') {
const hit = findNode(value, predicate);
if (hit) return hit;
}
}
return null;
}
/** 트리에서 total_earned_points_amount 노출 블록의 if 식 추출 */
function getEarnedIf(tree: any): string {
const node = findNode(
tree,
(n) => typeof n.if === 'string' && n.if.includes('total_earned_points_amount'),
);
if (!node) throw new Error('적립예정 블록 if 식을 찾지 못함');
return node.if as string;
}
function registerComponents() {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
}
// order.data.* 컨텍스트 (주문상세 결제정보) 프로브
function buildDetailProbe(earnedIf: string) {
return {
version: '1.0.0',
layout_name: 'test/earned-detail',
data_sources: [
{ id: 'order', type: 'api', endpoint: '/api/test/order', method: 'GET', auto_fetch: true },
],
components: [
{
type: 'basic',
name: 'Div',
if: earnedIf,
props: { 'data-testid': 'earned-block' },
children: [
{
type: 'basic',
name: 'Span',
props: { 'data-testid': 'earned-text' },
text: '+{{order.data.total_earned_points_amount_formatted ?? ""}}',
},
],
},
],
};
}
// 목록 iteration order.* 컨텍스트 프로브
function buildListProbe(earnedIf: string) {
return {
version: '1.0.0',
layout_name: 'test/earned-list',
data_sources: [
{ id: 'orders', type: 'api', endpoint: '/api/test/orders', method: 'GET', auto_fetch: true },
],
components: [
{
type: 'basic',
name: 'Div',
iteration: { source: '{{orders.data ?? []}}', item_var: 'order' },
children: [
{
type: 'basic',
name: 'P',
if: earnedIf,
props: { 'data-testid': 'earned-text' },
text: '+{{order.total_earned_points_amount_formatted ?? ""}}',
},
],
},
],
};
}
const normalDetail = {
data: {
total_earned_points_amount: 840,
total_earned_points_amount_formatted: '840원',
order_status: 'confirmed',
is_partially_cancelled: false,
},
};
const cancelledDetail = {
data: {
total_earned_points_amount: 840,
total_earned_points_amount_formatted: '840원',
order_status: 'cancelled',
is_partially_cancelled: false,
},
};
const partialCancelledDetail = {
data: {
total_earned_points_amount: 840,
total_earned_points_amount_formatted: '840원',
order_status: 'confirmed',
is_partially_cancelled: true,
},
};
describe('U19③-a 유저 주문상세 결제정보 적립예정 가드 (_payment.json)', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(registerComponents);
afterEach(() => { if (testUtils) testUtils.cleanup(); vi.clearAllMocks(); });
it('정상 주문은 적립예정이 노출된다', async () => {
testUtils = createLayoutTest(buildDetailProbe(getEarnedIf(paymentJson)));
testUtils.mockApi('order', { response: normalDetail });
await testUtils.render();
await waitFor(() => expect(screen.getByTestId('earned-text')).toHaveTextContent('840원'));
});
it('전체취소 주문은 적립예정이 미노출된다', async () => {
testUtils = createLayoutTest(buildDetailProbe(getEarnedIf(paymentJson)));
testUtils.mockApi('order', { response: cancelledDetail });
await testUtils.render();
await new Promise((r) => setTimeout(r, 50));
expect(screen.queryByTestId('earned-block')).not.toBeInTheDocument();
});
it('부분취소 주문은 적립예정이 미노출된다', async () => {
testUtils = createLayoutTest(buildDetailProbe(getEarnedIf(paymentJson)));
testUtils.mockApi('order', { response: partialCancelledDetail });
await testUtils.render();
await new Promise((r) => setTimeout(r, 50));
expect(screen.queryByTestId('earned-block')).not.toBeInTheDocument();
});
});
describe('U19③-b 유저 주문목록 카드 적립예정 가드 (_list.json)', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(registerComponents);
afterEach(() => { if (testUtils) testUtils.cleanup(); vi.clearAllMocks(); });
// 유저 주문목록은 UserOrderListResource 가 order_status 가 아닌 `status` 키로 노출한다.
const listRow = (status: string, partial: boolean) => ({
total_earned_points_amount: 840,
total_earned_points_amount_formatted: '840원',
status,
is_partially_cancelled: partial,
});
// 회귀 가드(라이브 검수에서 발견): _list.json 의 취소 가드는 UserOrderListResource 가
// 노출하는 실제 필드명 `order.status` 를 써야 한다. `order.order_status`(존재하지 않는 키)를
// 쓰면 항상 undefined 라 전체취소가 숨겨지지 않는다.
it('_list.json 적립예정 가드는 order.order_status 가 아닌 order.status 를 검사한다', () => {
const earnedIf = getEarnedIf(listJson);
expect(earnedIf).toContain("order.status !== 'cancelled'");
expect(earnedIf).not.toContain('order.order_status');
});
it('정상 주문 카드는 적립예정이 노출된다', async () => {
testUtils = createLayoutTest(buildListProbe(getEarnedIf(listJson)));
testUtils.mockApi('orders', { response: { data: [listRow('confirmed', false)] } });
await testUtils.render();
await waitFor(() => expect(screen.getByTestId('earned-text')).toHaveTextContent('840원'));
});
it('전체취소 주문 카드는 적립예정이 미노출된다', async () => {
testUtils = createLayoutTest(buildListProbe(getEarnedIf(listJson)));
testUtils.mockApi('orders', { response: { data: [listRow('cancelled', false)] } });
await testUtils.render();
await new Promise((r) => setTimeout(r, 50));
expect(screen.queryByTestId('earned-text')).not.toBeInTheDocument();
});
it('부분취소 주문 카드는 적립예정이 미노출된다', async () => {
testUtils = createLayoutTest(buildListProbe(getEarnedIf(listJson)));
testUtils.mockApi('orders', { response: { data: [listRow('confirmed', true)] } });
await testUtils.render();
await new Promise((r) => setTimeout(r, 50));
expect(screen.queryByTestId('earned-text')).not.toBeInTheDocument();
});
});
describe('U19③-e 주문완료 화면 적립예정 가드 (order_complete.json)', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(registerComponents);
afterEach(() => { if (testUtils) testUtils.cleanup(); vi.clearAllMocks(); });
// order_complete 는 orderData?.data.* 컨텍스트 — 별도 프로브
function buildOrderCompleteProbe(earnedIf: string) {
return {
version: '1.0.0',
layout_name: 'test/earned-complete',
data_sources: [
{ id: 'orderData', type: 'api', endpoint: '/api/test/order', method: 'GET', auto_fetch: true },
],
components: [
{
type: 'basic',
name: 'Div',
if: earnedIf,
props: { 'data-testid': 'earned-block' },
children: [
{
type: 'basic',
name: 'Span',
props: { 'data-testid': 'earned-text' },
text: '+{{orderData?.data?.total_earned_points_amount_formatted ?? ""}}',
},
],
},
],
};
}
it('정상 결제완료는 적립예정이 노출된다 (회귀 없음)', async () => {
testUtils = createLayoutTest(buildOrderCompleteProbe(getEarnedIf(orderCompleteJson)));
testUtils.mockApi('orderData', {
response: {
data: {
total_earned_points_amount: 840,
total_earned_points_amount_formatted: '840원',
order_status: 'paid',
is_partially_cancelled: false,
},
},
});
await testUtils.render();
await waitFor(() => expect(screen.getByTestId('earned-text')).toHaveTextContent('840원'));
});
it('전체취소 상태로 진입해도 적립예정이 미노출된다 (일관성)', async () => {
testUtils = createLayoutTest(buildOrderCompleteProbe(getEarnedIf(orderCompleteJson)));
testUtils.mockApi('orderData', {
response: {
data: {
total_earned_points_amount: 840,
total_earned_points_amount_formatted: '840원',
order_status: 'cancelled',
is_partially_cancelled: false,
},
},
});
await testUtils.render();
await new Promise((r) => setTimeout(r, 50));
expect(screen.queryByTestId('earned-block')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,209 @@
/**
* @file order-item-subtotal-display.test.tsx
* @description U19② — 무할인 주문 항목의 KRW 소계 표시 회귀 렌더 테스트
*
* 결함: OrderOption.subtotal_discount_amount 는 모델 decimal:2 캐스트로 JSON 에
* 문자열("0.00")로 직렬화된다. _items.json 의 무할인 분기 `if` 가 strict 비교
* (`=== 0`)를 쓰면 "0.00" === 0 → false 가 되어, 무할인 항목 소계가 할인/무할인
* 양 분기 모두에서 미렌더되어 화면에서 사라진다.
*
* 정정: OrderOptionResource 가 비교용 숫자 보조 필드 subtotal_discount_amount_value(float)
* 를 노출하고, _items.json 의 비교가 이 숫자 필드를 사용하도록 정정한다.
*
* 본 테스트는 _items.json 실제 파일에서 무할인/할인 분기의 `if` 식을 추출해 그대로
* 렌더(템플릿 엔진 ConditionEvaluator 실 평가)하므로, 비교 기준이 문자열 컬럼이면
* RED, 숫자 보조 필드면 GREEN 이 된다.
*
* @vitest-environment jsdom
*/
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
createLayoutTest,
screen,
waitFor,
} from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
import itemsJson from '../../../layouts/partials/mypage/orders/_items.json';
// ---- 테스트 컴포넌트 ----
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>{children}</div>
);
const TestSpan: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>{children || text}</span>
);
const TestFragment: React.FC<any> = ({ children }) => <>{children}</>;
/** 객체 트리에서 술어를 만족하는 첫 노드를 깊이우선 탐색 */
function findNode(node: any, predicate: (n: any) => boolean): any {
if (node == null || typeof node !== 'object') return null;
if (predicate(node)) return node;
for (const value of Object.values(node)) {
if (Array.isArray(value)) {
for (const item of value) {
const hit = findNode(item, predicate);
if (hit) return hit;
}
} else if (value && typeof value === 'object') {
const hit = findNode(value, predicate);
if (hit) return hit;
}
}
return null;
}
/** _items.json 에서 무할인 소계 분기의 실제 if 식을 추출 (line-through 없는 단일 Span) */
function getNoDiscountSubtotalIf(): string {
const node = findNode(
itemsJson,
(n) =>
typeof n.if === 'string' &&
n.if.includes('subtotal_discount_amount') &&
n.if.includes('=== 0') &&
n.name === 'Span'
);
if (!node) throw new Error('무할인 소계 분기 if 식을 _items.json 에서 찾지 못함');
return node.if as string;
}
/** _items.json 에서 할인 소계 분기(`> 0`)의 실제 if 식을 추출 */
function getDiscountSubtotalIf(): string {
const node = findNode(
itemsJson,
(n) =>
typeof n.if === 'string' &&
n.if.includes('subtotal_discount_amount') &&
n.if.includes('> 0') &&
n.name === 'Div'
);
if (!node) throw new Error('할인 소계 분기 if 식을 _items.json 에서 찾지 못함');
return node.if as string;
}
// 백엔드 직렬화 재현: decimal:2 컬럼은 문자열, _value 보조 필드는 숫자
const noDiscountItem = {
id: 1,
product_name: '무할인 상품',
subtotal_discount_amount: '0.00', // decimal:2 → 문자열
subtotal_discount_amount_value: 0, // (float) 보조 필드
subtotal_price_formatted: '30,000원',
mc_subtotal_price: { KRW: { formatted: '30,000원' } },
mc_final_amount: { KRW: { formatted: '30,000원' } },
};
const discountItem = {
id: 2,
product_name: '할인 상품',
subtotal_discount_amount: '3000.00',
subtotal_discount_amount_value: 3000,
subtotal_price_formatted: '30,000원',
mc_subtotal_price: { KRW: { formatted: '30,000원' } },
mc_final_amount: { KRW: { formatted: '27,000원' } },
};
function buildProbeLayout(item: any, noDiscountIf: string, discountIf: string) {
return {
version: '1.0.0',
layout_name: 'test/order-item-subtotal',
data_sources: [
{ id: 'order', type: 'api', endpoint: '/api/test/order', method: 'GET', auto_fetch: true },
],
components: [
{
type: 'basic',
name: 'Div',
iteration: { source: '{{order.data.options ?? []}}', item_var: 'item' },
children: [
// 할인 분기 (line-through + final)
{
type: 'basic',
name: 'Div',
if: discountIf,
props: { 'data-testid': 'discount-block' },
children: [
{
type: 'basic',
name: 'Span',
props: { 'data-testid': 'discount-subtotal' },
text: '{{item.mc_final_amount?.KRW?.formatted ?? ""}}',
},
],
},
// 무할인 분기 (단일 소계 Span)
{
type: 'basic',
name: 'Span',
if: noDiscountIf,
props: { 'data-testid': 'no-discount-subtotal' },
text: '{{item.mc_subtotal_price?.KRW?.formatted ?? item.subtotal_price_formatted ?? ""}}',
},
],
},
],
};
}
describe('U19② 무할인 주문 항목 소계 표시 (_items.json if 식 실 평가)', () => {
let testUtils: ReturnType<typeof createLayoutTest>;
beforeEach(() => {
const registry = ComponentRegistry.getInstance();
(registry as any).registry = {
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } },
};
});
afterEach(() => {
if (testUtils) testUtils.cleanup();
vi.clearAllMocks();
});
it('무할인 항목의 소계 Span 이 렌더된다 (decimal 문자열 strict 비교 회귀 차단)', async () => {
const layout = buildProbeLayout(noDiscountItem, getNoDiscountSubtotalIf(), getDiscountSubtotalIf());
testUtils = createLayoutTest(layout);
testUtils.mockApi('order', { response: { data: { options: [noDiscountItem] } } });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('no-discount-subtotal')).toBeInTheDocument();
expect(screen.getByTestId('no-discount-subtotal')).toHaveTextContent('30,000원');
});
// 무할인이므로 할인 분기는 미렌더
expect(screen.queryByTestId('discount-block')).not.toBeInTheDocument();
});
it('할인 항목은 할인 분기가 렌더되고 무할인 분기는 미렌더된다 (회귀 없음)', async () => {
const layout = buildProbeLayout(discountItem, getNoDiscountSubtotalIf(), getDiscountSubtotalIf());
testUtils = createLayoutTest(layout);
testUtils.mockApi('order', { response: { data: { options: [discountItem] } } });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('discount-subtotal')).toBeInTheDocument();
expect(screen.getByTestId('discount-subtotal')).toHaveTextContent('27,000원');
});
expect(screen.queryByTestId('no-discount-subtotal')).not.toBeInTheDocument();
});
it('비회원 주문상세도 동일 partial 공유로 무할인 소계가 렌더된다 (GuestOrderResource shape)', async () => {
// GuestOrderResource 는 OrderOptionResource::collection 을 그대로 노출하므로
// subtotal_discount_amount_value 보조 필드를 회원과 동일하게 가진다.
const guestNoDiscountItem = { ...noDiscountItem, id: 99 };
const layout = buildProbeLayout(
guestNoDiscountItem,
getNoDiscountSubtotalIf(),
getDiscountSubtotalIf(),
);
testUtils = createLayoutTest(layout);
testUtils.mockApi('order', { response: { data: { options: [guestNoDiscountItem] } } });
await testUtils.render();
await waitFor(() => {
expect(screen.getByTestId('no-discount-subtotal')).toHaveTextContent('30,000원');
});
});
});
@@ -0,0 +1,80 @@
/**
* @file shop-buy-now-direct-checkout.test.tsx
* @description 상품 상세 "바로 구매" 장바구니 미경유 검증 (직접 항목 체크아웃)
*
* 배경: "바로 구매"가 먼저 POST /cart 로 장바구니에 담은 뒤 체크아웃해, 장바구니 기존
* 동일 상품 수량과 합산되어 한도 초과 차단되거나 장바구니가 오염되던 결함.
* direct_items 로 장바구니를 경유하지 않고 바로 체크아웃하도록 변경.
*/
import { describe, it, expect } from 'vitest';
import purchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
/**
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
*/
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
if (!obj || typeof obj !== 'object') {
return acc;
}
if (predicate(obj)) {
acc.push(obj);
}
for (const value of Object.values(obj)) {
if (Array.isArray(value)) {
value.forEach((item) => collectNodes(item, predicate, acc));
} else if (value && typeof value === 'object') {
collectNodes(value, predicate, acc);
}
}
return acc;
}
describe('_purchase_card.json - 바로 구매 장바구니 미경유', () => {
// "바로 구매" 버튼 노드 (text = $t:shop.product.buy_now 자식 Span 보유) 의 액션 서브트리만 검사
const buyNowButton = collectNodes(
purchaseCard,
(n) =>
n.name === 'Button' &&
Array.isArray(n.actions) &&
JSON.stringify(n.children ?? []).includes('shop.product.buy_now')
)[0];
const buyNowApiCalls = buyNowButton
? collectNodes(buyNowButton.actions, (n) => n.handler === 'apiCall')
: [];
it('바로 구매 버튼이 존재한다', () => {
expect(buyNowButton, '바로 구매 버튼을 찾지 못함').toBeTruthy();
});
it('바로 구매 흐름이 체크아웃을 호출한다', () => {
const hasCheckout = buyNowApiCalls.some(
(n) => typeof n.target === 'string' && n.target.includes('/checkout')
);
expect(hasCheckout).toBe(true);
});
it('바로 구매 흐름이 장바구니 담기(POST /cart)를 거치지 않는다 (회귀 가드)', () => {
const cartPosts = buyNowApiCalls.filter(
(n) =>
typeof n.target === 'string' &&
/\/cart($|[^a-z])/.test(n.target) &&
n.params?.method === 'POST'
);
expect(cartPosts.length).toBe(0);
});
it('바로 구매 체크아웃 body 가 direct_items 를 전달한다', () => {
const usesDirectItems = buyNowApiCalls.some((n) => {
const body = n.params?.body;
return (
typeof n.target === 'string' &&
n.target.includes('/checkout') &&
typeof body === 'string' &&
body.includes('direct_items')
);
});
expect(usesDirectItems).toBe(true);
});
});
@@ -0,0 +1,72 @@
/**
* @file shop-cart-unavailable-message.test.tsx
* @description 상품 상세 담기/바로구매 실패 토스트 메시지 바인딩 검증 (U13②/U4/A25 후속)
*
* 배경: 판매중지·구매수량 한도 초과 담기 시 백엔드는 422 + errors.message(구체 안내)를
* 내려보내는데, 상품 상세의 담기/바로구매 onError 토스트가 상단 generic message 만 노출해
* "구매할 수 없는 상품이 있습니다"만 보이던 결함. error.errors?.message 우선 fallback 으로 정정.
*/
import { describe, it, expect } from 'vitest';
import detailPurchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
import optionPurchaseCard from '../../../layouts/partials/shop/_product_purchase_card.json';
/**
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
*/
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
if (!obj || typeof obj !== 'object') {
return acc;
}
if (predicate(obj)) {
acc.push(obj);
}
for (const value of Object.values(obj)) {
if (Array.isArray(value)) {
value.forEach((item) => collectNodes(item, predicate, acc));
} else if (value && typeof value === 'object') {
collectNodes(value, predicate, acc);
}
}
return acc;
}
/**
* 레이아웃의 모든 error 토스트(handler=toast, type=error, message 가 error 바인딩) 수집.
*/
function errorToasts(layout: any): any[] {
return collectNodes(
layout,
(n) =>
n.handler === 'toast' &&
n.params?.type === 'error' &&
typeof n.params?.message === 'string' &&
n.params.message.includes('error')
);
}
describe('상품 상세 담기/바로구매 실패 토스트 (U13②/U4/A25)', () => {
const detailToasts = errorToasts(detailPurchaseCard);
const optionToasts = errorToasts(optionPurchaseCard);
it('상세 구매 카드에 error 토스트가 존재한다', () => {
expect(detailToasts.length).toBeGreaterThan(0);
});
it('옵션 상품 카드에 error 토스트가 존재한다', () => {
expect(optionToasts.length).toBeGreaterThan(0);
});
it('모든 error 토스트가 error.errors?.message 를 우선 사용한다 (구체 안내)', () => {
[...detailToasts, ...optionToasts].forEach((toast) => {
expect(toast.params.message).toContain('error.errors?.message');
expect(toast.params.message).toContain('error.message');
});
});
it('error 토스트가 generic message 만 단독 참조하지 않는다 (회귀 가드)', () => {
[...detailToasts, ...optionToasts].forEach((toast) => {
expect(toast.params.message).not.toBe('{{error.message}}');
});
});
});
@@ -0,0 +1,57 @@
/**
* @file shop-cart-unavailable-modal.test.tsx
* @description 장바구니 구매불가 모달 reason별 사유 표시 검증 (U13②/U4/A25 후속)
*
* 배경: 모달이 stock/status reason 만 사유 줄을 그려, A25 로 도입한 max_qty/min_qty 와
* 구매대상제한(restricted) 항목은 상품명만 보이고 "왜 구매 불가인지"가 누락되던 결함.
* 모든 reason 에 대응 표시 분기를 추가.
*/
import { describe, it, expect } from 'vitest';
import modal from '../../../layouts/partials/shop/_modal_cart_unavailable.json';
/**
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
*/
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
if (!obj || typeof obj !== 'object') {
return acc;
}
if (predicate(obj)) {
acc.push(obj);
}
for (const value of Object.values(obj)) {
if (Array.isArray(value)) {
value.forEach((item) => collectNodes(item, predicate, acc));
} else if (value && typeof value === 'object') {
collectNodes(value, predicate, acc);
}
}
return acc;
}
describe('_modal_cart_unavailable.json - reason별 사유 표시 (A25)', () => {
// if 조건이 unavailableItem.reason 을 분기하는 노드들
const reasonNodes = collectNodes(
modal,
(n) => typeof n.if === 'string' && n.if.includes('unavailableItem.reason')
);
const ifConditions = reasonNodes.map((n) => n.if as string).join(' || ');
it.each([['stock'], ['status'], ['max_qty'], ['min_qty'], ['restricted']])(
"reason '%s' 에 대한 표시 분기가 존재한다",
(reason) => {
expect(ifConditions).toContain(`'${reason}'`);
}
);
it('max_qty/min_qty 표시는 limit/requested 를 치환한다', () => {
const maxNode = reasonNodes.find((n) => (n.if as string).includes("'max_qty'"));
const minNode = reasonNodes.find((n) => (n.if as string).includes("'min_qty'"));
expect(maxNode?.text).toContain('limit=');
expect(maxNode?.text).toContain('requested=');
expect(minNode?.text).toContain('limit=');
});
});
@@ -0,0 +1,114 @@
/**
* @file shop-purchase-quantity-limit.test.tsx
* @description 옵션 상품 구매수량 한도 UI 바인딩 검증 (A25 / MP05)
*
* 검증 항목:
* 1. 옵션 라인 QuantitySelector max 가 상품 max_purchase_qty 로 clamp 된다
* (max>0 시 Math.min(item.stock, max_purchase_qty), max=0 시 item.stock).
* 2. 구매/장바구니 버튼 disabled 가 선택 합계 min 미달 / max 초과 시 비활성화된다.
* 3. 한도 위반 안내 Span(min/max notice)이 존재한다.
*/
import { describe, it, expect } from 'vitest';
import purchaseCard from '../../../layouts/partials/shop/_product_purchase_card.json';
/**
* JSON 트리에서 조건을 만족하는 첫 노드를 재귀 탐색한다.
*/
function findNode(obj: any, predicate: (node: any) => boolean): any | null {
if (!obj || typeof obj !== 'object') {
return null;
}
if (predicate(obj)) {
return obj;
}
for (const value of Object.values(obj)) {
if (Array.isArray(value)) {
for (const item of value) {
const found = findNode(item, predicate);
if (found) {
return found;
}
}
} else if (value && typeof value === 'object') {
const found = findNode(value, predicate);
if (found) {
return found;
}
}
}
return null;
}
/**
* JSON 트리에서 조건을 만족하는 모든 노드를 수집한다.
*/
function collectNodes(obj: any, predicate: (node: any) => boolean, acc: any[] = []): any[] {
if (!obj || typeof obj !== 'object') {
return acc;
}
if (predicate(obj)) {
acc.push(obj);
}
for (const value of Object.values(obj)) {
if (Array.isArray(value)) {
value.forEach((item) => collectNodes(item, predicate, acc));
} else if (value && typeof value === 'object') {
collectNodes(value, predicate, acc);
}
}
return acc;
}
describe('_product_purchase_card.json - 옵션 라인 max clamp (A25)', () => {
it('QuantitySelector 의 max 가 상품 max_purchase_qty 로 clamp 된다', () => {
const selector = findNode(
purchaseCard,
(n) => n.name === 'QuantitySelector'
);
expect(selector, 'QuantitySelector 노드가 없다').toBeTruthy();
const max = selector.props?.max ?? '';
// max>0 시 Math.min(item.stock, max_purchase_qty), max=0 시 item.stock
expect(max).toContain('max_purchase_qty');
expect(max).toContain('Math.min(item.stock');
expect(max).toContain('item.stock');
});
});
describe('_product_purchase_card.json - 합계 버튼 한도 차단 (A25)', () => {
const buttons = collectNodes(
purchaseCard,
(n) => n.name === 'Button' && typeof n.props?.disabled === 'string'
);
it('구매/장바구니 버튼이 2개 이상 존재한다', () => {
expect(buttons.length).toBeGreaterThanOrEqual(2);
});
it('모든 구매 버튼 disabled 가 min 미달 / max 초과 합계 검증을 포함한다', () => {
buttons.forEach((btn) => {
const disabled = btn.props.disabled as string;
expect(disabled).toContain('min_purchase_qty');
expect(disabled).toContain('max_purchase_qty');
expect(disabled).toContain('reduce');
});
});
});
describe('_product_purchase_card.json - 한도 위반 안내 문구 (A25)', () => {
it('min/max 구매수량 안내 Span 이 존재한다', () => {
const minNotice = findNode(
purchaseCard,
(n) => typeof n.text === 'string' && n.text.includes('min_purchase_qty_notice')
);
const maxNotice = findNode(
purchaseCard,
(n) => typeof n.text === 'string' && n.text.includes('max_purchase_qty_notice')
);
expect(minNotice, 'min_purchase_qty_notice 안내가 없다').toBeTruthy();
expect(maxNotice, 'max_purchase_qty_notice 안내가 없다').toBeTruthy();
});
});
@@ -0,0 +1,145 @@
/**
* shop-soldout-computed.test.ts — 상품상세 옵션 품절 표시 (computed 인라인 방식)
*
* MP07 §2: 재고 없는 옵션을 옵션 드롭다운에서 "(품절)" 비활성으로 표시한다. $call 헬퍼
* 없이, show.json 의 `computed.optionChoices`(순수 인라인 배열식)가 백엔드 is_sold_out
* 플래그(ProductOptionResource)를 읽어 그룹별 선택지를 만들고, _purchase_card.json 의
* 옵션 select 가 `$computed.optionChoices?.[groupIndex]` 로 참조한다.
*
* 본 테스트는 (1) show.json 의 computed 표현식 정본을 실제 DataBindingEngine 으로 평가해
* 품절 판정(보수적: 호환 조합 전부 품절일 때만 disabled)이 맞는지, (2) _purchase_card.json
* 의 select options 표현식이 $computed.optionChoices 를 참조해 그 결과를 펼치는지 — 를
* 실제 표현식으로 검증한다(레이아웃 JSON 정본과 동일 문자열 사용 — 회귀 가드).
*
* @vitest-environment jsdom
*/
import { describe, it, expect, beforeEach } from 'vitest';
import { DataBindingEngine } from '@/core/template-engine/DataBindingEngine';
import showLayout from '../../../layouts/shop/show.json';
import purchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
// 레이아웃 정본에서 표현식을 직접 추출 — 정본이 바뀌면 테스트도 따라가 회귀를 잡는다.
const COMPUTED_EXPR: string = (showLayout as any).computed.optionChoices.replace(/^\{\{|\}\}$/g, '');
// _purchase_card.json 의 옵션 select options 표현식 (iteration 안의 Select)
function findOptionsExpr(node: any): string | null {
if (node && typeof node === 'object') {
if (node.name === 'Select' && node.props?.options) return node.props.options;
for (const k of Object.keys(node)) {
const v = (node as any)[k];
if (Array.isArray(v)) {
for (const c of v) {
const r = findOptionsExpr(c);
if (r) return r;
}
} else if (v && typeof v === 'object') {
const r = findOptionsExpr(v);
if (r) return r;
}
}
}
return null;
}
const OPTIONS_EXPR: string = (findOptionsExpr(purchaseCard) ?? '').replace(/^\{\{|\}\}$/g, '');
const colorGroup = { name_localized: '색상', values_localized: ['빨강', '파랑'] };
const sizeGroup = { name_localized: '사이즈', values_localized: ['S', 'L'] };
function opt(localized: Record<string, string>, soldOut: boolean): any {
return {
option_values_localized: localized,
stock_quantity: soldOut ? 0 : 10,
is_active: true,
is_sold_out: soldOut,
};
}
describe('상품상세 옵션 품절 표시 — computed 인라인 방식', () => {
let engine: DataBindingEngine;
beforeEach(() => {
engine = new DataBindingEngine();
});
function evalComputed(option_groups: any[], options: any[], currentSelection: Record<string, string> = {}) {
return engine.evaluateExpression(COMPUTED_EXPR, {
product: { data: { option_groups, options } },
_local: { currentSelection },
} as any) as any[];
}
it('show.json computed: 단일 그룹 — 재고0 옵션 값이 disabled + "(품절)" 라벨', () => {
const choices = evalComputed([colorGroup], [
opt({ 색상: '빨강' }, false),
opt({ 색상: '파랑' }, true),
]);
// choices[0] = 색상 그룹 선택지
const red = choices[0].find((c: any) => c.value === '빨강');
const blue = choices[0].find((c: any) => c.value === '파랑');
expect(red.disabled).toBe(false);
expect(blue.disabled).toBe(true);
// 품절 값은 라벨에 접미가 붙는다(원본 값보다 길다). 테스트 환경엔 $t 사전이 없어
// sold_out_suffix 키가 그대로 반환되므로 "품절" 문자열 자체가 아니라 접미 부착을 검증한다.
expect(blue.label).not.toBe('파랑');
expect(blue.label.startsWith('파랑 ')).toBe(true);
expect(red.label).toBe('빨강'); // 정상 값은 접미 없음
});
it('show.json computed: 다중 그룹 보수적 판정 — 일부만 품절이면 선택 가능, 전부 품절이면 비활성', () => {
// 빨강-S(품절) 빨강-L(정상) 파랑-S(품절) 파랑-L(품절)
const options = [
opt({ 색상: '빨강', 사이즈: 'S' }, true),
opt({ 색상: '빨강', 사이즈: 'L' }, false),
opt({ 색상: '파랑', 사이즈: 'S' }, true),
opt({ 색상: '파랑', 사이즈: 'L' }, true),
];
const choices = evalComputed([colorGroup, sizeGroup], options);
const colorChoices = choices[0];
expect(colorChoices.find((c: any) => c.value === '빨강').disabled).toBe(false); // 빨강-L 정상
expect(colorChoices.find((c: any) => c.value === '파랑').disabled).toBe(true); // 파랑 전부 품절
});
it('show.json computed: 하위 그룹 — 상위 선택(빨강) 호환 조합 기준 S 품절/L 정상', () => {
const options = [
opt({ 색상: '빨강', 사이즈: 'S' }, true),
opt({ 색상: '빨강', 사이즈: 'L' }, false),
opt({ 색상: '파랑', 사이즈: 'S' }, false),
opt({ 색상: '파랑', 사이즈: 'L' }, false),
];
const choices = evalComputed([colorGroup, sizeGroup], options, { 색상: '빨강' });
const sizeChoices = choices[1];
expect(sizeChoices.find((c: any) => c.value === 'S').disabled).toBe(true);
expect(sizeChoices.find((c: any) => c.value === 'L').disabled).toBe(false);
});
it('_purchase_card.json select options: $computed.optionChoices 를 참조해 품절 결과를 펼친다', () => {
// computed 결과를 미리 만들어 $computed 로 주입
const optionChoices = evalComputed([colorGroup], [
opt({ 색상: '빨강' }, false),
opt({ 색상: '파랑' }, true),
]);
const result = engine.evaluateExpression(OPTIONS_EXPR, {
group: colorGroup,
groupIndex: 0,
product: { data: { option_groups: [colorGroup] } },
_local: { currentSelection: {} },
_computed: { optionChoices },
} as any) as any[];
// [0]=placeholder, 이후 색상 선택지(품절 반영)
expect(result[0].value).toBe('');
expect(result.find((c) => c.value === '파랑')?.disabled).toBe(true);
expect(result.find((c) => c.value === '빨강')?.disabled).toBe(false);
});
it('_purchase_card.json select options: computed 부재 시 평문 폴백(품절 표시 없이 깨지지 않음)', () => {
const result = engine.evaluateExpression(OPTIONS_EXPR, {
group: colorGroup,
groupIndex: 0,
product: { data: { option_groups: [colorGroup] } },
_local: { currentSelection: {} },
_computed: {},
} as any) as any[];
expect(result.find((c) => c.value === '빨강')).toBeDefined();
expect(result.find((c) => c.value === '빨강')?.disabled).toBeUndefined();
});
});
@@ -0,0 +1,254 @@
/**
* @file shopAdditionalOptions.test.tsx
* @description 상품 추가옵션(유료 옵션) 유저 흐름 레이아웃 검증
*
* 1. 렌더링: 추가옵션 그룹별 선택지 표시(추가금 라벨) — 최소 레이아웃 실제 렌더
* 2. 구조: 실제 partial(_purchase_card / _cart_item / _modal_cart_option_change /
* 표시 4화면)이 추가옵션 바인딩·핸들러·필수 가드를 포함하는지 검증
*/
import React from 'react';
import { describe, it, expect, beforeEach } from 'vitest';
import { createLayoutTest, screen } from '@/core/template-engine/__tests__/utils/layoutTestUtils';
import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry';
import purchaseCard from '../../../layouts/partials/shop/detail/_purchase_card.json';
import cartItem from '../../../layouts/partials/shop/_cart_item.json';
import modalOptionChange from '../../../layouts/partials/shop/_modal_cart_option_change.json';
import checkoutItems from '../../../layouts/partials/shop/_checkout_items.json';
import orderComplete from '../../../layouts/shop/order_complete.json';
import mypageItems from '../../../layouts/partials/mypage/orders/_items.json';
// ============================================================
// 테스트용 컴포넌트
// ============================================================
const TestDiv: React.FC<any> = ({ className, children, 'data-testid': testId }) => (
<div className={className} data-testid={testId}>
{children}
</div>
);
const TestSpan: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
<span className={className} data-testid={testId}>
{children ?? text}
</span>
);
const TestP: React.FC<any> = ({ className, children, text, 'data-testid': testId }) => (
<p className={className} data-testid={testId}>
{children ?? text}
</p>
);
function setupRegistry(): ComponentRegistry {
const registry = ComponentRegistry.getInstance();
const Fragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}</>;
(registry as any).registry = {
Fragment: { component: Fragment, metadata: { name: 'Fragment', type: 'layout' } },
Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } },
Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } },
P: { component: TestP, metadata: { name: 'P', type: 'basic' } },
};
return registry;
}
// ============================================================
// 1. 렌더링 — 추가옵션 라인 표시 (장바구니 항목 스타일)
// ============================================================
describe('추가옵션 표시 렌더링', () => {
beforeEach(() => setupRegistry());
const layout = {
version: '1.0.0',
layout_name: 'shop_additional_options_test',
data_sources: [
{ id: 'cart', type: 'api', endpoint: '/api/cart', method: 'GET', auto_fetch: true },
],
components: [
{
type: 'basic',
name: 'Div',
iteration: { source: '{{cart.data.items ?? []}}', item_var: 'item' },
children: [
{
type: 'basic',
name: 'Div',
if: '{{item.additional_options?.length > 0}}',
iteration: { source: '{{item.additional_options ?? []}}', item_var: 'addOpt' },
children: [
{
type: 'basic',
name: 'P',
text: "{{addOpt.group_name}}: {{addOpt.name}}{{(addOpt.price_adjustment ?? 0) > 0 ? ' (+' + addOpt.price_adjustment.toLocaleString() + '원)' : ''}}",
},
],
},
],
},
],
};
it('선택된 추가옵션 그룹명·선택지명·추가금을 표시한다', async () => {
const testUtils = createLayoutTest(layout as any);
testUtils.mockApi('cart', {
response: {
data: {
items: [
{
id: 1,
additional_options: [
{ additional_option_id: 1, value_id: 101, group_name: '각인', name: '각인 추가', price_adjustment: 5000 },
],
},
],
},
},
});
await testUtils.render();
expect(
screen.getByText((c) => c.includes('각인 추가') && c.includes('5,000'))
).toBeInTheDocument();
testUtils.cleanup();
});
it('추가금 0인 선택지는 추가금 표기를 생략한다', async () => {
const testUtils = createLayoutTest(layout as any);
testUtils.mockApi('cart', {
response: {
data: {
items: [
{
id: 1,
additional_options: [
{ additional_option_id: 1, value_id: 100, group_name: '각인', name: '없음', price_adjustment: 0 },
],
},
],
},
},
});
const { container } = await testUtils.render();
expect(
screen.getByText((c) => c.includes('각인') && c.includes('없음'))
).toBeInTheDocument();
// 추가금 0 → '+' 표기 없음
expect(container.textContent).not.toContain('+0');
testUtils.cleanup();
});
});
// ============================================================
// 2. 구조 검증 — 실제 partial
// ============================================================
describe('_purchase_card.json 구조 — 블럭별 추가옵션', () => {
const str = JSON.stringify(purchaseCard);
it('블럭 내부 추가옵션 그룹 iteration이 product.data.additional_options를 사용한다', () => {
expect(str).toContain('product.data?.additional_options');
expect(str).toContain('"item_var":"addGroup"');
});
it('블럭별 추가옵션 변경 핸들러 setBlockAdditionalOption을 호출한다', () => {
expect(str).toContain('sirsoft-basic.setBlockAdditionalOption');
});
it('addSelectedItemIfComplete에 additionalOptionGroups를 전달한다', () => {
expect(str).toContain('"additionalOptionGroups"');
});
it('담기/구매 body에 additional_option_selections를 포함한다', () => {
expect(str).toContain('additional_option_selections');
expect(str).toContain('additional_option_id');
expect(str).toContain('value_id');
});
it('필수 추가옵션 미선택 차단 가드(additional_option_required)가 있다', () => {
expect(str).toContain('shop.additional_option_required');
expect(str).toContain('is_required');
});
it('레거시 카드레벨 자유텍스트 추가옵션 입력을 제거했다', () => {
// 구 스텁: additional_option_{{addOption.id}} 텍스트 input
expect(str).not.toContain('additional_option_{{addOption.id}}');
expect(str).not.toContain('_local.additionalOptions?.[addOption.id]');
});
it('선택된 옵션 블록은 space-y-4 부모 + iteration 자식으로 분리한다 (붙어 보이는 회귀 방지)', () => {
// G7 엔진은 iteration 노드를 N번 복제하므로, space-y-* 가 iteration 과 같은 노드에 있으면
// 각 아이템이 자기 wrapper 를 소유해 형제 간 간격이 0 이 된다. 따라서:
// - selectedOptionItems iteration 노드 자체에는 space-y-* 가 없어야 한다
// - 그 iteration 노드의 부모가 space-y-4 를 가져야 한다
const findParentOfSelectedIteration = (
node: any,
parent: any
): { iterNode: any; parent: any } | null => {
if (!node || typeof node !== 'object') return null;
const src = node.iteration?.source;
if (typeof src === 'string' && src.includes('_local.selectedOptionItems')) {
return { iterNode: node, parent };
}
for (const child of node.children ?? []) {
const found = findParentOfSelectedIteration(child, node);
if (found) return found;
}
return null;
};
let result: { iterNode: any; parent: any } | null = null;
for (const child of (purchaseCard as any).children ?? []) {
result = findParentOfSelectedIteration(child, purchaseCard);
if (result) break;
}
expect(result).not.toBeNull();
const iterClass = result!.iterNode.props?.className ?? '';
const parentClass = result!.parent?.props?.className ?? '';
// iteration 노드에는 space-y-* 금지 (동거 시 간격 미적용 회귀)
expect(iterClass).not.toMatch(/\bspace-y-/);
// 부모가 형제 간격(space-y-4)을 담당
expect(parentClass).toContain('space-y-4');
});
});
describe('_cart_item.json 구조 — 추가옵션 표시 + 모달 시드', () => {
const str = JSON.stringify(cartItem);
it('item.additional_options를 옵션 라인 아래 표시한다', () => {
expect(str).toContain('item.additional_options');
expect(str).toContain('addOpt.group_name');
});
it('옵션변경 모달 열기 시 additionalSelections를 현재 선택으로 시드한다', () => {
expect(str).toContain('additionalSelections');
expect(str).toContain('a.additional_option_id');
expect(str).toContain('a.value_id');
});
});
describe('_modal_cart_option_change.json 구조 — 추가옵션 재선택', () => {
const str = JSON.stringify(modalOptionChange);
it('optionProduct.additional_options 기반 그룹 재선택 UI가 있다', () => {
expect(str).toContain('optionProduct?.additional_options');
expect(str).toContain('additionalSelections');
});
it('PATCH body에 additional_option_selections를 포함한다', () => {
expect(str).toContain('additional_option_selections');
});
});
describe('표시 전용 화면 — 스냅샷 기반 추가옵션 별행', () => {
it('체크아웃 항목에 additional_options 표시가 있다', () => {
expect(JSON.stringify(checkoutItems)).toContain('item.additional_options');
});
it('주문완료 항목에 additional_options 표시가 있다', () => {
expect(JSON.stringify(orderComplete)).toContain('item.additional_options');
});
it('마이페이지 주문상세 항목에 additional_options 표시가 있다', () => {
expect(JSON.stringify(mypageItems)).toContain('item.additional_options');
});
});
@@ -1,3 +1,4 @@
// e2e:allow편집기 passthrough 결함#2 수정(admin 동기, data-editor-*/id 를 시각적 루트 Div 로 라우팅). 단위 회귀는 FileInput.test.tsx passthrough describe.
import React, { forwardRef, useRef, useCallback, useState } from 'react';
import { Div } from './Div';
import { Span } from './Span';
@@ -40,6 +41,20 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
const inputRef = (ref as React.RefObject<HTMLInputElement>) || internalRef;
const [fileName, setFileName] = useState<string>('');
// 레이아웃 편집기 식별 표식(data-editor-*) 과 DOM id 는 시각적 루트(<Div>)에 부착해야
// 캔버스에서 선택/편집이 닿는다. basic 컴포넌트라 DynamicRenderer 가 개별 data-editor-*
// 키를 props 로 주입하는데, 숨겨진 <Input className="hidden"> 는 0×0 이라 식별 표식이 닿아도
// 선택 불가. 식별/표식 키만 분리해 루트로 보낸다.
const rootEditorProps: Record<string, unknown> = {};
const inputProps: Record<string, unknown> = {};
Object.entries(props as Record<string, unknown>).forEach(([key, val]) => {
if (key.startsWith('data-editor-') || key === 'id' || key === 'onMouseMove' || key === 'onMouseLeave') {
rootEditorProps[key] = val;
} else {
inputProps[key] = val;
}
});
const handleClick = useCallback(() => {
if (!disabled && inputRef.current) {
inputRef.current.click();
@@ -81,7 +96,7 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
}, [onChange, inputRef]);
return (
<Div className={`flex items-center gap-2 ${className}`}>
<Div className={`flex items-center gap-2 ${className}`} {...rootEditorProps}>
<Input
ref={inputRef}
type="file"
@@ -89,7 +104,7 @@ export const FileInput = forwardRef<HTMLInputElement, FileInputProps>(({
onChange={handleChange as any}
disabled={disabled}
className="hidden"
{...props}
{...inputProps}
/>
<Button
type="button"
@@ -320,8 +320,22 @@ export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
// HTML 표준 속성이 아닌 것들을 필터링 (타입 안전성 개선)
const { loadingactions, formdata, ...validProps } = props as typeof props & NonStandardProps;
// 레이아웃 편집기 표식/핸들러(data-editor-*, onMouseMove/Leave 등)는 시각적
// 루트(wrapper div)에 부착해야 캔버스 선택/드래그가 컴포넌트 전체를 잡는다.
// 내부 input 에만 spread 하면 선택 박스가 input 으로 한정되고 error/검증/토글이
// 선택 영역 밖이 된다.
const editorRootProps: Record<string, unknown> = {};
const inputRestProps: Record<string, unknown> = {};
for (const [k, v] of Object.entries(validProps as Record<string, unknown>)) {
if (k.startsWith('data-editor-') || k === 'onMouseMove' || k === 'onMouseLeave') {
editorRootProps[k] = v;
} else {
inputRestProps[k] = v;
}
}
return (
<div className={`relative ${wrapperClassName}`}>
<div className={`relative ${wrapperClassName}`} {...editorRootProps}>
{/* 입력 필드 wrapper */}
<div className="relative">
<input
@@ -334,7 +348,7 @@ export const PasswordInput = forwardRef<HTMLInputElement, PasswordInputProps>(
onKeyDown={handleKeyEvent}
onKeyUp={handleKeyEvent}
disabled={disabled}
{...validProps}
{...inputRestProps}
/>
{/* 비밀번호 보기/숨기기 버튼 */}
@@ -1,3 +1,4 @@
// e2e:allow커스텀 드롭다운 루트 props spread 타입 안전 캐스팅(admin 동기). 단위 회귀는 Select.test.tsx.
import React, { useMemo, useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Div } from './Div';
@@ -28,6 +29,12 @@ export interface SelectProps extends Omit<React.SelectHTMLAttributes<HTMLSelectE
searchable?: boolean;
/** 검색 input placeholder */
searchPlaceholder?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용). Select 는 커스텀 드롭다운 루트에
* 개별 data-editor-* 키를 spread 해야 선택/편집이 닿는다(커스텀 루트
* passthrough). basic 컴포넌트라 `{...props}` 로 DOM 표준 속성(id 등)도 함께 흐른다.
*/
editorAttrs?: Record<string, unknown>;
}
/**
@@ -67,6 +74,7 @@ export const Select: React.FC<SelectProps> = ({
disabled,
searchable = false,
searchPlaceholder,
editorAttrs,
...props
}) => {
const [isOpen, setIsOpen] = useState(false);
@@ -237,6 +245,7 @@ export const Select: React.FC<SelectProps> = ({
value={value}
onChange={onChange as React.ChangeEventHandler<HTMLSelectElement>}
disabled={disabled}
{...editorAttrs}
{...props}
>
{children}
@@ -252,8 +261,13 @@ export const Select: React.FC<SelectProps> = ({
? `${className}${hasTextColor ? '' : ' text-gray-700 dark:text-gray-200'}`
: `w-full px-4 py-2.5 bg-gray-100 dark:bg-gray-700 border-0 rounded-xl text-gray-700 dark:text-gray-200 font-medium focus:ring-2 focus:ring-blue-500 focus:outline-none ${className}`;
// props 는 SelectHTMLAttributes 기반이라 Div(HTMLDivElement) 에 직접 spread 시 타입 불일치.
// 런타임 동작(편집기 data-editor-* / id 등 DOM 표준 속성 passthrough)은 동일하므로
// DOM-safe 레코드로 캐스팅해 커스텀 드롭다운 루트에 전달한다.
const rootDomProps = { ...editorAttrs, ...props } as Record<string, unknown>;
return (
<Div ref={containerRef} className="relative">
<Div ref={containerRef} className="relative" {...rootDomProps}>
<Button
ref={buttonRef}
type="button"
@@ -0,0 +1,48 @@
import { describe, it, expect } from 'vitest';
import { render } from '@testing-library/react';
import { FileInput } from '../FileInput';
describe('FileInput 컴포넌트 (sirsoft-basic)', () => {
// ========================================
// 레이아웃 편집기 passthrough
// ========================================
// 편집 모드에서 basic 컴포넌트에 주입되는 data-editor-* / id 는 시각적 루트(<div>)에
// 부착되어야 한다. 숨겨진 <input class="hidden"> (0×0) 에 부착되면 캔버스에서 선택 불가.
describe('편집기 passthrough (data-editor-* / id → 시각적 루트 <div>)', () => {
it('data-editor-* 표식이 숨겨진 input 이 아닌 루트 div 에 부착된다', () => {
const { container } = render(
<FileInput
data-editor-name="FileInput"
data-editor-path="1.children.0"
id="fi-root-id"
/>
);
const root = container.querySelector('[data-editor-name="FileInput"]') as HTMLElement;
expect(root).toBeTruthy();
expect(root.tagName.toLowerCase()).toBe('div');
expect(root.getAttribute('data-editor-path')).toBe('1.children.0');
expect(root.getAttribute('id')).toBe('fi-root-id');
expect(root.querySelector('button')).toBeTruthy();
});
it('숨겨진 file input 에는 편집 표식이 없다', () => {
const { container } = render(
<FileInput data-editor-name="FileInput" data-editor-path="2.children.1" id="fi-id" />
);
const hiddenInput = container.querySelector('input[type="file"]') as HTMLElement;
expect(hiddenInput).toBeTruthy();
expect(hiddenInput.getAttribute('data-editor-name')).toBeNull();
expect(hiddenInput.getAttribute('data-editor-path')).toBeNull();
expect(hiddenInput.getAttribute('id')).toBeNull();
});
it('기능 prop(name 등)은 file input 에 그대로 전달된다', () => {
const { container } = render(
<FileInput name="upload_field" data-editor-name="FileInput" />
);
const hiddenInput = container.querySelector('input[type="file"]') as HTMLInputElement;
expect(hiddenInput.getAttribute('name')).toBe('upload_field');
});
});
});
@@ -431,4 +431,49 @@ describe('PasswordInput 컴포넌트', () => {
expect(screen.getByTestId('icon-triangle-exclamation')).toBeInTheDocument();
});
});
// 레이아웃 편집기 표식(data-editor-*)은 내부 input 이 아니라
// 시각적 루트(wrapper div)에 부착되어야 캔버스 선택/드래그가 컴포넌트 전체를 잡는다.
describe('레이아웃 편집기 표식 부착 위치', () => {
it('data-editor-* / onMouseMove 는 wrapper 루트 div 에 부착', () => {
const onMouseMove = vi.fn();
const { container } = render(
<PasswordInput
wrapperClassName="vpw-root"
{...({
'data-editor-id': 'auto_PW_1',
'data-editor-name': 'PasswordInput',
'data-editor-path': '0.children.1',
onMouseMove,
} as Record<string, unknown>)}
/>
);
// 루트 div 가 표식을 가져야 함
const root = container.firstElementChild as HTMLElement;
expect(root.tagName).toBe('DIV');
expect(root).toHaveClass('vpw-root');
expect(root.getAttribute('data-editor-id')).toBe('auto_PW_1');
expect(root.getAttribute('data-editor-name')).toBe('PasswordInput');
expect(root.getAttribute('data-editor-path')).toBe('0.children.1');
// 내부 input 에는 data-editor-* 가 없어야 함 (루트로만 흘러야 함)
const input = container.querySelector('input') as HTMLElement;
expect(input.getAttribute('data-editor-path')).toBeNull();
expect(input.getAttribute('data-editor-id')).toBeNull();
});
it('일반 input 속성(name/placeholder)은 내부 input 에 그대로 전달', () => {
const { container } = render(
<PasswordInput
name="user_password"
placeholder="비밀번호 입력"
{...({ 'data-editor-name': 'PasswordInput' } as Record<string, unknown>)}
/>
);
const input = container.querySelector('input') as HTMLInputElement;
expect(input.getAttribute('name')).toBe('user_password');
expect(input.getAttribute('placeholder')).toBe('비밀번호 입력');
// 편집기 표식은 input 에 누출되지 않음
expect(input.getAttribute('data-editor-name')).toBeNull();
});
});
});
@@ -1,3 +1,4 @@
// e2e:allow 편집기 ComponentRegistry 등록 정합(basic Header/Footer export 제거 — composite 와 이름 충돌 해소, SlotContainer 번들 포함). 편집기 캔버스 렌더는 Chrome MCP 라이브 실측 + Vitest(headerEditorSpecAndCurrencySlot/HeaderPropRender)로 검증. 사용자 사이트 런타임 무변경.
/**
* 기본 HTML 매핑 컴포넌트 Export
*
@@ -38,8 +39,10 @@ export { Section, type SectionProps } from './Section';
export { Svg, type SvgProps } from './Svg';
export { Icon, type IconProps } from './Icon';
export { Code, type CodeProps } from './Code';
export { Footer, type FooterProps } from './Footer';
export { Header, type HeaderProps } from './Header';
// basic Header/Footer(HTML <header>/<footer> 래퍼)는 레이아웃 사용처 0이며 composite
// Header/Footer 와 이름이 겹쳐 편집기 ComponentRegistry 에서 중복 등록 경고를 유발한다.
// 사이트 헤더/푸터는 composite 컴포넌트가 담당하므로 basic 래퍼 export 를 제거한다
// (필요 시 Div + role/시맨틱 태그로 대체). 파일 자체는 보존(직접 import 경로는 유지).
export { Hr, type HrProps } from './Hr';
// Icon 타입 정의 (enum 및 타입)
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
import { Div } from '../basic/Div';
import { Img } from '../basic/Img';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
/**
* 아바타 크기 타입
@@ -80,6 +81,14 @@ export interface AvatarProps {
isWithdrawn?: boolean;
/** 비회원 여부 (author.is_guest보다 우선) @default false */
isGuest?: boolean;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -131,6 +140,8 @@ export const Avatar: React.FC<AvatarProps> = ({
text,
isWithdrawn = false,
isGuest = false,
id,
editorAttrs,
}) => {
// 명시적 props > author 추출값 순서로 결정
const actualAvatar = avatar ?? author?.avatar;
@@ -179,7 +190,7 @@ export const Avatar: React.FC<AvatarProps> = ({
};
return (
<Div className={containerClasses}>
<Div className={containerClasses} id={id} {...editorAttrs}>
{actualAvatar && !actualIsGuest && !actualIsWithdrawn ? (
<Img
src={actualAvatar}
@@ -21,6 +21,7 @@ import { Label } from '../basic/Label';
import { Input } from '../basic/Input';
import { Img } from '../basic/Img';
import { Avatar } from './Avatar';
import type { EditorAttrs } from '../../types';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
@@ -74,6 +75,12 @@ export interface AvatarUploaderProps {
deleteSuccessActions?: Array<Record<string, any>>;
/** 삭제 실패 시 실행할 액션 배열 */
deleteErrorActions?: Array<Record<string, any>>;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
// AvatarUploader size를 Avatar size로 매핑
@@ -111,6 +118,8 @@ export function AvatarUploader({
uploadErrorActions,
deleteSuccessActions,
deleteErrorActions,
id,
editorAttrs,
}: AvatarUploaderProps) {
const inputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false);
@@ -420,7 +429,7 @@ export function AvatarUploader({
);
return (
<Div className={`flex flex-col items-center gap-3 ${className}`}>
<Div className={`flex flex-col items-center gap-3 ${className}`} id={id} {...editorAttrs}>
{/* 아바타 이미지 - 업로드 확인 시 미리보기 표시 */}
{showUploadConfirm && previewUrl ? (
<Div className="relative">
@@ -3,6 +3,7 @@ import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
/**
* G7Core 다국어 헬퍼
@@ -39,6 +40,15 @@ export interface ExpandableContentProps {
* children 렌더링
*/
children?: React.ReactNode;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -68,6 +78,8 @@ export const ExpandableContent: React.FC<ExpandableContentProps> = ({
collapseText,
className = '',
children,
id,
editorAttrs,
}) => {
const [isExpanded, setIsExpanded] = useState(false);
const [needsExpand, setNeedsExpand] = useState(false);
@@ -120,7 +132,7 @@ export const ExpandableContent: React.FC<ExpandableContentProps> = ({
const resolvedCollapseText = collapseText || t('sirsoft-ecommerce.shop.product.collapse_detail');
return (
<Div className={className}>
<Div className={className} id={id} {...editorAttrs}>
{/* 콘텐츠 컨테이너 */}
<Div className="relative">
<Div
@@ -60,6 +60,8 @@ export const FileUploader = forwardRef<FileUploaderRef, FileUploaderProps>(
enablePrimarySelection = false,
primaryFileId,
onPrimaryChange,
id,
editorAttrs,
},
ref
) => {
@@ -208,7 +210,7 @@ export const FileUploader = forwardRef<FileUploaderRef, FileUploaderProps>(
return (
<FileUploaderProvider value={contextValue}>
<Div className={className}>
<Div id={id} className={className} {...editorAttrs}>
{/* 드롭존 + 파일 목록 통합 영역 */}
<FileDropZone
isDragOver={uploader.isDragOver}
@@ -4,6 +4,8 @@
* @module composite/FileUploader/types
*/
import type { EditorAttrs } from '../../../types';
// ========== Types ==========
export interface Attachment {
@@ -151,6 +153,10 @@ export interface FileUploaderProps {
/** 순서 변경 API (기본값: /api/attachments/reorder) */
reorder?: string;
};
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID) */
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
export interface FileUploaderRef {
@@ -33,6 +33,13 @@ import { Icon } from '../basic/Icon';
const t = (key: string, params?: Record<string, string | number>) =>
(window as any).G7Core?.t?.(key, params) ?? key;
// G7 표준 반응형 breakpoint — 모바일(< 768) / 데스크톱(>= 1024).
// 레이아웃 편집기 프리뷰 호환을 위해 Tailwind md:/lg:/sm: 미디어쿼리 대신
// G7Core.useResponsive() width 기반 분기 사용 (편집 가능 템플릿은 G7 표준
// responsive 만 허용 — viewport 미디어쿼리는 프리뷰 overrideWidth 를 무시).
const TABLET_BREAKPOINT = 768;
const DESKTOP_BREAKPOINT = 1024;
// G7Core.dispatch() navigate 헬퍼
const navigate = (path: string) => {
(window as any).G7Core?.dispatch?.({
@@ -72,6 +79,8 @@ interface FooterProps {
linkGroups?: FooterLinkGroup[];
/** 추가 CSS 클래스 */
className?: string;
/** 레이아웃 편집기 식별 속성(data-editor-*) — 시각적 루트에 spread */
editorAttrs?: Record<string, unknown>;
}
/**
@@ -103,9 +112,23 @@ const Footer: React.FC<FooterProps> = ({
socialLinks = {},
linkGroups,
className = '',
editorAttrs,
}) => {
const currentYear = new Date().getFullYear();
// G7 표준 반응형 — useResponsive() 로 프리뷰 overrideWidth 수신 (편집기 디바이스
// 전환에 정상 반응). hook 미주입 시 window.innerWidth fallback.
const G7Core = (window as any).G7Core;
const useResponsive = G7Core?.useResponsive as (() => { width: number }) | undefined;
const responsiveValue = useResponsive?.();
const width =
responsiveValue?.width ??
(typeof window !== 'undefined' ? window.innerWidth : DESKTOP_BREAKPOINT);
const isMobile = width < TABLET_BREAKPOINT;
const isDesktop = width >= DESKTOP_BREAKPOINT;
// 링크 그룹 그리드 컬럼 — 모바일 1열 / 태블릿 2열 / 데스크톱 5열.
const gridColumns = isMobile ? 1 : isDesktop ? 5 : 2;
// 기본 링크 그룹
const defaultLinkGroups: FooterLinkGroup[] = [
{
@@ -146,11 +169,17 @@ const Footer: React.FC<FooterProps> = ({
};
return (
<FooterBasic className={`bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800 ${className}`}>
<FooterBasic
{...((editorAttrs ?? {}) as Record<string, never>)}
className={`bg-gray-50 dark:bg-gray-900 border-t border-gray-200 dark:border-gray-800 ${className}`}
>
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">
<Div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-8">
{/* 사이트 정보 */}
<Div className="lg:col-span-2">
<Div
className="grid gap-8"
style={{ gridTemplateColumns: `repeat(${gridColumns}, minmax(0, 1fr))` }}
>
{/* 사이트 정보 — 데스크톱(5열)에서만 2칸 차지 */}
<Div style={isDesktop ? { gridColumn: 'span 2 / span 2' } : undefined}>
<H3 className="text-lg font-bold text-gray-900 dark:text-white">{siteName}</H3>
{siteDescription && (
<P className="mt-2 text-sm text-gray-600 dark:text-gray-400">{siteDescription}</P>
@@ -198,7 +227,10 @@ const Footer: React.FC<FooterProps> = ({
</Div>
{/* 저작권 */}
<Div className="mt-8 pt-8 border-t border-gray-200 dark:border-gray-800 flex flex-col sm:flex-row justify-between items-center gap-4">
<Div
className="mt-8 pt-8 border-t border-gray-200 dark:border-gray-800 flex justify-between items-center gap-4"
style={{ flexDirection: isMobile ? 'column' : 'row' }}
>
<P className="text-sm text-gray-500 dark:text-gray-400">
{copyrightText || `© ${currentYear} ${siteName}. All rights reserved.`}
</P>
@@ -33,6 +33,9 @@ import { ThemeToggle } from './ThemeToggle';
// Avatar 컴포넌트 import
import { Avatar } from './Avatar';
// SlotContainer — 헤더 통화 등 모듈 주입 UI 를 떙겨 렌더 (헤더는 주입 모듈을 모름)
import { SlotContainer } from './SlotContainer';
// NotificationCenter 컴포넌트 import
import { NotificationCenter, type NotificationItem } from './NotificationCenter';
@@ -87,6 +90,8 @@ interface HeaderProps {
shopBase?: string;
/** 추가 CSS 클래스 */
className?: string;
/** 레이아웃 편집기 식별 속성(data-editor-*) — 시각적 루트에 spread */
editorAttrs?: Record<string, unknown>;
// ===== 알림센터 드롭다운 Props =====
/** 알림 목록 (NotificationCenter에 전달) */
@@ -157,6 +162,7 @@ const Header: React.FC<HeaderProps> = ({
currentLocale = 'ko',
shopBase = '/shop',
className = '',
editorAttrs,
// 알림센터
notifications = [],
notificationHasMore = false,
@@ -178,10 +184,12 @@ const Header: React.FC<HeaderProps> = ({
const [searchQuery, setSearchQuery] = useState('');
const [showUserMenu, setShowUserMenu] = useState(false);
const [showMoreBoards, setShowMoreBoards] = useState(false);
const [showLangMenu, setShowLangMenu] = useState(false);
const [dropdownPosition, setDropdownPosition] = useState<{ top: number; left: number }>({ top: 0, left: 0 });
const [currentPath, setCurrentPath] = useState(window.location.pathname);
const userMenuRef = useRef<HTMLDivElement>(null);
const moreButtonRef = useRef<HTMLDivElement>(null);
const langMenuRef = useRef<HTMLDivElement>(null);
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준 — 위지윅 overrideWidth 호환)
const G7Core = (window as any).G7Core;
@@ -244,6 +252,9 @@ const Header: React.FC<HeaderProps> = ({
if (moreButtonRef.current && !moreButtonRef.current.contains(event.target as Node)) {
setShowMoreBoards(false);
}
if (langMenuRef.current && !langMenuRef.current.contains(event.target as Node)) {
setShowLangMenu(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
@@ -267,17 +278,25 @@ const Header: React.FC<HeaderProps> = ({
});
};
// 언어 변경 핸들러
// 언어 변경 핸들러 — 헤더 독립 언어 버튼(코어 기능)에서 호출. setLocale 은 비회원도 동작.
const handleLocaleChange = (locale: string) => {
(window as any).G7Core?.dispatch?.({
handler: 'setLocale',
target: locale,
});
setShowUserMenu(false);
setShowLangMenu(false);
};
// 로케일 코드 → 표시명 (활성 언어팩 native_name 우선, 폴백 사전)
const getLocaleName = (locale: string): string =>
(window as any).G7Core?.state?.get?.('_global.appConfig.localeNames')?.[locale] ??
(locale === 'ko' ? '한국어' : locale === 'en' ? 'English' : locale === 'ja' ? '日本語' : locale === 'zh' ? '中文' : locale === 'es' ? 'Español' : locale === 'fr' ? 'Français' : locale === 'de' ? 'Deutsch' : locale.toUpperCase());
return (
<HeaderBasic className={`sticky top-0 z-50 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 ${className}`}>
<HeaderBasic
{...((editorAttrs ?? {}) as Record<string, never>)}
className={`sticky top-0 z-50 bg-white dark:bg-gray-900 border-b border-gray-200 dark:border-gray-800 ${className}`}
>
{/* 상단 바 */}
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Div className="flex items-center justify-between h-16">
@@ -352,6 +371,57 @@ const Header: React.FC<HeaderProps> = ({
)}
</Button>
{/* 언어 선택 — 헤더 독립 버튼(코어 기능, 비회원 포함 전체 노출). 공간 절약 위해 아이콘+로케일 코드만.
언어는 항상 존재(이커머스 무관) → 템플릿 헤더 내장. */}
{availableLocales && availableLocales.length > 1 && (
<Div ref={langMenuRef} className="relative">
<Button
onClick={() => setShowLangMenu(!showLangMenu)}
className="flex items-center gap-1.5 px-2.5 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg cursor-pointer transition-colors"
aria-haspopup="listbox"
aria-expanded={showLangMenu}
aria-label={t('common.language')}
>
<Icon name="globe" className="w-4 h-4" />
<Span className="font-medium uppercase">{currentLocale}</Span>
<Icon name="chevron-down" className="w-3 h-3" />
</Button>
{showLangMenu && (
<Div
role="listbox"
className="absolute right-0 mt-2 w-44 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg py-1 z-50 overflow-hidden"
>
{availableLocales.map((locale) => {
const isActive = locale === currentLocale;
return (
<Button
key={locale}
role="option"
aria-selected={isActive}
onClick={() => handleLocaleChange(locale)}
className={`w-full px-4 py-2.5 text-left text-sm flex items-center gap-3 cursor-pointer transition-colors ${
isActive
? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<Icon name="globe" className="w-4 h-4" />
<Span className="flex-1 font-medium">{getLocaleName(locale)}</Span>
{isActive && <Icon name="check" className="w-4 h-4" />}
</Button>
);
})}
</Div>
)}
</Div>
)}
{/* 통화 선택 — 이커머스 모듈이 'header_currency' 슬롯에 주입(layout_extensions).
헤더는 슬롯 이름만 알고 통화/모듈을 모름. 모듈 비활성 시 빈 슬롯 → 미렌더(인프라 자동 게이트).
id 지정 필수 — 같은 슬롯이 모바일 헤더 SlotContainer 와 동시 렌더되므로 주입 컴포넌트
root id 가 컨테이너별로 스코프되도록(SlotContainer 가 id 로 자식 root id 를 고유화) 한다. */}
<SlotContainer slotId="header_currency" id="header_currency_slot_desktop" className="flex items-center" />
{/* 사용자 메뉴 */}
{user?.uuid ? (
<Div ref={userMenuRef} className="relative">
@@ -415,31 +485,7 @@ const Header: React.FC<HeaderProps> = ({
</Button>
</Div>
{/* 언어 선택 (availableLocales가 있을 때만 표시) */}
{availableLocales && availableLocales.length > 1 && (
<>
<Hr className="my-1 border-gray-200 dark:border-gray-700" />
<Div className="py-1">
<Div className="px-4 py-2 text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">
{t('common.language')}
</Div>
{availableLocales.map((locale) => (
<Button
key={locale}
onClick={() => handleLocaleChange(locale)}
className={`block w-full text-left px-4 py-2 text-sm cursor-pointer ${
locale === currentLocale
? 'text-blue-600 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20'
: 'text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
}`}
>
<Icon name="globe" className="inline w-4 h-4 mr-2" />
{(window as any).G7Core?.state?.get?.('_global.appConfig.localeNames')?.[locale] ?? (locale === 'ko' ? '한국어' : locale === 'en' ? 'English' : locale === 'ja' ? '日本語' : locale === 'zh' ? '中文' : locale === 'es' ? 'Español' : locale === 'fr' ? 'Français' : locale === 'de' ? 'Deutsch' : locale.toUpperCase())}
</Button>
))}
</Div>
</>
)}
{/* 언어 선택은 헤더 독립 버튼으로 일원화(드롭다운에서 제거) — 비회원도 헤더에서 전환 가능 */}
<Hr className="my-1 border-gray-200 dark:border-gray-700" />
<Button
@@ -453,16 +499,23 @@ const Header: React.FC<HeaderProps> = ({
)}
</Div>
) : (
<Div className="flex items-center gap-2">
<Div className="flex items-center gap-1.5">
{/* 주문조회 — 로그인 페이지로 진입. 회원은 로그인 후 redirect 파라미터로 마이페이지 주문 내역으로 이동, 비회원은 로그인 페이지의 '비회원 주문 조회' 링크로 폼 진입. 로그아웃된 회원이 비회원 페이지에서 막다른 길에 빠지는 케이스를 차단한다. */}
<Button
onClick={() => navigate('/login?redirect=/mypage/orders')}
className="px-2.5 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white cursor-pointer"
>
{t('shop.guest_order_form.nav_link')}
</Button>
<Button
onClick={() => navigate('/login')}
className="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white cursor-pointer"
className="px-2.5 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white cursor-pointer"
>
{t('auth.login')}
</Button>
<Button
onClick={() => navigate('/register')}
className="px-4 py-2 text-sm font-medium text-white bg-emerald-500 rounded-lg hover:bg-emerald-600 cursor-pointer"
className="ml-1 px-3 py-2 text-sm font-medium text-white bg-emerald-500 rounded-lg hover:bg-emerald-600 cursor-pointer"
>
{t('auth.register_link')}
</Button>
@@ -487,14 +540,14 @@ const Header: React.FC<HeaderProps> = ({
<Nav className="border-t border-gray-200 dark:border-gray-800">
<Div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<Div className="flex items-center gap-1 h-12 overflow-x-auto">
<Button onClick={() => navigate('/')} className={getNavButtonClass(isActiveRoute('/', true))}>
<Button onClick={() => navigate('/')} className={getNavButtonClass(isActiveRoute('/', true))} data-testid="nav-home">
{t('nav.home')}
</Button>
<Button onClick={() => navigate('/boards/popular')} className={`flex items-center gap-1 ${getNavButtonClass(isActiveRoute('/boards/popular'))}`}>
<Button onClick={() => navigate('/boards/popular')} className={`flex items-center gap-1 ${getNavButtonClass(isActiveRoute('/boards/popular'))}`} data-testid="nav-popular">
<Span className="text-orange-500">🔥</Span>
{t('nav.popular')}
</Button>
<Button onClick={() => navigate(`${shopBase === '/' ? '' : shopBase}/products`)} className={`flex items-center gap-1 ${getNavButtonClass(isShopActive())}`}>
<Button onClick={() => navigate(`${shopBase === '/' ? '' : shopBase}/products`)} className={`flex items-center gap-1 ${getNavButtonClass(isShopActive())}`} data-testid="nav-shop">
<Span>🛒</Span>
{t('nav.shop')}
</Button>
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
// @ts-ignore - DOMPurify 타입 정의 없음
import DOMPurify from 'dompurify';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface HtmlContentProps {
/**
@@ -32,6 +33,15 @@ export interface HtmlContentProps {
* content보다 우선순위가 높음
*/
text?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -69,6 +79,8 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
isHtml = true,
className = '',
purifyConfig,
id,
editorAttrs,
}) => {
// text prop이 우선순위가 높음 (레이아웃 JSON에서 사용)
const actualContent = text ?? content ?? '';
@@ -88,7 +100,7 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
`.trim().replace(/\s+/g, ' ');
return (
<Div className={textClasses}>
<Div className={textClasses} id={id} {...editorAttrs}>
{actualContent}
</Div>
);
@@ -181,8 +193,10 @@ export const HtmlContent: React.FC<HtmlContentProps> = ({
return (
<Div
id={id}
className={containerClasses}
dangerouslySetInnerHTML={{ __html: sanitizedHtml }}
{...editorAttrs}
/>
);
};
@@ -5,6 +5,7 @@ import { Button } from '../basic/Button';
import { Textarea } from '../basic/Textarea';
import { Input } from '../basic/Input';
import { HtmlContent } from './HtmlContent';
import type { EditorAttrs } from '../../types';
// G7Core 참조
const G7Core = () => (window as any).G7Core;
@@ -90,6 +91,15 @@ export interface HtmlEditorProps {
* 읽기 전용 모드
*/
readOnly?: boolean;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -127,6 +137,8 @@ export const HtmlEditor: React.FC<HtmlEditorProps> = ({
name = 'content',
htmlFieldName = 'content_mode',
readOnly = false,
id,
editorAttrs,
}) => {
// HTML 모드 내부 상태 (Toggle과 동기화)
const [isHtml, setIsHtml] = useState(isHtmlProp);
@@ -188,7 +200,7 @@ export const HtmlEditor: React.FC<HtmlEditorProps> = ({
}, []);
return (
<Div className={`space-y-2 ${className}`}>
<Div className={`space-y-2 ${className}`} id={id} {...editorAttrs}>
{/* 라벨 및 HTML 모드 토글 */}
<Div className="flex items-center justify-between">
@@ -20,6 +20,9 @@ import 'yet-another-react-lightbox/plugins/thumbnails.css';
import { Button } from '../basic/Button';
import { I } from '../basic/I';
import { Div } from '../basic/Div';
import { Img } from '../basic/Img';
import type { EditorAttrs } from '../../types';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
@@ -70,6 +73,18 @@ export interface ImageGalleryProps {
showThumbnails?: boolean;
/** 커스텀 다운로드 핸들러 (제공 시 기본 다운로드 로직 대신 실행) */
onDownload?: (image: GalleryImage, index: number) => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용).
* 본 컴포넌트는 서드파티 Lightbox 모달(`createPortal` 로 body 렌더)이라 런타임에는
* 인라인 DOM 이 없다. 편집 모드(editorAttrs 존재)에서는 캔버스 선택·속성 편집이
* 가능하도록 인라인 placeholder(이미지 썸네일 그리드)를 대신 렌더하고 거기에
* editorAttrs·id 를 부착한다. 런타임(editorAttrs 미주입)은 종전 Lightbox 동작 그대로.
*
*/
editorAttrs?: EditorAttrs;
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID — 편집 placeholder 루트에 부착) */
id?: string;
}
// ========== Helper Functions ==========
@@ -185,6 +200,8 @@ export const ImageGallery: React.FC<ImageGalleryProps> = ({
showDownload = true,
showThumbnails = true,
onDownload,
editorAttrs,
id,
}) => {
// 현재 슬라이드 인덱스 (다운로드 버튼용)
const [currentIndex, setCurrentIndex] = useState(startIndex);
@@ -214,6 +231,37 @@ export const ImageGallery: React.FC<ImageGalleryProps> = ({
currentIndexRef.current = currentIndex;
}, [currentIndex]);
// 편집 모드(편집기 캔버스) — Lightbox 모달은 인라인 DOM 이 없어 선택·편집 불가.
// editorAttrs 가 주입되면 인라인 placeholder(썸네일 그리드)를 대신 렌더해
// 캔버스에서 선택·속성 편집이 가능하게 한다. 런타임(editorAttrs 미주입)은 미진입.
// (Hooks 규칙 — 모든 hook 호출 이후에 분기 return)
if (editorAttrs) {
const previewImages = (images ?? []).slice(0, 4);
return (
<Div
id={id}
className="grid grid-cols-2 gap-2 p-3 rounded-lg border border-dashed border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-800"
{...editorAttrs}
>
{previewImages.length > 0 ? (
previewImages.map((image, index) => (
<Img
key={index}
src={image.thumbnail || image.src}
alt={image.title || ''}
className="w-full aspect-square object-cover rounded bg-gray-200 dark:bg-gray-700"
/>
))
) : (
<Div className="col-span-2 flex items-center justify-center py-6 text-sm text-gray-400 dark:text-gray-500">
<I className="fa-regular fa-images mr-2" />
{t('editor.component.image_gallery')}
</Div>
)}
</Div>
);
}
return (
<Lightbox
open={isOpen}
@@ -5,6 +5,7 @@ import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Input } from '../basic/Input';
import type { EditorAttrs } from '../../types';
/**
* 알림 아이템 인터페이스
@@ -61,6 +62,10 @@ export interface NotificationCenterProps {
/** 드롭다운 정렬 방향 — "right"(기본): 우측 정렬되어 좌측으로 확장 / "left": 좌측 정렬되어 우측으로 확장 */
dropdownAlign?: 'left' | 'right';
className?: string;
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID) */
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
/**
@@ -102,6 +107,8 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
onUnreadOnlyToggle,
dropdownAlign = 'right',
className = '',
id,
editorAttrs,
}) => {
const [showNotifications, setShowNotifications] = useState(false);
const notificationRef = useRef<HTMLDivElement>(null);
@@ -277,7 +284,7 @@ export const NotificationCenter: React.FC<NotificationCenterProps> = ({
}, [showNotifications, dropdownAlign, notifications.length]);
return (
<Div ref={notificationRef} className={`relative ${className}`}>
<Div ref={notificationRef} className={`relative ${className}`} id={id} {...editorAttrs}>
<Button
onClick={handleToggle}
className="relative p-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors cursor-pointer"
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
@@ -17,6 +18,14 @@ export interface PaginationProps {
style?: React.CSSProperties;
prevText?: string;
nextText?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -47,6 +56,8 @@ export const Pagination: React.FC<PaginationProps> = ({
style,
prevText,
nextText,
id,
editorAttrs,
}) => {
// 페이지 번호 생성 알고리즘
@@ -122,6 +133,7 @@ export const Pagination: React.FC<PaginationProps> = ({
style={style}
role="navigation"
aria-label={t('common.pagination')}
id={id} {...editorAttrs}
>
{/* First Button */}
{showFirstLast && (
@@ -9,6 +9,7 @@ import React from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:PostReactions')) ?? {
@@ -43,6 +44,12 @@ interface PostReactionsProps {
size?: 'sm' | 'md' | 'lg';
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
interface ReactionConfig {
@@ -100,6 +107,8 @@ const PostReactions: React.FC<PostReactionsProps> = ({
onReact,
size = 'md',
className = '',
id,
editorAttrs,
}) => {
const sizeClasses = {
sm: 'px-2 py-1 text-xs gap-1',
@@ -147,7 +156,7 @@ const PostReactions: React.FC<PostReactionsProps> = ({
};
return (
<Div className={`flex flex-wrap gap-2 ${className}`}>
<Div className={`flex flex-wrap gap-2 ${className}`} id={id} {...editorAttrs}>
{REACTION_CONFIGS.map((config) => {
const count = getReactionCount(config.type);
const isActive = userReaction === config.type;
@@ -5,7 +5,7 @@
* 다중 통화를 지원하며, 할인율 뱃지를 표시합니다.
*/
import React from 'react';
import React, { useEffect, useState } from 'react';
// @ts-ignore - DOMPurify 타입 정의 없음
import DOMPurify from 'dompurify';
@@ -16,10 +16,39 @@ import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { H3 } from '../basic/H3';
import { Img } from '../basic/Img';
import type { EditorAttrs } from '../../types';
// G7Core 전역 상태 훅
const useGlobalState = (key: string) =>
(window as any).G7Core?.state?.get?.(key);
/**
* 선호 통화를 전역 상태에서 읽고, 변경을 구독하는 훅.
*
* 회귀 배경: 종전 `G7Core.state.get('preferredCurrency')` 는 key 를 무시하고
* _global 전체 객체를 반환해(G7CoreGlobals: get: () => getGlobalState()) 통화 코드가
* 아닌 객체가 들어가 multi_currency 조회가 항상 KRW 폴백되었고, 단발 get 이라 헤더에서
* 통화를 바꿔도 카드가 리렌더되지 않았다(상품 리스트/검색/캐러셀 KRW 고정 결함).
* → 전체 객체에서 `.preferredCurrency` 키로 접근 + state.subscribe 로 리렌더한다.
*
* @returns 현재 선호 통화 코드(미설정 시 'KRW')
*/
const usePreferredCurrency = (): string => {
const read = (): string => {
const state = (window as any).G7Core?.state?.get?.();
return (state && state.preferredCurrency) || 'KRW';
};
const [currency, setCurrency] = useState<string>(read);
useEffect(() => {
const subscribe = (window as any).G7Core?.state?.subscribe;
// 구독 시점과 마운트 사이 변경분 보정
setCurrency(read());
if (typeof subscribe !== 'function') return;
const unsubscribe = subscribe((state: Record<string, any>) => {
setCurrency((state && state.preferredCurrency) || 'KRW');
});
return typeof unsubscribe === 'function' ? unsubscribe : undefined;
}, []);
return currency;
};
// G7Core.dispatch() navigate 헬퍼
const navigate = (path: string) => {
@@ -78,6 +107,14 @@ interface ProductCardProps {
shopBase?: string;
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -132,8 +169,10 @@ const ProductCard: React.FC<ProductCardProps> = ({
onClick,
shopBase = '/shop',
className = '',
id,
editorAttrs,
}) => {
const preferredCurrency = useGlobalState('preferredCurrency') || 'KRW';
const preferredCurrency = usePreferredCurrency();
/**
* 다중 통화 가격을 가져옵니다.
@@ -187,6 +226,7 @@ const ProductCard: React.FC<ProductCardProps> = ({
<Button
onClick={handleClick}
className={`block w-full text-left group bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-lg transition-shadow cursor-pointer ${className}`}
id={id} {...editorAttrs}
>
{/* 이미지 영역 */}
<Div className="relative aspect-square overflow-hidden bg-gray-100 dark:bg-gray-700">
@@ -13,6 +13,7 @@ import { Img } from '../basic/Img';
import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { ImageGallery, useImageGallery, GalleryImage } from './ImageGallery';
import type { EditorAttrs } from '../../types';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const G7Core = (window as any).G7Core;
@@ -42,6 +43,12 @@ export interface ProductImageViewerProps {
images: ProductImage[];
/** 커스텀 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
// ========== Helper ==========
@@ -58,6 +65,8 @@ const getImageSrc = (image: ProductImage): string => {
export const ProductImageViewer: React.FC<ProductImageViewerProps> = ({
images = [],
className = '',
id,
editorAttrs,
}) => {
const [selectedIndex, setSelectedIndex] = useState(0);
const { openGallery, galleryProps } = useImageGallery();
@@ -80,6 +89,7 @@ export const ProductImageViewer: React.FC<ProductImageViewerProps> = ({
return (
<Div
className={`flex items-center justify-center bg-gray-100 dark:bg-gray-700 rounded-lg aspect-square ${className}`}
id={id} {...editorAttrs}
>
<Div className="text-center text-gray-400 dark:text-gray-500">
<Icon name="image" size="3x" className="mb-3 opacity-50" />
@@ -92,7 +102,7 @@ export const ProductImageViewer: React.FC<ProductImageViewerProps> = ({
const currentImage = images[selectedIndex] ?? images[0];
return (
<Div className={className}>
<Div id={id} className={className} {...editorAttrs}>
{/* 메인 이미지 */}
<Div className="relative overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-700 aspect-square mb-3">
<Button
@@ -10,6 +10,7 @@ import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Input } from '../basic/Input';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
interface QuantitySelectorProps {
/** 현재 수량 */
@@ -26,6 +27,14 @@ interface QuantitySelectorProps {
disabled?: boolean;
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -72,6 +81,8 @@ const QuantitySelector: React.FC<QuantitySelectorProps> = ({
size = 'md',
disabled = false,
className = '',
id,
editorAttrs,
}) => {
const sizeClasses = {
sm: {
@@ -128,6 +139,7 @@ const QuantitySelector: React.FC<QuantitySelectorProps> = ({
return (
<Div
className={`inline-flex items-center border border-gray-300 dark:border-gray-600 rounded-lg ${classes.container} ${className}`}
id={id} {...editorAttrs}
>
{/* 감소 버튼 */}
<Button
@@ -21,6 +21,7 @@ import { Input } from '../basic/Input';
import { Textarea } from '../basic/Textarea';
import { H3 } from '../basic/H3';
import { Label } from '../basic/Label';
import type { EditorAttrs } from '../../types';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
@@ -43,6 +44,14 @@ interface RichTextEditorProps {
disabled?: boolean;
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
type FormatType =
@@ -96,6 +105,8 @@ const RichTextEditor: React.FC<RichTextEditorProps> = ({
minHeight = '300px',
disabled = false,
className = '',
id,
editorAttrs,
}) => {
const editorRef = useRef<HTMLDivElement>(null);
const [content, setContent] = useState(initialValue);
@@ -185,7 +196,7 @@ const RichTextEditor: React.FC<RichTextEditorProps> = ({
];
return (
<Div className={`border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden ${className}`}>
<Div className={`border border-gray-300 dark:border-gray-600 rounded-lg overflow-hidden ${className}`} id={id} {...editorAttrs}>
{/* 툴바 */}
<Div className="flex flex-wrap items-center gap-1 p-2 bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
{/* 텍스트 포맷 */}
@@ -6,6 +6,7 @@ import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
// G7Core.t() 번역 함수 참조
const t = (key: string, params?: Record<string, string | number>) =>
@@ -28,6 +29,14 @@ export interface SearchBarProps {
showSuggestions?: boolean;
className?: string;
style?: React.CSSProperties;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -72,6 +81,8 @@ export const SearchBar: React.FC<SearchBarProps> = ({
showSuggestions = false,
className = '',
style,
id,
editorAttrs,
}) => {
// props로 전달된 값이 없으면 다국어 키 사용
const resolvedPlaceholder = placeholder ?? t('common.search_placeholder');
@@ -127,7 +138,7 @@ export const SearchBar: React.FC<SearchBarProps> = ({
};
return (
<Div ref={containerRef} className={`relative ${className}`} style={style}>
<Div ref={containerRef} className={`relative ${className}`} style={style} id={id} {...editorAttrs}>
<Form onSubmit={handleSubmit} className="relative">
<Div className={`relative flex items-center ${showButton ? 'gap-2' : ''}`}>
{/* Input wrapper */}
@@ -0,0 +1,259 @@
/**
* SlotContainer.tsx
*
* 동적 슬롯에 등록된 컴포넌트들을 렌더링하는 컨테이너 컴포넌트
*
* SlotContainer는 SlotContext에서 지정된 슬롯 ID에 등록된 모든 컴포넌트를 수집하고,
* slotOrder 기준으로 정렬하여 렌더링합니다.
*
* 통짜 TSX 컴포넌트(예: Header)가 레이아웃 JSON 노드(`"slot": "..."`)로 주입된 UI를
* 떙겨 쓰는 코어 슬롯 시스템의 소비 측 컴포넌트입니다. 빈 슬롯이면 null 을 렌더하므로
* "모듈 활성 시에만 노출"이 확장 주입 인프라로 자동 충족됩니다(헤더는 주입 모듈을 모름).
*
* @module SlotContainer
*
* @example
* ```json
* {
* "type": "composite",
* "name": "SlotContainer",
* "props": {
* "slotId": "header_currency",
* "className": "flex items-center"
* }
* }
* ```
*/
import React, { useEffect, useState, useCallback } from 'react';
import { Div } from '../basic/Div';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Comp:SlotContainer')) ?? {
log: (...args: unknown[]) => console.log('[Comp:SlotContainer]', ...args),
warn: (...args: unknown[]) => console.warn('[Comp:SlotContainer]', ...args),
error: (...args: unknown[]) => console.error('[Comp:SlotContainer]', ...args),
};
/**
* 슬롯에 주입된 컴포넌트의 root id 를 컨테이너 id 로 스코프해 고유화한다.
*
* 같은 슬롯 컴포넌트가 여러 SlotContainer(예: 헤더 데스크톱/모바일)에서 렌더되면 주입
* 컴포넌트의 정적 root id 가 컨테이너마다 같은 값으로 중복 출력되어 HTML id 유일성을
* 위반한다. 컨테이너 고유 id 가 있고 컴포넌트가 root id 를 가지면 `{id}__{containerId}`
* 로 스코프한다. 둘 중 하나라도 없으면 원본 그대로(무영향).
*
* @param componentDef 주입 컴포넌트 정의
* @param containerId 이 SlotContainer 의 DOM id (없으면 스코프 안 함)
* @returns 스코프된(또는 원본) 컴포넌트 정의
*/
export function scopeSlotChildDef<T extends { id?: unknown }>(
componentDef: T,
containerId: string | undefined,
): T {
if (
containerId &&
componentDef &&
typeof componentDef.id === 'string' &&
componentDef.id.length > 0
) {
return { ...componentDef, id: `${componentDef.id}__${containerId}` };
}
return componentDef;
}
/**
* SlotContainer Props
*/
export interface SlotContainerProps {
/**
* 슬롯 ID
*
* 이 슬롯에 등록된 컴포넌트들을 렌더링합니다.
*/
slotId: string;
/**
* 컨테이너 CSS 클래스
*/
className?: string;
/**
* 빈 슬롯일 때 표시할 내용
*/
emptyContent?: React.ReactNode;
/**
* 인라인 스타일
*/
style?: React.CSSProperties;
/**
* 컴포넌트 ID (DOM id)
*/
id?: string;
/**
* 자식 컴포넌트 (children을 통한 fallback 또는 slot 컴포넌트가 아닌 정적 컨텐츠)
*/
children?: React.ReactNode;
}
/**
* SlotRegistration 타입 (SlotContext에서 정의된 것과 호환)
*/
interface SlotRegistration {
componentDef: any;
dataContext: Record<string, any>;
order: number;
parentFormContext: any;
getParentComponentContext: () => { state: Record<string, any>; setState: (updates: any) => void };
translationContext: any;
registrationKey: string;
}
/**
* SlotContext 값 타입
*/
interface SlotContextValue {
getSlotComponents: (slotId: string) => SlotRegistration[];
subscribeToSlot: (slotId: string, callback: () => void) => () => void;
isEnabled: boolean;
}
/**
* SlotContainer 컴포넌트
*
* SlotContext에서 지정된 슬롯 ID에 등록된 컴포넌트들을 수집하여 렌더링합니다.
* 컴포넌트는 slotOrder 기준으로 정렬됩니다.
*
* 이 컴포넌트는 SlotContext를 사용하므로 SlotProvider 내부에서만 동작합니다.
* SlotProvider는 DynamicRenderer의 루트에서 자동으로 래핑됩니다.
*
* @param props SlotContainerProps
*/
export const SlotContainer: React.FC<SlotContainerProps> = ({
slotId,
className = '',
emptyContent,
style,
id,
children,
}) => {
const [slotComponents, setSlotComponents] = useState<SlotRegistration[]>([]);
const [, forceUpdate] = useState({});
// SlotContext 가져오기 (window.__slotContextValue 또는 G7Core.getSlotContext() 사용)
const getSlotContext = useCallback((): SlotContextValue | null => {
const directSlotContext = (window as any).__slotContextValue;
if (directSlotContext) {
return directSlotContext;
}
const g7Core = (window as any).G7Core;
if (!g7Core) return null;
const slotContext = g7Core.getSlotContext?.();
return slotContext || null;
}, []);
// 슬롯 컴포넌트 업데이트 함수
const updateSlotComponents = useCallback(() => {
const slotContext = getSlotContext();
if (slotContext && slotContext.isEnabled) {
setSlotComponents(slotContext.getSlotComponents(slotId));
}
}, [slotId, getSlotContext]);
// 슬롯 구독 및 업데이트
useEffect(() => {
const slotContext = getSlotContext();
if (!slotContext || !slotContext.isEnabled) {
return;
}
updateSlotComponents();
const unsubscribe = slotContext.subscribeToSlot(slotId, () => {
updateSlotComponents();
forceUpdate({});
});
return unsubscribe;
}, [slotId, getSlotContext, updateSlotComponents]);
// G7Core에서 DynamicRenderer 가져오기
const getDynamicRenderer = useCallback(() => {
const g7Core = (window as any).G7Core;
if (!g7Core) return null;
return g7Core.getDynamicRenderer?.();
}, []);
// 빈 슬롯 처리
if (slotComponents.length === 0) {
if (emptyContent) {
return (
<Div className={className} style={style} id={id}>
{emptyContent}
</Div>
);
}
if (children) {
return (
<Div className={className} style={style} id={id}>
{children}
</Div>
);
}
return null;
}
const DynamicRenderer = getDynamicRenderer();
const g7Core = (window as any).G7Core;
if (!DynamicRenderer || !g7Core) {
logger.error('G7Core or DynamicRenderer not available');
return null;
}
return (
<Div className={className} style={style} id={id}>
{slotComponents.map((registration) => {
const {
componentDef,
dataContext,
parentFormContext,
getParentComponentContext,
translationContext,
} = registration;
// 같은 슬롯 컴포넌트가 여러 SlotContainer(헤더 데스크톱/모바일)에서 렌더될 때
// 주입 컴포넌트 root id 를 컨테이너 id 로 스코프해 HTML id 중복을 막는다.
const scopedDef = scopeSlotChildDef(componentDef, id);
return (
<DynamicRenderer
key={scopedDef.id || `slot-${slotId}-${registration.order}`}
componentDef={scopedDef}
dataContext={dataContext}
translationContext={translationContext}
registry={g7Core.getComponentRegistry()}
bindingEngine={g7Core.getDataBindingEngine()}
translationEngine={g7Core.getTranslationEngine()}
actionDispatcher={g7Core.getActionDispatcher()}
parentComponentContext={getParentComponentContext?.()}
parentFormContextProp={parentFormContext}
isRootRenderer={false}
/>
);
})}
{children}
</Div>
);
};
export default SlotContainer;
@@ -9,6 +9,7 @@ import React from 'react';
import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
/**
* 소셜 로그인 아이콘 SVG 컴포넌트
@@ -70,6 +71,12 @@ interface SocialLoginButtonsProps {
variant?: 'full' | 'icon';
/** 추가 CSS 클래스 */
className?: string;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
interface ProviderConfig {
@@ -144,6 +151,8 @@ const SocialLoginButtons: React.FC<SocialLoginButtonsProps> = ({
mode = 'login',
variant = 'full',
className = '',
id,
editorAttrs,
}) => {
const handleSocialLogin = (provider: SocialProvider) => {
// OAuth 인증 URL로 리다이렉트
@@ -164,7 +173,7 @@ const SocialLoginButtons: React.FC<SocialLoginButtonsProps> = ({
if (variant === 'icon') {
return (
<Div className={`flex justify-center gap-4 ${className}`}>
<Div className={`flex justify-center gap-4 ${className}`} id={id} {...editorAttrs}>
{filteredProviders.map((provider) => (
<Button
key={provider.id}
@@ -180,7 +189,7 @@ const SocialLoginButtons: React.FC<SocialLoginButtonsProps> = ({
}
return (
<Div className={`space-y-3 ${className}`}>
<Div className={`space-y-3 ${className}`} id={id} {...editorAttrs}>
{filteredProviders.map((provider) => (
<Button
key={provider.id}
@@ -6,6 +6,7 @@ import { IconName } from '../basic/IconTypes';
import { Div } from '../basic/Div';
import { Span } from '../basic/Span';
import { Select } from '../basic/Select';
import type { EditorAttrs } from '../../types';
export interface Tab {
id: string | number;
@@ -26,6 +27,14 @@ export interface TabNavigationProps {
hiddenTabIds?: (string | number)[];
/** 모바일 전환 임계값 (px). 기본값 768 — G7 ResponsiveContext mobile 프리셋과 동일 */
mobileBreakpoint?: number;
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -67,6 +76,8 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
style,
hiddenTabIds = [],
mobileBreakpoint = 768,
id,
editorAttrs,
}) => {
// G7Core.useResponsive를 통해 반응형 상태 구독 (G7 표준)
const G7Core = (window as any).G7Core;
@@ -102,9 +113,12 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
: tabs;
// 모바일: Select 드롭다운 단일 렌더
// 데스크톱 분기와 동일하게 id/editorAttrs 를 루트에 spread 해야 레이아웃 편집기가
// 모바일 디바이스 미리보기에서도 이 노드를 선택/측정할 수 있다(모든 렌더 분기 패리티 —
// 누락 시 모바일 프리뷰에서 data-editor-* 가 사라져 캔버스에서 선택 불가).
if (isMobile) {
return (
<Div className={`relative ${className}`} style={style}>
<Div className={`relative ${className}`} style={style} id={id} {...editorAttrs}>
<Select
value={activeTabId !== undefined ? String(activeTabId) : ''}
onChange={handleSelectChange}
@@ -154,7 +168,7 @@ export const TabNavigation: React.FC<TabNavigationProps> = ({
// 데스크톱: 탭 버튼 단일 렌더
return (
<Div className={`relative ${className}`} style={style}>
<Div className={`relative ${className}`} style={style} id={id} {...editorAttrs}>
<Nav className={navClasses}>
{visibleTabs.map((tab) => (
<Button
@@ -4,6 +4,7 @@ import { Button } from '../basic/Button';
import { Icon } from '../basic/Icon';
import { IconName } from '../basic/IconTypes';
import { Span } from '../basic/Span';
import type { EditorAttrs } from '../../types';
/**
* 테마 모드 타입
@@ -24,6 +25,10 @@ export interface ThemeToggleProps {
lightText?: string;
/** 다크 모드 텍스트 (다국어 키 사용 권장) */
darkText?: string;
/** DOM id 속성 (레이아웃 편집기 코어 일괄 ID) */
id?: string;
/** 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread) */
editorAttrs?: EditorAttrs;
}
/**
@@ -93,6 +98,8 @@ export const ThemeToggle: React.FC<ThemeToggleProps> = ({
autoText = 'System',
lightText = 'Light',
darkText = 'Dark',
id,
editorAttrs,
}) => {
// 초기 테마를 즉시 로드하고 적용
const initialTheme = getInitialTheme();
@@ -157,7 +164,7 @@ export const ThemeToggle: React.FC<ThemeToggleProps> = ({
};
return (
<Div ref={menuRef} className={`relative ${className}`}>
<Div ref={menuRef} className={`relative ${className}`} id={id} {...editorAttrs}>
{/* 테마 토글 버튼 */}
<Button
onClick={() => setShowMenu(!showMenu)}
@@ -45,6 +45,7 @@ import { Div } from '../basic/Div';
import { Button } from '../basic/Button';
import { Span } from '../basic/Span';
import { Icon } from '../basic/Icon';
import type { EditorAttrs } from '../../types';
// G7Core 참조
const getG7Core = () => (window as any).G7Core;
@@ -177,6 +178,15 @@ export interface UserInfoProps {
hideMenuItems?: string[];
/** 기본 메뉴에 추가할 항목 */
appendMenuItems?: MenuItemConfig[];
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
// 레이아웃별 컨테이너 클래스
@@ -234,6 +244,8 @@ export const UserInfo: React.FC<UserInfoProps> = ({
menuItems,
hideMenuItems = [],
appendMenuItems = [],
id,
editorAttrs,
}) => {
// 명시적 props > author 추출값 순서로 결정
const actualUserId = userId ?? author?.uuid;
@@ -365,7 +377,7 @@ export const UserInfo: React.FC<UserInfoProps> = ({
// 비회원인 경우
if (actualIsGuest || !actualUserId) {
return (
<Div className={containerClass}>
<Div className={containerClass} id={id} {...editorAttrs}>
<Div className="flex items-center gap-1.5 text-gray-400 dark:text-gray-500">
<Span>{actualName}</Span>
<Span className="text-xs px-1.5 py-0.5 bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded">
@@ -380,7 +392,7 @@ export const UserInfo: React.FC<UserInfoProps> = ({
// 탈퇴한 사용자인 경우
if (actualIsWithdrawn) {
return (
<Div className={containerClass}>
<Div className={containerClass} id={id} {...editorAttrs}>
<Span className="text-gray-400 dark:text-gray-500 line-through">
{actualName}
</Span>
@@ -399,7 +411,7 @@ export const UserInfo: React.FC<UserInfoProps> = ({
: `${defaultColorClass} font-medium`.trim();
return (
<Div ref={containerRef} className={`relative inline-block ${className}`}>
<Div ref={containerRef} className={`relative inline-block ${className}`} id={id} {...editorAttrs}>
<Div className={LAYOUT_CLASSES[layout]}>
<Button
ref={buttonRef}
@@ -0,0 +1,90 @@
/**
* Footer 반응형 회귀 테스트
*
* 정책: 레이아웃 편집 가능 템플릿은 G7 표준 responsive(useResponsive) 만 사용한다.
* Footer 는 Tailwind md:/lg:/sm: 미디어쿼리 대신 useResponsive().width 기반으로
* 그리드 컬럼/flex 방향을 분기해야 위지윅 프리뷰 디바이스 전환(overrideWidth)에
* 정상 반응한다. 본 테스트는 width 별 분기를 가드한다.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render } from '@testing-library/react';
import Footer from '../Footer';
function mockResponsive(width: number) {
return vi.fn(() => ({
width,
isMobile: width < 768,
isTablet: width >= 768 && width < 1024,
isDesktop: width >= 1024,
matchedPreset: (width < 768 ? 'mobile' : width < 1024 ? 'tablet' : 'desktop') as
| 'mobile'
| 'tablet'
| 'desktop',
}));
}
describe('Footer — G7 표준 responsive 분기', () => {
let originalG7Core: any;
function setWidth(width: number) {
originalG7Core = (window as any).G7Core;
(window as any).G7Core = {
...originalG7Core,
useResponsive: mockResponsive(width),
t: (k: string) => k,
};
}
afterEach(() => {
(window as any).G7Core = originalG7Core;
vi.clearAllMocks();
});
it('데스크톱(1280) — 링크 그룹 그리드 5열', () => {
setWidth(1280);
const { container } = render(<Footer />);
const grid = container.querySelector('.grid') as HTMLElement;
expect(grid).toBeTruthy();
expect(grid.style.gridTemplateColumns).toBe('repeat(5, minmax(0, 1fr))');
});
it('태블릿(820) — 그리드 2열', () => {
setWidth(820);
const { container } = render(<Footer />);
const grid = container.querySelector('.grid') as HTMLElement;
expect(grid.style.gridTemplateColumns).toBe('repeat(2, minmax(0, 1fr))');
});
it('모바일(390) — 그리드 1열 + 저작권 영역 세로(column)', () => {
setWidth(390);
const { container } = render(<Footer />);
const grid = container.querySelector('.grid') as HTMLElement;
expect(grid.style.gridTemplateColumns).toBe('repeat(1, minmax(0, 1fr))');
// 저작권 영역 flexDirection = column (모바일)
const cols = Array.from(container.querySelectorAll('div')).filter(
(d) => d.style.flexDirection === 'column'
);
expect(cols.length).toBeGreaterThan(0);
});
it('데스크톱 — 저작권 영역 flexDirection row', () => {
setWidth(1280);
const { container } = render(<Footer />);
const rows = Array.from(container.querySelectorAll('div')).filter(
(d) => d.style.flexDirection === 'row'
);
expect(rows.length).toBeGreaterThan(0);
});
it('Footer 마크업에 Tailwind 반응형 그리드 클래스(md:grid-cols / lg:grid-cols)를 사용하지 않음', () => {
setWidth(1280);
const { container } = render(<Footer />);
const html = container.innerHTML;
// 정책: 편집 가능 템플릿은 viewport 미디어쿼리 그리드/flex 분기 금지
expect(html).not.toContain('md:grid-cols');
expect(html).not.toContain('lg:grid-cols');
expect(html).not.toContain('sm:flex-row');
});
});
@@ -0,0 +1,114 @@
// e2e:allow Vitest 컴포넌트 렌더 테스트(편집기 속성→실제 Header prop 렌더 검증). 편집기 캔버스 통합은 Chrome MCP 라이브 실측으로 별도 검증.
/**
* @file HeaderPropRender.test.tsx
* @description 실제 Header 컴포넌트 prop 렌더링 검증.
*
* 기존 Header.test.tsx 는 MockHeader(가짜)로 구조만 본다. 본 스위트는 실제 Header.tsx 를
* 렌더해 editor-spec 으로 노출한 핵심 prop(siteName / logo / maxVisibleBoards / shopBase /
* availableLocales / currentLocale)이 실제 출력 DOM·동작에 반영됨을 검증한다.
*
* 데스크톱 폭으로 useResponsive 를 모킹해 데스크톱 헤더 분기(검색바·언어 선택기·게시판 탭)를
* 렌더한다.
*
* @vitest-environment jsdom
*/
import React from 'react';
import { render, screen, within } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import Header from '../Header';
const navigate = vi.fn();
beforeEach(() => {
(window as any).G7Core = {
t: (key: string, params?: Record<string, unknown>) => {
const map: Record<string, string> = {
'common.search_placeholder': '검색어를 입력하세요...',
'common.language': '언어',
};
return map[key] ?? key;
},
// 데스크톱 폭 — 검색바/언어선택기/게시판 탭 데스크톱 분기 렌더
useResponsive: () => ({ width: 1280, breakpoint: 'desktop' }),
dispatch: vi.fn((action: any) => {
if (action?.handler === 'navigate') navigate(action?.params?.path);
}),
state: { getLocal: () => ({}), getGlobal: () => ({}) },
getSlotContext: () => ({
getSlotComponents: () => [],
subscribeToSlot: () => () => {},
isEnabled: true,
}),
};
(window as any).__slotContextValue = (window as any).G7Core.getSlotContext();
});
afterEach(() => {
vi.clearAllMocks();
delete (window as any).G7Core;
delete (window as any).__slotContextValue;
});
const boards = [
{ id: 1, table_id: 'free', subject: '자유게시판', name: '자유게시판' },
{ id: 2, table_id: 'qa', subject: '질문답변', name: '질문답변' },
{ id: 3, table_id: 'notice', subject: '공지사항', name: '공지사항' },
{ id: 4, table_id: 'review', subject: '후기', name: '후기' },
];
describe('Header prop 렌더링 — 편집기 속성이 사용자 화면에 반영', () => {
it('siteName prop 이 로고 영역 텍스트로 렌더된다 (logo 없을 때)', () => {
render(<Header siteName="우리 사이트" availableLocales={['ko', 'en']} currentLocale="ko" />);
expect(screen.getByText('우리 사이트')).toBeInTheDocument();
});
it('logo prop 이 있으면 img 의 src/alt 로 렌더된다', () => {
render(
<Header siteName="우리 사이트" logo="/custom-logo.png" availableLocales={['ko', 'en']} currentLocale="ko" />,
);
const img = screen.getByAltText('우리 사이트') as HTMLImageElement;
expect(img).toBeInTheDocument();
expect(img.getAttribute('src')).toBe('/custom-logo.png');
});
it('maxVisibleBoards prop 이 탭에 표시되는 게시판 수를 제한한다', () => {
const { container } = render(
<Header
siteName="S"
boards={boards as any}
maxVisibleBoards={2}
availableLocales={['ko', 'en']}
currentLocale="ko"
/>,
);
// 처음 2개 게시판은 탭으로 노출, 나머지는 "더보기" 뒤로 숨김
const nav = container.querySelector('nav');
expect(nav).not.toBeNull();
const navText = nav!.textContent ?? '';
expect(navText).toContain('자유게시판');
expect(navText).toContain('질문답변');
});
it('availableLocales 가 2개 이상이면 언어 선택기(현재 로케일 코드)가 렌더된다', () => {
render(<Header siteName="S" availableLocales={['ko', 'en']} currentLocale="en" />);
// 현재 로케일 코드가 uppercase 로 트리거에 표시
expect(screen.getByText('en')).toBeInTheDocument();
});
it('availableLocales 가 1개 이하이면 언어 선택기가 렌더되지 않는다', () => {
const { container } = render(<Header siteName="S" availableLocales={['ko']} currentLocale="ko" />);
// globe 아이콘(언어 트리거)이 없어야 함
const langTrigger = container.querySelector('[aria-label="언어"]');
expect(langTrigger).toBeNull();
});
it('header_currency 슬롯 컨테이너가 렌더된다 (모듈 통화 셀렉터 주입 지점)', () => {
// SlotContainer 는 빈 슬롯이면 null 이지만, 컴포넌트가 마운트되어 슬롯을 구독해야 한다.
// 슬롯 등록분이 생기면 즉시 렌더되도록 SlotContext 구독이 성립함을 보장(번들 포함 회귀 차단은
// headerEditorSpecAndCurrencySlot.test 가 담당). 여기서는 렌더가 throw 없이 완료됨을 확인.
expect(() =>
render(<Header siteName="S" availableLocales={['ko', 'en']} currentLocale="ko" />),
).not.toThrow();
});
});
@@ -0,0 +1,83 @@
/**
* ImageGallery 편집 모드 placeholder 회귀 테스트
*
* ImageGallery 는 서드파티 Lightbox 모달(isOpen=false 시 DOM 미렌더)이라 편집기
* 캔버스에서 선택·편집이 불가능했다(6 propControl 도달 불가). 편집 모드(editorAttrs
* 주입) 에서는 인라인 placeholder(썸네일 그리드)를 대신 렌더해 editorAttrs·id 를
* 부착하도록 보강했다. 본 테스트는 그 동작을 잠근다.
*/
import React from 'react';
import { render } from '@testing-library/react';
import { describe, it, expect, beforeEach } from 'vitest';
import { ImageGallery } from '../ImageGallery';
// G7Core.t mock (편집 모드 placeholder 라벨 + basic 컴포넌트 의존)
beforeEach(() => {
(window as any).G7Core = {
t: (key: string) => key,
};
});
const editorAttrs = {
'data-editor-id': 'auto_ImageGallery_test',
'data-editor-name': 'ImageGallery',
'data-editor-type': 'composite',
'data-editor-path': '3',
} as Record<string, string>;
const sampleImages = [
{ src: 'https://example.com/a.jpg', title: '이미지 A' },
{ src: 'https://example.com/b.jpg', title: '이미지 B', thumbnail: 'https://example.com/b-thumb.jpg' },
];
describe('ImageGallery 편집 모드 placeholder', () => {
it('editorAttrs 주입 시 인라인 placeholder 루트에 editorAttrs 와 id 가 부착된다', () => {
const { container } = render(
<ImageGallery
images={sampleImages}
isOpen={false}
onClose={() => {}}
id="ig-edit"
editorAttrs={editorAttrs}
/>
);
const node = container.querySelector('[data-editor-name="ImageGallery"]');
expect(node, '편집 모드에서 인라인 placeholder 가 렌더되어야 함').not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ig-edit');
});
it('editorAttrs 주입 시 이미지 썸네일이 placeholder 에 렌더된다 (썸네일 우선)', () => {
const { container } = render(
<ImageGallery
images={sampleImages}
isOpen={false}
onClose={() => {}}
editorAttrs={editorAttrs}
/>
);
const imgs = container.querySelectorAll('img');
expect(imgs.length).toBe(2);
// 두 번째 이미지는 thumbnail 우선
expect(imgs[1]).toHaveAttribute('src', 'https://example.com/b-thumb.jpg');
});
it('이미지가 없으면 placeholder 안내 라벨을 렌더한다', () => {
const { container } = render(
<ImageGallery images={[]} isOpen={false} onClose={() => {}} editorAttrs={editorAttrs} />
);
const node = container.querySelector('[data-editor-name="ImageGallery"]');
expect(node).not.toBeNull();
expect(node?.textContent).toContain('editor.component.image_gallery');
});
it('editorAttrs 미주입(런타임)이면 인라인 placeholder 를 렌더하지 않는다', () => {
const { container } = render(
<ImageGallery images={sampleImages} isOpen={false} onClose={() => {}} />
);
// 런타임 경로 — placeholder div(data-editor-name) 가 없어야 함
const node = container.querySelector('[data-editor-name="ImageGallery"]');
expect(node).toBeNull();
});
});
@@ -5,7 +5,7 @@
*/
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { render, screen, fireEvent, act } from '@testing-library/react';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import ProductCard from '../ProductCard';
@@ -471,6 +471,119 @@ describe('ProductCard 컴포넌트', () => {
});
});
describe('다중 통화 표시 (선택 통화 환산)', () => {
const multiCurrencyProduct = {
id: 7,
name_localized: '면 손수건',
thumbnail_url: '/img/handkerchief.jpg',
selling_price: 3000,
selling_price_formatted: '3,000원',
list_price: 5000,
list_price_formatted: '5,000원',
discount_rate: 40,
multi_currency_selling_price: {
KRW: { value: 3000, formatted: '3,000원' },
USD: { value: 2.55, formatted: '$2.55' },
JPY: { value: 345, formatted: '¥345' },
},
multi_currency_list_price: {
KRW: { value: 5000, formatted: '5,000원' },
USD: { value: 4.25, formatted: '$4.25' },
JPY: { value: 575, formatted: '¥575' },
},
};
/**
* 실 환경처럼 G7Core.state.get() 은 인자(key)를 무시하고 _global 전체 객체를 반환한다.
* (G7CoreGlobals.ts: get: () => templateApp.getGlobalState())
* ProductCard 가 키 접근/구독을 올바로 하지 않으면 이 mock 에서 KRW 폴백으로 회귀한다.
*/
const installGlobalState = (preferredCurrency: string) => {
const listeners: Array<(s: any) => void> = [];
const state = { preferredCurrency };
(window as any).__templateApp = {
getGlobalState: () => state,
onGlobalStateChange: (l: (s: any) => void) => {
listeners.push(l);
return () => {
const i = listeners.indexOf(l);
if (i >= 0) listeners.splice(i, 1);
};
},
};
(window as any).G7Core = {
...mockG7Core,
state: {
get: () => state, // key 무시, 전체 객체 반환 (실 동작)
set: (updates: Record<string, any>) => {
Object.assign(state, updates);
listeners.forEach((l) => l(state));
},
subscribe: (l: (s: any) => void) => {
listeners.push(l);
return () => {
const i = listeners.indexOf(l);
if (i >= 0) listeners.splice(i, 1);
};
},
},
};
};
it('USD 선택 시 판매가/정가가 USD 로 표시되어야 함 (KRW 고정 회귀 차단)', () => {
installGlobalState('USD');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('$2.55')).toBeInTheDocument();
expect(screen.getByText('$4.25')).toBeInTheDocument();
expect(screen.queryByText('3,000원')).not.toBeInTheDocument();
expect(screen.queryByText('5,000원')).not.toBeInTheDocument();
});
it('JPY 선택 시 JPY 로 표시되어야 함', () => {
installGlobalState('JPY');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('¥345')).toBeInTheDocument();
expect(screen.getByText('¥575')).toBeInTheDocument();
});
it('KRW(기본) 선택 시 KRW 로 표시되어야 함', () => {
installGlobalState('KRW');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('3,000원')).toBeInTheDocument();
expect(screen.getByText('5,000원')).toBeInTheDocument();
});
it('통화를 USD 로 변경하면 리렌더되어 USD 로 갱신되어야 함 (반응성 회귀 차단)', async () => {
installGlobalState('KRW');
render(<ProductCard product={multiCurrencyProduct} />);
expect(screen.getByText('3,000원')).toBeInTheDocument();
// 헤더에서 통화 변경 → 전역 상태 갱신 (set 이 구독자에게 통지)
await act(async () => {
(window as any).G7Core.state.set({ preferredCurrency: 'USD' });
});
expect(screen.getByText('$2.55')).toBeInTheDocument();
expect(screen.queryByText('3,000원')).not.toBeInTheDocument();
});
it('multi_currency 데이터가 없으면 기본 포맷(_formatted)으로 폴백해야 함', () => {
installGlobalState('USD');
render(
<ProductCard
product={{
id: 8,
name_localized: '단순 상품',
thumbnail_url: '/img/x.jpg',
selling_price: 10000,
selling_price_formatted: '10,000원',
}}
/>
);
expect(screen.getByText('10,000원')).toBeInTheDocument();
});
});
describe('검색 하이라이트', () => {
const highlightedProduct: Product = {
...mockProduct,
@@ -210,6 +210,30 @@ describe('TabNavigation 컴포넌트', () => {
expect(trigger).toBeInTheDocument();
});
// 회귀: 모바일 분기 루트에도 id/editorAttrs 가
// spread 되어야 레이아웃 편집기가 모바일 디바이스 미리보기에서 이 노드를 선택/측정할 수
// 있다. 종전 모바일 분기는 데스크톱 분기와 달리 id/editorAttrs 누락 → 모바일 프리뷰에서
// data-editor-* 가 사라져 캔버스 선택 불가(모든 렌더 분기 editorAttrs 패리티 규율).
it('모바일 분기 루트에도 id/editorAttrs(data-editor-*)가 spread 되어야 함', () => {
const { container } = render(
<TabNavigation
tabs={defaultTabs}
activeTabId="detail"
id="mypageTabNavigation"
editorAttrs={{
'data-editor-path': '2.children.1',
'data-editor-name': 'TabNavigation',
'data-editor-type': 'composite',
} as any}
/>
);
const root = container.firstElementChild as HTMLElement;
expect(root).toBeTruthy();
expect(root.id).toBe('mypageTabNavigation');
expect(root.getAttribute('data-editor-path')).toBe('2.children.1');
expect(root.getAttribute('data-editor-name')).toBe('TabNavigation');
});
it('현재 활성 탭의 label을 Select trigger에 표시해야 함', () => {
render(<TabNavigation tabs={defaultTabs} activeTabId="detail" />);
@@ -422,3 +422,55 @@ describe('UserInfo 드롭다운 위치 (fixed 배치)', () => {
expect(screen.queryByTestId('author-dropdown-menu')).not.toBeInTheDocument();
});
});
// #1 회귀: UserInfo 의 비회원/탈퇴 분기 렌더가
// editorAttrs(data-editor-*) 와 id 를 루트에 전달해야 한다. 누락 시 레이아웃 편집기에서
// isGuest/isWithdrawn 상태의 UserInfo 가 캔버스에서 선택·편집 불가(데이터 결정 노드처럼
// data-editor-name 미부착). 회원 분기는 이미 전달하므로 세 분기 모두 패리티를 보장한다.
describe('UserInfo 편집기 패스스루 (editorAttrs/id) — 전 분기 패리티', () => {
const editorAttrs = {
'data-editor-id': 'auto_UserInfo_test',
'data-editor-name': 'UserInfo',
'data-editor-type': 'composite',
'data-editor-path': '3',
} as Record<string, string>;
it('비회원 분기 루트에 editorAttrs 와 id 가 전달되어야 함', () => {
const { container } = render(
<UserInfo name="익명" isGuest id="ui-guest" editorAttrs={editorAttrs} />
);
const node = container.querySelector('[data-editor-name="UserInfo"]');
expect(node).not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ui-guest');
});
it('탈퇴 회원 분기 루트에 editorAttrs 와 id 가 전달되어야 함', () => {
const { container } = render(
<UserInfo
author={{ id: 1, uuid: 'u1', name: '탈퇴자', status: 'withdrawn' }}
isWithdrawn
id="ui-withdrawn"
editorAttrs={editorAttrs}
/>
);
const node = container.querySelector('[data-editor-name="UserInfo"]');
expect(node).not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ui-withdrawn');
});
it('회원 분기 루트에도 editorAttrs 와 id 가 전달되어야 함 (패리티 기준)', () => {
const { container } = render(
<UserInfo
author={{ id: 1, uuid: 'u1', name: '홍길동' }}
id="ui-member"
editorAttrs={editorAttrs}
/>
);
const node = container.querySelector('[data-editor-name="UserInfo"]');
expect(node).not.toBeNull();
expect(node).toHaveAttribute('data-editor-path', '3');
expect(node).toHaveAttribute('id', 'ui-member');
});
});
@@ -1,3 +1,4 @@
// e2e:allow 편집기 ComponentRegistry 등록맵에 SlotContainer 추가(편집기 IIFE 번들 포함 — 헤더 통화 슬롯 렌더). 편집기 캔버스 렌더는 Chrome MCP 라이브 실측 + Vitest 로 검증. 사용자 사이트 런타임 무변경.
/**
* sirsoft-basic 템플릿 Composite 컴포넌트 등록
*
@@ -44,6 +45,7 @@ export { AvatarUploader } from './AvatarUploader';
export { UserInfo } from './UserInfo';
export { Modal } from './Modal';
export { TabNavigation } from './TabNavigation';
export { SlotContainer } from './SlotContainer';
// AddressSearch는 별도 컴포넌트가 아닌 sirsoft-daum_postcode 플러그인의 extension_point 방식 사용
/**
@@ -65,6 +67,10 @@ export const compositeComponents = {
Header: () => import('./Header'),
Footer: () => import('./Footer'),
MobileNav: () => import('./MobileNav'),
// 슬롯 컨테이너 — 모듈 주입 UI(헤더 통화 셀렉터 등)를 떙겨 렌더. 등록맵 누락 시
// 편집기 캔버스 IIFE 번들에 포함되지 않아 "Component not found in bundle" 로 렌더 실패한다
// (운영 사이트는 별도 등록 경로라 정상이나 편집기 미리보기에서만 슬롯이 통째로 비는 회귀).
SlotContainer: () => import('./SlotContainer'),
NotificationCenter: () => import('./NotificationCenter'),
// 상품
@@ -1,5 +1,6 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface ContainerProps {
/**
@@ -21,6 +22,11 @@ export interface ContainerProps {
* 자식 요소
*/
children?: React.ReactNode;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -33,9 +39,10 @@ export const Container: React.FC<ContainerProps> = ({
className,
style,
children,
editorAttrs,
}) => {
return (
<Div id={id} className={className} style={style}>
<Div id={id} className={className} style={style} {...editorAttrs}>
{children}
</Div>
);
@@ -1,7 +1,13 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface FlexProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* Flex 방향
*/
@@ -56,6 +62,11 @@ export interface FlexProps {
* 클릭 이벤트 핸들러
*/
onClick?: () => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -79,6 +90,7 @@ export interface FlexProps {
* </Flex>
*/
export const Flex: React.FC<FlexProps> = ({
id,
children,
direction = 'row',
justify = 'start',
@@ -90,6 +102,7 @@ export const Flex: React.FC<FlexProps> = ({
className = '',
style,
onClick,
editorAttrs,
}) => {
// Tailwind CSS 클래스 생성
const classes: string[] = ['flex'];
@@ -159,7 +172,7 @@ export const Flex: React.FC<FlexProps> = ({
}
return (
<Div className={classes.join(' ')} style={style} onClick={onClick}>
<Div id={id} className={classes.join(' ')} style={style} onClick={onClick} {...editorAttrs}>
{children}
</Div>
);
@@ -1,7 +1,13 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface GridProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* Grid 열 개수
*/
@@ -67,6 +73,11 @@ export interface GridProps {
* 클릭 이벤트 핸들러
*/
onClick?: () => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -95,6 +106,7 @@ export interface GridProps {
* </Grid>
*/
export const Grid: React.FC<GridProps> = ({
id,
children,
cols = 1,
responsive,
@@ -107,6 +119,7 @@ export const Grid: React.FC<GridProps> = ({
className = '',
style,
onClick,
editorAttrs,
}) => {
// Tailwind CSS 클래스 생성
const classes: string[] = ['grid'];
@@ -178,7 +191,7 @@ export const Grid: React.FC<GridProps> = ({
}
return (
<Div className={classes.join(' ')} style={style} onClick={onClick}>
<Div id={id} className={classes.join(' ')} style={style} onClick={onClick} {...editorAttrs}>
{children}
</Div>
);
@@ -3,8 +3,14 @@ import { Section as BaseSection } from '../basic/Section';
import { Div } from '../basic/Div';
import { H2 } from '../basic/H2';
import { P } from '../basic/P';
import type { EditorAttrs } from '../../types';
export interface SectionLayoutProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 섹션 제목
*/
@@ -69,6 +75,11 @@ export interface SectionLayoutProps {
* 클릭 이벤트 핸들러
*/
onClick?: () => void;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -95,6 +106,7 @@ export interface SectionLayoutProps {
* </Section>
*/
export const SectionLayout: React.FC<SectionLayoutProps> = ({
id,
title,
subtitle,
children,
@@ -108,6 +120,7 @@ export const SectionLayout: React.FC<SectionLayoutProps> = ({
className = '',
style,
onClick,
editorAttrs,
}) => {
// Tailwind CSS 클래스 생성
const classes: string[] = [];
@@ -183,7 +196,7 @@ export const SectionLayout: React.FC<SectionLayoutProps> = ({
}
return (
<BaseSection className={classes.join(' ')} style={style} onClick={onClick}>
<BaseSection id={id} className={classes.join(' ')} style={style} onClick={onClick} {...editorAttrs}>
{/* 제목 영역 */}
{(title || subtitle) && (
<Div className="mb-4">
@@ -1,7 +1,13 @@
import React from 'react';
import { Div } from '../basic/Div';
import type { EditorAttrs } from '../../types';
export interface ThreeColumnLayoutProps {
/**
* DOM id 속성 (레이아웃 편집기 코어 일괄 ID)
*/
id?: string;
/**
* 왼쪽 영역 너비
*/
@@ -36,6 +42,11 @@ export interface ThreeColumnLayoutProps {
* 인라인 스타일
*/
style?: React.CSSProperties;
/**
* 레이아웃 편집기 주입 속성 (편집 모드 전용, 루트에 spread)
*/
editorAttrs?: EditorAttrs;
}
/**
@@ -54,6 +65,7 @@ export interface ThreeColumnLayoutProps {
* />
*/
export const ThreeColumnLayout: React.FC<ThreeColumnLayoutProps> = ({
id,
leftWidth = '250px',
rightWidth = '300px',
leftSlot,
@@ -61,6 +73,7 @@ export const ThreeColumnLayout: React.FC<ThreeColumnLayoutProps> = ({
rightSlot,
className = '',
style,
editorAttrs,
}) => {
// 컨테이너 스타일
const containerClasses = `flex flex-row w-full h-full ${className}`.trim();
@@ -84,7 +97,7 @@ export const ThreeColumnLayout: React.FC<ThreeColumnLayoutProps> = ({
};
return (
<Div className={containerClasses} style={style}>
<Div id={id} className={containerClasses} style={style} {...editorAttrs}>
{/* 왼쪽 영역 */}
<Div className="flex flex-col" style={leftStyle}>
{leftSlot}
@@ -0,0 +1,90 @@
/**
* @file downloadAttachment.test.ts
* @description 게시판 첨부 다운로드 핸들러 단위 검증 (이슈 #413 item 58b)
*
* 배경: 기존 다운로드는 레이아웃의 <a href="{{download_url}}"> 브라우저 직접 링크(GET)였다.
* G7 은 Sanctum 토큰 전용 인증인데 <a> 네비게이션에는 토큰이 실리지 않아
* optional.sanctum 라우트가 guest 로 통과 → 활동이력 행위자(user_id)가 NULL 로 남았다.
*
* 이 핸들러는 ImageGallery.downloadAuthenticatedFile 패턴을 재사용해
* G7Core.api.get(url, { responseType: 'blob' }) 로 토큰을 동반한 요청을 보낸다.
* 핵심은 "코어 ApiClient(api.get)를 통해 요청해야 토큰이 실린다" 이므로
* 실제 호출 인자를 단언한다(거짓 통과 방지).
*
* @scenario card=user_post
* @effects download_via_api_client_with_token,filename_preserved,download_failure_shows_error_toast
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { downloadAttachmentHandler } from '../downloadAttachment';
describe('downloadAttachmentHandler — 토큰 동반 첨부 다운로드 (이슈 #413 item 58b)', () => {
let apiGetSpy: ReturnType<typeof vi.fn>;
let createObjectURLSpy: ReturnType<typeof vi.fn>;
let revokeObjectURLSpy: ReturnType<typeof vi.fn>;
let clickSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
apiGetSpy = vi.fn().mockResolvedValue(new Blob(['file-content']));
(window as any).G7Core = {
api: { get: apiGetSpy },
toast: { error: vi.fn() },
createLogger: () => ({ log: vi.fn(), warn: vi.fn(), error: vi.fn() }),
};
createObjectURLSpy = vi.fn().mockReturnValue('blob:mock-object-url');
revokeObjectURLSpy = vi.fn();
(URL as any).createObjectURL = createObjectURLSpy;
(URL as any).revokeObjectURL = revokeObjectURLSpy;
// <a> 클릭이 jsdom 에서 네비게이션을 시도하지 않도록 click 만 가로챈다.
clickSpy = vi.fn();
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(clickSpy);
});
afterEach(() => {
delete (window as any).G7Core;
vi.restoreAllMocks();
});
it('코어 ApiClient(api.get)로 responseType:blob 요청을 보낸다 (토큰 경로 보장)', async () => {
await downloadAttachmentHandler({
params: {
url: '/api/modules/sirsoft-board/boards/notice/attachment/abc123',
filename: '보고서.pdf',
},
});
expect(apiGetSpy).toHaveBeenCalledTimes(1);
expect(apiGetSpy).toHaveBeenCalledWith(
'/api/modules/sirsoft-board/boards/notice/attachment/abc123',
{ responseType: 'blob' },
);
});
it('받은 blob 을 objectURL 로 변환해 filename 으로 다운로드하고 revoke 한다', async () => {
await downloadAttachmentHandler({
params: { url: '/d/x', filename: '보고서.pdf' },
});
expect(createObjectURLSpy).toHaveBeenCalledTimes(1);
expect(clickSpy).toHaveBeenCalledTimes(1);
expect(revokeObjectURLSpy).toHaveBeenCalledWith('blob:mock-object-url');
});
it('url 이 없으면 api 호출 없이 조용히 반환한다', async () => {
await downloadAttachmentHandler({ params: { filename: 'x.pdf' } });
expect(apiGetSpy).not.toHaveBeenCalled();
});
it('다운로드 실패 시 throw 하지 않고 에러 토스트를 띄운다', async () => {
apiGetSpy.mockRejectedValueOnce(new Error('network'));
await expect(
downloadAttachmentHandler({ params: { url: '/d/x', filename: 'x.pdf' } }),
).resolves.toBeUndefined();
expect((window as any).G7Core.toast.error).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,164 @@
/**
* @file identityLauncher.test.ts
* @description sirsoft-basic IDV launcher 의 인증 대상(target) 결정 로직 테스트.
*
* launcher 는 흐름별 폼 경로 하드코딩을 폐기하고, 다음 우선순위로 target 을 결정한다:
* 1. payload.target (흐름이 apiCall identity_target 으로 선언 — 범용 진입점)
* 2. 로그인 사용자 세션 (currentUser / user / auth.user 의 email·phone)
* 3. (하위호환) signup/password_reset 폼
*
* 검증 방식: launcher 가 startChallenge 의 fetch 로 challenge 를 시작할 때
* body.target 에 어떤 값이 실리는지 단언한다.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { sirsoftBasicIdentityLauncher } from '../identityLauncher';
type Target = { email?: string; phone?: string };
/** challenge 시작 fetch 에 실린 body 를 캡처. */
let lastChallengeBody: any = null;
/** challenge 시작 fetch 에 실린 headers 를 캡처. */
let lastChallengeHeaders: Record<string, string> | null = null;
const mockFetch = vi.fn(async (_url: string, init?: RequestInit) => {
lastChallengeBody = init?.body ? JSON.parse(init.body as string) : null;
lastChallengeHeaders = (init?.headers as Record<string, string>) ?? null;
return {
ok: true,
status: 200,
json: async () => ({
success: true,
data: {
id: 'ch_1',
expires_at: new Date(Date.now() + 300000).toISOString(),
render_hint: 'text_code',
max_attempts: 5,
},
}),
} as any;
});
/** launcher 가 openModal 후 deferred 를 await 하므로, 즉시 cancelled 로 resolve 해 hang 방지. */
const makeG7Core = (state: Record<string, any>) => ({
dispatch: vi.fn(async () => undefined),
state: {
get: vi.fn(() => state),
getGlobal: vi.fn(() => state),
getLocal: vi.fn(() => state._local ?? {}),
set: vi.fn(),
subscribe: vi.fn(() => () => undefined),
},
api: { getToken: vi.fn(() => null) },
identity: {
createDeferred: vi.fn(() => Promise.resolve({ status: 'cancelled' })),
redirectExternally: vi.fn(() => Promise.resolve({ status: 'cancelled' })),
},
createLogger: vi.fn(() => ({ log: vi.fn(), warn: vi.fn(), error: vi.fn() })),
});
const basePayload = {
policy_key: 'sirsoft-ecommerce.payment.confirm',
purpose: 'sensitive_action',
provider_id: 'g7:core.mail',
render_hint: 'text_code',
return_request: { method: 'POST', url: '/api/orders' },
};
/** challenge body.target 추출 헬퍼. */
const sentTarget = (): Target | undefined => lastChallengeBody?.target;
beforeEach(() => {
lastChallengeBody = null;
lastChallengeHeaders = null;
mockFetch.mockClear();
vi.stubGlobal('fetch', mockFetch);
window.localStorage.clear();
});
afterEach(() => {
vi.unstubAllGlobals();
delete (window as any).G7Core;
window.localStorage.clear();
});
describe('sirsoftBasicIdentityLauncher — challenge 요청 로케일 헤더', () => {
it('g7_locale 을 Accept-Language 헤더로 부착한다 (IDV 메일이 화면 언어를 따르도록)', async () => {
window.localStorage.setItem('g7_locale', 'ko');
(window as any).G7Core = makeG7Core({ _local: {} });
await sirsoftBasicIdentityLauncher({
...basePayload,
target: { email: 'guest@example.com' },
} as any);
expect(lastChallengeHeaders?.['Accept-Language']).toBe('ko');
});
it('g7_locale 미설정 시 Accept-Language 를 부착하지 않는다 (브라우저 기본/서버 폴백)', async () => {
(window as any).G7Core = makeG7Core({ _local: {} });
await sirsoftBasicIdentityLauncher({
...basePayload,
target: { email: 'guest@example.com' },
} as any);
expect(lastChallengeHeaders?.['Accept-Language']).toBeUndefined();
});
});
describe('sirsoftBasicIdentityLauncher — resolveTarget 우선순위', () => {
it('payload.target(흐름 선언값) 을 1순위로 challenge body 에 동봉한다 (email + phone)', async () => {
(window as any).G7Core = makeG7Core({ _local: {} });
await sirsoftBasicIdentityLauncher({
...basePayload,
target: { email: 'guest@example.com', phone: '01012345678' },
} as any);
expect(sentTarget()).toEqual({ email: 'guest@example.com', phone: '01012345678' });
});
it('payload.target 에 phone 만 있으면 email 은 하위 단계(세션)에서 보충한다', async () => {
(window as any).G7Core = makeG7Core({
currentUser: { email: 'member@example.com' },
_local: {},
});
await sirsoftBasicIdentityLauncher({
...basePayload,
target: { phone: '01099998888' },
} as any);
expect(sentTarget()).toEqual({ email: 'member@example.com', phone: '01099998888' });
});
it('선언값 없으면 로그인 사용자(currentUser) email·phone 으로 도출한다', async () => {
(window as any).G7Core = makeG7Core({
currentUser: { email: 'member@example.com', phone: '01055556666' },
_local: {},
});
await sirsoftBasicIdentityLauncher({ ...basePayload } as any);
expect(sentTarget()).toEqual({ email: 'member@example.com', phone: '01055556666' });
});
it('선언값·세션 없으면 signup 폼 email 로 하위호환 도출한다', async () => {
(window as any).G7Core = makeG7Core({
_local: { registerForm: { email: 'newuser@example.com' } },
});
await sirsoftBasicIdentityLauncher({ ...basePayload, purpose: 'signup' } as any);
expect(sentTarget()).toEqual({ email: 'newuser@example.com' });
});
it('선언값·세션·폼 모두 없으면 target 을 동봉하지 않는다 (서버 세션 도출)', async () => {
(window as any).G7Core = makeG7Core({ _local: {} });
await sirsoftBasicIdentityLauncher({ ...basePayload } as any);
expect(sentTarget()).toBeUndefined();
});
});
@@ -0,0 +1,420 @@
/**
* @file productOptionsAdditional.test.ts
* @description 상품 추가옵션(유료 옵션) 핸들러 테스트
*
* 검증 대상:
* - addSelectedItemIfCompleteHandler: 블럭 생성 시 기본 추가옵션(is_default) 자동 적용 + 추가금 반영 소계
* - setBlockAdditionalOptionHandler: 블럭별 추가옵션 선택/해제 + 추가금×수량 재계산 + 다통화 환산
* - updateSelectedItemQuantityHandler: 추가옵션 포함 단가 × 수량
* - toAdditionalOptionSelectionsPayload: 백엔드 입력 형식 변환
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import {
addSelectedItemIfCompleteHandler,
setBlockAdditionalOptionHandler,
updateSelectedItemQuantityHandler,
toAdditionalOptionSelectionsPayload,
} from '../productOptions';
// G7Core mock (토스트 등)
beforeEach(() => {
(window as any).G7Core = {
toast: { warning: vi.fn() },
t: (k: string) => k,
};
});
const optionGroups = [
{ name: '색상', name_localized: '색상', values: ['블랙'], values_localized: ['블랙'] },
];
const options = [
{
id: 10,
option_code: 'C-BLACK',
option_values: [{ key: '색상', value: '블랙' }],
option_values_localized: { 색상: '블랙' },
option_name: '블랙',
option_name_localized: '블랙',
price_adjustment: 0,
selling_price: 10000,
selling_price_formatted: '10,000원',
list_price: 10000,
list_price_formatted: '10,000원',
multi_currency_selling_price: {
KRW: { value: 10000, formatted: '₩10,000' },
USD: { value: 10, formatted: '$10.00' },
},
stock_quantity: 99,
is_active: true,
},
];
const additionalOptionGroups = [
{
id: 1,
name: '각인',
is_required: true,
values: [
{ id: 100, name: '없음', price_adjustment: 0, is_default: true },
{ id: 101, name: '각인 추가', price_adjustment: 5000, is_default: false, allow_custom_text: true },
],
},
{
id: 2,
name: '포장',
is_required: false,
values: [{ id: 200, name: '선물포장', price_adjustment: 2000, is_default: false }],
},
];
function captureSetState() {
const calls: any[] = [];
return {
setState: (u: any) => calls.push(u),
get last() {
return calls[calls.length - 1];
},
calls,
};
}
describe('addSelectedItemIfCompleteHandler — 추가옵션 기본 적용', () => {
it('블럭 생성 시 is_default 선택지를 자동 적용한다 (각인=없음, 추가금 0)', () => {
const ctx = captureSetState();
addSelectedItemIfCompleteHandler(
{
handler: 'x',
params: {
productId: 1,
optionGroups,
options,
currentSelection: {},
selectedOptionItems: [],
preferredCurrency: 'KRW',
additionalOptionGroups,
newGroupName: '색상',
newValue: '블랙',
},
} as any,
ctx as any
);
const item = ctx.last.selectedOptionItems[0];
expect(item.additionalOptionSelections).toEqual({ 1: 100 });
expect(item.additionalOptionsTotal).toBe(0);
// 옵션가 10000 + 추가금 0 = 10000
expect(item.totalPrice).toBe(10000);
});
// 비필수 그룹은 is_default 선택지가 있어도 자동 선택하지 않는다 ("선택하세요" 유지).
// 관리자 추가옵션 선택지는 라디오라 그룹당 1개가 항상 is_default 로 시드되므로,
// 비필수까지 자동 적용하면 원치 않은 선택/추가금이 강제로 붙는 회귀가 발생한다.
it('비필수 그룹은 is_default 선택지가 있어도 자동 선택하지 않는다', () => {
const groupsWithDefaultOnOptional = [
{
id: 1,
name: '각인',
is_required: true,
values: [
{ id: 100, name: '없음', price_adjustment: 0, is_default: true },
{ id: 101, name: '각인 추가', price_adjustment: 5000, is_default: false },
],
},
{
id: 2,
name: '포장',
is_required: false,
// 첫 선택지가 is_default=true (관리자 폼 시드 패턴) — 그래도 미선택 유지되어야 함
values: [
{ id: 200, name: '기본포장', price_adjustment: 0, is_default: true },
{ id: 201, name: '선물포장', price_adjustment: 2000, is_default: false },
],
},
];
const ctx = captureSetState();
addSelectedItemIfCompleteHandler(
{
handler: 'x',
params: {
productId: 1,
optionGroups,
options,
currentSelection: {},
selectedOptionItems: [],
preferredCurrency: 'KRW',
additionalOptionGroups: groupsWithDefaultOnOptional,
newGroupName: '색상',
newValue: '블랙',
},
} as any,
ctx as any
);
const item = ctx.last.selectedOptionItems[0];
// 필수(각인=1)만 자동 선택, 비필수(포장=2)는 키 자체가 없어야 함 → "선택하세요" 유지
expect(item.additionalOptionSelections).toEqual({ 1: 100 });
expect(item.additionalOptionSelections).not.toHaveProperty('2');
expect(item.additionalOptionsTotal).toBe(0);
});
// 필수 그룹이 하나도 없으면 자동 선택이 전혀 일어나지 않는다.
it('필수 그룹이 없으면 추가옵션을 전혀 자동 선택하지 않는다', () => {
const allOptionalGroups = [
{
id: 2,
name: '포장',
is_required: false,
values: [{ id: 200, name: '기본포장', price_adjustment: 0, is_default: true }],
},
];
const ctx = captureSetState();
addSelectedItemIfCompleteHandler(
{
handler: 'x',
params: {
productId: 1,
optionGroups,
options,
currentSelection: {},
selectedOptionItems: [],
preferredCurrency: 'KRW',
additionalOptionGroups: allOptionalGroups,
newGroupName: '색상',
newValue: '블랙',
},
} as any,
ctx as any
);
const item = ctx.last.selectedOptionItems[0];
expect(item.additionalOptionSelections).toEqual({});
expect(item.additionalOptionsTotal).toBe(0);
});
});
describe('setBlockAdditionalOptionHandler — 블럭별 추가옵션 선택', () => {
it('각인 추가(+5000) 선택 시 추가금·소계·다통화가 재계산된다', () => {
const block = {
id: '블랙',
optionId: 10,
options: { 색상: '블랙' },
optionValues: { 색상: '블랙' },
quantity: 1,
stock: 99,
unitPrice: 10000,
unitPriceFormatted: '10,000원',
totalPrice: 10000,
totalPriceFormatted: '10,000원',
multiCurrencyUnitPrice: {
KRW: { value: 10000, formatted: '₩10,000' },
USD: { value: 10, formatted: '$10.00' },
},
multiCurrencyTotalPrice: {
KRW: { value: 10000, formatted: '₩10,000' },
USD: { value: 10, formatted: '$10.00' },
},
additionalOptionSelections: { 1: 100 },
additionalOptionsTotal: 0,
};
const ctx = captureSetState();
setBlockAdditionalOptionHandler(
{
handler: 'x',
params: {
itemIndex: 0,
additionalOptionId: 1,
valueId: 101,
selectedOptionItems: [block],
additionalOptionGroups,
preferredCurrency: 'KRW',
},
} as any,
ctx as any
);
const updated = ctx.last.selectedOptionItems[0];
expect(updated.additionalOptionSelections).toEqual({ 1: 101 });
expect(updated.additionalOptionsTotal).toBe(5000);
expect(updated.totalPrice).toBe(15000);
// USD 환산: 추가금 5000 × (10/10000) = 5 → 단가 10 + 5 = 15
expect(updated.multiCurrencyTotalPrice.USD.value).toBe(15);
});
it('두 그룹 동시 선택 시 추가금이 합산된다 (각인+5000 + 포장+2000)', () => {
const block = {
quantity: 2,
unitPrice: 10000,
multiCurrencyUnitPrice: { KRW: { value: 10000, formatted: '' } },
additionalOptionSelections: { 1: 101 },
additionalOptionsTotal: 5000,
};
const ctx = captureSetState();
setBlockAdditionalOptionHandler(
{
handler: 'x',
params: {
itemIndex: 0,
additionalOptionId: 2,
valueId: 200,
selectedOptionItems: [block],
additionalOptionGroups,
preferredCurrency: 'KRW',
},
} as any,
ctx as any
);
const updated = ctx.last.selectedOptionItems[0];
expect(updated.additionalOptionsTotal).toBe(7000);
// (10000 + 7000) × 2 = 34000
expect(updated.totalPrice).toBe(34000);
});
it('직접입력 모드: customText 만 갱신하고 선택 value 는 유지한다', () => {
const block = {
quantity: 1,
unitPrice: 10000,
multiCurrencyUnitPrice: { KRW: { value: 10000, formatted: '' } },
additionalOptionSelections: { 1: 101 },
additionalOptionCustomTexts: {},
additionalOptionsTotal: 5000,
};
const ctx = captureSetState();
setBlockAdditionalOptionHandler(
{
handler: 'x',
params: {
itemIndex: 0,
additionalOptionId: 1,
valueId: 101,
customText: '홍길동',
selectedOptionItems: [block],
additionalOptionGroups,
preferredCurrency: 'KRW',
},
} as any,
ctx as any
);
const updated = ctx.last.selectedOptionItems[0];
expect(updated.additionalOptionCustomTexts).toEqual({ 1: '홍길동' });
expect(updated.additionalOptionSelections).toEqual({ 1: 101 });
// 직접입력은 가격 무관 — 추가금 그대로
expect(updated.additionalOptionsTotal).toBe(5000);
});
it('직접입력 미허용 선택지로 변경 시 기존 customText 가 정리된다', () => {
const block = {
quantity: 1,
unitPrice: 10000,
multiCurrencyUnitPrice: { KRW: { value: 10000, formatted: '' } },
additionalOptionSelections: { 1: 101 },
additionalOptionCustomTexts: { 1: '홍길동' },
additionalOptionsTotal: 5000,
};
const ctx = captureSetState();
// value 100(없음, allow_custom_text 없음) 으로 변경
setBlockAdditionalOptionHandler(
{
handler: 'x',
params: {
itemIndex: 0,
additionalOptionId: 1,
valueId: 100,
selectedOptionItems: [block],
additionalOptionGroups,
preferredCurrency: 'KRW',
},
} as any,
ctx as any
);
const updated = ctx.last.selectedOptionItems[0];
expect(updated.additionalOptionCustomTexts).toEqual({});
});
it('플레이스홀더("") 선택 시 해당 그룹 선택이 해제된다', () => {
const block = {
quantity: 1,
unitPrice: 10000,
multiCurrencyUnitPrice: { KRW: { value: 10000, formatted: '' } },
additionalOptionSelections: { 1: 101, 2: 200 },
additionalOptionsTotal: 7000,
};
const ctx = captureSetState();
setBlockAdditionalOptionHandler(
{
handler: 'x',
params: {
itemIndex: 0,
additionalOptionId: 2,
valueId: '',
selectedOptionItems: [block],
additionalOptionGroups,
preferredCurrency: 'KRW',
},
} as any,
ctx as any
);
const updated = ctx.last.selectedOptionItems[0];
expect(updated.additionalOptionSelections).toEqual({ 1: 101 });
expect(updated.additionalOptionsTotal).toBe(5000);
expect(updated.totalPrice).toBe(15000);
});
});
describe('updateSelectedItemQuantityHandler — 추가옵션 포함 수량 배수 (D6)', () => {
it('추가금 포함 단가 × 수량으로 소계를 계산한다', () => {
const block = {
quantity: 1,
unitPrice: 10000,
multiCurrencyUnitPrice: { KRW: { value: 10000, formatted: '' } },
additionalOptionSelections: { 1: 101 },
additionalOptionsTotal: 5000,
};
const ctx = captureSetState();
updateSelectedItemQuantityHandler(
{
handler: 'x',
params: {
itemIndex: 0,
newQuantity: 3,
selectedOptionItems: [block],
preferredCurrency: 'KRW',
},
} as any,
ctx as any
);
const updated = ctx.last.selectedOptionItems[0];
// (10000 + 5000) × 3 = 45000
expect(updated.totalPrice).toBe(45000);
expect(updated.quantity).toBe(3);
});
});
describe('toAdditionalOptionSelectionsPayload — 백엔드 입력 변환', () => {
it('{groupId: valueId} → [{additional_option_id, value_id}]', () => {
expect(toAdditionalOptionSelectionsPayload({ 1: 101, 2: 200 })).toEqual([
{ additional_option_id: 1, value_id: 101 },
{ additional_option_id: 2, value_id: 200 },
]);
});
it('빈 선택은 빈 배열', () => {
expect(toAdditionalOptionSelectionsPayload(undefined)).toEqual([]);
expect(toAdditionalOptionSelectionsPayload({})).toEqual([]);
});
it('customText 가 있으면 custom_text 를 포함한다', () => {
expect(toAdditionalOptionSelectionsPayload({ 1: 101 }, { 1: '홍길동' })).toEqual([
{ additional_option_id: 1, value_id: 101, custom_text: '홍길동' },
]);
});
it('빈/공백 customText 는 custom_text 를 생략한다', () => {
expect(toAdditionalOptionSelectionsPayload({ 1: 101 }, { 1: ' ' })).toEqual([
{ additional_option_id: 1, value_id: 101 },
]);
});
});
@@ -0,0 +1,114 @@
/**
* @file productOptionsTotalCurrency.test.ts
* @description 상품 옵션 총금액 통화별 포맷 맵 핸들러 테스트 (D2/D3)
*
* 배경: 레이아웃 "총 금액"이 표현식에서 핸들러를 호출할 수 없어(엔진 제약) KRW 로 고정되던 결함.
* 핸들러가 통화별 합계 포맷 맵을 setState 로 노출하면 레이아웃은 단순 조회만 한다.
*
* - addSelectedItemIfComplete / updateSelectedItemQuantity / removeSelectedItem:
* selectedTotalMultiCurrency 에 통화별 합계 formatted 노출
* - updateNoOptionQuantity: noOptionTotalMultiCurrency 에 단가×수량 통화별 formatted 노출
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import {
updateSelectedItemQuantityHandler,
removeSelectedItemHandler,
updateNoOptionQuantityHandler,
} from '../productOptions';
const mockG7Core = {
state: { get: vi.fn(() => ({})), getLocal: vi.fn(() => ({})), setLocal: vi.fn() },
toast: { show: vi.fn(), warning: vi.fn() },
t: vi.fn((key: string) => key),
};
const makeItem = (overrides: any = {}) => ({
id: 'opt1',
optionId: 1,
options: {},
optionValues: {},
quantity: 1,
stock: 99,
unitPrice: 3000,
unitPriceFormatted: '3,000원',
totalPrice: 3000,
totalPriceFormatted: '3,000원',
multiCurrencyUnitPrice: {
KRW: { value: 3000, formatted: '3,000원' },
USD: { value: 2.55, formatted: '$2.55' },
},
multiCurrencyTotalPrice: {
KRW: { value: 3000, formatted: '3,000원' },
USD: { value: 2.55, formatted: '$2.55' },
},
...overrides,
});
describe('productOptions 총금액 통화별 포맷 맵 (D2/D3)', () => {
beforeEach(() => {
(window as any).G7Core = mockG7Core;
});
afterEach(() => {
vi.restoreAllMocks();
delete (window as any).G7Core;
});
it('updateSelectedItemQuantity 가 selectedTotalMultiCurrency 통화별 합계를 setState 한다', () => {
const setState = vi.fn();
updateSelectedItemQuantityHandler(
{ handler: 'x', params: { itemIndex: 0, newQuantity: 2, selectedOptionItems: [makeItem()], preferredCurrency: 'USD' } } as any,
{ setState } as any
);
const arg = setState.mock.calls[0][0];
expect(arg.selectedTotalMultiCurrency).toBeDefined();
// 수량 2 → USD 합계 $5.10, KRW 6,000원 (서로 다른 통화 포맷)
expect(arg.selectedTotalMultiCurrency.USD.formatted).toContain('$');
expect(arg.selectedTotalMultiCurrency.KRW.formatted).not.toContain('$');
expect(arg.selectedTotalMultiCurrency.USD.value).toBeCloseTo(5.1, 2);
});
it('removeSelectedItem 이 남은 항목으로 selectedTotalMultiCurrency 를 재계산한다', () => {
const setState = vi.fn();
removeSelectedItemHandler(
{ handler: 'x', params: { itemIndex: 0, selectedOptionItems: [makeItem(), makeItem({ id: 'opt2' })] } } as any,
{ setState } as any
);
const arg = setState.mock.calls[0][0];
expect(arg.selectedOptionItems).toHaveLength(1);
expect(arg.selectedTotalMultiCurrency.USD.value).toBeCloseTo(2.55, 2);
});
it('removeSelectedItem 이 마지막 항목 제거 시 빈 합계 맵을 만든다', () => {
const setState = vi.fn();
removeSelectedItemHandler(
{ handler: 'x', params: { itemIndex: 0, selectedOptionItems: [makeItem()] } } as any,
{ setState } as any
);
const arg = setState.mock.calls[0][0];
expect(arg.selectedOptionItems).toHaveLength(0);
expect(arg.selectedTotalMultiCurrency).toEqual({});
});
it('updateNoOptionQuantity 가 단가×수량 통화별 noOptionTotalMultiCurrency 를 setState 한다', () => {
const setState = vi.fn();
updateNoOptionQuantityHandler(
{
handler: 'x',
params: {
newQuantity: 3,
multiCurrencyUnitPrice: {
KRW: { value: 10000, formatted: '10,000원' },
USD: { value: 8.5, formatted: '$8.50' },
},
},
} as any,
{ setState } as any
);
const arg = setState.mock.calls[0][0];
expect(arg.noOptionQuantity).toBe(3);
expect(arg.noOptionTotalMultiCurrency.USD.value).toBeCloseTo(25.5, 2);
expect(arg.noOptionTotalMultiCurrency.USD.formatted).toContain('$');
expect(arg.noOptionTotalMultiCurrency.KRW.formatted).not.toContain('$');
});
});
@@ -0,0 +1,91 @@
/**
* @file redirectToLoginWithReturn.test.ts
* @description 비로그인 게시판/비밀글 진입 → /login?redirect=현재경로 핸들러 단위 검증 (이슈 #413 item 28)
*
* 핸들러는 window.location(pathname+search)을 직접 읽어 redirect 를 보존하고,
* G7Core.dispatch 로 navigate 를 발화한다. errorHandling context 에 route/query 가 없는
* 제약을 우회하는 핵심 동작이므로 실제 호출 인자를 단언한다(거짓 통과 방지).
*
* @scenario has_query:with_query,without_query
* @effects redirect_preserves_pathname,redirect_preserves_query_string
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { redirectToLoginWithReturnHandler } from '../redirectToLoginWithReturn';
/**
* jsdom 의 window.location 을 지정 경로로 교체한다.
*
* @param pathname 경로
* @param search 쿼리스트링 (예: "?page=2")
*/
function mockLocation(pathname: string, search = ''): void {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { pathname, search } as unknown as Location,
});
}
describe('redirectToLoginWithReturnHandler — /login?redirect=현재경로 (이슈 #413 item 28)', () => {
let dispatchSpy: ReturnType<typeof vi.fn>;
const originalLocation = window.location;
beforeEach(() => {
dispatchSpy = vi.fn().mockResolvedValue(undefined);
(window as any).G7Core = { dispatch: dispatchSpy };
});
afterEach(() => {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: originalLocation,
});
delete (window as any).G7Core;
vi.restoreAllMocks();
});
it('query 없는 경로에서 redirect 가 pathname 으로 보존되어야 한다', async () => {
mockLocation('/board/members');
await redirectToLoginWithReturnHandler();
expect(dispatchSpy).toHaveBeenCalledTimes(1);
expect(dispatchSpy).toHaveBeenCalledWith({
handler: 'navigate',
params: {
path: '/login',
query: { redirect: '/board/members' },
},
});
});
it('query 포함 경로에서 redirect 가 search 까지 보존되어야 한다', async () => {
mockLocation('/board/members', '?page=2');
await redirectToLoginWithReturnHandler();
const call = dispatchSpy.mock.calls[0][0];
expect(call.handler).toBe('navigate');
expect(call.params.path).toBe('/login');
expect(call.params.query.redirect).toBe('/board/members?page=2');
});
it('navigate 핸들러로만 발화한다 (redirect 표현식 미사용)', async () => {
mockLocation('/board/members/123');
await redirectToLoginWithReturnHandler();
const call = dispatchSpy.mock.calls[0][0];
expect(call.handler).toBe('navigate');
expect(call.params.query.redirect).toBe('/board/members/123');
});
it('G7Core.dispatch 가 없으면 throw 하지 않고 조용히 반환한다', async () => {
mockLocation('/board/members');
delete (window as any).G7Core;
await expect(redirectToLoginWithReturnHandler()).resolves.toBeUndefined();
});
});
@@ -2,9 +2,9 @@
* @file storageHandlers.test.ts
* @description 스토리지 핸들러 테스트
*
* 테스트 케이스 (#141~#148, 8개)
* - localStorage 핸들러: #141~#144 (4개)
* - initCartKey/옵션 관련: #145~#148 (4개)
* 테스트 케이스 (141~148, 8개)
* - localStorage 핸들러: 141~144 (4개)
* - initCartKey/옵션 관련: 145~148 (4개)
*
* 핸들러는 ActionDispatcher의 (action, context) 시그니처를 따릅니다.
* - action.params에서 파라미터를 읽음
@@ -20,6 +20,8 @@ import {
regenerateCartKeyHandler,
saveToStorageHandler,
loadFromStorageHandler,
initGuestOrderTokenHandler,
saveGuestOrderTokenHandler,
} from '../storageHandlers';
/**
@@ -51,6 +53,35 @@ const mockLocalStorage = (() => {
};
})();
/**
* sessionStorage Mock 설정 (비회원 주문 토큰용)
*/
const mockSessionStorage = (() => {
let store: Record<string, string> = {};
return {
getItem: vi.fn((key: string) => store[key] ?? null),
setItem: vi.fn((key: string, value: string) => {
store[key] = value;
}),
removeItem: vi.fn((key: string) => {
delete store[key];
}),
clear: vi.fn(() => {
store = {};
}),
get store() {
return store;
},
reset() {
store = {};
this.getItem.mockClear();
this.setItem.mockClear();
this.removeItem.mockClear();
this.clear.mockClear();
},
};
})();
/**
* G7Core Mock 설정
*/
@@ -58,6 +89,7 @@ const mockG7Core = {
state: {
get: vi.fn(() => ({})),
set: vi.fn(),
subscribe: vi.fn(() => vi.fn()),
},
createLogger: vi.fn(() => ({
log: vi.fn(),
@@ -80,9 +112,18 @@ describe('storageHandlers', () => {
writable: true,
});
// sessionStorage Mock 설정 (비회원 주문 토큰)
mockSessionStorage.reset();
Object.defineProperty(window, 'sessionStorage', {
value: mockSessionStorage,
writable: true,
});
// G7Core Mock 설정
mockG7Core.state.get.mockClear();
mockG7Core.state.set.mockClear();
mockG7Core.state.subscribe.mockClear();
mockG7Core.state.subscribe.mockImplementation(() => vi.fn());
(window as any).G7Core = mockG7Core;
// G7Config Mock 설정 (비로그인 상태 기본값)
@@ -97,8 +138,8 @@ describe('storageHandlers', () => {
});
describe('localStorage 핸들러', () => {
// #141: saveToStorage
it('#141 saveToStorage가 localStorage.setItem을 호출한다', () => {
// 141: saveToStorage
it('141 saveToStorage가 localStorage.setItem을 호출한다', () => {
// Given
const action = {
params: {
@@ -114,8 +155,8 @@ describe('storageHandlers', () => {
expect(mockLocalStorage.setItem).toHaveBeenCalledWith('g7_cart_key', 'ck_abc123');
});
// #142: loadFromStorage
it('#142 loadFromStorage가 localStorage.getItem 값을 반환한다', () => {
// 142: loadFromStorage
it('142 loadFromStorage가 localStorage.getItem 값을 반환한다', () => {
// Given
mockLocalStorage.setItem('g7_cart_key', 'ck_xyz789');
const action = { params: { key: 'g7_cart_key' } };
@@ -127,8 +168,8 @@ describe('storageHandlers', () => {
expect(result).toBe('ck_xyz789');
});
// #143: clearCartKey (removeItem 호출)
it('#143 clearCartKey가 localStorage.removeItem을 호출한다', () => {
// 143: clearCartKey (removeItem 호출)
it('143 clearCartKey가 localStorage.removeItem을 호출한다', () => {
// Given
mockLocalStorage.setItem('g7_cart_key', 'ck_abc123');
@@ -140,8 +181,8 @@ describe('storageHandlers', () => {
expect(mockG7Core.state.set).toHaveBeenCalledWith({ cartKey: null });
});
// #144: 존재하지 않는 키 조회
it('#144 존재하지 않는 키 조회 시 null을 반환한다', () => {
// 144: 존재하지 않는 키 조회
it('144 존재하지 않는 키 조회 시 null을 반환한다', () => {
// Given
const action = { params: { key: 'unknown_key' } };
@@ -156,8 +197,8 @@ describe('storageHandlers', () => {
// initCartKeyHandler 구현: localStorage 에 키 있으면 로드, 없으면 백엔드 API 로 발급.
// 로컬 UUID 생성이 아니라 /api/modules/sirsoft-ecommerce/cart/key 호출 방식.
describe('initCartKey 핸들러', () => {
// #145: 기존 cartKey 로드 (로그인/비로그인 공통)
it('#145 기존 cartKey가 있으면 API 호출 없이 로드한다', async () => {
// 145: 기존 cartKey 로드 (로그인/비로그인 공통)
it('145 기존 cartKey가 있으면 API 호출 없이 로드한다', async () => {
// Given
mockG7Config.user = null;
mockLocalStorage.setItem('g7_cart_key', 'existing-cart-key');
@@ -171,8 +212,8 @@ describe('storageHandlers', () => {
expect(mockG7Core.state.set).toHaveBeenCalledWith({ cartKey: 'existing-cart-key' });
});
// #146: 비로그인 — 기존 cartKey 없으면 백엔드 API 에서 발급
it('#146 기존 cartKey가 없으면 백엔드 API로 발급하여 저장한다', async () => {
// 146: 비로그인 — 기존 cartKey 없으면 백엔드 API 에서 발급
it('146 기존 cartKey가 없으면 백엔드 API로 발급하여 저장한다', async () => {
// Given
mockG7Config.user = null;
const issuedKey = 'ck_issued_from_api';
@@ -193,8 +234,8 @@ describe('storageHandlers', () => {
expect(mockG7Core.state.set).toHaveBeenCalledWith({ cartKey: issuedKey });
});
// #147: 로그인 사용자도 cartKey 발급 경로는 동일 (API 헤더 포함 필요)
it('#147 로그인 사용자도 cartKey가 없으면 API로 발급한다', async () => {
// 147: 로그인 사용자도 cartKey 발급 경로는 동일 (API 헤더 포함 필요)
it('147 로그인 사용자도 cartKey가 없으면 API로 발급한다', async () => {
// Given
mockG7Config.user = { id: 1, name: 'User' };
const issuedKey = 'ck_logged_in_key';
@@ -211,8 +252,8 @@ describe('storageHandlers', () => {
expect(mockG7Core.state.set).toHaveBeenCalledWith({ cartKey: issuedKey });
});
// #148: regenerateCartKey — 비로그인 사용자는 API 로 새 키 발급
it('#148 regenerateCartKey가 비로그인 사용자에게 새로운 키를 발급한다', async () => {
// 148: regenerateCartKey — 비로그인 사용자는 API 로 새 키 발급
it('148 regenerateCartKey가 비로그인 사용자에게 새로운 키를 발급한다', async () => {
// Given
mockG7Config.user = null;
mockLocalStorage.setItem('g7_cart_key', 'old-key');
@@ -270,4 +311,70 @@ describe('storageHandlers', () => {
expect(result).toBe('fallback');
});
});
describe('비회원 주문 토큰 — initGuestOrderToken (verify→상세 SPA 전이 토큰 보존)', () => {
const FUTURE = new Date(Date.now() + 30 * 60 * 1000).toISOString();
const PAST = new Date(Date.now() - 60 * 1000).toISOString();
it('sessionStorage 에 유효 토큰이 있으면 그 값으로 _global.guestOrderToken 을 set 한다 (새로고침/재방문 경로)', () => {
mockSessionStorage.store['g7_guest_order_token'] = 'tok-from-session';
mockSessionStorage.store['g7_guest_order_expires_at'] = FUTURE;
mockG7Core.state.get.mockReturnValue({ guestOrderToken: null });
initGuestOrderTokenHandler();
expect(mockG7Core.state.set).toHaveBeenCalledWith({ guestOrderToken: 'tok-from-session' });
});
it('sessionStorage 가 비었지만 _global 에 in-memory 토큰이 있으면 보존한다 (조회 폼 verify→상세 SPA 전이, sessionStorage 미영속 환경 포함)', () => {
// 회귀 핵심: 베이스 init_actions 재실행 시 빈 sessionStorage 를 읽어
// saveGuestOrderToken 이 _global 에 동기 set 한 유효 토큰을 null 로 덮어쓰면
// 상세 데이터소스가 X-Guest-Order-Token 없이 호출 → 404.
mockG7Core.state.get.mockReturnValue({ guestOrderToken: 'tok-in-memory' });
initGuestOrderTokenHandler();
// null 로 덮어쓰지 않는다 — set 이 호출되지 않거나, 호출돼도 토큰을 비우지 않음
const nulledCall = mockG7Core.state.set.mock.calls.find(
(c) => c[0] && Object.prototype.hasOwnProperty.call(c[0], 'guestOrderToken') && c[0].guestOrderToken == null
);
expect(nulledCall, 'in-memory _global 토큰을 null 로 덮어쓰면 안 됨 (SPA 전이 토큰 누락 404 회귀)').toBeUndefined();
});
it('sessionStorage 도 비고 _global 도 비면 guestOrderToken 을 null 로 명시 설정한다 (비인증 방문자)', () => {
mockG7Core.state.get.mockReturnValue({ guestOrderToken: null });
initGuestOrderTokenHandler();
expect(mockG7Core.state.set).toHaveBeenCalledWith({ guestOrderToken: null });
});
it('sessionStorage 토큰이 만료됐으면 폐기하고, in-memory 토큰이 있어도 보존하지 않는다 (만료 우선)', () => {
mockSessionStorage.store['g7_guest_order_token'] = 'tok-expired';
mockSessionStorage.store['g7_guest_order_expires_at'] = PAST;
mockG7Core.state.get.mockReturnValue({ guestOrderToken: 'tok-in-memory' });
initGuestOrderTokenHandler();
// 만료 → sessionStorage 정리 + _global 도 null
expect(mockSessionStorage.removeItem).toHaveBeenCalledWith('g7_guest_order_token');
expect(mockG7Core.state.set).toHaveBeenCalledWith({ guestOrderToken: null });
});
});
describe('비회원 주문 토큰 — saveGuestOrderToken', () => {
it('token/orderNumber/expiresAt 3개 키를 sessionStorage 에 동기 기록하고 _global.guestOrderToken 을 set 한다', () => {
const action = { params: { token: 'tok-1', orderNumber: 'ORD-1', expiresAt: '2099-01-01T00:00:00Z' } };
saveGuestOrderTokenHandler(action);
expect(mockSessionStorage.setItem).toHaveBeenCalledWith('g7_guest_order_token', 'tok-1');
expect(mockSessionStorage.setItem).toHaveBeenCalledWith('g7_guest_order_number', 'ORD-1');
expect(mockSessionStorage.setItem).toHaveBeenCalledWith('g7_guest_order_expires_at', '2099-01-01T00:00:00Z');
expect(mockG7Core.state.set).toHaveBeenCalledWith({ guestOrderToken: 'tok-1' });
});
});
// initPreferredCurrency 핸들러는 이커머스 모듈로 이전되었다.
// 테스트: modules/_bundled/sirsoft-ecommerce/resources/js/__tests__/handlers/initPreferredCurrency.test.ts
});
@@ -0,0 +1,68 @@
/**
* downloadAttachment 핸들러
*
* 게시판 첨부파일을 토큰 동반 요청으로 다운로드한다 (이슈 #413 item 58b).
*
* 배경: 기존 다운로드는 레이아웃의 <a href="{{download_url}}"> 브라우저 직접 링크(GET)였다.
* G7 은 Sanctum 토큰 전용 인증인데 <a> 네비게이션에는 Authorization 헤더(토큰)가 실리지 않아,
* download_url 이 가리키는 optional.sanctum 라우트가 요청을 guest 로 통과시켰다.
* 그 결과 회원이 받아도 서버의 Auth::id() 가 NULL 이 되어 활동이력(attachment.download)의
* 행위자(user_id)가 비어 있었다(upload/board.update 는 정상이었다).
*
* 해소: 코어 ApiClient(G7Core.api.get)로 blob 요청을 보내면 Authorization 헤더가 자동 첨부되어
* 토큰이 실린다. 받은 blob 을 objectURL 로 변환해 <a download> 클릭으로 저장한다
* (composite/ImageGallery.tsx 의 downloadAuthenticatedFile 과 동일 패턴).
*
* 비회원: 토큰이 없으므로 종전과 동일하게 user_id 가 NULL 로 남는다(현행 정책 유지).
*/
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = (window as any).G7Core?.createLogger?.('Handler:DownloadAttachment') ?? {
log: (...args: unknown[]) => console.log('[Handler:DownloadAttachment]', ...args),
warn: (...args: unknown[]) => console.warn('[Handler:DownloadAttachment]', ...args),
error: (...args: unknown[]) => console.error('[Handler:DownloadAttachment]', ...args),
};
/**
* 첨부파일을 토큰 동반 요청으로 다운로드하는 핸들러
*
* ActionDispatcher 는 handler(action, context) 형태로 호출한다.
* params 는 resolveParams 로 이미 표현식이 해석된 값을 받는다.
*
* @param action 액션 정의 (params.url=다운로드 URL, params.filename=저장 파일명)
* @param _context 액션 컨텍스트 (미사용)
* @return Promise<void>
*/
export async function downloadAttachmentHandler(action?: any, _context?: any): Promise<void> {
const G7Core = (window as any).G7Core;
const { url, filename } = action?.params || {};
if (!url) {
logger.warn('다운로드 URL 이 없어 요청을 건너뜁니다.');
return;
}
if (!G7Core?.api?.get) {
logger.error('G7Core.api.get 이 초기화되지 않아 다운로드를 실행할 수 없습니다.');
return;
}
try {
// 코어 ApiClient 경로 → Authorization(Bearer) 헤더 자동 첨부 → 회원 토큰이 실린다.
const blob = await G7Core.api.get(url, { responseType: 'blob' });
if (blob) {
const objectUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = objectUrl;
link.download = filename || '';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(objectUrl);
}
} catch (error) {
logger.error('첨부파일 다운로드 실패', error);
G7Core?.toast?.error?.(G7Core?.t?.('common.download_failed') ?? 'Download failed');
}
}
@@ -28,6 +28,11 @@ const logger = ((window as any).G7Core?.createLogger?.('Template:sirsoft-basic:I
* 코어가 launcher 에 전달하는 verification payload (런타임 형태).
* 코어 타입 import 를 피하려고 로컬에 정의 — 실제 형식은 `resources/js/core/identity/types.ts` 와 동일.
*/
interface IdentityVerificationTarget {
email?: string;
phone?: string;
}
interface VerificationPayload {
policy_key: string;
purpose: string;
@@ -36,6 +41,8 @@ interface VerificationPayload {
challenge_start_url?: string;
redirect_url?: string;
return_request?: { method: string; url: string; headers_echo?: string[] } | null;
/** 흐름이 apiCall identity_target 으로 선언한 인증 대상 — 코어 인터셉터가 병합해 전달. */
target?: IdentityVerificationTarget | null;
}
/**
@@ -48,29 +55,56 @@ type VerificationResult =
| { status: 'failed'; failureCode: string; reason?: string };
/**
* 가입/비밀번호 재설정 폼 등에서 target.email 을 추출합니다.
* 인증 대상(이메일·전화)을 결정합니다.
*
* 우선순위: signup form > password_reset form > 로그인 사용자
* 우선순위 (필드별 보충 머지 — email/phone 각각 첫 비어있지 않은 값 채택):
* 1. `payload.target` — 흐름이 apiCall `identity_target` 으로 선언한 값 (범용 진입점, 비로그인 흐름의 핵심)
* 2. 로그인 사용자 세션 (`currentUser` / `user` / `auth.user` 의 email·phone)
* 3. (하위호환) signup/password_reset 폼 — `identity_target` 미선언 기존 레이아웃 대비
*
* 흐름별 폼 경로 하드코딩을 폐기하고 선언값을 1순위로 둠으로써, 주문/게시판/임의 액션 어떤 흐름이든
* 레이아웃이 `identity_target` 만 선언하면 launcher 변경 없이 동작한다.
*
* 반환값은 launcher 에서 두 곳에 사용:
* 1) 첫 POST /api/identity/challenges body 에 동봉
* 2) `_global.identityChallenge.target` 에 저장 — 모달 재전송 액션이 같은 target 을 재사용
*
* @param payload 코어 인터셉터가 전달한 verification payload (target 병합 포함)
* @returns 인증 대상 또는 null (email·phone 둘 다 없으면 — 로그인 사용자는 서버 세션 도출)
*/
function resolveTargetEmail(payload: VerificationPayload): { email?: string } | null {
function resolveTarget(payload: VerificationPayload): IdentityVerificationTarget | null {
const G7Core = (window as any).G7Core;
const local = G7Core?.state?.getLocal?.() ?? {};
const global = G7Core?.state?.getGlobal?.() ?? G7Core?.state?.get?.() ?? {};
const candidates: Array<string | undefined> = [
const pick = (...candidates: Array<unknown>): string | undefined =>
candidates.find((v): v is string => typeof v === 'string' && v.length > 0);
const email = pick(
payload.target?.email,
global?.currentUser?.email,
global?.user?.email,
global?.auth?.user?.email,
payload.purpose === 'signup' ? local?.registerForm?.email : undefined,
payload.purpose === 'password_reset' ? local?.passwordResetForm?.email : undefined,
payload.purpose === 'password_reset' ? local?.email : undefined,
global?.user?.email,
global?.auth?.user?.email,
];
);
const email = candidates.find((v) => typeof v === 'string' && v.length > 0);
return email ? { email } : null;
const phone = pick(
payload.target?.phone,
global?.currentUser?.phone,
global?.user?.phone,
global?.auth?.user?.phone,
);
if (!email && !phone) {
return null;
}
const target: IdentityVerificationTarget = {};
if (email) target.email = email;
if (phone) target.phone = phone;
return target;
}
/**
@@ -82,19 +116,44 @@ function getAuthHeader(): Record<string, string> {
return token ? { Authorization: `Bearer ${token}` } : {};
}
/**
* 현재 앱 언어를 Accept-Language 헤더로 추출합니다 (있으면).
*
* challenge POST 는 ApiClient 를 우회하는 raw fetch 라, ApiClient 가 모든 요청에
* 부착하는 `Accept-Language: g7_locale`(ApiClient.ts) 을 여기서 동일하게 부착해야
* 서버 SetLocale 이 사용자 화면 언어로 IDV 메일을 렌더한다. 누락 시 challenge 요청이
* 브라우저 기본 언어로 전송되어 메일이 주문 화면 언어와 달라진다(비회원 결제 등).
*/
function getLocaleHeader(): Record<string, string> {
try {
const locale =
typeof window !== 'undefined' ? window.localStorage?.getItem('g7_locale') : null;
return locale ? { 'Accept-Language': locale } : {};
} catch {
return {};
}
}
interface ChallengeResponseData {
id: string;
expires_at: string;
render_hint: string;
public_payload?: Record<string, unknown>;
redirect_url?: string;
/** 허용 최대 시도 횟수 — 0 은 무제한 (popup/SDK 형 provider). 코어 mail provider 는 환경설정값을 반영. */
max_attempts?: number;
}
/**
* `POST /api/identity/challenges` 로 challenge 를 시작합니다.
*
* @param payload verification payload
* @param target launcher 본체에서 1회 계산한 인증 대상 (startChallenge 와 _global 저장이 동일 값 공유)
*/
async function startChallenge(payload: VerificationPayload): Promise<ChallengeResponseData> {
const target = resolveTargetEmail(payload);
async function startChallenge(
payload: VerificationPayload,
target: IdentityVerificationTarget | null,
): Promise<ChallengeResponseData> {
const body: Record<string, unknown> = { purpose: payload.purpose };
if (payload.provider_id) body.provider_id = payload.provider_id;
if (target) body.target = target;
@@ -106,6 +165,7 @@ async function startChallenge(payload: VerificationPayload): Promise<ChallengeRe
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
...getLocaleHeader(),
...getAuthHeader(),
},
body: JSON.stringify(body),
@@ -124,13 +184,16 @@ async function startChallenge(payload: VerificationPayload): Promise<ChallengeRe
render_hint: data.render_hint ?? payload.render_hint ?? 'text_code',
public_payload: data.public_payload,
redirect_url: data.redirect_url,
max_attempts: typeof data.max_attempts === 'number' ? data.max_attempts : undefined,
};
}
/**
* sirsoft-basic 의 IDV launcher 본체.
*
* 테스트에서 직접 호출할 수 있도록 export (런타임 진입점은 registerSirsoftBasicIdentityLauncher).
*/
async function sirsoftBasicIdentityLauncher(payload: VerificationPayload): Promise<VerificationResult> {
export async function sirsoftBasicIdentityLauncher(payload: VerificationPayload): Promise<VerificationResult> {
const G7Core = (window as any).G7Core;
const identity = G7Core?.identity;
@@ -144,10 +207,14 @@ async function sirsoftBasicIdentityLauncher(payload: VerificationPayload): Promi
return identity.redirectExternally(payload);
}
// 인증 대상을 1회 계산 — startChallenge body 와 _global.identityChallenge.target 저장이 동일 값 공유
// (모달 재전송이 같은 target 으로 challenge 재요청). 흐름 선언값(payload.target) 우선.
const target = resolveTarget(payload);
// (2) Challenge 시작
let challenge: ChallengeResponseData;
try {
challenge = await startChallenge(payload);
challenge = await startChallenge(payload, target);
} catch (err) {
logger.error('Challenge 시작 실패:', err);
try {
@@ -178,11 +245,14 @@ async function sirsoftBasicIdentityLauncher(payload: VerificationPayload): Promi
}
// (3) _global.identityChallenge 네임스페이스 setup
// target 도 함께 저장 — 모달 재전송 액션이 같은 target 으로 challenge 재요청 가능하게
const target = resolveTargetEmail(payload);
// 위에서 1회 계산한 target 을 재사용 — 모달 재전송 액션이 같은 target 으로 challenge 재요청 가능하게
const expiresMs = challenge.expires_at ? new Date(challenge.expires_at).getTime() : 0;
const remainingSeconds = expiresMs > 0 ? Math.max(0, Math.floor((expiresMs - Date.now()) / 1000)) : 0;
// maxAttempts: 백엔드 응답값이 있으면 사용, 없으면 0(무제한 — popup/SDK 형 provider 의 기본).
// 코어 mail provider 응답에는 환경설정의 max_attempts 가 정확히 반영되므로 화면 카운트도 정합.
const maxAttempts = typeof challenge.max_attempts === 'number' ? challenge.max_attempts : 0;
G7Core.state.set({
identityChallenge: {
policy_key: payload.policy_key,
@@ -196,7 +266,7 @@ async function sirsoftBasicIdentityLauncher(payload: VerificationPayload): Promi
code: '',
error: null,
attempts: 0,
maxAttempts: 5,
maxAttempts,
remainingSeconds,
resendCooldown: 0,
},
@@ -9,6 +9,9 @@
import {
addSelectedItemIfCompleteHandler,
updateSelectedItemQuantityHandler,
removeSelectedItemHandler,
updateNoOptionQuantityHandler,
setBlockAdditionalOptionHandler,
} from './productOptions';
// 장바구니 관련 핸들러
@@ -35,6 +38,10 @@ import {
regenerateCartKeyHandler,
saveToStorageHandler,
loadFromStorageHandler,
initGuestOrderTokenHandler,
saveGuestOrderTokenHandler,
clearGuestOrderTokenHandler,
clearGuestTokenOnEntryHandler,
} from './storageHandlers';
// 다중 통화 관련 핸들러
@@ -48,6 +55,12 @@ import {
// 테마 관련 핸들러
import { setThemeHandler, initThemeHandler } from './setThemeHandler';
// 인증 리다이렉트 관련 핸들러
import { redirectToLoginWithReturnHandler } from './redirectToLoginWithReturn';
// 게시판 첨부 다운로드 핸들러 (토큰 동반 → 활동이력 행위자 기록)
import { downloadAttachmentHandler } from './downloadAttachment';
// 언어 관련 핸들러는 엔진 레벨(ActionDispatcher)에서 처리
// setLocale 핸들러는 ActionDispatcher에 빌트인으로 등록되어 있음
@@ -74,6 +87,9 @@ export const handlers = {
// 상품 옵션
'sirsoft-basic.addSelectedItemIfComplete': addSelectedItemIfCompleteHandler,
'sirsoft-basic.updateSelectedItemQuantity': updateSelectedItemQuantityHandler,
'sirsoft-basic.removeSelectedItem': removeSelectedItemHandler,
'sirsoft-basic.updateNoOptionQuantity': updateNoOptionQuantityHandler,
'sirsoft-basic.setBlockAdditionalOption': setBlockAdditionalOptionHandler,
// 다중 통화
'sirsoft-basic.getDisplayPrice': getDisplayPriceHandler,
@@ -86,6 +102,12 @@ export const handlers = {
setTheme: setThemeHandler,
initTheme: initThemeHandler,
// 인증 리다이렉트 (비로그인 게시판/비밀글 진입 → /login?redirect=현재경로)
redirectToLoginWithReturn: redirectToLoginWithReturnHandler,
// 게시판 첨부 다운로드 (토큰 동반 → 활동이력 행위자 기록)
downloadAttachment: downloadAttachmentHandler,
// 언어: setLocale은 엔진 레벨(ActionDispatcher)에서 빌트인으로 처리
// 장바구니
@@ -107,6 +129,10 @@ export const handlers = {
regenerateCartKey: regenerateCartKeyHandler,
saveToStorage: saveToStorageHandler,
loadFromStorage: loadFromStorageHandler,
initGuestOrderToken: initGuestOrderTokenHandler,
saveGuestOrderToken: saveGuestOrderTokenHandler,
clearGuestOrderToken: clearGuestOrderTokenHandler,
clearGuestTokenOnEntry: clearGuestTokenOnEntryHandler,
};
/**
@@ -125,6 +151,9 @@ export type SirsoftBasicHandlers = typeof handlers;
export {
addSelectedItemIfCompleteHandler,
updateSelectedItemQuantityHandler,
removeSelectedItemHandler,
updateNoOptionQuantityHandler,
setBlockAdditionalOptionHandler,
getDisplayPriceHandler,
formatCurrencyHandler,
getCurrencySymbol,
@@ -132,6 +161,10 @@ export {
savePreferredCurrencyHandler,
setThemeHandler,
initThemeHandler,
// 인증 리다이렉트
redirectToLoginWithReturnHandler,
// 게시판 첨부 다운로드
downloadAttachmentHandler,
// setLocaleHandler는 엔진 레벨에서 처리하므로 제거됨
// 장바구니
toggleCartItemSelectionHandler,
@@ -150,4 +183,8 @@ export {
regenerateCartKeyHandler,
saveToStorageHandler,
loadFromStorageHandler,
initGuestOrderTokenHandler,
saveGuestOrderTokenHandler,
clearGuestOrderTokenHandler,
clearGuestTokenOnEntryHandler,
};
@@ -106,9 +106,12 @@ export function savePreferredCurrencyHandler(
}
/**
* 유효한 통화 코드인지 확인합니다.
* 유효한 통화 코드 형식인지 확인합니다.
*
* 관리자가 추가/삭제하는 통화를 하드코딩 목록이 막지 않도록(A1-⑥), 고정 화이트리스트가 아니라
* ISO 4217 형식(영문 대문자 3자리)으로 검증한다. 실제 노출 통화 제한은 셀렉터가 표시하는
* _global.availableCurrencies(is_default || exchange_rate>0)가 담당한다.
*/
function isValidCurrency(code: string): boolean {
const validCurrencies = ['KRW', 'USD', 'JPY', 'CNY', 'EUR'];
return validCurrencies.includes(code);
return typeof code === 'string' && /^[A-Z]{3}$/.test(code);
}
@@ -55,6 +55,33 @@ interface ProductOptionRecord {
is_active: boolean;
}
/**
* 추가옵션 선택지 (PublicProductResource.additional_options[].values[])
*/
interface AdditionalOptionValue {
id: number;
name: string;
price_adjustment: number;
is_default: boolean;
/** 직접입력 허용 — 이 선택지 선택 시 자유 텍스트 입력칸 노출(입력 필수) */
allow_custom_text?: boolean;
}
/**
* 추가옵션 그룹 (PublicProductResource.additional_options[])
*/
interface AdditionalOptionGroup {
id: number;
name: string;
is_required: boolean;
values: AdditionalOptionValue[];
}
/**
* 블럭별 추가옵션 선택 상태 (additional_option_id → value_id)
*/
type AdditionalOptionSelections = Record<number, number>;
interface SelectedItem {
id: string;
optionId: number;
@@ -68,6 +95,12 @@ interface SelectedItem {
totalPriceFormatted: string;
multiCurrencyUnitPrice?: Record<string, { value: number; formatted: string }>;
multiCurrencyTotalPrice?: Record<string, { value: number; formatted: string }>;
/** 블럭별 추가옵션 선택 (그룹ID → 선택지ID) */
additionalOptionSelections?: AdditionalOptionSelections;
/** 블럭별 추가옵션 직접입력 텍스트 (그룹ID → custom_text). allow_custom_text 선택지 한정 */
additionalOptionCustomTexts?: Record<number, string>;
/** 블럭별 추가옵션 추가금 합계 (KRW 기준, 단위당) */
additionalOptionsTotal?: number;
}
interface AddSelectedItemParams {
@@ -77,6 +110,8 @@ interface AddSelectedItemParams {
currentSelection: Record<string, string>;
selectedOptionItems: SelectedItem[];
preferredCurrency: string;
/** 상품 추가옵션 카탈로그 (기본 선택지 자동 적용용) */
additionalOptionGroups?: AdditionalOptionGroup[];
/** sequence 상태 동기화 우회: 방금 선택한 그룹명 */
newGroupName?: string;
/** sequence 상태 동기화 우회: 방금 선택한 값 */
@@ -90,6 +125,17 @@ interface UpdateQuantityParams {
preferredCurrency: string;
}
interface SetBlockAdditionalOptionParams {
itemIndex: number;
additionalOptionId: number;
valueId: number | string;
/** 직접입력 텍스트 입력 시 전달 (value 선택 변경 시에는 미전달) */
customText?: string;
selectedOptionItems: SelectedItem[];
additionalOptionGroups: AdditionalOptionGroup[];
preferredCurrency: string;
}
/**
* G7Core ActionContext (ActionDispatcher에서 전달)
*/
@@ -141,18 +187,38 @@ function formatPrice(amount: number, currencyCode: string = 'KRW'): string {
/**
* 다중 통화 총 가격 재계산
*
* 추가옵션 추가금(additionalUnitKrw)이 있으면 KRW 환율 기준으로 환산해 각 통화 단가에 가산한다.
* 추가옵션은 공개 응답에 다통화 컬럼이 없으므로(plan §245) 기본통화(KRW) 단가 비율로 환산한다.
*
* @param unitPriceMap 옵션 단가 다통화 맵
* @param quantity 수량
* @param additionalUnitKrw 추가옵션 추가금 합계 (KRW 기준, 단위당). 기본 0.
*/
function recalcMultiCurrencyTotal(
unitPriceMap: Record<string, { value: number; formatted: string }> | undefined,
quantity: number
quantity: number,
additionalUnitKrw: number = 0
): Record<string, { value: number; formatted: string }> | undefined {
if (!unitPriceMap) return undefined;
// KRW 단가를 환산 기준으로 사용 (옵션의 KRW 단가 대비 타통화 비율)
const krwUnit = (unitPriceMap.KRW as any)?.value ?? (unitPriceMap.KRW as any)?.price ?? 0;
const result: Record<string, { value: number; formatted: string }> = {};
for (const [code, data] of Object.entries(unitPriceMap)) {
// API는 { price, formatted } 형태, 내부는 { value, formatted } 형태 — 둘 다 지원
const unitValue = (data as any)?.value ?? (data as any)?.price ?? 0;
const total = unitValue * quantity;
// 추가금 통화 환산: KRW 기준 추가금 × (해당통화 단가 / KRW 단가). KRW 자신은 그대로.
let additionalConverted = 0;
if (additionalUnitKrw > 0) {
if (code === 'KRW') {
additionalConverted = additionalUnitKrw;
} else if (krwUnit > 0) {
additionalConverted = (additionalUnitKrw * unitValue) / krwUnit;
}
}
const total = (unitValue + additionalConverted) * quantity;
result[code] = {
value: total,
formatted: formatPrice(total, code),
@@ -161,6 +227,86 @@ function recalcMultiCurrencyTotal(
return result;
}
/**
* 선택된 옵션 항목들의 통화별 합계 포맷 맵을 계산합니다.
*
* 레이아웃 "총 금액"은 표현식 컨텍스트에서 핸들러를 호출할 수 없으므로(엔진 제약),
* 합계 금액을 통화별로 미리 포맷해 _local 에 노출한다 → 레이아웃은 단순 조회만 한다.
* (선택 통화 KRW 고정 결함 D2 해소)
*
* @param items 선택된 옵션 항목 목록
* @returns 통화코드 => { value, formatted } 합계 맵
*/
function buildSelectedTotalMultiCurrency(
items: SelectedItem[]
): Record<string, { value: number; formatted: string }> {
const totals: Record<string, number> = {};
for (const item of items) {
const mc = item?.multiCurrencyTotalPrice;
if (mc) {
for (const [code, data] of Object.entries(mc)) {
const v = (data as any)?.value ?? (data as any)?.price ?? 0;
totals[code] = (totals[code] ?? 0) + v;
}
}
}
const result: Record<string, { value: number; formatted: string }> = {};
for (const [code, value] of Object.entries(totals)) {
result[code] = { value, formatted: formatPrice(value, code) };
}
return result;
}
/**
* 블럭의 추가옵션 선택으로부터 추가금 합계(KRW, 단위당)를 계산한다.
*
* @param selections 블럭별 추가옵션 선택 (그룹ID → 선택지ID)
* @param groups 상품 추가옵션 카탈로그
* @returns 추가금 합계 (KRW)
*/
function computeAdditionalOptionsTotal(
selections: AdditionalOptionSelections | undefined,
groups: AdditionalOptionGroup[] | undefined
): number {
if (!selections || !groups?.length) return 0;
let total = 0;
for (const group of groups) {
const valueId = selections[group.id];
if (valueId == null) continue;
const value = group.values?.find(v => v.id === Number(valueId));
if (value) total += value.price_adjustment ?? 0;
}
return total;
}
/**
* 추가옵션 선택을 백엔드 입력 형식으로 변환한다.
* additional_option_selections: [{ additional_option_id, value_id }]
*
* @param selections 블럭별 추가옵션 선택 (그룹ID → 선택지ID)
* @param customTexts 블럭별 직접입력 텍스트 (그룹ID → custom_text)
* @returns 백엔드 입력 배열
*/
export function toAdditionalOptionSelectionsPayload(
selections: AdditionalOptionSelections | undefined,
customTexts?: Record<number, string>
): Array<{ additional_option_id: number; value_id: number; custom_text?: string }> {
if (!selections) return [];
return Object.entries(selections)
.filter(([, valueId]) => valueId != null)
.map(([groupId, valueId]) => {
const entry: { additional_option_id: number; value_id: number; custom_text?: string } = {
additional_option_id: Number(groupId),
value_id: Number(valueId),
};
const customText = customTexts?.[Number(groupId)];
if (typeof customText === 'string' && customText.trim() !== '') {
entry.custom_text = customText.trim();
}
return entry;
});
}
/**
* 옵션 그룹의 키 (name_localized 우선, 폴백으로 name)
*/
@@ -325,6 +471,24 @@ export function addSelectedItemIfCompleteHandler(
optionLabels[groupKey] = currentSelection[groupKey];
});
// 추가옵션 초기 선택: 필수(is_required) 그룹에 한해 기본 선택지(is_default)를 자동 적용한다.
// 비필수 그룹은 "선택하세요" 미선택 상태를 유지해야 한다 — 추가옵션 선택지는 라디오 방식이라
// 그룹당 1개가 항상 is_default 로 마킹되므로(관리자 폼이 첫 선택지를 기본으로 시드), 비필수까지
// 자동 적용하면 사용자가 원치 않은 추가금/선택이 강제로 붙는다.
const additionalOptionGroups = params.additionalOptionGroups ?? [];
const additionalOptionSelections: AdditionalOptionSelections = {};
for (const group of additionalOptionGroups) {
if (!group.is_required) continue;
const defaultValue = group.values?.find(v => v.is_default);
if (defaultValue) additionalOptionSelections[group.id] = defaultValue.id;
}
const additionalOptionsTotal = computeAdditionalOptionsTotal(
additionalOptionSelections,
additionalOptionGroups
);
const blockUnitTotal = unitPrice + additionalOptionsTotal;
const newItem: SelectedItem = {
id: optionKey,
optionId: matchedOption.id,
@@ -337,14 +501,22 @@ export function addSelectedItemIfCompleteHandler(
stock: matchedOption.stock_quantity ?? 999,
unitPrice,
unitPriceFormatted: formatPrice(unitPrice, preferredCurrency),
totalPrice: unitPrice,
totalPriceFormatted: formatPrice(unitPrice, preferredCurrency),
totalPrice: blockUnitTotal,
totalPriceFormatted: formatPrice(blockUnitTotal, preferredCurrency),
multiCurrencyUnitPrice: matchedOption.multi_currency_selling_price,
multiCurrencyTotalPrice: recalcMultiCurrencyTotal(matchedOption.multi_currency_selling_price as any, 1),
multiCurrencyTotalPrice: recalcMultiCurrencyTotal(
matchedOption.multi_currency_selling_price as any,
1,
additionalOptionsTotal
),
additionalOptionSelections,
additionalOptionsTotal,
};
const nextItems = [...items, newItem];
context.setState?.({
selectedOptionItems: [...items, newItem],
selectedOptionItems: nextItems,
selectedTotalMultiCurrency: buildSelectedTotalMultiCurrency(nextItems),
currentSelection: {},
__mergeMode: 'shallow',
});
@@ -371,15 +543,157 @@ export function updateSelectedItemQuantityHandler(
if (idx !== itemIndex) return item;
const unitPrice = item?.unitPrice ?? 0;
const totalPrice = unitPrice * newQuantity;
const additionalOptionsTotal = item?.additionalOptionsTotal ?? 0;
const totalPrice = (unitPrice + additionalOptionsTotal) * newQuantity;
return {
...item,
quantity: newQuantity,
totalPrice,
totalPriceFormatted: formatPrice(totalPrice, preferredCurrency),
multiCurrencyTotalPrice: recalcMultiCurrencyTotal(item?.multiCurrencyUnitPrice, newQuantity),
multiCurrencyTotalPrice: recalcMultiCurrencyTotal(
item?.multiCurrencyUnitPrice,
newQuantity,
additionalOptionsTotal
),
};
});
context.setState?.({ selectedOptionItems: updatedItems });
context.setState?.({
selectedOptionItems: updatedItems,
selectedTotalMultiCurrency: buildSelectedTotalMultiCurrency(updatedItems),
});
}
/**
* 블럭별 추가옵션 선택 변경 및 가격 재계산
*
* 특정 옵션 블럭의 추가옵션 그룹 선택을 갱신하고, 추가금 합계·소계·다통화를 재계산한다.
* 가격 표시는 클라이언트 계산이며 결제금액 SSoT 는 서버(plan D13).
*
* G7Core에서 (action: ActionDefinition, context: ActionContext) 시그니처로 호출됩니다.
*/
export function setBlockAdditionalOptionHandler(
action: ActionDefinition,
context: ActionContext
): void {
const params = action.params as SetBlockAdditionalOptionParams;
if (!params) return;
const { selectedOptionItems, additionalOptionGroups, preferredCurrency } = params;
const itemIndex = Number(params.itemIndex) || 0;
const additionalOptionId = Number(params.additionalOptionId);
// customText 키가 params 에 존재하면 직접입력 모드 (value 선택 변경 아님)
const isCustomTextMode = Object.prototype.hasOwnProperty.call(params, 'customText');
// 빈 문자열(플레이스홀더) 선택 시 해당 그룹 선택 해제
const valueId = params.valueId === '' || params.valueId == null ? null : Number(params.valueId);
const updatedItems = (selectedOptionItems ?? []).map((item, idx) => {
if (idx !== itemIndex) return item;
const selections: AdditionalOptionSelections = { ...(item.additionalOptionSelections ?? {}) };
const customTexts: Record<number, string> = { ...(item.additionalOptionCustomTexts ?? {}) };
if (isCustomTextMode) {
// 직접입력 모드: 텍스트만 갱신 (선택 value 는 유지)
const text = String(params.customText ?? '');
if (text.trim() === '') {
delete customTexts[additionalOptionId];
} else {
customTexts[additionalOptionId] = text;
}
} else if (valueId == null) {
// 그룹 선택 해제 → 선택·직접입력 모두 정리
delete selections[additionalOptionId];
delete customTexts[additionalOptionId];
} else {
selections[additionalOptionId] = valueId;
// 새 선택지가 직접입력을 허용하지 않으면 기존 직접입력 텍스트 정리
const group = (additionalOptionGroups ?? []).find((g) => g.id === additionalOptionId);
const value = group?.values?.find((v) => v.id === valueId);
if (!value?.allow_custom_text) {
delete customTexts[additionalOptionId];
}
}
const additionalOptionsTotal = computeAdditionalOptionsTotal(selections, additionalOptionGroups);
const unitPrice = item?.unitPrice ?? 0;
const quantity = item?.quantity ?? 1;
const totalPrice = (unitPrice + additionalOptionsTotal) * quantity;
return {
...item,
additionalOptionSelections: selections,
additionalOptionCustomTexts: customTexts,
additionalOptionsTotal,
totalPrice,
totalPriceFormatted: formatPrice(totalPrice, preferredCurrency),
multiCurrencyTotalPrice: recalcMultiCurrencyTotal(
item?.multiCurrencyUnitPrice,
quantity,
additionalOptionsTotal
),
};
});
context.setState?.({
selectedOptionItems: updatedItems,
selectedTotalMultiCurrency: buildSelectedTotalMultiCurrency(updatedItems),
});
}
/**
* 선택된 옵션 항목을 제거하고 통화별 합계를 재계산합니다.
*
* 레이아웃에서 filter 로 직접 제거하면 selectedTotalMultiCurrency(통화별 합계 포맷)를
* 갱신할 수 없어(표현식은 핸들러 호출 불가) stale 합계가 남는다. 제거도 핸들러로 처리해
* 합계 맵을 함께 재계산한다(D2).
*
* G7Core에서 (action: ActionDefinition, context: ActionContext) 시그니처로 호출됩니다.
*/
export function removeSelectedItemHandler(
action: ActionDefinition,
context: ActionContext
): void {
const params = action.params as { itemIndex?: number | string; selectedOptionItems?: SelectedItem[] };
if (!params) return;
const itemIndex = Number(params.itemIndex) || 0;
const nextItems = (params.selectedOptionItems ?? []).filter((_, idx) => idx !== itemIndex);
context.setState?.({
selectedOptionItems: nextItems,
selectedTotalMultiCurrency: buildSelectedTotalMultiCurrency(nextItems),
});
}
/**
* 옵션 없는 상품의 수량을 변경하고 통화별 총액 포맷 맵을 재계산합니다.
*
* 옵션 없는 상품 총액 = 단가 × 수량. 레이아웃 표현식은 핸들러를 호출할 수 없어
* 통화별 포맷(소수점/기호)을 만들 수 없으므로, 수량 변경 시 통화별 총액 formatted 를
* noOptionTotalMultiCurrency 에 미리 계산해 노출한다(KRW 고정 결함 D3 해소).
*
* @param action.params.newQuantity 변경 수량
* @param action.params.multiCurrencyUnitPrice 단가 통화맵(product.multi_currency_selling_price)
* G7Core에서 (action: ActionDefinition, context: ActionContext) 시그니처로 호출됩니다.
*/
export function updateNoOptionQuantityHandler(
action: ActionDefinition,
context: ActionContext
): void {
const params = action.params as {
newQuantity?: number | string;
multiCurrencyUnitPrice?: Record<string, { value?: number; price?: number; formatted: string }>;
};
if (!params) return;
const quantity = Math.max(1, Number(params.newQuantity) || 1);
context.setState?.({
noOptionQuantity: quantity,
noOptionTotalMultiCurrency: recalcMultiCurrencyTotal(
params.multiCurrencyUnitPrice as Record<string, { value: number; formatted: string }> | undefined,
quantity
),
});
}
@@ -0,0 +1,60 @@
/**
* redirectToLoginWithReturn 핸들러
*
* 비로그인 회원전용 게시판/비밀글 진입 시 로그인 페이지로 보내되,
* 현재 경로(pathname + querystring)를 redirect 파라미터로 보존한다.
* 로그인 폼은 {{query.redirect ?? '/'}} 로 복원하므로(_login_form.json:155),
* 로그인 성공 후 원래 위치로 복귀한다.
*
* 배경: 게시판 목록/상세 데이터소스 401(auth_mode: optional + 토큰 없음)은
* 코어 ApiClient 자동가드를 우회하고 errorHandling 경로로 진입하는데,
* 그 context 에는 route/query 가 없다(TemplateApp.ts setDefaultContext 는 navigate 만 주입).
* 따라서 레이아웃 표현식으로는 현재 경로를 캡처할 수 없으므로, 핸들러가 window.location 을
* 직접 읽어 우회한다(identityLauncher.ts 의 window.location.href 선례와 동일 패턴).
*
* window.location.pathname 은 항상 '/' 로 시작하는 same-origin path 이므로 외부 URL 주입이
* 불가능하다(open redirect 안전).
*/
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Handler:RedirectToLoginWithReturn')) ?? {
log: (...args: unknown[]) => console.log('[Handler:RedirectToLoginWithReturn]', ...args),
warn: (...args: unknown[]) => console.warn('[Handler:RedirectToLoginWithReturn]', ...args),
error: (...args: unknown[]) => console.error('[Handler:RedirectToLoginWithReturn]', ...args),
};
/**
* 로그인 페이지로 이동하되 현재 경로를 redirect 로 보존하는 핸들러
*
* ActionDispatcher 는 handler(action, context) 형태로 호출하지만(ActionDispatcher.ts),
* 이 핸들러는 action/context 를 사용하지 않는다 — 현재 경로는 window.location 에서 직접 읽는다.
*
* @param _action 액션 정의 (미사용)
* @param _context 액션 컨텍스트 (미사용)
* @return Promise<void>
*/
export async function redirectToLoginWithReturnHandler(
_action?: any,
_context?: any
): Promise<void> {
const G7Core = (window as any).G7Core;
if (!G7Core?.dispatch) {
logger.error('G7Core.dispatch 가 초기화되지 않아 로그인 리다이렉트를 실행할 수 없습니다.');
return;
}
// 핸들러는 표현식 화이트리스트 제약 밖 — window.location 직접 접근 가능.
// pathname + search 로 현재 경로(쿼리스트링 포함)를 보존한다.
const returnUrl = window.location.pathname + window.location.search;
await G7Core.dispatch({
handler: 'navigate',
params: {
path: '/login',
// navigate 가 params.query 를 URLSearchParams 로 인코딩(ActionDispatcher.ts handleNavigate).
// 로그인 폼은 {{query.redirect ?? '/'}} 로 복원(_login_form.json).
query: { redirect: returnUrl },
},
});
}
@@ -13,6 +13,9 @@
const CART_KEY_STORAGE_NAME = 'g7_cart_key';
const CART_KEY_API_ENDPOINT = '/api/modules/sirsoft-ecommerce/cart/key';
const GUEST_ORDER_TOKEN_STORAGE_NAME = 'g7_guest_order_token';
const GUEST_ORDER_NUMBER_STORAGE_NAME = 'g7_guest_order_number';
const GUEST_ORDER_EXPIRES_AT_STORAGE_NAME = 'g7_guest_order_expires_at';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Handler:Storage')) ?? {
@@ -249,3 +252,157 @@ export function loadFromStorageHandler(
return defaultValue || null;
}
}
/**
* sessionStorage 의 비회원 주문 토큰을 모두 삭제합니다 (내부 헬퍼).
*
* 토큰/주문번호/만료시각 3개 키를 함께 비웁니다.
*/
function clearGuestOrderTokenInternal(): void {
try {
sessionStorage.removeItem(GUEST_ORDER_TOKEN_STORAGE_NAME);
sessionStorage.removeItem(GUEST_ORDER_NUMBER_STORAGE_NAME);
sessionStorage.removeItem(GUEST_ORDER_EXPIRES_AT_STORAGE_NAME);
} catch {
// sessionStorage 접근 불가 시 무시
}
}
/**
* 비회원 주문 조회 토큰 초기화 (init_actions 전용)
*
* sessionStorage 의 g7_guest_order_token 을 읽어 `_global.guestOrderToken` 에 설정한다.
* 표준 loadFromSessionStorage 핸들러는 `context.setState`(React 컴포넌트 state)를 호출해
* `_local` 에만 영향을 주므로, `_global` 에 토큰을 설정하려면 `G7Core.state.set` 직접 호출이 필요하다.
* `initCartKey` 와 동일한 패턴.
*
* 동작:
* 1. sessionStorage 에서 토큰/만료시각 로드 (탭 종료 시 자동 소실 — 공유 PC 안전)
* 2. 만료된 토큰은 자동 폐기 (3개 키 모두 제거)
* 3. `_global.guestOrderToken` 에 토큰 또는 null 설정
* 4. `_user_base.globalHeaders` 의 `X-Guest-Order-Token: {{_global.guestOrderToken}}` 패턴이
* 토큰 있을 때만 `guest/orders/*` 호출에 헤더 자동 주입 (엔진이 null/빈값 자동 제외)
*
* @param _action 액션 정의 (사용하지 않음)
* @param _context 액션 컨텍스트 (사용하지 않음)
*/
export function initGuestOrderTokenHandler(
_action?: any,
_context?: any
): void {
let token: string | null = null;
let expiresAt: string | null = null;
try {
token = sessionStorage.getItem(GUEST_ORDER_TOKEN_STORAGE_NAME);
expiresAt = sessionStorage.getItem(GUEST_ORDER_EXPIRES_AT_STORAGE_NAME);
} catch {
// sessionStorage 접근 불가 시 무시
}
// 만료된 토큰 자동 폐기 (백엔드도 동일 시각 기준으로 거부하지만 로컬에서 미리 정리)
// expiresAt 이 invalid 포맷이면 getTime() 이 NaN → NaN <= now 비교가 false 라
// 만료 인식이 안 되는 회귀를 방어한다. invalid 토큰도 명시적으로 폐기.
let expired = false;
if (token) {
const expiryTs = expiresAt ? new Date(expiresAt).getTime() : NaN;
if (isNaN(expiryTs) || expiryTs <= Date.now()) {
clearGuestOrderTokenInternal();
token = null;
expired = true;
}
}
if (token) {
// sessionStorage 에 유효 토큰이 있으면 그 값으로 _global 동기화 (새로고침/재방문 경로)
setGlobalState({ guestOrderToken: token });
logger.log('Guest order token loaded from sessionStorage');
return;
}
// sessionStorage 에 토큰이 없을 때, 직전 단계(verify onSuccess saveGuestOrderToken)가
// 이미 _global.guestOrderToken 에 동기 set 해 둔 in-memory 토큰을 보존한다.
// 조회 폼 verify→상세 SPA 전이에서 sessionStorage 쓰기가 제때 반영되지 않거나
// (브라우저/프라이버시 모드) 비활성인 환경에서도, navigate 로 살아남은 _global 토큰으로
// 상세 데이터소스가 X-Guest-Order-Token 을 주입할 수 있게 한다.
// 단, 만료로 명시 폐기된 경우(expired)는 in-memory 토큰도 비운다.
if (!expired) {
const G7Core = (window as any).G7Core;
const existing = G7Core?.state?.get?.('_global')?.guestOrderToken;
if (typeof existing === 'string' && existing !== '') {
logger.log('Guest order token preserved from in-memory _global (sessionStorage empty)');
return;
}
}
setGlobalState({ guestOrderToken: null });
logger.log('No guest order token (visitor not authenticated)');
}
// 표시 통화(preferredCurrency) 초기화 핸들러는 이커머스 모듈로 이전되었다
// (modules/_bundled/sirsoft-ecommerce/resources/js/handlers/initPreferredCurrency.ts).
// "통화 = 커머스 책임" 원칙 — 레이아웃은 `sirsoft-ecommerce.initPreferredCurrency` 로 호출한다.
/**
* 비회원 주문 토큰을 sessionStorage 에 저장하고 _global 에 동기 set 합니다.
*
* 토큰/주문번호/만료시각 3개 키를 함께 저장하며, _global.guestOrderToken 도 즉시 갱신해
* 직후 호출되는 navigate 의 globalHeaders 자동 주입이 동작하도록 한다.
*
* @param action params.token, params.orderNumber, params.expiresAt 필수
* @param _context 액션 컨텍스트 (사용하지 않음)
*/
export function saveGuestOrderTokenHandler(
action?: any,
_context?: any
): void {
const { token, orderNumber, expiresAt } = action?.params || {};
if (!token || !orderNumber || !expiresAt) {
logger.warn('saveGuestOrderToken: token, orderNumber, expiresAt are required');
return;
}
try {
sessionStorage.setItem(GUEST_ORDER_TOKEN_STORAGE_NAME, token);
sessionStorage.setItem(GUEST_ORDER_NUMBER_STORAGE_NAME, orderNumber);
sessionStorage.setItem(GUEST_ORDER_EXPIRES_AT_STORAGE_NAME, expiresAt);
} catch {
// sessionStorage 접근 불가 시 무시 (private 모드 등) — _global 만 set 되어 현재 페이지는 동작
}
setGlobalState({ guestOrderToken: token });
}
/**
* 비회원 주문 토큰을 sessionStorage 에서 삭제하고 _global 도 비웁니다.
*
* 비회원 주문 취소/구매확정/명시적 로그아웃 등 토큰 무효화 시점에서 호출.
*
* @param _action 액션 정의 (사용하지 않음)
* @param _context 액션 컨텍스트 (사용하지 않음)
*/
export function clearGuestOrderTokenHandler(
_action?: any,
_context?: any
): void {
clearGuestOrderTokenInternal();
setGlobalState({ guestOrderToken: null });
}
/**
* 비회원 주문 조회 폼(guest_order_form) 진입 시 sessionStorage 의 비회원 주문 토큰을 초기화한다.
*
* 비회원 주문 조회 폼은 매번 새로 본인 확인을 거치는 게 표준 패턴(eBay/Best Buy/카페24/
* 11번가/G마켓 등). 결제 직후 자동 verify 로 받은 토큰은 완료/상세 화면에서는 유효하지만,
* 사용자가 헤더 '비회원 주문 조회' 메뉴 등을 통해 조회 폼에 도달했을 때는 의도가
* "다시 조회" 이므로 토큰을 비워 폼이 정상 노출되도록 한다.
*
* 만료된 토큰도 같은 경로로 자연스럽게 정리된다.
*
* @param _action 액션 정의 (사용하지 않음)
* @param _context 액션 컨텍스트 (사용하지 않음)
*/
export function clearGuestTokenOnEntryHandler(
_action?: any,
_context?: any
): void {
clearGuestOrderTokenInternal();
setGlobalState({ guestOrderToken: null });
}
+12 -4
View File
@@ -1,3 +1,4 @@
// e2e:allow편집기 위젯(icon-picker) 등록을 module-load 시점으로 이동(결함#3, admin 동기 — 직접 하드로드 시 위젯 누락 해소). 단위 회귀는 registerEditorWidgets.test.ts(module-load 등록 + index.ts 최상위 호출 정적 가드).
/**
* Sirsoft Basic User Template
*
@@ -88,10 +89,6 @@ export {
type IconProps,
Code,
type CodeProps,
Footer as BasicFooter,
type FooterProps as BasicFooterProps,
Header as BasicHeader,
type HeaderProps as BasicHeaderProps,
Hr,
type HrProps,
IconName,
@@ -114,6 +111,9 @@ import { handlerMap } from './handlers';
// IDV Modal Launcher (engine-v1.46.0+)
import { registerSirsoftBasicIdentityLauncher } from './handlers/identityLauncher';
// 레이아웃 편집기 커스텀 위젯(icon-picker 등) 등록
import { registerSirsoftBasicEditorWidgets } from './layout-editor/registerEditorWidgets';
// handlerMap을 전역으로 노출 (로케일 변경 시 재등록용)
if (typeof window !== 'undefined') {
(window as any).G7TemplateHandlers = handlerMap;
@@ -171,5 +171,13 @@ export function initTemplate(): void {
}
}
// 레이아웃 편집기 커스텀 위젯(icon-picker) 등록 — 모듈 로드 시점에 즉시 실행한다.
// ActionDispatcher 가용을 기다리는 `registerHandlers`(window.load
// 게이트) 안에서 등록하면, 편집기 URL 을 직접 하드로드한 경로에서 등록이 편집기 셸 마운트보다
// 늦어 icon-picker 위젯이 누락된다("Unsupported control"). `G7Core.layoutEditor` 예약 접수함
// (ready 큐 stub)은 편집기 로드 전 등록도 큐로 보존했다가 flush 하므로, 핸들러 등록 타이밍과
// 무관하게 모듈 로드 시 즉시 등록하는 것이 진입 경로(SPA 전환 / 직접 로드)와 무관하게 결정적이다.
registerSirsoftBasicEditorWidgets();
// 템플릿 초기화 자동 실행
initTemplate();
@@ -0,0 +1,184 @@
/**
* IconPickerWidget.tsx — sirsoft-basic 템플릿 소유 아이콘 피커 위젯
*
* 레이아웃 편집기 [속성] 탭에서 아이콘명 prop(`Icon.name`/`IconButton.iconName` 등)을
* **검색 가능한 그리드 드롭다운**으로 고른다. 값은 아이콘명 문자열(propValue 로
* `node.props[propKey]` 기록).
*
* **소유 경계**: 아이콘 검색 그리드 UI 는 라이브러리(Font Awesome) 종속
* 지식이므로 **템플릿이 소유**한다. 코어는 icon-picker 위젯을 제공하지 않으며, 본 위젯을
* `G7Core.layoutEditor.registerWidget('icon-picker', ...)` 로 등록해 사용한다(코어 예약
* 접수함이 편집기 로드 전 등록도 큐로 보존 → 편집기 로드 시 flush). 카탈로그(`control.icons`)
* 도 템플릿 editor-spec 이 공급한다. 본 위젯은 Font Awesome 클래스(`fas fa-{value}`)로
* 프리뷰를 직접 렌더한다(템플릿이 자기 라이브러리를 알기 때문).
*
* 카탈로그 미공급 시 자유입력(text) 폴백.
*/
import React from 'react';
/** 코어 WidgetProps 와 호환되는 최소 형태 — 코어 타입 import 회피(IIFE 번들 분리 안전) */
interface IconCatalogEntry {
value: string;
label?: string;
keywords?: string[];
group?: string;
preview?: { html?: string; className?: string };
}
interface IconPickerWidgetProps {
control: { icons?: unknown; iconColumns?: number; iconSearchPlaceholder?: string } & Record<
string,
unknown
>;
value: unknown;
onChange: (value: unknown) => void;
t: (key: string, params?: Record<string, string | number>) => string;
}
function readCatalog(control: IconPickerWidgetProps['control']): IconCatalogEntry[] {
const icons = control.icons;
if (!Array.isArray(icons)) return [];
return icons.filter(
(e): e is IconCatalogEntry =>
!!e && typeof e === 'object' && typeof (e as IconCatalogEntry).value === 'string',
);
}
function entryLabel(entry: IconCatalogEntry, t: IconPickerWidgetProps['t']): string {
const label = entry.label;
if (typeof label === 'string') return label.startsWith('$t:') ? t(label.slice(3)) : label;
return entry.value;
}
function matchesQuery(entry: IconCatalogEntry, label: string, q: string): boolean {
if (q === '') return true;
const needle = q.toLowerCase();
if (entry.value.toLowerCase().includes(needle)) return true;
if (label.toLowerCase().includes(needle)) return true;
return (entry.keywords ?? []).some((k) => k.toLowerCase().includes(needle));
}
/** FA 프리뷰 — preview.html → preview.className → `fas fa-{value}` (FA 직접 렌더) → 텍스트 */
function IconPreview({ entry }: { entry: IconCatalogEntry }): React.ReactElement {
const preview = entry.preview;
if (preview?.html) {
return (
<span
className="g7le-icon-preview"
dangerouslySetInnerHTML={{ __html: preview.html }}
style={previewBox}
/>
);
}
if (preview?.className) {
return <span className={`g7le-icon-preview ${preview.className}`} style={previewBox} />;
}
// 템플릿은 자기 라이브러리(Font Awesome)를 알므로 클래스 직접 합성.
return <i className={`fas fa-${entry.value}`} style={previewBox} aria-hidden="true" />;
}
export function IconPickerWidget({
control,
value,
onChange,
t,
}: IconPickerWidgetProps): React.ReactElement {
const catalog = readCatalog(control);
const current = value === undefined || value === null ? '' : String(value);
const columns = typeof control.iconColumns === 'number' ? control.iconColumns : 6;
const searchPlaceholderKey = control.iconSearchPlaceholder;
const searchPlaceholder =
typeof searchPlaceholderKey === 'string' && searchPlaceholderKey.startsWith('$t:')
? t(searchPlaceholderKey.slice(3))
: t('layout_editor.icon_picker.search_placeholder');
const [query, setQuery] = React.useState('');
// 카탈로그 미공급 → 자유입력 폴백.
if (catalog.length === 0) {
return (
<div
className="g7le-widget g7le-widget--icon-picker"
data-testid="g7le-widget-icon-picker"
style={wrap}
>
<input
type="text"
className="g7le-widget g7le-widget--icon-free"
data-testid="g7le-widget-icon-picker-free"
value={current}
placeholder={t('layout_editor.icon_picker.free_input_hint')}
onChange={(e) => onChange(e.target.value === '' ? undefined : e.target.value)}
style={inputStyle}
/>
</div>
);
}
const labelOf = (e: IconCatalogEntry): string => entryLabel(e, t);
const filtered = catalog.filter((e) => matchesQuery(e, labelOf(e), query));
return (
<div
className="g7le-widget g7le-widget--icon-picker"
data-testid="g7le-widget-icon-picker"
style={wrap}
>
<input
type="text"
className="g7le-widget g7le-widget--icon-search"
data-testid="g7le-widget-icon-picker-search"
value={query}
placeholder={searchPlaceholder}
onChange={(e) => setQuery(e.target.value)}
style={inputStyle}
/>
<div
className="g7le-icon-grid"
data-testid="g7le-widget-icon-picker-grid"
style={{ ...grid, gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` }}
>
<button
type="button"
data-testid="g7le-icon-cell-none"
title={t('layout_editor.icon_picker.none')}
onClick={() => onChange(undefined)}
aria-pressed={current === ''}
style={current === '' ? cellSelected : cell}
>
<span style={previewText}>—</span>
</button>
{filtered.map((entry) => {
const selected = entry.value === current;
return (
<button
key={entry.value}
type="button"
data-testid={`g7le-icon-cell-${entry.value}`}
title={labelOf(entry)}
aria-pressed={selected}
onClick={() => onChange(entry.value)}
style={selected ? cellSelected : cell}
>
<IconPreview entry={entry} />
</button>
);
})}
</div>
{filtered.length === 0 && (
<div data-testid="g7le-widget-icon-picker-empty" style={emptyHint}>
{t('layout_editor.icon_picker.no_results')}
</div>
)}
</div>
);
}
const wrap: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 6, width: '100%' };
const inputStyle: React.CSSProperties = { padding: '5px 8px', fontSize: 12, border: '1px solid #cbd5e1', borderRadius: 6, width: '100%' };
const grid: React.CSSProperties = { display: 'grid', gap: 4, maxHeight: 220, overflowY: 'auto', padding: 2 };
const cell: React.CSSProperties = { display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: 34, padding: 4, border: '1px solid #e2e8f0', borderRadius: 6, background: '#fff', cursor: 'pointer' };
const cellSelected: React.CSSProperties = { ...cell, border: '2px solid #2563eb', background: '#eff6ff' };
const previewBox: React.CSSProperties = { display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 16, lineHeight: 1 };
const previewText: React.CSSProperties = { fontSize: 10, color: '#475569', fontFamily: 'monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: '100%' };
const emptyHint: React.CSSProperties = { fontSize: 11, color: '#94a3b8', fontStyle: 'italic', padding: '4px 2px' };
@@ -0,0 +1,69 @@
/**
* IconPickerWidget.test.tsx — 템플릿 소유 아이콘 피커 위젯
*
* 검증: 카탈로그 그리드 렌더 / 검색 필터 / 선택 → onChange / 카탈로그 없으면 자유입력 폴백.
*/
import React from 'react';
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { IconPickerWidget } from '../IconPickerWidget';
const t = (k: string) => k;
const catalog = [
{ value: 'star', keywords: ['star', 'favorite'] },
{ value: 'heart', keywords: ['heart', 'love'] },
{ value: 'house', keywords: ['house', 'home'] },
];
function renderWidget(control: any, value: unknown = '', onChange = vi.fn()) {
render(<IconPickerWidget control={control} value={value} onChange={onChange} t={t} />);
return onChange;
}
describe('템플릿 IconPickerWidget', () => {
it('카탈로그가 있으면 검색 + 그리드 렌더(자유입력 아님)', () => {
renderWidget({ icons: catalog, iconColumns: 8 });
expect(screen.getByTestId('g7le-widget-icon-picker-search')).toBeTruthy();
expect(screen.getByTestId('g7le-widget-icon-picker-grid')).toBeTruthy();
expect(screen.queryByTestId('g7le-widget-icon-picker-free')).toBeNull();
// 3개 아이콘 + "없음" 셀
expect(screen.getByTestId('g7le-icon-cell-star')).toBeTruthy();
expect(screen.getByTestId('g7le-icon-cell-heart')).toBeTruthy();
expect(screen.getByTestId('g7le-icon-cell-none')).toBeTruthy();
});
it('검색어로 카탈로그를 필터한다(value/keywords)', () => {
renderWidget({ icons: catalog });
const search = screen.getByTestId('g7le-widget-icon-picker-search');
fireEvent.change(search, { target: { value: 'love' } }); // heart 의 keyword
expect(screen.getByTestId('g7le-icon-cell-heart')).toBeTruthy();
expect(screen.queryByTestId('g7le-icon-cell-star')).toBeNull();
expect(screen.queryByTestId('g7le-icon-cell-house')).toBeNull();
});
it('아이콘 셀 클릭 → onChange(value)', () => {
const onChange = renderWidget({ icons: catalog });
fireEvent.click(screen.getByTestId('g7le-icon-cell-heart'));
expect(onChange).toHaveBeenCalledWith('heart');
});
it('"없음" 클릭 → onChange(undefined) (prop 삭제)', () => {
const onChange = renderWidget({ icons: catalog }, 'star');
fireEvent.click(screen.getByTestId('g7le-icon-cell-none'));
expect(onChange).toHaveBeenCalledWith(undefined);
});
it('카탈로그 미공급 → 자유입력 폴백', () => {
renderWidget({ icons: [] });
expect(screen.getByTestId('g7le-widget-icon-picker-free')).toBeTruthy();
expect(screen.queryByTestId('g7le-widget-icon-picker-grid')).toBeNull();
});
it('FA 프리뷰: 셀에 fas fa-{value} 글리프 렌더', () => {
renderWidget({ icons: [{ value: 'heart' }] });
const cell = screen.getByTestId('g7le-icon-cell-heart');
expect(cell.querySelector('i.fas.fa-heart')).toBeTruthy();
});
});
@@ -0,0 +1,91 @@
/**
* registerEditorWidgets.test.ts — 편집기 커스텀 위젯 등록
*
* 배경: icon-picker 등록이 `initTemplate`의 `registerHandlers`(window.load + ActionDispatcher
* 재시도 게이트) 안에 묶여 있어, 편집기 URL 을 직접 하드로드한 경로에서 등록이 편집기 셸 마운트보다
* 늦어 위젯이 누락("Unsupported control")됐다. 등록은 ActionDispatcher 가용과 무관하게
* `G7Core.layoutEditor` 예약 접수함(ready 큐 stub)으로 즉시 수행돼야 한다.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve } from 'node:path';
import { registerSirsoftBasicEditorWidgets } from '../registerEditorWidgets';
declare const window: Window & typeof globalThis & { G7Core?: Record<string, unknown> };
const __dir = dirname(fileURLToPath(import.meta.url));
const INDEX_TS = resolve(__dir, '../../index.ts');
describe(' — basic 편집기 위젯 등록 (ActionDispatcher 무관)', () => {
beforeEach(() => {
delete window.G7Core;
});
afterEach(() => {
delete window.G7Core;
});
it('실제 레지스트리가 있으면 icon-picker 를 즉시 등록한다', () => {
const registerWidget = vi.fn();
window.G7Core = { layoutEditor: { registerWidget } };
registerSirsoftBasicEditorWidgets();
expect(registerWidget).toHaveBeenCalledTimes(1);
expect(registerWidget.mock.calls[0][0]).toBe('icon-picker');
expect(typeof registerWidget.mock.calls[0][1]).toBe('function');
});
it('ActionDispatcher 부재 + ready 큐 stub 만 있어도 등록 호출이 흘러간다', () => {
const queue: Array<[string, ...unknown[]]> = [];
window.G7Core = {
layoutEditor: {
__isStub: true,
__queue: queue,
registerWidget: (name: string, comp: unknown) => queue.push(['widget', name, comp]),
},
};
registerSirsoftBasicEditorWidgets();
expect(queue).toHaveLength(1);
expect(queue[0][0]).toBe('widget');
expect(queue[0][1]).toBe('icon-picker');
});
it('G7Core.layoutEditor 부재 시 throw 없이 no-op', () => {
window.G7Core = {};
expect(() => registerSirsoftBasicEditorWidgets()).not.toThrow();
window.G7Core = { layoutEditor: {} };
expect(() => registerSirsoftBasicEditorWidgets()).not.toThrow();
});
it('index.ts 가 registerSirsoftBasicEditorWidgets 를 모듈 최상위에서 호출한다(핸들러 게이트 밖)', () => {
const src = readFileSync(INDEX_TS, 'utf8');
const lines = src.split(/\r?\n/);
const fnStart = lines.findIndex((l) => /export function initTemplate\s*\(/.test(l));
expect(fnStart).toBeGreaterThanOrEqual(0);
let depth = 0;
let fnEnd = -1;
for (let i = fnStart; i < lines.length; i++) {
depth += (lines[i].match(/{/g) || []).length;
depth -= (lines[i].match(/}/g) || []).length;
if (i > fnStart && depth === 0) {
fnEnd = i;
break;
}
}
expect(fnEnd).toBeGreaterThan(fnStart);
const invocationLines = lines
.map((l, i) => ({ l, i }))
.filter(({ l }) => /registerSirsoftBasicEditorWidgets\s*\(\s*\)/.test(l))
.filter(({ l }) => !/^\s*import\b/.test(l));
expect(invocationLines.length).toBeGreaterThan(0);
for (const { i } of invocationLines) {
expect(i < fnStart || i > fnEnd).toBe(true);
}
});
});
@@ -0,0 +1,34 @@
/**
* registerEditorWidgets.ts — sirsoft-basic 편집기 커스텀 위젯 등록
*
* 템플릿 부트스트랩(initTemplate)에서 호출. `G7Core.layoutEditor` 는 코어 예약 접수함
* (stub)이 메인 번들에서 항상 노출하므로, 편집기 셸 로드 전에 호출해도 등록이 큐에
* 보존되었다가 편집기 로드 시 flush 된다(타이밍 안전).
*
* 등록 위젯:
* - `icon-picker` — Font Awesome 검색 그리드(템플릿 소유 UI, 라이브러리 종속).
*/
import React from 'react';
import { IconPickerWidget } from './IconPickerWidget';
const logger = (window as any).G7Core?.createLogger?.('Template:sirsoft-basic:EditorWidgets') ?? {
log: (...a: unknown[]) => console.log('[Template:sirsoft-basic:EditorWidgets]', ...a),
warn: (...a: unknown[]) => console.warn('[Template:sirsoft-basic:EditorWidgets]', ...a),
};
/**
* 편집기 커스텀 위젯을 코어 레지스트리에 등록한다. 멱등 — `G7Core.layoutEditor` 부재(코어
* 미초기화)면 no-op(다음 호출에서 재시도하거나 stub 이 보존).
*/
export function registerSirsoftBasicEditorWidgets(): void {
if (typeof window === 'undefined') return;
const layoutEditor = (window as any).G7Core?.layoutEditor;
if (!layoutEditor?.registerWidget) {
logger.warn('G7Core.layoutEditor 미노출 — icon-picker 위젯 등록 보류');
return;
}
// 코어 위젯 레지스트리는 React 컴포넌트를 받는다. WidgetProps 형태로 호출됨.
layoutEditor.registerWidget('icon-picker', IconPickerWidget as React.ComponentType<unknown>);
logger.log("편집기 위젯 'icon-picker' 등록됨(Font Awesome 검색 그리드)");
}
@@ -142,6 +142,11 @@
* 컴포넌트 스타일
*/
@layer components {
/* 레이아웃 시맨틱 유틸리티 */
.flex-between {
@apply flex items-center justify-between;
}
/* 버튼 기본 스타일 */
.btn {
@apply inline-flex items-center justify-center font-medium rounded-lg transition-colors;
@@ -623,3 +623,25 @@ xl:items-start xl:items-end xl:items-center
2xl:px-0 2xl:px-4 2xl:px-6 2xl:px-8 2xl:px-12 2xl:px-16
2xl:py-0 2xl:py-4 2xl:py-6 2xl:py-8 2xl:py-12 2xl:py-16
2xl:gap-0 2xl:gap-4 2xl:gap-6 2xl:gap-8 2xl:gap-12 2xl:gap-16
/*
* 레이아웃 편집기 다크 모드 classToken
* 편집기 [스타일] 탭 다크 세부탭이 editor-spec.json 의 classToken 컨트롤 토큰에 dark: prefix 를
* 붙여 적용한다(정렬/방향/줄바꿈/정렬·아이템 정렬/글자크기·굵기·자간·행간). 그 클래스가 빌드 CSS 에
* 없으면(레이아웃 JSON 에서 미사용 시 Tailwind 가 생성 안 함) 다크에서 화면에 반영되지 않으므로
* 여기서 보장한다. 토큰 목록의 SSoT 는 editor-spec.json — 컨트롤 토큰 변경 시 함께 갱신.
*/
dark:block dark:flex dark:flex-1 dark:flex-auto dark:flex-col dark:flex-none dark:flex-row dark:flex-wrap
dark:font-bold dark:font-normal dark:font-semibold
dark:items-center dark:items-end dark:items-start dark:items-stretch
dark:justify-around dark:justify-between dark:justify-center dark:justify-end dark:justify-start
dark:leading-normal dark:leading-relaxed dark:leading-tight
dark:self-center dark:self-end dark:self-start dark:self-stretch
dark:text-2xl dark:text-3xl dark:text-base dark:text-center dark:text-left dark:text-lg dark:text-right dark:text-sm dark:text-xl dark:text-xs
dark:tracking-normal dark:tracking-tight dark:tracking-wide
/* 편집기 색상 컨트롤 프리셋 — textColor/backgroundColor classToken 프리셋의 dark: 변형 */
dark:text-gray-900 dark:text-gray-700 dark:text-gray-500 dark:text-white dark:text-blue-600 dark:text-red-600 dark:text-green-600
dark:bg-white dark:bg-gray-50 dark:bg-gray-100 dark:bg-gray-800 dark:bg-gray-900 dark:bg-blue-600 dark:bg-red-600
/* (라이트+다크) — editor-spec classToken/scale 도출 */
bg-blue-600 bg-gray-100 bg-gray-50 bg-gray-800 bg-gray-900 bg-red-600 bg-white block border border-0 border-blue-600 border-dashed border-dotted border-gray-300 border-gray-500 border-gray-700 border-gray-900 border-green-600 border-red-600 border-solid border-white flex flex-1 flex-auto flex-col flex-none flex-row flex-wrap font-bold font-normal font-semibold italic items-center items-end items-start items-stretch justify-around justify-between justify-center justify-end justify-start leading-normal leading-relaxed leading-tight opacity-0 opacity-100 opacity-25 opacity-50 opacity-75 overflow-auto overflow-hidden overflow-visible overflow-x-auto overflow-y-auto rounded rounded-full rounded-lg rounded-none rounded-sm rounded-xl self-center self-end self-start self-stretch shadow shadow-2xl shadow-lg shadow-none shadow-sm shadow-xl text-2xl text-3xl text-base text-blue-600 text-center text-gray-500 text-gray-700 text-gray-900 text-green-600 text-justify text-left text-lg text-red-600 text-right text-sm text-white text-xl text-xs tracking-normal tracking-tight tracking-wide underline whitespace-normal whitespace-nowrap whitespace-pre-wrap
dark:bg-blue-600 dark:bg-gray-100 dark:bg-gray-50 dark:bg-gray-800 dark:bg-gray-900 dark:bg-red-600 dark:bg-white dark:block dark:border dark:border-0 dark:border-blue-600 dark:border-dashed dark:border-dotted dark:border-gray-300 dark:border-gray-500 dark:border-gray-700 dark:border-gray-900 dark:border-green-600 dark:border-red-600 dark:border-solid dark:border-white dark:flex dark:flex-1 dark:flex-auto dark:flex-col dark:flex-none dark:flex-row dark:flex-wrap dark:font-bold dark:font-normal dark:font-semibold dark:italic dark:items-center dark:items-end dark:items-start dark:items-stretch dark:justify-around dark:justify-between dark:justify-center dark:justify-end dark:justify-start dark:leading-normal dark:leading-relaxed dark:leading-tight dark:opacity-0 dark:opacity-100 dark:opacity-25 dark:opacity-50 dark:opacity-75 dark:overflow-auto dark:overflow-hidden dark:overflow-visible dark:overflow-x-auto dark:overflow-y-auto dark:rounded dark:rounded-full dark:rounded-lg dark:rounded-none dark:rounded-sm dark:rounded-xl dark:self-center dark:self-end dark:self-start dark:self-stretch dark:shadow dark:shadow-2xl dark:shadow-lg dark:shadow-none dark:shadow-sm dark:shadow-xl dark:text-2xl dark:text-3xl dark:text-base dark:text-blue-600 dark:text-center dark:text-gray-500 dark:text-gray-700 dark:text-gray-900 dark:text-green-600 dark:text-justify dark:text-left dark:text-lg dark:text-red-600 dark:text-right dark:text-sm dark:text-white dark:text-xl dark:text-xs dark:tracking-normal dark:tracking-tight dark:tracking-wide dark:underline dark:whitespace-normal dark:whitespace-nowrap dark:whitespace-pre-wrap
@@ -1,3 +1,30 @@
import type React from 'react';
/**
* 레이아웃 편집기 주입 속성 (editor attributes)
*
* 편집 모드에서 코어 `DynamicRenderer` 가 각 nesting 컴포넌트에 단일 prop 으로
* 주입하는 DOM 표식/이벤트 핸들러 묶음입니다. 컴포넌트는 이 객체를 받아
* **시각적 루트 요소**에 그대로 spread(`{...editorAttrs}`) 해야 합니다.
*
* - 사용자 페이지(비편집)에서는 주입되지 않으므로 `editorAttrs === undefined`,
* `{...undefined}` 는 no-op → DOM 구조/속성 불변 (사용자 페이지 ↔ 프리뷰 패리티 유지).
* - 포함 내용: `data-editor-*` 표식(드롭 슬롯/드래그 핸들 DOM 쿼리용) + 선택/hover 핸들러.
* - 도메인 prop 은 컴포넌트가 명시 구조분해하므로 이 객체로 누출되지 않습니다.
*
*/
export interface EditorAttrs {
'data-editor-id'?: string;
'data-editor-name'?: string;
'data-editor-type'?: string;
'data-editor-path'?: string;
onClick?: (event: React.MouseEvent) => void;
onMouseMove?: (event: React.MouseEvent) => void;
onMouseLeave?: (event: React.MouseEvent) => void;
/** 미래 확장 여지 (현재 주입 키 외 임의 data-/aria- 속성 허용) */
[key: string]: unknown;
}
/**
* 핸들러 컨텍스트 타입 정의 (테스트 호환용)
*