fix(core, sirsoft-ecommerce, sirsoft-basic): 배송국가 다국어 표시·입력 지원
$localized 가 ActionDispatcher 경로에서 항상 ko 를 반환했다. 컨텍스트에 $locale 이 없다는 것은 "로케일이 ko" 라는 뜻이 아니라 "이 경로가 로케일을 넘기지 않는다" 는 뜻인데, context.$locale || 'ko' 로 하드코딩 폴백하고 있었다. 바로 아래 $t 는 engine-v1.38.2 에서 이미 앱 설정 회수 폴백을 갖췄으나 $localized 만 정의 순서상 그 폴백보다 위에 있어 혜택을 받지 못했다. 로케일/templateId 해석을 두 헬퍼 앞으로 끌어올려 공유한다 (engine-v1.52.1). 국가 추가 폼은 이름 입력칸이 ko/en 두 칸으로 고정돼 그 외 언어의 국가명을 넣을 수 없었다. 설치된 언어를 $locales 로 순회해 입력칸을 만들고, 추가 조건도 특정 로케일 대신 "어느 한 언어라도 채워졌는가" 로 바꾼다. 백엔드 StoreEcommerceSettingsRequest 도 name 을 array 로만 요구하므로 계약이 일치한다. 저장 시 입력하지 않은 로케일은 남기지 않는다. 기존 저장본에 박힌 빈 문자열은 업그레이드 스텝이 청소한다 — 부재 로케일은 서버 localize_catalog_field 가 읽기 시점에 언어팩으로 보강하므로, 빈 문자열은 그 보강을 막는 어중간한 상태였다. 동일 결함 재발을 막는 audit 룰(engine-context-locale-hardcoded-fallback)을 함께 추가한다. 수정 전 코드에서 1건 검출, 수정 후 0건을 확인했다.
This commit is contained in:
1 parent
0f84657a5c
commit
051ed1e528
27 files changed
+996
-190
No files matched your search
@@ -4,15 +4,17 @@
|
||||
형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며,
|
||||
[Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다.
|
||||
|
||||
## [1.0.2] - 2026-07-09
|
||||
## [1.0.2] - 2026-07-10
|
||||
|
||||
### Changed
|
||||
|
||||
- 쇼핑몰 환경설정 > 배송설정에서 배송가능 국가를 추가할 때, 사이트에 설치된 모든 언어에 대해 국가명을 입력할 수 있습니다. 기존에는 한국어·영어 두 칸만 있어 그 외 언어의 국가명을 넣을 방법이 없었습니다. 언어를 새로 설치하면 입력칸도 함께 늘어납니다. 입력하지 않은 언어는 저장되지 않으며, 기본 제공 국가는 언어팩이 자동으로 채웁니다.
|
||||
- 휴대폰·태블릿 화면에서 통화·배송국가 선택이 메뉴 안의 접었다 펼치는 항목으로 바뀌었습니다. 접혀 있을 때도 현재 선택된 통화와 배송국가가 함께 표시되어 펼치지 않아도 확인할 수 있고, 펼치면 가로 버튼으로 나열됩니다. 좁은 화면의 메뉴 안에서 드롭다운이 잘려 보이던 문제가 함께 해소됩니다. 데스크톱 화면의 드롭다운은 그대로입니다. 관리자 화면도 동일하게 적용됩니다.
|
||||
- 휴대폰 화면에서 주문 취소·주문상태 일괄변경 팝업의 상품 목록이 표 대신 상품별 카드 형태로 표시됩니다.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 배송국가 이름이 어떤 언어로 화면을 보든 항상 한국어로만 표시되던 문제를 수정했습니다. 이제 사용자·관리자 헤더의 배송국가 선택, 회원가입의 배송국가 선택, 관리자 회원정보와 주문상세의 배송국가, 배송설정의 기본 배송국가가 모두 현재 보고 있는 언어로 표시됩니다. 일본어처럼 나중에 추가한 언어에서도 언어팩이 제공하는 국가명이 그대로 반영됩니다.
|
||||
- 쇼핑몰 환경설정의 은행 관리에서 은행코드를 입력해도 입력한 값이 보이지 않던 문제를 수정했습니다 — 좁은 화면에서 입력칸이 글자가 들어갈 수 없을 만큼 줄어들고 있었습니다.
|
||||
- 휴대폰 화면에서 주문 취소·주문상태 일괄변경 팝업의 금액이 "249,000원" 대신 "249,000" / "원" 처럼 숫자 중간에서 잘려 보이던 문제를 수정했습니다. 금액은 앞으로도 숫자 중간에서 줄바꿈되지 않으며, "결제완료" 같은 상태 이름도 "결제완" / "료" 로 쪼개지지 않습니다.
|
||||
- 휴대폰 화면에서 쇼핑몰 환경설정 화면이 좌우로 넘쳐 가로 스크롤이 생기던 문제를 수정했습니다 (이메일 입력 줄, 쇼핑몰 이름·종목 입력칸, 탭 영역).
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@
|
||||
"props": {
|
||||
"name": "ecommerce_preferred_shipping_country",
|
||||
"value": "{{_local.form?.ecommerce_preferred_shipping_country ?? user?.data?.ecommerce_preferred_shipping_country ?? _global.modules?.['sirsoft-ecommerce']?.shipping?.default_country ?? 'KR'}}",
|
||||
"options": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ value: c.code, label: (c.name?.[_global.locale] ?? c.name?.ko ?? c.code) }))}}",
|
||||
"options": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ value: c.code, label: ($localized(c.name, 'sirsoft-ecommerce::settings.countries.' + (c.code ?? '') + '.name') || c.code) }))}}",
|
||||
"className": "w-full sm:w-64"
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -24,11 +24,11 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"comment": "헤더 배송국가 셀렉터 목록 파생 주입 (유저 헤더 미러). 활성 국가만 {code, name(현지화)} 형태로. 해외배송 활성 게이트는 셀렉터 if 가 international_shipping_enabled 로 별도 체크(유저 헤더 동형). 셀렉터 if 게이트가 이 파생 상태(availableShippingCountries)를 참조.",
|
||||
"comment": "헤더 배송국가 셀렉터 목록 파생 주입 (유저 헤더 미러). 활성 국가만 {code, name(현지화)} 형태로. 해외배송 활성 게이트는 셀렉터 if 가 international_shipping_enabled 로 별도 체크(유저 헤더 동형). 셀렉터 if 게이트가 이 파생 상태(availableShippingCountries)를 참조. 국가명 $localized(name, fallbackKey): 활성 로케일 키는 서버(localize_catalog_field)가 settings.countries.{code}.name 으로 미리 보강해 통상 즉시 hit 한다. fallbackKey 와 || c.code 는 보강이 실패한 경우의 방어선.",
|
||||
"handler": "setState",
|
||||
"params": {
|
||||
"target": "global",
|
||||
"availableShippingCountries": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ code: c.code, name: (c.name?.[_global.locale] ?? c.name?.ko ?? c.code) }))}}"
|
||||
"availableShippingCountries": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ code: c.code, name: ($localized(c.name, 'sirsoft-ecommerce::settings.countries.' + (c.code ?? '') + '.name') || c.code) }))}}"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@
|
||||
"props": {
|
||||
"name": "preferred_shipping_country",
|
||||
"value": "{{_local?.registerForm?.preferred_shipping_country ?? _global.preferredShippingCountry ?? _global.modules?.['sirsoft-ecommerce']?.shipping?.default_country ?? 'KR'}}",
|
||||
"options": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ value: c.code, label: (c.name?.[_global.locale] ?? c.name?.ko ?? c.code) }))}}",
|
||||
"options": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ value: c.code, label: ($localized(c.name, 'sirsoft-ecommerce::settings.countries.' + (c.code ?? '') + '.name') || c.code) }))}}",
|
||||
"className": "w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500",
|
||||
"disabled": "{{_local?.isRegistering}}"
|
||||
}
|
||||
|
||||
+176
@@ -520,6 +520,182 @@ describe('D10 (defect #3) — 마이페이지 주소록 모달 국가 Select +
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 배송국가명 다국어 표시 회귀 (#459)
|
||||
*
|
||||
* 두 가지 회귀를 동시에 차단한다.
|
||||
*
|
||||
* ① `_global.locale` 은 존재하지 않는 경로다. 엔진은 로케일을 최상위 `$locale` 로만 노출하므로
|
||||
* (template-engine.ts::createGlobalVariables) 이를 인덱스로 쓰면 표현식이 항상 undefined 가 되어
|
||||
* `?? name?.ko` 폴백으로 떨어진다 → 어떤 로케일에서도 한국어 국가명이 표시된다.
|
||||
*
|
||||
* ② `$localized(value)` 를 fallbackKey 없이 호출하면, 저장본(settings/shipping.json)에 해당 로케일
|
||||
* 키가 없을 때 헬퍼가 ko 로 폴백한다. 기본 10개국은 언어팩이 라벨을 갖고 있으므로 fallbackKey
|
||||
* (`sirsoft-ecommerce::settings.countries.{code}.name`)를 넘겨야 언어팩 보강이 적용된다.
|
||||
* 이미 마이그레이션된 _shipping_country_table/_cards 와 동일한 계약이다(catalogLangPackFallback.test).
|
||||
*/
|
||||
describe('#459 — 배송국가명 다국어 표시 ($localized + fallbackKey)', () => {
|
||||
/** 국가 lang key 접두사 — 저장본에 로케일 키가 없을 때 언어팩으로 보강되는 경로 */
|
||||
const COUNTRY_LANG_PREFIX = 'sirsoft-ecommerce::settings.countries.';
|
||||
|
||||
/** [설명 라벨, 파일 경로, base] */
|
||||
const surfaces: Array<[string, string, string]> = [
|
||||
['사용자 헤더 셀렉터', 'layouts/_user_base.json', templateRoot],
|
||||
['관리자 헤더 셀렉터', 'resources/extensions/header-currency-selector-admin.json', moduleRoot],
|
||||
['회원가입 배송국가 필드', 'resources/extensions/register-shipping-country-field.json', moduleRoot],
|
||||
['관리자 회원 배송국가 필드', 'resources/extensions/admin-user-shipping-country-field.json', moduleRoot],
|
||||
[
|
||||
'관리자 주문상세 배송국가',
|
||||
'resources/layouts/admin/partials/admin_ecommerce_order_detail/_partial_order_info.json',
|
||||
moduleRoot,
|
||||
],
|
||||
['배송설정 기본국가 Select', 'resources/layouts/admin/partials/admin_ecommerce_settings/_tab_shipping.json', moduleRoot],
|
||||
];
|
||||
|
||||
for (const [label, rel, base] of surfaces) {
|
||||
it(`${label}: 존재하지 않는 경로 _global.locale 을 인덱스로 쓰지 않는다`, () => {
|
||||
const raw = serialize(rel, base);
|
||||
expect(raw).not.toMatch(/\[\s*_global\.locale\s*\]/);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 국가명을 표시하는 각 표현식이 $localized 를 fallbackKey 와 함께 호출하는지 검증한다.
|
||||
* `needle` 은 그 표현식을 담은 줄을 특정하기 위한 고유 문자열이다.
|
||||
*/
|
||||
const localizedCalls: Array<[string, string, string, string]> = [
|
||||
['사용자 헤더 파생', 'layouts/_user_base.json', templateRoot, '"availableShippingCountries"'],
|
||||
[
|
||||
'관리자 헤더 파생',
|
||||
'resources/extensions/header-currency-selector-admin.json',
|
||||
moduleRoot,
|
||||
'"availableShippingCountries"',
|
||||
],
|
||||
[
|
||||
'회원가입 Select options',
|
||||
'resources/extensions/register-shipping-country-field.json',
|
||||
moduleRoot,
|
||||
'"options"',
|
||||
],
|
||||
[
|
||||
'관리자 회원폼 Select options',
|
||||
'resources/extensions/admin-user-shipping-country-field.json',
|
||||
moduleRoot,
|
||||
'"options"',
|
||||
],
|
||||
[
|
||||
'배송설정 기본국가 Select options',
|
||||
'resources/layouts/admin/partials/admin_ecommerce_settings/_tab_shipping.json',
|
||||
moduleRoot,
|
||||
'"options"',
|
||||
],
|
||||
];
|
||||
|
||||
for (const [label, rel, base, needle] of localizedCalls) {
|
||||
it(`${label}: $localized 를 국가 lang key fallbackKey 와 함께 호출한다`, () => {
|
||||
const line = serialize(rel, base)
|
||||
.split('\n')
|
||||
.find((l) => l.includes(needle) && l.includes('$localized('));
|
||||
expect(line, `${needle} 를 담은 $localized 호출 줄 존재`).toBeTruthy();
|
||||
expect(line!).toContain(COUNTRY_LANG_PREFIX);
|
||||
// 폴백 체인은 헬퍼 + 언어팩이 담당한다 — 레이아웃에서 ko 를 명시 폴백하지 않는다.
|
||||
expect(line!).not.toContain('name?.ko');
|
||||
});
|
||||
}
|
||||
|
||||
it('관리자 주문상세 Select options: $localized + fallbackKey', () => {
|
||||
const line = serialize(
|
||||
'resources/layouts/admin/partials/admin_ecommerce_order_detail/_partial_order_info.json'
|
||||
)
|
||||
.split('\n')
|
||||
.find((l) => l.includes('available_countries') && l.includes('"options"'));
|
||||
expect(line, '배송국가 Select options 존재').toBeTruthy();
|
||||
expect(line!).toContain('$localized(');
|
||||
expect(line!).toContain(COUNTRY_LANG_PREFIX);
|
||||
expect(line!).not.toContain('name?.ko');
|
||||
});
|
||||
|
||||
it('관리자 주문상세: 해외배송 OFF 시 표시되는 주문 스냅샷 국가명도 $localized 로 현지화된다', () => {
|
||||
// 주문 스냅샷(recipient_country_name)은 주문 시점 다국어 JSON — 언어팩 보강 대상이 아니므로
|
||||
// fallbackKey 없이 $localized 단독 호출로 충분하다(활성 로케일 → ko → en → 첫 값).
|
||||
const line = serialize(
|
||||
'resources/layouts/admin/partials/admin_ecommerce_order_detail/_partial_order_info.json'
|
||||
)
|
||||
.split('\n')
|
||||
.find((l) => l.includes('recipient_country_name') && l.includes('"text"'));
|
||||
expect(line, '스냅샷 국가명 표시 노드 존재').toBeTruthy();
|
||||
expect(line!).toContain('$localized(');
|
||||
expect(line!).not.toContain('name?.ko');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 배송국가 추가 폼 다국어 입력 회귀 (#459)
|
||||
*
|
||||
* 운영자가 직접 추가한 국가는 언어팩에 lang key 가 없으므로 보강 대상이 아니다. 따라서 활성 언어팩
|
||||
* 전체(`$locales`)에 대해 이름을 입력할 수 있어야 하며, ko/en 두 칸 하드코딩이면 ja 등 나머지
|
||||
* 로케일에는 영원히 이름을 넣을 수 없다. 백엔드 검증은 이미 로케일 무제한(`name.*`)이다.
|
||||
*/
|
||||
describe('#459 — 배송국가 추가 폼 다국어 입력 ($locales 순회)', () => {
|
||||
const json = read('resources/layouts/admin/partials/admin_ecommerce_settings/_tab_shipping.json');
|
||||
const raw = serialize('resources/layouts/admin/partials/admin_ecommerce_settings/_tab_shipping.json');
|
||||
|
||||
const addForm = walk(json, (n) => n.id === 'add_country_form');
|
||||
|
||||
it('국가 추가 폼이 존재한다', () => {
|
||||
expect(addForm).toBeTruthy();
|
||||
});
|
||||
|
||||
it('국가명 입력칸이 $locales 순회로 생성된다 (ko/en 하드코딩 제거)', () => {
|
||||
const iterNode = walk(addForm, (n) => typeof n.iteration?.source === 'string'
|
||||
&& n.iteration.source.includes('$locales'));
|
||||
expect(iterNode, '$locales 를 순회하는 입력칸 노드 존재').toBeTruthy();
|
||||
|
||||
// 로케일별 입력칸은 newCountry.name[<loc>] 로 써야 한다 — 고정 .ko/.en 경로 금지
|
||||
const formRaw = JSON.stringify(addForm);
|
||||
expect(formRaw).not.toContain('newCountry.name.ko');
|
||||
expect(formRaw).not.toContain('newCountry.name.en');
|
||||
expect(formRaw).not.toContain('newCountry?.name?.ko');
|
||||
expect(formRaw).not.toContain('newCountry?.name?.en');
|
||||
});
|
||||
|
||||
it('입력칸 라벨이 로케일 표시명(localeNames)으로 동적 생성된다', () => {
|
||||
const formRaw = JSON.stringify(addForm);
|
||||
expect(formRaw).toContain('localeNames');
|
||||
// 고정 라벨 키(country_name_ko/en) 잔존 0
|
||||
expect(formRaw).not.toContain('countries.country_name_ko');
|
||||
expect(formRaw).not.toContain('countries.country_name_en');
|
||||
});
|
||||
|
||||
it('추가 버튼 활성 조건이 특정 로케일(ko)에 고정되지 않는다', () => {
|
||||
const formRaw = JSON.stringify(addForm);
|
||||
// 최소 하나의 로케일에 이름이 있으면 추가 가능 — 백엔드 validateCountryNames 와 동일 계약
|
||||
expect(formRaw).not.toContain('!_local.newCountry?.name?.ko');
|
||||
});
|
||||
|
||||
it('신규 국가 초기 상태가 $locales 기반으로 만들어진다 (빈 ko/en 리터럴 금지)', () => {
|
||||
const addButton = walk(json, (n) => n.id === 'add_country_button');
|
||||
expect(addButton).toBeTruthy();
|
||||
const init = JSON.stringify(addButton.actions);
|
||||
expect(init).not.toContain('"ko": ""');
|
||||
expect(init).not.toContain('"en": ""');
|
||||
});
|
||||
|
||||
it('배송국가 카드/테이블에서 이름 편집이 가능하면 동일하게 $locales 를 순회한다', () => {
|
||||
// 편집 진입점이 없다면(현재 구조) 이 테스트는 자동 통과 — 추가 시 회귀 차단용 가드
|
||||
for (const rel of [
|
||||
'resources/layouts/admin/partials/admin_ecommerce_settings/_shipping_country_table.json',
|
||||
'resources/layouts/admin/partials/admin_ecommerce_settings/_shipping_country_cards.json',
|
||||
]) {
|
||||
const r = serialize(rel);
|
||||
if (r.includes('name.ko') || r.includes('name.en')) {
|
||||
expect(r, `${rel} 이름 편집이 로케일 하드코딩`).toContain('$locales');
|
||||
}
|
||||
}
|
||||
expect(raw).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('D7 (defect #5) — 관리자 주문상세 국내/해외 분기 폼', () => {
|
||||
const json = read('resources/layouts/admin/partials/admin_ecommerce_order_detail/_partial_order_info.json');
|
||||
const raw = serialize('resources/layouts/admin/partials/admin_ecommerce_order_detail/_partial_order_info.json');
|
||||
|
||||
+26
-13
@@ -210,33 +210,46 @@ describe('배송설정 탭 콘텐츠 (_tab_shipping.json)', () => {
|
||||
expect(addForm.if).toContain('international_shipping_enabled');
|
||||
});
|
||||
|
||||
it('국가 추가 폼에 코드/한국어명/영문명 Input이 있다', () => {
|
||||
it('국가 추가 폼에 코드 Input + 설치 언어마다 반복되는 국가명 Input이 있다', () => {
|
||||
// #459: 이름 입력칸은 ko/en 두 칸 고정이 아니라 $locales 순회로 언어 수만큼 생성된다.
|
||||
// 따라서 정적 노드 트리에는 name Input 이 "템플릿 1개"로만 존재한다.
|
||||
const addForm = findById(allNodes, 'add_country_form');
|
||||
const formNodes = flattenAll(addForm);
|
||||
const inputs = formNodes.filter((n: any) => n.name === 'Input');
|
||||
// code, name.ko, name.en => 3개
|
||||
expect(inputs.length).toBeGreaterThanOrEqual(3);
|
||||
// code input
|
||||
|
||||
const codeInput = inputs.find((i: any) => i.props?.value?.includes('newCountry?.code'));
|
||||
expect(codeInput).toBeDefined();
|
||||
expect(codeInput.props?.maxLength).toBe(10);
|
||||
// name.ko input
|
||||
const koInput = inputs.find((i: any) => i.props?.value?.includes('newCountry?.name?.ko'));
|
||||
expect(koInput).toBeDefined();
|
||||
// name.en input
|
||||
const enInput = inputs.find((i: any) => i.props?.value?.includes('newCountry?.name?.en'));
|
||||
expect(enInput).toBeDefined();
|
||||
|
||||
// 로케일 인덱싱 이름 입력칸 (name?.[loc]) — 특정 로케일 하드코딩이 아니어야 한다
|
||||
const nameInput = inputs.find((i: any) => i.props?.value?.includes('newCountry?.name?.[loc]'));
|
||||
expect(nameInput).toBeDefined();
|
||||
|
||||
// 그 입력칸을 감싼 Div 가 $locales 를 순회한다
|
||||
const iterated = formNodes.find(
|
||||
(n: any) => n.iteration?.source?.includes('$locales') && n.iteration?.item_var === 'loc'
|
||||
);
|
||||
expect(iterated).toBeDefined();
|
||||
|
||||
// ko/en 고정 입력칸 잔존 0 (회귀 차단)
|
||||
expect(inputs.some((i: any) => i.props?.value?.includes('newCountry?.name?.ko'))).toBe(false);
|
||||
expect(inputs.some((i: any) => i.props?.value?.includes('newCountry?.name?.en'))).toBe(false);
|
||||
});
|
||||
|
||||
it('추가 버튼은 code와 name.ko가 없으면 disabled', () => {
|
||||
it('추가 버튼은 코드가 없거나 모든 언어의 이름이 비면 disabled', () => {
|
||||
// #459: 특정 로케일(ko)을 필수로 강제하지 않는다.
|
||||
// 백엔드 StoreEcommerceSettingsRequest 도 name 을 array 로만 요구한다.
|
||||
const addForm = findById(allNodes, 'add_country_form');
|
||||
const formNodes = flattenAll(addForm);
|
||||
const buttons = formNodes.filter((n: any) => n.name === 'Button');
|
||||
// 추가 버튼 (disabled prop 가진 것)
|
||||
const addButton = buttons.find((b: any) => b.props?.disabled);
|
||||
expect(addButton).toBeDefined();
|
||||
expect(addButton.props.disabled).toContain('newCountry?.code');
|
||||
expect(addButton.props.disabled).toContain('newCountry?.name?.ko');
|
||||
// "어느 한 언어라도 채워졌는가" 조건
|
||||
expect(addButton.props.disabled).toContain('Object.values');
|
||||
expect(addButton.props.disabled).toContain('some');
|
||||
// ko 필수 조건 잔존 0 (회귀 차단)
|
||||
expect(addButton.props.disabled).not.toContain('newCountry?.name?.ko');
|
||||
});
|
||||
|
||||
it('추가 버튼 클릭 시 available_countries에 새 국가가 push된다', () => {
|
||||
|
||||
@@ -275,10 +275,6 @@
|
||||
"country_code": "Country Code",
|
||||
"country_code_placeholder": "e.g., KR",
|
||||
"country_name": "Country Name",
|
||||
"country_name_ko": "Korean Name",
|
||||
"name_ko_placeholder": "e.g., South Korea",
|
||||
"country_name_en": "English Name",
|
||||
"name_en_placeholder": "e.g., South Korea",
|
||||
"is_active": "Active",
|
||||
"actions": "Actions",
|
||||
"delete": "Delete",
|
||||
|
||||
@@ -275,10 +275,6 @@
|
||||
"country_code": "국가코드",
|
||||
"country_code_placeholder": "예: KR",
|
||||
"country_name": "국가명",
|
||||
"country_name_ko": "한국어명",
|
||||
"name_ko_placeholder": "예: 한국",
|
||||
"country_name_en": "영문명",
|
||||
"name_en_placeholder": "예: South Korea",
|
||||
"is_active": "사용",
|
||||
"actions": "관리",
|
||||
"delete": "삭제",
|
||||
|
||||
+2
-2
@@ -1614,7 +1614,7 @@
|
||||
"props": {
|
||||
"name": "recipient_country_code",
|
||||
"value": "{{_local.form.recipient_country_code ?? order?.data?.shipping_address?.recipient_country_code ?? 'KR'}}",
|
||||
"options": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ value: c.code, label: (c.name?.[_global.locale] ?? c.name?.ko ?? c.code) }))}}",
|
||||
"options": "{{(_global.modules?.['sirsoft-ecommerce']?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({ value: c.code, label: ($localized(c.name, 'sirsoft-ecommerce::settings.countries.' + (c.code ?? '') + '.name') || c.code) }))}}",
|
||||
"className": "w-full",
|
||||
"disabled": "{{order?.data?.abilities?.can_update !== true}}"
|
||||
},
|
||||
@@ -1634,7 +1634,7 @@
|
||||
"name": "Span",
|
||||
"if": "{{_global.modules?.['sirsoft-ecommerce']?.shipping?.international_shipping_enabled !== true}}",
|
||||
"props": { "className": "text-gray-900 dark:text-white" },
|
||||
"text": "{{order?.data?.shipping_address?.recipient_country_name?.[_global.locale] ?? order?.data?.shipping_address?.recipient_country_name?.ko ?? order?.data?.shipping_address?.recipient_country_code ?? 'KR'}}"
|
||||
"text": "{{$localized(order?.data?.shipping_address?.recipient_country_name) || order?.data?.shipping_address?.recipient_country_code || 'KR'}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+18
-49
@@ -58,7 +58,7 @@
|
||||
"props": {
|
||||
"value": "{{_local.form?.shipping?.default_country ?? 'KR'}}",
|
||||
"className": "w-full",
|
||||
"options": "{{(_local.form?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({value: c.code, label: $localized(c.name)}))}}",
|
||||
"options": "{{(_local.form?.shipping?.available_countries ?? []).filter(c => c.is_active).map(c => ({value: c.code, label: ($localized(c.name, 'sirsoft-ecommerce::settings.countries.' + (c.code ?? '') + '.name') || c.code)}))}}",
|
||||
"disabled": "{{_computed.isReadOnly}}"
|
||||
},
|
||||
"actions": [
|
||||
@@ -216,19 +216,13 @@
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"comment": "신규 국가의 name 은 활성 언어팩($locales) 전체에 대한 빈 문자열 맵으로 시드한다. 언어팩이 추가되면 입력칸도 함께 늘어나야 하므로 로케일을 리터럴로 열거하지 않는다.",
|
||||
"type": "click",
|
||||
"handler": "setState",
|
||||
"params": {
|
||||
"target": "local",
|
||||
"isAddingCountry": true,
|
||||
"newCountry": {
|
||||
"code": "",
|
||||
"name": {
|
||||
"ko": "",
|
||||
"en": ""
|
||||
},
|
||||
"is_active": true
|
||||
}
|
||||
"newCountry": "{{ { code: '', name: Object.fromEntries(($locales ?? []).map(l => [l, ''])), is_active: true } }}"
|
||||
}
|
||||
}
|
||||
],
|
||||
@@ -305,24 +299,31 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"comment": "국가명 입력칸은 활성 언어팩($locales) 마다 하나씩 생성된다. iteration 은 이 Div 자신을 로케일 수만큼 복제하므로, 부모(flex flex-wrap)가 입력칸들을 가로로 흘린다. 언어팩이 추가되면 입력칸도 자동으로 늘어난다 — 로케일 리터럴 열거 금지.",
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"iteration": {
|
||||
"source": "{{$locales ?? []}}",
|
||||
"item_var": "loc"
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"comment": "라벨 = 로케일 표시명(예: 한국어 / English / 日本語). appConfig.localeNames 부재 시 로케일 코드로 폴백.",
|
||||
"type": "basic",
|
||||
"name": "Label",
|
||||
"props": {
|
||||
"className": "text-tertiary block font-medium mb-1"
|
||||
},
|
||||
"text": "$t:sirsoft-ecommerce.admin.settings.shipping.countries.country_name_ko"
|
||||
"text": "{{_global.appConfig?.localeNames?.[loc] ?? loc}}"
|
||||
},
|
||||
{
|
||||
"comment": "setState 는 params 키의 표현식을 해석하지 않는다(엔진 제약). 따라서 `newCountry.name.<loc>` 같은 동적 키 대신 name 객체를 통째로 재구성해 넣는다.",
|
||||
"type": "basic",
|
||||
"name": "Input",
|
||||
"props": {
|
||||
"value": "{{_local.newCountry?.name?.ko ?? ''}}",
|
||||
"value": "{{_local.newCountry?.name?.[loc] ?? ''}}",
|
||||
"className": "w-40",
|
||||
"placeholder": "$t:sirsoft-ecommerce.admin.settings.shipping.countries.name_ko_placeholder",
|
||||
"placeholder": "{{$t('sirsoft-ecommerce.admin.settings.shipping.countries.country_name') + ' (' + (_global.appConfig?.localeNames?.[loc] ?? loc) + ')'}}",
|
||||
"disabled": "{{_computed.isReadOnly}}"
|
||||
},
|
||||
"actions": [
|
||||
@@ -331,41 +332,7 @@
|
||||
"handler": "setState",
|
||||
"params": {
|
||||
"target": "local",
|
||||
"newCountry.name.ko": "{{$event.target.value}}"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Div",
|
||||
"children": [
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Label",
|
||||
"props": {
|
||||
"className": "text-tertiary block font-medium mb-1"
|
||||
},
|
||||
"text": "$t:sirsoft-ecommerce.admin.settings.shipping.countries.country_name_en"
|
||||
},
|
||||
{
|
||||
"type": "basic",
|
||||
"name": "Input",
|
||||
"props": {
|
||||
"value": "{{_local.newCountry?.name?.en ?? ''}}",
|
||||
"className": "w-40",
|
||||
"placeholder": "$t:sirsoft-ecommerce.admin.settings.shipping.countries.name_en_placeholder",
|
||||
"disabled": "{{_computed.isReadOnly}}"
|
||||
},
|
||||
"actions": [
|
||||
{
|
||||
"type": "change",
|
||||
"handler": "setState",
|
||||
"params": {
|
||||
"target": "local",
|
||||
"newCountry.name.en": "{{$event.target.value}}"
|
||||
"newCountry.name": "{{ { ...(_local.newCountry?.name ?? {}), [loc]: $event.target.value } }}"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -380,11 +347,12 @@
|
||||
},
|
||||
"children": [
|
||||
{
|
||||
"comment": "활성 조건: 국가코드 + 최소 하나의 로케일 이름. StoreEcommerceSettingsRequest 의 available_countries.*.name 규칙이 array 만 요구하고 특정 로케일 키를 강제하지 않으므로, 프론트도 ko 를 필수로 두지 않는다.",
|
||||
"type": "basic",
|
||||
"name": "Button",
|
||||
"props": {
|
||||
"type": "button",
|
||||
"disabled": "{{_computed.isReadOnly || !_local.newCountry?.code || !_local.newCountry?.name?.ko}}",
|
||||
"disabled": "{{_computed.isReadOnly || !(_local.newCountry?.code ?? '').trim() || !Object.values(_local.newCountry?.name ?? {}).some(v => (v ?? '').trim() !== '')}}",
|
||||
"className": "px-3 py-1.5 text-sm bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg hover:bg-gray-800 dark:hover:bg-gray-100 font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
},
|
||||
"actions": [
|
||||
@@ -393,10 +361,11 @@
|
||||
"handler": "sequence",
|
||||
"actions": [
|
||||
{
|
||||
"comment": "입력하지 않은 로케일의 빈 문자열은 저장본에 남기지 않는다 — 부재 로케일은 언어팩(settings.countries.{code}.name)이 보강하거나, 운영자가 나중에 채운다.",
|
||||
"handler": "setState",
|
||||
"params": {
|
||||
"target": "local",
|
||||
"form.shipping.available_countries": "{{[...(_local.form?.shipping?.available_countries ?? []), { code: _local.newCountry.code, name: _local.newCountry.name, is_active: true }]}}",
|
||||
"form.shipping.available_countries": "{{[...(_local.form?.shipping?.available_countries ?? []), { code: _local.newCountry.code.trim().toUpperCase(), name: Object.fromEntries(Object.entries(_local.newCountry?.name ?? {}).filter(e => (e[1] ?? '').trim() !== '').map(e => [e[0], e[1].trim()])), is_active: true }]}}",
|
||||
"isAddingCountry": false,
|
||||
"newCountry": null,
|
||||
"hasChanges": true
|
||||
|
||||
+199
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* 배송설정 배송국가 — 다국어 표시/입력 회귀 (#459).
|
||||
*
|
||||
* 배경: 배송국가명이 UI 로케일과 무관하게 항상 한국어로 렌더됐다. 원인은 두 겹이었다.
|
||||
* 1) 레이아웃이 `name[_global.locale]` 로 직접 색인 — 로케일 키 부재 시 폴백 없음.
|
||||
* 2) 엔진 `$localized()` 가 `context.$locale || 'ko'` 로 로케일을 확정 — `init_actions`
|
||||
* 같은 ActionDispatcher 경로는 `$locale` 을 넘기지 않으므로 **항상** ko 를 반환했다
|
||||
* (engine-v1.52.1 에서 `window.__templateApp.getConfig()` 회수로 수정).
|
||||
* 또한 국가 추가 폼의 이름 입력칸이 ko/en 2칸으로 하드코딩돼 있어 언어를 추가해도
|
||||
* 그 언어의 이름을 넣을 수 없었다 → `$locales` 순회로 전환.
|
||||
*
|
||||
* 측정 규율 (이 spec 을 고칠 사람에게):
|
||||
* - **국가명 문자열을 하드코딩하지 않는다**("South Korea" 등). 시드 데이터가 바뀌면
|
||||
* 거짓 실패하고, 무엇보다 "ko 가 아닌 무언가"를 렌더한다는 사실만으로는 회귀를 못 잡는다.
|
||||
* API 응답에서 그 로케일의 기대값을 **런타임에 도출**해 화면과 대조한다.
|
||||
* - **로케일 목록을 하드코딩하지 않는다**. 언어는 계속 추가된다(PO 지시). 설치된 언어는
|
||||
* `$locales` 에서 읽는다.
|
||||
* - 회귀(= ko 고정) 판정은 "en 값과 같다" 로는 부족하다. ko 와 en 이 같은 국가(예: 코드
|
||||
* 폴백)만 골라 보면 통과해 버린다. **ko 값과 다른 국가가 하나라도 있는지** 먼저 확인한
|
||||
* 뒤, 그 국가에서 화면값 === en 값을 단언한다.
|
||||
*
|
||||
* @scenario shipping_country_i18n locale=en|ja × surface=settings_list|add_form
|
||||
* @effects country_names_localized_by_active_locale,
|
||||
* country_names_not_pinned_to_ko,
|
||||
* add_form_inputs_follow_installed_locales,
|
||||
* add_button_enabled_by_any_locale_name
|
||||
*/
|
||||
import { test, expect, authenticatePage } from '../../fixtures/ecommerce-auth';
|
||||
import type { Page } from '@playwright/test';
|
||||
|
||||
const SHIPPING_SETTINGS_URL = '/admin/ecommerce/settings?tab=shipping';
|
||||
|
||||
/** 활성 배송국가의 원본 다국어 이름(name 객체)을 앱 상태에서 읽는다. */
|
||||
async function activeCountryNames(page: Page): Promise<Array<Record<string, string>>> {
|
||||
return page.evaluate(() => {
|
||||
const core = (window as any).G7Core;
|
||||
const shipping = core?.state?.getGlobal?.()?.modules?.['sirsoft-ecommerce']?.shipping;
|
||||
return (shipping?.available_countries ?? [])
|
||||
.filter((c: any) => c.is_active)
|
||||
.map((c: any) => (typeof c.name === 'object' && c.name ? c.name : {}));
|
||||
});
|
||||
}
|
||||
|
||||
/** 현재 UI 로케일. */
|
||||
async function activeLocale(page: Page): Promise<string> {
|
||||
return page.evaluate(() => (window as any).__templateApp?.getConfig?.()?.locale ?? '');
|
||||
}
|
||||
|
||||
/** 헤더 배송국가 셀렉터가 파생한 표시명 (init_actions/ActionDispatcher 경로 — 회귀 지점). */
|
||||
async function derivedHeaderNames(page: Page): Promise<string[]> {
|
||||
return page.evaluate(() =>
|
||||
((window as any).G7Core?.state?.getGlobal?.()?.availableShippingCountries ?? []).map((c: any) => c.name),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 설치된 언어의 `{ 코드: 표시명 }` 맵. 하드코딩 금지 — 언어는 계속 추가된다(PO 지시).
|
||||
* 레이아웃의 이름 입력칸 라벨이 쓰는 것과 동일한 출처(`appConfig.localeNames`)를 읽는다.
|
||||
*/
|
||||
async function localeDisplayNames(page: Page): Promise<Record<string, string>> {
|
||||
return page.evaluate(() => (window as any).G7Core?.state?.getGlobal?.()?.appConfig?.localeNames ?? {});
|
||||
}
|
||||
|
||||
/** 국가 표(`_local.form.shipping`)가 시드됐는지. */
|
||||
async function formSeeded(page: Page): Promise<boolean> {
|
||||
return page.evaluate(() => {
|
||||
const form = (window as any).G7Core?.state?.getLocal?.()?.form;
|
||||
return Array.isArray(form?.shipping?.available_countries) && form.shipping.available_countries.length > 0;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 배송설정 탭이 데이터를 받아 국가 목록을 **화면에** 그릴 때까지 기다린다.
|
||||
*
|
||||
* 상태(available_countries)만 기다리면 DOM 이 아직 비어 있어 body 텍스트가 `""` 다.
|
||||
*
|
||||
* 재진입 1회 허용 — 사전 결함(#459 검수 중 발견): settings 데이터소스의 `initLocal: "form"`
|
||||
* 시드가 간헐적으로 유실돼 `_local.form` 이 비고 표가 "No shipping countries" 로 렌더된다.
|
||||
* 이때 `_global.modules[...]` 와 데이터소스에는 국가가 정상 적재돼 있다(= 로딩 실패가 아님).
|
||||
* 이 spec 의 대상은 다국어 표시이므로, 시드 유실 시 1회 재진입해 본 검증을 이어간다.
|
||||
* **이 재진입은 그 결함의 회피가 아니라 격리다** — 결함 자체는 별도 이슈로 추적한다.
|
||||
*/
|
||||
async function gotoShippingSettings(page: Page, token: string): Promise<void> {
|
||||
await authenticatePage(page, token);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
await page.goto(SHIPPING_SETTINGS_URL);
|
||||
await page.waitForLoadState('domcontentloaded', { timeout: 30_000 });
|
||||
await expect.poll(async () => (await activeCountryNames(page)).length, { timeout: 30_000 }).toBeGreaterThan(0);
|
||||
|
||||
const seeded = await expect
|
||||
.poll(async () => formSeeded(page), { timeout: 15_000 })
|
||||
.toBe(true)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (seeded) break;
|
||||
if (attempt === 1) throw new Error('_local.form 시드 유실이 2회 연속 발생 (사전 결함)');
|
||||
}
|
||||
|
||||
const locale = await activeLocale(page);
|
||||
const expected = (await activeCountryNames(page)).map((n) => n[locale]).filter(Boolean);
|
||||
if (expected.length > 0) {
|
||||
await expect
|
||||
.poll(async () => (await page.locator('body').innerText()).includes(expected[0]), { timeout: 30_000 })
|
||||
.toBe(true);
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('@sirsoft-ecommerce 배송국가 다국어', () => {
|
||||
// @scenario shipping_country_i18n:settings_list
|
||||
// @effects country_names_localized_by_active_locale, country_names_not_pinned_to_ko
|
||||
test('국가 목록이 활성 로케일 값으로 렌더된다 (ko 고정 회귀 차단)', async ({ page, settingsToken }) => {
|
||||
await gotoShippingSettings(page, settingsToken);
|
||||
|
||||
const locale = await activeLocale(page);
|
||||
const names = await activeCountryNames(page);
|
||||
|
||||
// 이 테스트가 의미를 가지려면 "ko 와 다른 활성 로케일 값" 이 최소 1건 있어야 한다.
|
||||
// (전부 같으면 ko 고정 회귀를 구분할 수 없어 거짓 통과한다.)
|
||||
const discriminating = names.filter((n) => n[locale] && n.ko && n[locale] !== n.ko);
|
||||
test.skip(
|
||||
discriminating.length === 0,
|
||||
`활성 로케일(${locale}) 값이 ko 와 모두 동일 — 회귀 판별 불가한 시드`,
|
||||
);
|
||||
|
||||
const body = await page.locator('body').innerText();
|
||||
for (const name of discriminating) {
|
||||
expect(body, `활성 로케일(${locale}) 이름이 렌더돼야 한다`).toContain(name[locale]);
|
||||
expect(body, `ko 이름(${name.ko})이 렌더되면 ko 고정 회귀`).not.toContain(name.ko);
|
||||
}
|
||||
});
|
||||
|
||||
// @scenario shipping_country_i18n:header_derivation
|
||||
// @effects country_names_localized_by_active_locale, country_names_not_pinned_to_ko
|
||||
test('헤더 파생 목록도 활성 로케일 값을 쓴다 (ActionDispatcher 경로 $localized)', async ({
|
||||
page,
|
||||
settingsToken,
|
||||
}) => {
|
||||
await gotoShippingSettings(page, settingsToken);
|
||||
|
||||
const locale = await activeLocale(page);
|
||||
const names = await activeCountryNames(page);
|
||||
const discriminating = names.filter((n) => n[locale] && n.ko && n[locale] !== n.ko);
|
||||
test.skip(discriminating.length === 0, `활성 로케일(${locale}) 값이 ko 와 모두 동일`);
|
||||
|
||||
await expect.poll(async () => (await derivedHeaderNames(page)).length, { timeout: 20_000 }).toBeGreaterThan(0);
|
||||
const derived = await derivedHeaderNames(page);
|
||||
|
||||
// 파생 목록에 ko 전용 값이 섞이면 회귀. (init_actions 는 $locale 을 넘기지 않는 경로다.)
|
||||
const koOnly = discriminating.map((n) => n.ko).filter((ko) => derived.includes(ko));
|
||||
expect(koOnly, `헤더 파생값: ${JSON.stringify(derived)}`).toEqual([]);
|
||||
});
|
||||
|
||||
// @scenario shipping_country_i18n:add_form
|
||||
// @effects add_form_inputs_follow_installed_locales, add_button_enabled_by_any_locale_name
|
||||
test('국가 추가 폼의 이름 입력칸이 설치된 언어 수만큼 생기고, 어느 한 언어만 채워도 추가된다', async ({
|
||||
page,
|
||||
settingsToken,
|
||||
}) => {
|
||||
await gotoShippingSettings(page, settingsToken);
|
||||
|
||||
const localeNames = await localeDisplayNames(page);
|
||||
const locales = Object.keys(localeNames);
|
||||
expect(locales.length, '설치된 언어를 못 읽었다').toBeGreaterThan(0);
|
||||
|
||||
await page.getByRole('button', { name: /Add Country|국가 추가|国追加/ }).click();
|
||||
|
||||
// 국가 코드 입력칸(placeholder="KR")이 있는 행이 곧 추가 폼이다.
|
||||
const codeInput = page.locator('input[placeholder="KR"]');
|
||||
await expect(codeInput).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// 이름 입력칸은 placeholder 가 `... (언어표시명)` 으로 끝난다.
|
||||
// 언어 목록을 하드코딩하지 않고 localeNames 로 셀렉터를 만든다.
|
||||
const nameInputs = locales.map((code) => page.locator(`input[placeholder$="(${localeNames[code]})"]`));
|
||||
for (const [i, input] of nameInputs.entries()) {
|
||||
await expect(input, `${locales[i]} 이름 입력칸이 있어야 한다`).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
const addButton = page.getByRole('button', { name: /^(Add|추가|追加)$/ });
|
||||
await expect(addButton).toBeDisabled();
|
||||
|
||||
// 코드만 채워도 여전히 비활성 (이름이 전부 비어 있음)
|
||||
await codeInput.fill('zz');
|
||||
await expect(addButton).toBeDisabled();
|
||||
|
||||
// 공백만 채워도 비활성 (.trim() 가드)
|
||||
await nameInputs[0].fill(' ');
|
||||
await expect(addButton, '공백만 입력하면 추가 불가여야 한다').toBeDisabled();
|
||||
await nameInputs[0].fill('');
|
||||
|
||||
// 마지막 언어 한 칸만 채워도 활성 — ko 고정 조건이면 여기서 실패한다.
|
||||
await nameInputs[nameInputs.length - 1].fill('Zed Test Country');
|
||||
await expect(addButton, '어느 한 언어만 채워도 추가 가능해야 한다').toBeEnabled();
|
||||
|
||||
// 저장하지 않고 폼을 닫아 부작용을 남기지 않는다.
|
||||
await page.getByRole('button', { name: /^(Cancel|취소|キャンセル)$/ }).first().click();
|
||||
});
|
||||
});
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Tests\Unit\Upgrades;
|
||||
|
||||
use App\Extension\UpgradeContext;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Modules\Sirsoft\Ecommerce\Tests\ModuleTestCase;
|
||||
|
||||
/**
|
||||
* 배송가능 국가명의 빈 로케일 키 청소 마이그레이션 테스트 (#459)
|
||||
*
|
||||
* 구 국가 추가 폼은 한국어/영문 두 입력칸을 항상 렌더했고, 운영자가 한쪽을 비운 채 저장하면
|
||||
* `{"ko":"프랑스","en":""}` 처럼 빈 문자열이 저장본에 박혔다. 빈 문자열은 "값이 있음" 도
|
||||
* "부재" 도 아닌 어중간한 상태라, 저장본을 읽는 쪽마다 처리가 갈린다.
|
||||
*
|
||||
* 부재 로케일은 비워 두는 것이 이 시스템의 계약이다 — 기본 10개국은 언어팩
|
||||
* (settings.countries.{code}.name)이 읽기 시점에 보강하고, 운영자가 직접 추가한 국가는
|
||||
* 운영자가 채운다. 따라서 빈 문자열 키는 제거해 "부재" 로 정규화한다.
|
||||
*
|
||||
* 이름을 새로 채우지는 않는다(PO 결정) — 청소만 한다.
|
||||
*/
|
||||
class PruneEmptyShippingCountryNameLocalesTest extends ModuleTestCase
|
||||
{
|
||||
private const MIGRATION_NS = 'App\\Upgrades\\Data\\Ext\\Modules\\SirsoftEcommerce\\V1_0_2\\Migrations\\PruneEmptyShippingCountryNameLocales';
|
||||
|
||||
private string $settingsPath;
|
||||
|
||||
private string $settingsFile;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
// DataMigration 클래스는 오토로드 밖 — 직접 로드
|
||||
$migDir = dirname(__DIR__, 3).'/upgrades/data/1.0.2/migrations';
|
||||
require_once $migDir.'/PruneEmptyShippingCountryNameLocales.php';
|
||||
|
||||
// 운영 storage 오염 방지: 테스트 환경 경로 (마이그레이션의 runningUnitTests 분기와 일치)
|
||||
$this->settingsPath = storage_path('framework/testing/modules/sirsoft-ecommerce/settings');
|
||||
$this->settingsFile = $this->settingsPath.'/shipping.json';
|
||||
}
|
||||
|
||||
protected function tearDown(): void
|
||||
{
|
||||
if (File::exists($this->settingsFile)) {
|
||||
File::delete($this->settingsFile);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
private function migration(): object
|
||||
{
|
||||
$class = self::MIGRATION_NS;
|
||||
|
||||
return new $class;
|
||||
}
|
||||
|
||||
private function context(): UpgradeContext
|
||||
{
|
||||
return new UpgradeContext(
|
||||
fromVersion: '1.0.1',
|
||||
toVersion: '1.0.2',
|
||||
currentStep: '1.0.2',
|
||||
);
|
||||
}
|
||||
|
||||
private function writeSettings(array $settings): void
|
||||
{
|
||||
File::ensureDirectoryExists($this->settingsPath);
|
||||
File::put($this->settingsFile, json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
private function readCountries(): array
|
||||
{
|
||||
$settings = json_decode((string) File::get($this->settingsFile), true);
|
||||
|
||||
return collect($settings['available_countries'])->keyBy('code')->all();
|
||||
}
|
||||
|
||||
public function test_empty_string_locale_keys_are_removed(): void
|
||||
{
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'available_countries' => [
|
||||
['code' => 'KR', 'name' => ['ko' => '대한민국', 'en' => 'South Korea'], 'is_active' => true],
|
||||
['code' => 'FR', 'name' => ['ko' => '프랑스', 'en' => ''], 'is_active' => true],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$byCode = $this->readCountries();
|
||||
// 채워진 값은 그대로
|
||||
$this->assertSame(['ko' => '대한민국', 'en' => 'South Korea'], $byCode['KR']['name']);
|
||||
// 빈 문자열 키만 제거 — 부재로 정규화
|
||||
$this->assertSame(['ko' => '프랑스'], $byCode['FR']['name']);
|
||||
}
|
||||
|
||||
public function test_whitespace_only_locale_keys_are_removed(): void
|
||||
{
|
||||
// 공백만 입력한 경우도 빈 값으로 취급
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'available_countries' => [
|
||||
['code' => 'DE', 'name' => ['ko' => '독일', 'en' => ' ', 'ja' => "\t"], 'is_active' => false],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$this->assertSame(['ko' => '독일'], $this->readCountries()['DE']['name']);
|
||||
}
|
||||
|
||||
public function test_surviving_values_are_trimmed(): void
|
||||
{
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'available_countries' => [
|
||||
['code' => 'IT', 'name' => ['ko' => ' 이탈리아 ', 'en' => ' Italy '], 'is_active' => true],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$this->assertSame(['ko' => '이탈리아', 'en' => 'Italy'], $this->readCountries()['IT']['name']);
|
||||
}
|
||||
|
||||
public function test_no_locale_names_leaves_empty_object_not_null(): void
|
||||
{
|
||||
// 모든 로케일이 빈 값이면 name 은 빈 객체가 된다(키 자체는 유지) — 백엔드 검증이
|
||||
// `name` 을 array 로 요구하므로 null 로 만들면 저장이 깨진다.
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'available_countries' => [
|
||||
['code' => 'XX', 'name' => ['ko' => '', 'en' => ''], 'is_active' => false],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$this->assertSame([], $this->readCountries()['XX']['name']);
|
||||
}
|
||||
|
||||
public function test_country_names_are_never_filled_in(): void
|
||||
{
|
||||
// PO 결정: 이름을 새로 채우지 않는다. 부재 로케일은 언어팩이 읽기 시점에 보강한다.
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'available_countries' => [
|
||||
['code' => 'KR', 'name' => ['ko' => '대한민국'], 'is_active' => true],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
// ja/en 이 추가되지 않아야 한다
|
||||
$this->assertSame(['ko' => '대한민국'], $this->readCountries()['KR']['name']);
|
||||
}
|
||||
|
||||
public function test_other_country_fields_are_preserved(): void
|
||||
{
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'international_shipping_enabled' => true,
|
||||
'available_countries' => [
|
||||
['code' => 'KR', 'name' => ['ko' => '대한민국', 'en' => ''], 'is_active' => true],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$settings = json_decode((string) File::get($this->settingsFile), true);
|
||||
$this->assertTrue($settings['international_shipping_enabled']);
|
||||
$this->assertSame('KR', $settings['default_country']);
|
||||
$this->assertTrue($settings['available_countries'][0]['is_active']);
|
||||
$this->assertSame('KR', $settings['available_countries'][0]['code']);
|
||||
}
|
||||
|
||||
public function test_is_idempotent(): void
|
||||
{
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'available_countries' => [
|
||||
['code' => 'KR', 'name' => ['ko' => '대한민국'], 'is_active' => true],
|
||||
['code' => 'FR', 'name' => ['ko' => '프랑스', 'en' => ''], 'is_active' => true],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
$first = $this->readCountries();
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
$second = $this->readCountries();
|
||||
|
||||
$this->assertSame($first, $second);
|
||||
$this->assertSame(['ko' => '프랑스'], $second['FR']['name']);
|
||||
}
|
||||
|
||||
public function test_missing_file_is_noop(): void
|
||||
{
|
||||
if (File::exists($this->settingsFile)) {
|
||||
File::delete($this->settingsFile);
|
||||
}
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$this->assertFalse(File::exists($this->settingsFile));
|
||||
}
|
||||
|
||||
public function test_missing_available_countries_is_noop(): void
|
||||
{
|
||||
$this->writeSettings(['default_country' => 'KR']);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$settings = json_decode((string) File::get($this->settingsFile), true);
|
||||
$this->assertSame('KR', $settings['default_country']);
|
||||
$this->assertArrayNotHasKey('available_countries', $settings);
|
||||
}
|
||||
|
||||
public function test_non_array_name_is_left_untouched(): void
|
||||
{
|
||||
// 구 스키마 잔재(문자열 name)는 이 마이그레이션의 책임이 아니다 — 건드리지 않는다.
|
||||
$this->writeSettings([
|
||||
'default_country' => 'KR',
|
||||
'available_countries' => [
|
||||
['code' => 'KR', 'name' => '대한민국', 'is_active' => true],
|
||||
],
|
||||
]);
|
||||
|
||||
($this->migration())->run($this->context());
|
||||
|
||||
$this->assertSame('대한민국', $this->readCountries()['KR']['name']);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Sirsoft\Ecommerce\Upgrades;
|
||||
|
||||
use App\Extension\AbstractUpgradeStep;
|
||||
|
||||
/**
|
||||
* Ecommerce 모듈 1.0.2 업그레이드 스텝
|
||||
*
|
||||
* 배송가능 국가명(shipping.available_countries[].name)의 저장본에 남아 있는 빈 로케일 키를
|
||||
* 제거한다. 구 국가 추가 폼이 한국어/영문 두 칸만 렌더했던 탓에, 한쪽을 비운 채 저장하면
|
||||
* 빈 문자열이 저장본에 박혔다. 부재 로케일은 비워 두는 것이 계약이며(언어팩이 읽기 시점에
|
||||
* 보강), 빈 문자열은 그 계약을 어기는 어중간한 상태였다.
|
||||
*
|
||||
* 국가명을 새로 채우지는 않는다 — 언어팩 보강이 그 역할을 한다.
|
||||
*
|
||||
* 모든 비즈니스 로직은 data/1.0.2/migrations/ 로 격리(AbstractUpgradeStep 규약).
|
||||
*
|
||||
* @upgrade-path B
|
||||
*/
|
||||
class Upgrade_1_0_2 extends AbstractUpgradeStep {}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace App\Upgrades\Data\Ext\Modules\SirsoftEcommerce\V1_0_2\Migrations;
|
||||
|
||||
use App\Extension\Upgrade\DataMigration;
|
||||
use App\Extension\UpgradeContext;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
/**
|
||||
* 배송가능 국가명(available_countries[].name)의 빈 로케일 키를 제거.
|
||||
*
|
||||
* 구 국가 추가 폼은 한국어/영문 두 입력칸만 렌더했고, 운영자가 한쪽을 비운 채 저장하면
|
||||
* `{"ko":"프랑스","en":""}` 처럼 빈 문자열이 저장본에 박혔다. 빈 문자열은 "값이 있음" 도
|
||||
* "부재" 도 아닌 어중간한 상태다.
|
||||
*
|
||||
* 이 시스템의 계약은 "부재 로케일은 비워 둔다" 이다 — 기본 국가는 언어팩
|
||||
* (`sirsoft-ecommerce::settings.countries.{code}.name`)이 읽기 시점에 보강하고
|
||||
* (EcommerceSettingsService::getAllSettings), 운영자가 직접 추가한 국가는 운영자가 채운다.
|
||||
* 따라서 빈 문자열 키를 제거해 "부재" 로 정규화한다.
|
||||
*
|
||||
* 이름을 새로 채우지는 않는다 — 언어팩 보강이 그 역할을 하며, 저장본에 값을 박으면
|
||||
* 운영자 편집값으로 승격되어 이후 언어팩 갱신이 반영되지 않는다.
|
||||
*
|
||||
* name 이 배열이 아닌 구 스키마 잔재(문자열)는 이 마이그레이션의 책임이 아니라 건드리지 않는다.
|
||||
*
|
||||
* idempotent: 빈 키가 없고 모든 값이 trim 상태면 no-op (파일 쓰기 없음).
|
||||
*
|
||||
* V-1 안전: Illuminate\Support\Facades\File + 로컬 헬퍼만 사용.
|
||||
*/
|
||||
class PruneEmptyShippingCountryNameLocales implements DataMigration
|
||||
{
|
||||
private const MODULE_IDENTIFIER = 'sirsoft-ecommerce';
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'PruneEmptyShippingCountryNameLocales';
|
||||
}
|
||||
|
||||
public function run(UpgradeContext $context): void
|
||||
{
|
||||
$path = $this->settingsFilePath();
|
||||
|
||||
if (! File::exists($path)) {
|
||||
$context->logger->info('[ecommerce:1.0.2] shipping.json 미존재 — 국가명 빈 로케일 청소 스킵');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$settings = json_decode((string) File::get($path), true);
|
||||
if (! is_array($settings) || ! isset($settings['available_countries']) || ! is_array($settings['available_countries'])) {
|
||||
$context->logger->info('[ecommerce:1.0.2] shipping.json 에 배송가능 국가 목록 없음 — 국가명 빈 로케일 청소 스킵');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$countries = $settings['available_countries'];
|
||||
$prunedKeys = 0;
|
||||
|
||||
foreach ($countries as $idx => $country) {
|
||||
$name = $country['name'] ?? null;
|
||||
|
||||
// 구 스키마 잔재(문자열 name)는 대상 아님
|
||||
if (! is_array($name)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cleaned = $this->pruneEmptyLocales($name);
|
||||
|
||||
if ($cleaned !== $name) {
|
||||
$prunedKeys += count($name) - count($cleaned);
|
||||
$countries[$idx]['name'] = $cleaned;
|
||||
}
|
||||
}
|
||||
|
||||
if ($countries === $settings['available_countries']) {
|
||||
$context->logger->info('[ecommerce:1.0.2] 국가명에 빈 로케일 키 없음 — 변경 없음 (idempotent)');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$settings['available_countries'] = $countries;
|
||||
|
||||
// 인코딩 플래그는 EcommerceSettingsService 의 저장부와 동일해야 한다.
|
||||
// 다르면 이 스텝이 국가명과 무관한 값(URL 등)의 이스케이프까지 조용히 바꿔 쓴다.
|
||||
File::put($path, json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
|
||||
|
||||
$context->logger->info(sprintf(
|
||||
'[ecommerce:1.0.2] 국가명 빈 로케일 키 %d개 제거 완료 (국가 %d개 검사)',
|
||||
$prunedKeys,
|
||||
count($countries),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* 다국어 이름 맵에서 빈 값(공백 포함) 로케일 키를 제거하고 남은 값을 trim 합니다.
|
||||
*
|
||||
* 모든 로케일이 비어 있으면 빈 배열을 반환합니다 — null 이 아니라 빈 배열이어야
|
||||
* 백엔드 검증(`shipping.available_countries.*.name` => array)이 깨지지 않습니다.
|
||||
*
|
||||
* @param array<string, mixed> $name 로케일 => 국가명 맵
|
||||
* @return array<string, string> 빈 로케일이 제거되고 trim 된 맵
|
||||
*/
|
||||
private function pruneEmptyLocales(array $name): array
|
||||
{
|
||||
$cleaned = [];
|
||||
|
||||
foreach ($name as $locale => $value) {
|
||||
if (! is_string($value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$trimmed = trim($value);
|
||||
if ($trimmed === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$cleaned[$locale] = $trimmed;
|
||||
}
|
||||
|
||||
return $cleaned;
|
||||
}
|
||||
|
||||
/**
|
||||
* shipping.json 의 저장 경로를 반환합니다.
|
||||
*
|
||||
* 테스트 환경에서는 운영 storage 오염을 막기 위해 framework/testing 경로를 사용합니다
|
||||
* (EcommerceSettingsService 의 저장 경로 분기와 동일).
|
||||
*
|
||||
* @return string 설정 파일 절대 경로
|
||||
*/
|
||||
private function settingsFilePath(): string
|
||||
{
|
||||
$base = app()->runningUnitTests()
|
||||
? 'framework/testing/modules/'
|
||||
: 'app/modules/';
|
||||
|
||||
return storage_path($base.self::MODULE_IDENTIFIER.'/settings/shipping.json');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user