Files
Gnuboard7/modules/_bundled/sirsoft-ecommerce/resources/js/handlers/updateOptionField.ts
T
HeuJung b5c0ec1178 fix(core,ecommerce,board,page,admin_basic,basic): 목록 응답의 하위 컬렉션 전량 직렬화 해소
관리자 상품목록을 한 페이지 여는 것만으로 그 페이지 모든 상품의 옵션이 응답에 실렸다.
같은 패턴을 저장소 전역에서 찾아 14개 목록 엔드포인트를 함께 정리했다.

근본 원인은 둘이다. Resource 가 whenLoaded 로 방어하는데 Repository 가 목록 쿼리에서
관계를 무조건 로드해 가드가 항상 참이 되는 가짜 가드, 그리고 toListArray 경량 표현을
정의해 두고도 컬렉션이 toArray 를 부르는 목록/상세 미분리다. 둘 다 응답만 보면
정상이라 오류도 경고도 없이 페이로드만 불어난다.

목록은 화면이 실제로 그리는 것만 싣는다. 개수·합계는 PHP 컬렉션 연산이 아니라 DB
집계로, 대표 1건이 필요한 곳은 관계 자체를 oldestOfMany 로 좁힌다. eager load 의
limit(1) 은 부모별이 아니라 배치 쿼리 전체에 걸려 첫 행만 값을 갖게 되므로 쓸 수 없다.

뺀 값에는 대체 경로를 먼저 만들었다. 상품 옵션은 행을 펼칠 때 배치로 불러오고(상품 수와
무관하게 쿼리 상수), 종전 동작이 필요한 호출자를 위해 ?with_options=1 등 opt-in 을 남겼다.
배송정책 국가설정과 리뷰 첨부 이미지는 소비처를 실측한 결과 화면이 실제로 그리고 있어
제거하지 않았다 — 그 소비 사실을 회귀 테스트로 고정했다.

재발 방지로 정적 검사 룰 4종과 규정 문서 항목을 함께 넣었다.
2026-08-05 21:20:05 +09:00

339 lines
15 KiB
TypeScript

/**
* 옵션 필드 업데이트 핸들러
*
* 상품 옵션의 인라인 편집 시 데이터소스를 업데이트합니다.
* selling_price 변경 시 다중통화 가격을 자동 재계산합니다.
*/
import type { ActionContext } from '../types';
import { calculateCurrencyPricesHandler } from './calculateCurrencyPrices';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Ecom:UpdateOption')) ?? {
log: (...args: unknown[]) => console.log('[Ecom:UpdateOption]', ...args),
warn: (...args: unknown[]) => console.warn('[Ecom:UpdateOption]', ...args),
error: (...args: unknown[]) => console.error('[Ecom:UpdateOption]', ...args),
};
interface UpdateOptionFieldParams {
productId: number | string;
optionId: number | string;
field: string;
value: any;
dataSourceId?: string;
}
interface OptionFieldError {
productId: string;
optionId: string;
field: string;
message: string;
}
/**
* 커스텀 핸들러에 전달되는 액션 객체 인터페이스
* ActionDispatcher는 (action, context) 형태로 핸들러를 호출합니다.
*/
interface ActionWithParams {
handler: string;
params?: UpdateOptionFieldParams;
[key: string]: any;
}
/**
* 옵션 필드 업데이트 핸들러
*
* G7Core.dataSource API를 사용하여 products 데이터소스를 직접 업데이트합니다.
* selling_price 변경 시 다중통화 가격을 자동 재계산합니다.
*
* @param action 액션 객체 (params 포함)
* @param context 액션 컨텍스트
*/
export function updateOptionFieldHandler(
action: ActionWithParams,
context: ActionContext
): void {
// 커스텀 핸들러는 (action, context) 형태로 호출되므로 action.params에서 추출
const params = (action.params || {}) as UpdateOptionFieldParams;
const { productId, optionId, field, value, dataSourceId = 'products' } = params;
if (!productId || !optionId || !field) {
logger.warn('[updateOptionField] Missing required params:', { productId, optionId, field });
return;
}
const G7Core = (window as any).G7Core;
if (!G7Core?.dataSource?.get || !G7Core?.dataSource?.set) {
logger.warn('[updateOptionField] G7Core.dataSource API is not available');
return;
}
// 데이터소스에서 현재 데이터 가져오기
const currentData = G7Core.dataSource.get(dataSourceId);
if (!currentData) {
console.warn(`[updateOptionField] DataSource '${dataSourceId}' not found`);
return;
}
// API 응답 구조: { success: true, data: { data: [...products], pagination: {...} } }
const productsArray = currentData.data?.data || [];
if (!Array.isArray(productsArray) || productsArray.length === 0) {
logger.warn('[updateOptionField] Products data is empty or invalid');
return;
}
// currencies는 _global 상태에서 가져옴
const globalState = G7Core.state.get() || {};
const currencies = globalState.modules?.['sirsoft-ecommerce']?.language_currency?.currencies;
// 현재 에러 상태 가져오기
const currentErrors: OptionFieldError[] = globalState._local?.optionFieldErrors || [];
let newErrors = [...currentErrors];
// 기본 옵션 판매가 → 상품 판매가 역동기화가 발생했는지 추적
// (발생 시 상품의 selling_price 도 modifiedProductFields 에 기록해야 일괄 저장에 포함됨)
let productSellingPriceSynced = false;
// 대상 옵션을 실제로 찾았는지 추적.
//
// 옵션 지연 로딩(#518) 이후 목록 행의 `options` 는 펼치기 전까지 `undefined` 다. 찾지
// 못한 채로 아래 modified 추적을 돌리면 존재하지 않는 옵션이 수정 대상으로 기록되고,
// 일괄 저장이 그 유령 키를 `option_items` 에 실어 보낸다.
let optionFound = false;
// 상품 목록에서 해당 상품과 옵션 찾아서 업데이트
const updatedProducts = productsArray.map((product: any) => {
if (String(product.id) === String(productId)) {
const options = product.options || [];
// 해당 옵션 찾기
const optionIndex = options.findIndex(
(o: any) => String(o.id) === String(optionId)
);
if (optionIndex === -1) {
logger.warn('[updateOptionField] Option not found:', optionId);
return product;
}
optionFound = true;
const currentOption = options[optionIndex];
// 값이 변경되지 않았으면 업데이트하지 않음 (성능 최적화)
const currentFieldValue = currentOption[field];
// 객체 비교 (다국어 필드 등)를 위해 JSON 문자열로 비교
const isEqual = typeof value === 'object' && value !== null
? JSON.stringify(currentFieldValue) === JSON.stringify(value)
: String(currentFieldValue) === String(value);
if (isEqual) {
logger.log(`[updateOptionField] No change for option ${optionId}.${field}, skipping`);
return product;
}
let finalValue = value;
const numericValue = parseFloat(value) || 0;
// selling_price 검증: 정가를 초과할 수 없음
if (field === 'selling_price') {
const listPrice = parseFloat(currentOption.list_price) || 0;
if (listPrice > 0 && numericValue > listPrice) {
// 에러 추가
const errorExists = newErrors.some(
(e) =>
e.productId === String(productId) &&
e.optionId === String(optionId) &&
e.field === field
);
if (!errorExists) {
newErrors.push({
productId: String(productId),
optionId: String(optionId),
field: 'selling_price',
message: '판매가는 정가를 초과할 수 없습니다.',
});
}
// 값을 정가로 제한
finalValue = listPrice;
} else {
// 에러 제거
newErrors = newErrors.filter(
(e) =>
!(
e.productId === String(productId) &&
e.optionId === String(optionId) &&
e.field === field
)
);
}
} else {
// 다른 필드 변경 시 해당 필드 에러 제거
newErrors = newErrors.filter(
(e) =>
!(
e.productId === String(productId) &&
e.optionId === String(optionId) &&
e.field === field
)
);
}
// 옵션 업데이트
const updatedOptions = [...options];
const updatedOption: any = {
...updatedOptions[optionIndex],
[field]: finalValue,
_modified: true,
};
// 상품 판매가 역동기화 여부 (기본 옵션 판매가 변경 시)
// 백엔드 모델 정의(ProductOption::getSellingPrice): option.selling_price = product.selling_price + price_adjustment
// → price_adjustment 는 "상품 판매가 대비 가산액". 기본 옵션은 정의상 가산액 0.
let productSellingPriceSync: number | null = null;
// selling_price 변경 시 price_adjustment 재계산 (상품 판매가 대비)
if (field === 'selling_price') {
const newSellingPrice = parseFloat(finalValue) || 0;
if (currentOption.is_default === true) {
// 역방향 동기화: 기본 옵션 판매가 = 상품 판매가 → price_adjustment 0
productSellingPriceSync = newSellingPrice;
updatedOption.price_adjustment = 0;
} else {
// 비기본 옵션: price_adjustment = 옵션 판매가 - 상품 판매가 (상품 판매가 불변)
const productSellingPrice = parseFloat(product.selling_price) || 0;
updatedOption.price_adjustment = newSellingPrice - productSellingPrice;
}
updatedOption.price_adjustment_formatted =
(updatedOption.price_adjustment >= 0 ? '+' : '') +
updatedOption.price_adjustment.toLocaleString() + '원';
}
// selling_price 변경 시 다중통화 가격 자동 재계산
if (field === 'selling_price' && currencies && Array.isArray(currencies)) {
updatedOption.multi_currency_selling_price = calculateCurrencyPricesHandler(
{ basePrice: finalValue, currencies },
context
);
logger.log(`[updateOptionField] Recalculated multi_currency_selling_price for option ${optionId}`);
}
updatedOptions[optionIndex] = updatedOption;
// 기본 옵션 판매가 변경 → 상품 판매가 동기화 + 비기본 옵션 판매가 재계산
// (상품등록/수정 폼의 역방향 동기화와 동일 시맨틱: 상품 폼 productOptionHandlers.recalcOptionsFromProductPrice)
if (productSellingPriceSync !== null) {
for (let i = 0; i < updatedOptions.length; i++) {
if (i === optionIndex) continue;
const sibling = updatedOptions[i];
const adj = parseFloat(sibling.price_adjustment) || 0;
const siblingSellingPrice = productSellingPriceSync + adj;
const updatedSibling: any = { ...sibling, selling_price: siblingSellingPrice };
if (currencies && Array.isArray(currencies)) {
updatedSibling.multi_currency_selling_price = calculateCurrencyPricesHandler(
{ basePrice: siblingSellingPrice, currencies },
context
);
}
updatedOptions[i] = updatedSibling;
}
}
// stock_quantity 변경 시 상품의 총 재고를 옵션 재고 합계로 업데이트
let updatedStockQuantity = product.stock_quantity;
let updatedOptionStockSum = product.option_stock_sum;
if (field === 'stock_quantity') {
const newValue = parseInt(value, 10) || 0;
updatedOptionStockSum = updatedOptions.reduce((sum: number, opt: any) => {
if (opt.is_active === false) return sum;
return sum + (parseInt(opt.stock_quantity, 10) || 0);
}, 0);
updatedStockQuantity = updatedOptionStockSum;
logger.log(`[updateOptionField] Updated product stock to option sum: ${updatedStockQuantity}`);
}
const updatedProduct: any = {
...product,
options: updatedOptions,
stock_quantity: updatedStockQuantity,
option_stock_sum: updatedOptionStockSum,
_modified: true,
};
// 기본 옵션 판매가 → 상품 판매가 동기화 (+ 상품 다중통화 재계산)
if (productSellingPriceSync !== null) {
updatedProduct.selling_price = productSellingPriceSync;
if (currencies && Array.isArray(currencies)) {
updatedProduct.multi_currency_selling_price = calculateCurrencyPricesHandler(
{ basePrice: productSellingPriceSync, currencies },
context
);
}
productSellingPriceSynced = true;
logger.log(`[updateOptionField] Reverse-synced product ${productId} selling_price to ${productSellingPriceSync} from default option`);
}
return updatedProduct;
}
return product;
});
// 대상 옵션을 찾지 못했으면 아무것도 바꾸지 않는다.
//
// 아직 옵션을 불러오지 않은 행(`options === undefined`)이나 이미 삭제된 옵션이 여기에
// 해당한다. 그대로 진행하면 데이터소스를 같은 값으로 다시 써서 불필요한 리렌더를 만들고,
// 존재하지 않는 옵션이 modified 로 기록돼 일괄 저장 페이로드에 실린다.
if (!optionFound) {
return;
}
// 데이터소스 업데이트 (UI 자동 리렌더링)
// 구조: { success, data: { data: [...], pagination, statistics } }
G7Core.dataSource.set(dataSourceId, {
...currentData,
data: {
...currentData.data,
data: updatedProducts,
},
});
// 변경된 옵션 ID와 필드명을 _local 상태에서 추적 + 에러 상태 업데이트
// G7Core.state.setLocal을 사용하여 컴포넌트 로컬 상태 직접 업데이트
const currentLocal = G7Core.state.getLocal() || {};
const modifiedOptionIds = new Set(currentLocal.modifiedOptionIds || []);
const optionKey = `${productId}-${optionId}`;
modifiedOptionIds.add(optionKey);
// 수정된 필드명 추적 (옵션별로 어떤 필드가 수정되었는지 기록)
const modifiedOptionFields: Record<string, string[]> = { ...(currentLocal.modifiedOptionFields || {}) };
const existingFields = new Set(modifiedOptionFields[optionKey] || []);
existingFields.add(field);
modifiedOptionFields[optionKey] = Array.from(existingFields);
const setLocalPayload: Record<string, any> = {
modifiedOptionIds: Array.from(modifiedOptionIds),
modifiedOptionFields,
optionFieldErrors: newErrors,
};
// 기본 옵션 판매가 → 상품 판매가 역동기화가 발생했으면 상품도 수정 대상으로 기록
// (일괄 저장이 modifiedProductFields 의 selling_price 를 보고 상품 판매가를 전송하므로 필수)
if (productSellingPriceSynced) {
const modifiedProductIds = new Set(currentLocal.modifiedProductIds || []);
modifiedProductIds.add(productId);
const modifiedProductFields: Record<string, string[]> = { ...(currentLocal.modifiedProductFields || {}) };
const productKey = String(productId);
const productFields = new Set(modifiedProductFields[productKey] || []);
productFields.add('selling_price');
modifiedProductFields[productKey] = Array.from(productFields);
setLocalPayload.modifiedProductIds = Array.from(modifiedProductIds);
setLocalPayload.modifiedProductFields = modifiedProductFields;
}
G7Core.state.setLocal(setLocalPayload);
logger.log(`[updateOptionField] Updated option ${productId}/${optionId}.${field} =`, value);
}