Files
Gnuboard7/modules/_bundled/sirsoft-ecommerce/resources/js/handlers/bulkUpdateHandlers.ts
T
HeuJung e21bff678f fix(core,ecommerce,board,basic,pay_kginicis,pay_nhnkcp,pay_nicepayments): 7.0.6 회귀 3건·잠복 결함 3건 해소 + 통화 하드코딩 전수 제거
7.0.6 사이클에서 유입된 회귀 3건을 출시 전에 닫는다. 추가옵션 저장소의
반환 타입 선언이 실제 반환(중첩 맵)과 어긋나 추가옵션 있는 상품의 담기·
바로구매가 죽었고, 검색 엔진이 결과 소비 시점에 SELECT 를 재작성해 정렬이
참조하던 스코어 별칭을 지웠으며, 미들웨어 targets 가 늘어난 라우트를
따라가지 못해 비회원 현금영수증이 전면 불능이었다. 셋 다 정적 검사의
사각지대였으므로 룰 2건과 계약 테스트를 함께 세워 재발을 막는다.

같은 유형의 잠복 결함 3건(빈 반환의 타입 불일치 2건, 없는 메서드 호출 1건)도
호출 경로가 생기는 순간 fatal 이므로 함께 닫았다.

브라우저 검수 중 드러난 선행 결함 5건을 이어서 수정한다. 엔진이 event 키로
선언한 액션을 React prop 으로 연결하지 않아 오류 없이 조용히 무반응이었고,
연결한 뒤에는 커스텀 컴포넌트의 이벤트 payload 가 유실됐다. 비회원 주문상세
응답에 현금영수증 키가 없어 발급 결과에 도달할 수 없었으며, 입금확인과
현금영수증 발급이 base 통화 금액을 써서 결제 통화가 다른 주문에서 각각
저장 실패와 잘못된 증빙을 냈다.

마지막으로 통화 단위를 코드·문구에서 걷어내 설정으로 이관한다. 다국어
문구의 원/円, 프론트의 KRW 고정표와 리터럴 폴백 173건, 서버 포맷의 통화
코드 리터럴이 대상이며, 기본 통화가 원이 아닌 상점에서 값은 맞고 단위만
틀린 금액이 예외 없이 나가던 문제였다. 통화 판정을 설정 단일 출처로 모으고
규칙 3건을 정적 검사로 고정했다.
2026-08-10 09:07:46 +09:00

953 lines
41 KiB
TypeScript

/**
* 통합 일괄 업데이트 핸들러
*
* 상품/옵션의 일괄 변경 + 개별 인라인 수정을 동시 처리합니다.
* - 상품 체크 시: 상품 API 호출 (해당 상품의 옵션 자동 포함)
* - 상품 미체크 + 옵션만 체크: 옵션 API 호출
*
* "일괄 적용" 버튼 → 확인 모달 → 이 핸들러 호출
*/
import type { ActionContext } from '../types';
import { formatAmountInCurrency } from './calculateCurrencyPrices';
import { reloadExpandedOptions } from './expandedOptionsHandlers';
// Logger 설정 (G7Core 초기화 전에도 동작하도록 폴백 포함)
const logger = ((window as any).G7Core?.createLogger?.('Ecom:BulkUpdate')) ?? {
log: (...args: unknown[]) => console.log('[Ecom:BulkUpdate]', ...args),
warn: (...args: unknown[]) => console.warn('[Ecom:BulkUpdate]', ...args),
error: (...args: unknown[]) => console.error('[Ecom:BulkUpdate]', ...args),
};
/**
* 커스텀 핸들러에 전달되는 액션 객체 인터페이스
*/
interface ActionWithParams {
handler: string;
params?: Record<string, any>;
target?: string;
onSuccess?: any;
onError?: any;
[key: string]: any;
}
/**
* 일괄 변경 조건 인터페이스
*/
interface BulkChangeCondition {
method: 'set' | 'add' | 'subtract' | 'percent';
value: number;
}
/**
* 상품 일괄 변경 조건
*/
interface ProductBulkChanges {
sales_status?: string;
display_status?: string;
}
/**
* 옵션 일괄 변경 조건
*/
interface OptionBulkChanges {
price_adjustment?: BulkChangeCondition;
stock_quantity?: BulkChangeCondition;
}
/**
* 상품 개별 수정 아이템
*/
interface ProductItem {
id: number;
name?: Record<string, string>;
list_price?: number;
selling_price?: number;
sales_status?: string;
display_status?: string;
}
/**
* 옵션 개별 수정 아이템
*/
interface OptionItem {
product_id: number;
option_id: number;
option_name?: string | Record<string, string>;
sku?: string;
list_price?: number;
price_adjustment?: number;
stock_quantity?: number;
safe_stock_quantity?: number;
is_default?: boolean;
is_active?: boolean;
}
/**
* 확인 데이터 인터페이스
*/
interface BulkConfirmData {
products: Array<{
id: number;
name: string;
changes: string;
}>;
options: Array<{
productId: number;
optionId: number;
productName: string;
optionName: string;
changes: string;
/** 개별 열거 대신 상품 단위로 묶은 항목인지 (목록에서 펼치지 않은 상품) */
aggregate?: boolean;
/** aggregate 항목이 대표하는 옵션 수 (비활성 포함 전체) */
optionCount?: number;
}>;
summary: {
productCount: number;
optionCount: number;
hasBulkChanges: boolean;
hasInlineChanges: boolean;
};
}
/**
* G7Core 인터페이스 (타입 안전성)
*/
interface G7CoreInterface {
dataSource: {
get: (id: string) => any;
set: (id: string, data: any) => void;
refetch: (id: string) => Promise<any>;
};
state: {
get: () => Record<string, any>;
set: (updates: Record<string, any>) => void;
getLocal: () => Record<string, any>;
setLocal: (updates: Record<string, any>) => void;
};
api: {
patch: (url: string, data: any) => Promise<any>;
};
toast: {
success: (message: string) => void;
warning: (message: string) => void;
error: (message: string) => void;
};
t: (key: string, params?: Record<string, any>) => string;
modal: {
close: (id?: string) => void;
};
}
/**
* 일괄 업데이트 실패 처리
*
* 서버가 내려준 실제 메시지/검증 에러를 토스트와 모달에 그대로 노출한다.
* 기존에는 catch 에서 error 를 버리고 고정 t 문자열만 토스트로 띄워
* "왜 실패했는지" 를 확인할 수 없었다 (모달에도 상세 미표시).
*
* - 토스트: 서버 message → error.message → 폴백 t 문자열 순으로 정확한 문구 표시
* - 모달: validation errors 를 평탄화하여 `_global.bulkUpdateErrors` 에 저장하고
* 모달을 닫지 않아 사용자가 어떤 필드가 거부됐는지 확인 가능
*
* @param G7Core G7Core 인스턴스
* @param error catch 로 전달된 에러 (axios 에러: error.response.data 에 본문)
* @param fallbackKey 서버 메시지가 없을 때 사용할 다국어 키
* @return void
*/
function handleBulkUpdateError(G7Core: G7CoreInterface, error: any, fallbackKey: string): void {
const data = error?.response?.data ?? {};
const serverMessage: string = data?.message || error?.message || '';
// validation errors 평탄화 (필드별 첫 메시지 목록)
const errorsObj = data?.errors;
const detailMessages: string[] = errorsObj && typeof errorsObj === 'object'
? Object.values(errorsObj).map((msgs: any) => (Array.isArray(msgs) ? msgs[0] : String(msgs)))
: [];
// 토스트: 정확한 서버 메시지 우선
const toastMessage = serverMessage || G7Core.t(fallbackKey);
G7Core.toast.error(toastMessage);
// 모달: 상세 에러를 노출하고 닫지 않음
G7Core.state.set({
bulkUpdateErrors: detailMessages.length > 0 ? detailMessages : (toastMessage ? [toastMessage] : []),
});
}
/**
* 다국어 객체에서 로컬라이즈된 문자열 추출
* option_name, product name 등 {en: "...", ko: "..."} 형태의 객체 처리
*/
function localizeValue(value: any): string {
if (typeof value === 'string') return value;
if (value && typeof value === 'object') {
return value.ko || value.en || JSON.stringify(value);
}
return String(value ?? '');
}
/**
* 판매/전시 상태 enum 값을 다국어 라벨로 변환
*
* 일괄 변경 확인 모달에서 raw enum 값(on_sale, visible 등)이 그대로 노출되던 결함을 해결한다.
* 드롭다운 옵션과 동일한 SSoT(`enums.{sales_status,display_status}.*`)를 참조하여
* 표시 라벨을 통일한다. 미정의 키는 원본 값으로 폴백한다.
*
* @param G7Core G7Core 인스턴스
* @param type 상태 종류 ('sales_status' | 'display_status')
* @param value 변환할 enum 값
* @return 다국어 라벨 (미정의 시 원본 값)
*/
function localizeStatus(
G7Core: G7CoreInterface,
type: 'sales_status' | 'display_status',
value: string
): string {
if (!value) return String(value ?? '');
const label = G7Core.t(`sirsoft-ecommerce.enums.${type}.${value}`);
// t()가 키를 찾지 못하면 빈 문자열을 반환하므로 원본 값으로 폴백
return label || value;
}
/**
* G7Core 가져오기
*/
function getG7Core(): G7CoreInterface | null {
const G7Core = (window as any).G7Core;
if (!G7Core) {
logger.error('[bulkUpdate] G7Core is not available');
return null;
}
return G7Core;
}
/**
* 통합 일괄 업데이트 핸들러
*
* 상품 체크 여부에 따라 API 호출 결정:
* - selectedItems.length > 0 → 상품 API 호출 (옵션 자동 포함)
* - selectedItems.length === 0 && selectedOptionIds.length > 0 → 옵션 API 호출
*/
export function bulkUpdateHandler(action: ActionWithParams, context: ActionContext): void {
const G7Core = getG7Core();
if (!G7Core) return;
const localState = G7Core.state.getLocal() || {};
const globalState = G7Core.state.get() || {};
// 모달에서 호출 시 _local 대신 _global.bulkSelectedItems 사용
// (일괄 적용 버튼 클릭 시 setState로 _global에 복사됨)
const selectedItems: number[] = globalState.bulkSelectedItems || localState.selectedItems || [];
const selectedOptionIds: string[] = globalState.bulkSelectedOptionIds || localState.selectedOptionIds || [];
logger.log('[bulkUpdate] globalState.bulkSelectedItems:', globalState.bulkSelectedItems);
logger.log('[bulkUpdate] localState.selectedItems:', localState.selectedItems);
logger.log('[bulkUpdate] Final selectedItems:', selectedItems);
// API 호출 결정: 상품 체크가 우선
if (selectedItems.length > 0) {
// 상품이 체크된 경우 → 상품 API 호출 (옵션 자동 포함)
bulkUpdateProductsInternal(G7Core, globalState, localState, selectedItems);
} else if (selectedOptionIds.length > 0) {
// 상품 미체크 + 옵션만 체크된 경우 → 옵션 API 호출
bulkUpdateOptionsInternal(G7Core, globalState, localState, selectedOptionIds);
} else {
// 아무것도 체크 안 됨
G7Core.toast.warning(G7Core.t('sirsoft-ecommerce.admin.product.bulk.no_selection'));
}
}
/**
* 상품 일괄 업데이트 내부 함수
* 상품과 해당 옵션을 함께 처리
*/
function bulkUpdateProductsInternal(
G7Core: G7CoreInterface,
globalState: Record<string, any>,
localState: Record<string, any>,
selectedIds: number[]
): void {
const dataSource = G7Core.dataSource.get('products');
const products = dataSource?.data?.data || [];
// 1. 상품 일괄 변경 조건 수집
const productBulkChanges: ProductBulkChanges = {};
if (globalState.bulkSalesStatus) {
productBulkChanges.sales_status = globalState.bulkSalesStatus;
}
if (globalState.bulkDisplayStatus) {
productBulkChanges.display_status = globalState.bulkDisplayStatus;
}
// 2. 옵션 일괄 변경 조건 수집
const optionBulkChanges: OptionBulkChanges = {};
// bulkPriceCondition은 표시용 문자열("+100원")이므로, bulkPriceMethod/Value/Unit로 객체 생성
if (globalState.bulkPriceMethod && globalState.bulkPriceValue !== undefined && globalState.bulkPriceValue !== null && globalState.bulkPriceValue !== '') {
const priceMethodMap: Record<string, 'set' | 'add' | 'subtract' | 'percent'> = {
'fixed': 'set',
'increase': 'add',
'decrease': 'subtract',
};
// percent 단위인 경우 method를 'percent'로, 감소 시 음수 값 사용
if (globalState.bulkPriceUnit === 'percent') {
optionBulkChanges.price_adjustment = {
method: 'percent',
value: globalState.bulkPriceMethod === 'decrease'
? -(Number(globalState.bulkPriceValue) || 0)
: Number(globalState.bulkPriceValue) || 0,
};
} else {
optionBulkChanges.price_adjustment = {
method: priceMethodMap[globalState.bulkPriceMethod] || 'add',
value: Number(globalState.bulkPriceValue) || 0,
};
}
}
// bulkStockCondition은 표시용 문자열("+10개")이므로, bulkStockMethod와 bulkStockValue로 객체 생성
if (globalState.bulkStockMethod && globalState.bulkStockValue !== undefined && globalState.bulkStockValue !== null && globalState.bulkStockValue !== '') {
const stockMethodMap: Record<string, 'set' | 'add' | 'subtract'> = {
'set': 'set',
'increase': 'add',
'decrease': 'subtract',
};
optionBulkChanges.stock_quantity = {
method: stockMethodMap[globalState.bulkStockMethod] || 'add',
value: Number(globalState.bulkStockValue) || 0,
};
}
// 3. 개별 인라인 수정 수집 (상품 + 옵션 모두)
// modifiedProductIds, modifiedOptionIds, modifiedFields를 함께 확인
const modifiedProductIds: number[] = localState.modifiedProductIds || [];
const modifiedOptionIds: string[] = localState.modifiedOptionIds || [];
const modifiedProductFields: Record<string, string[]> = localState.modifiedProductFields || {};
const modifiedOptionFieldsMap: Record<string, string[]> = localState.modifiedOptionFields || {};
// 개별 체크된 옵션 (상품이 체크되지 않은 옵션들)
const selectedOptionIds: string[] = globalState.bulkSelectedOptionIds || localState.selectedOptionIds || [];
const selectedProductIdSet = new Set(selectedIds);
const productItems: ProductItem[] = [];
const optionItems: OptionItem[] = [];
/**
* 옵션 인라인 수정 데이터 수집 헬퍼 (실제 수정된 필드만 포함)
*/
function collectOptionItem(p: any, opt: any, optionKey: string): void {
const isOptionModified = opt._modified || modifiedOptionIds.includes(optionKey);
if (isOptionModified) {
const item: OptionItem = { product_id: p.id, option_id: opt.id };
const optModifiedFields = modifiedOptionFieldsMap[optionKey] || [];
// 실제 수정된 필드만 적용 (bulk_changes에 없는 것만)
if (!optionBulkChanges.price_adjustment && optModifiedFields.includes('price_adjustment')) {
item.price_adjustment = opt.price_adjustment;
}
if (!optionBulkChanges.price_adjustment && optModifiedFields.includes('selling_price')) {
// selling_price 변경 시 price_adjustment도 재계산되어 있으므로 함께 전송
item.price_adjustment = opt.price_adjustment;
}
if (!optionBulkChanges.stock_quantity && optModifiedFields.includes('stock_quantity')) {
item.stock_quantity = opt.stock_quantity;
}
if (optModifiedFields.includes('option_name')) item.option_name = opt.option_name;
if (optModifiedFields.includes('sku')) item.sku = opt.sku;
if (optModifiedFields.includes('list_price')) item.list_price = opt.list_price;
if (optModifiedFields.includes('safe_stock_quantity')) item.safe_stock_quantity = opt.safe_stock_quantity;
if (optModifiedFields.includes('is_default')) item.is_default = opt.is_default;
if (optModifiedFields.includes('is_active')) item.is_active = opt.is_active;
// 실제 변경 사항이 있는 경우에만 추가
if (Object.keys(item).length > 2) {
optionItems.push(item);
}
}
}
products
.filter((p: any) => selectedIds.includes(p.id))
.forEach((p: any) => {
// 상품 인라인 수정 (_modified 플래그 또는 modifiedProductIds 배열 확인)
const isProductModified = p._modified || modifiedProductIds.includes(p.id);
if (isProductModified) {
const item: ProductItem = { id: p.id };
const productKey = String(p.id);
const pModifiedFields = modifiedProductFields[productKey] || [];
// 실제 수정된 필드만 적용 (bulk_changes에 없는 것만)
if (!productBulkChanges.sales_status && pModifiedFields.includes('sales_status')) {
item.sales_status = p.sales_status;
}
if (!productBulkChanges.display_status && pModifiedFields.includes('display_status')) {
item.display_status = p.display_status;
}
if (pModifiedFields.includes('name')) item.name = p.name;
if (pModifiedFields.includes('list_price')) item.list_price = p.list_price;
if (pModifiedFields.includes('selling_price')) item.selling_price = p.selling_price;
// 실제 변경 사항이 있는 경우에만 추가
if (Object.keys(item).length > 1) {
productItems.push(item);
}
}
// 해당 상품의 모든 옵션 인라인 수정 (상품 체크 시 옵션 자동 포함)
(p.options || []).forEach((opt: any) => {
const optionKey = `${p.id}-${opt.id}`;
collectOptionItem(p, opt, optionKey);
});
});
// 4. 체크된 상품에 속하지 않은 개별 체크된 옵션 처리
if (selectedOptionIds.length > 0) {
products.forEach((p: any) => {
// 이미 체크된 상품의 옵션은 위에서 처리됨
if (selectedProductIdSet.has(p.id)) {
return;
}
(p.options || []).forEach((opt: any) => {
const optionKey = `${p.id}-${opt.id}`;
// 개별 체크된 옵션만 처리
if (selectedOptionIds.includes(optionKey)) {
collectOptionItem(p, opt, optionKey);
}
});
});
}
// 4. 상품 API 호출 (옵션 데이터 포함)
const payload: Record<string, any> = {
ids: selectedIds,
};
if (Object.keys(productBulkChanges).length > 0) {
payload.bulk_changes = productBulkChanges;
}
if (productItems.length > 0) {
payload.items = productItems;
}
if (Object.keys(optionBulkChanges).length > 0) {
payload.option_bulk_changes = optionBulkChanges;
}
if (optionItems.length > 0) {
payload.option_items = optionItems;
}
// 처리 중 상태 표시
// 재시도 시 이전 실패 상세를 초기화하여 stale 에러가 모달에 남지 않도록 한다
G7Core.state.set({ isProcessing: true, bulkUpdateErrors: [] });
G7Core.api.patch('/api/modules/sirsoft-ecommerce/admin/products/bulk-update', payload)
.then((response: any) => {
G7Core.toast.success(
G7Core.t('sirsoft-ecommerce.admin.product.bulk.update_success', {
products: response?.data?.products_updated || 0,
options: response?.data?.options_updated || 0,
})
);
// 상태 초기화
resetBulkState(G7Core);
// DataSource 리프레시 + 펼친 행 옵션 재로드
refetchProductsAndReloadExpanded(G7Core);
// 모달 닫기
G7Core.modal.close();
})
.catch((error: any) => {
logger.error('[bulkUpdateProducts] Error:', error);
handleBulkUpdateError(G7Core, error, 'sirsoft-ecommerce.admin.product.bulk.update_error');
})
.finally(() => {
G7Core.state.set({ isProcessing: false });
});
}
/**
* 옵션 일괄 업데이트 내부 함수
* 특정 옵션만 개별 처리 (상품 미체크 시)
*/
function bulkUpdateOptionsInternal(
G7Core: G7CoreInterface,
globalState: Record<string, any>,
localState: Record<string, any>,
selectedOptionIds: string[]
): void {
const dataSource = G7Core.dataSource.get('products');
const products = dataSource?.data?.data || [];
// 1. 일괄 변경 조건 수집
const bulkChanges: OptionBulkChanges = {};
// bulkPriceCondition은 표시용 문자열("+100원")이므로, bulkPriceMethod/Value/Unit로 객체 생성
if (globalState.bulkPriceMethod && globalState.bulkPriceValue !== undefined && globalState.bulkPriceValue !== null && globalState.bulkPriceValue !== '') {
const priceMethodMap: Record<string, 'set' | 'add' | 'subtract' | 'percent'> = {
'fixed': 'set',
'increase': 'add',
'decrease': 'subtract',
};
// percent 단위인 경우 method를 'percent'로, 감소 시 음수 값 사용
if (globalState.bulkPriceUnit === 'percent') {
bulkChanges.price_adjustment = {
method: 'percent',
value: globalState.bulkPriceMethod === 'decrease'
? -(Number(globalState.bulkPriceValue) || 0)
: Number(globalState.bulkPriceValue) || 0,
};
} else {
bulkChanges.price_adjustment = {
method: priceMethodMap[globalState.bulkPriceMethod] || 'add',
value: Number(globalState.bulkPriceValue) || 0,
};
}
}
// bulkStockCondition은 표시용 문자열("+10개")이므로, bulkStockMethod와 bulkStockValue로 객체 생성
if (globalState.bulkStockMethod && globalState.bulkStockValue !== undefined && globalState.bulkStockValue !== null && globalState.bulkStockValue !== '') {
const stockMethodMap: Record<string, 'set' | 'add' | 'subtract'> = {
'set': 'set',
'increase': 'add',
'decrease': 'subtract',
};
bulkChanges.stock_quantity = {
method: stockMethodMap[globalState.bulkStockMethod] || 'add',
value: Number(globalState.bulkStockValue) || 0,
};
}
// 2. 개별 인라인 수정 수집 (실제 수정된 필드만)
const modifiedOptionFieldsMap: Record<string, string[]> = localState.modifiedOptionFields || {};
const modifiedOptionIds: string[] = localState.modifiedOptionIds || [];
const items: OptionItem[] = [];
products.forEach((product: any) => {
(product.options || []).forEach((opt: any) => {
const optionKey = `${product.id}-${opt.id}`;
const isOptionModified = opt._modified || modifiedOptionIds.includes(optionKey);
if (selectedOptionIds.includes(optionKey) && isOptionModified) {
const item: OptionItem = { product_id: product.id, option_id: opt.id };
const optModifiedFields = modifiedOptionFieldsMap[optionKey] || [];
// 실제 수정된 필드만 적용 (bulk_changes에 없는 것만)
if (!bulkChanges.price_adjustment && optModifiedFields.includes('price_adjustment')) {
item.price_adjustment = opt.price_adjustment;
}
if (!bulkChanges.price_adjustment && optModifiedFields.includes('selling_price')) {
item.price_adjustment = opt.price_adjustment;
}
if (!bulkChanges.stock_quantity && optModifiedFields.includes('stock_quantity')) {
item.stock_quantity = opt.stock_quantity;
}
if (optModifiedFields.includes('option_name')) item.option_name = opt.option_name;
if (optModifiedFields.includes('sku')) item.sku = opt.sku;
if (optModifiedFields.includes('list_price')) item.list_price = opt.list_price;
if (optModifiedFields.includes('safe_stock_quantity')) item.safe_stock_quantity = opt.safe_stock_quantity;
if (optModifiedFields.includes('is_default')) item.is_default = opt.is_default;
if (optModifiedFields.includes('is_active')) item.is_active = opt.is_active;
// 실제 변경 사항이 있는 경우에만 추가
if (Object.keys(item).length > 2) {
items.push(item);
}
}
});
});
// 3. 옵션 API 호출
const payload: Record<string, any> = {
ids: selectedOptionIds,
};
if (Object.keys(bulkChanges).length > 0) {
payload.bulk_changes = bulkChanges;
}
if (items.length > 0) {
payload.items = items;
}
// 처리 중 상태 표시
// 재시도 시 이전 실패 상세를 초기화하여 stale 에러가 모달에 남지 않도록 한다
G7Core.state.set({ isProcessing: true, bulkUpdateErrors: [] });
G7Core.api.patch('/api/modules/sirsoft-ecommerce/admin/options/bulk-update', payload)
.then((response: any) => {
G7Core.toast.success(
G7Core.t('sirsoft-ecommerce.admin.product.bulk.option_update_success', {
count: response?.data?.options_updated || 0,
})
);
// 상태 초기화
resetBulkState(G7Core);
// DataSource 리프레시 + 펼친 행 옵션 재로드
refetchProductsAndReloadExpanded(G7Core);
// 모달 닫기
G7Core.modal.close();
})
.catch((error: any) => {
logger.error('[bulkUpdateOptions] Error:', error);
handleBulkUpdateError(G7Core, error, 'sirsoft-ecommerce.admin.product.bulk.option_update_error');
})
.finally(() => {
G7Core.state.set({ isProcessing: false });
});
}
/**
* 목록을 새로 받은 뒤 펼쳐진 행의 옵션을 다시 채웁니다.
*
* 목록 응답은 옵션을 싣지 않으므로, 리페치만 하면 펼친 행이 열린 채 옵션만 사라진다
* (`resetBulkState` 는 `expandedRows` 를 지우지 않는다 — 저장 후에도 보던 행은 그대로 열려 있는
* 것이 맞다). 저장 결과를 확인해야 하므로 `force: true` 로 서버 값을 다시 가져온다.
*
* @param G7Core G7Core 인스턴스
* @return void
*/
function refetchProductsAndReloadExpanded(G7Core: G7CoreInterface): void {
Promise.resolve(G7Core.dataSource.refetch('products'))
.then(() => {
reloadExpandedOptions(G7Core, { force: true });
})
.catch((error: any) => {
// 옵션 재로드 실패의 사용자 통지는 reloadExpandedOptions 내부가 담당한다
logger.error('[bulkUpdate] Failed to refetch products:', error);
});
}
/**
* 일괄 변경 상태 초기화
*/
function resetBulkState(G7Core: G7CoreInterface): void {
// 로컬 상태 초기화
G7Core.state.setLocal({
modifiedProductIds: [],
modifiedOptionIds: [],
modifiedProductFields: {},
modifiedOptionFields: {},
selectedItems: [],
selectedOptionIds: [],
});
// 글로벌 상태 초기화
G7Core.state.set({
bulkSalesStatus: null,
bulkDisplayStatus: null,
bulkPriceCondition: null,
bulkStockCondition: null,
bulkConfirmData: null,
bulkUpdateErrors: [],
});
}
/**
* 확인 모달에 표시할 변경 예정 데이터 빌드 핸들러
*
* DataSource에서 체크된 항목 중 변경 사항 추출,
* 상단 일괄 변경 설정 + 인라인 수정 사항 병합하여 요약 생성
*/
export function buildConfirmDataHandler(action: ActionWithParams, context: ActionContext): void {
const G7Core = getG7Core();
if (!G7Core) return;
const localState = G7Core.state.getLocal() || {};
const globalState = G7Core.state.get() || {};
const dataSource = G7Core.dataSource.get('products');
const products = dataSource?.data?.data || [];
// 단일 SSoT: 실제 API 호출(bulkUpdateHandler)과 동일하게 _global 우선으로 선택 소스를 읽는다.
// 적용 sequence 가 setState(target:global) 로 _local.selected* → _global.bulkSelected* 복사 후
// buildConfirmData 를 호출하므로, _local 만 읽으면 전체선택 경로에서 빈 모달이 떠 표시↔동작이 어긋났다.
const selectedItems: number[] = globalState.bulkSelectedItems || localState.selectedItems || [];
const selectedOptionIds: string[] = globalState.bulkSelectedOptionIds || localState.selectedOptionIds || [];
const confirmData: BulkConfirmData = {
products: [],
options: [],
summary: {
productCount: 0,
optionCount: 0,
hasBulkChanges: false,
hasInlineChanges: false,
},
};
// 일괄 변경 조건 확인
const hasBulkChanges = !!(
globalState.bulkSalesStatus ||
globalState.bulkDisplayStatus ||
globalState.bulkPriceCondition ||
globalState.bulkStockCondition
);
confirmData.summary.hasBulkChanges = hasBulkChanges;
// modifiedProductIds, modifiedOptionIds, modifiedFields 확인 (인라인 수정 여부)
const modifiedProductIds: number[] = localState.modifiedProductIds || [];
const modifiedOptionIds: string[] = localState.modifiedOptionIds || [];
const modifiedProductFields: Record<string, string[]> = localState.modifiedProductFields || {};
const modifiedOptionFieldsMap: Record<string, string[]> = localState.modifiedOptionFields || {};
// 상품별 변경 사항 수집
// 체크된 상품의 ID Set (체크된 상품의 옵션은 별도로 처리하지 않음)
const selectedProductIdSet = new Set(selectedItems);
/**
* 옵션 인라인 변경사항 수집 (중복 코드 제거를 위한 헬퍼)
*/
function collectOptionChanges(opt: any, optionKey: string, isOptionModified: boolean): string[] {
const optChanges: string[] = [];
const optModifiedFields = modifiedOptionFieldsMap[optionKey] || [];
// 옵션 일괄 변경 표시
// bulkPriceCondition / bulkStockCondition 은 레이아웃이 만든 표시용 문자열("+1000원", "+10개")이다.
// 객체(.method/.value)로 접근하면 "재고: undefined undefined" 가 되므로 문자열을 그대로 사용
if (globalState.bulkPriceCondition) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_price_adjustment_inline', {
value: globalState.bulkPriceCondition,
})
|| `Price adjustment: ${globalState.bulkPriceCondition}`
);
}
if (globalState.bulkStockCondition) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_stock_inline', {
value: globalState.bulkStockCondition,
})
|| `Stock: ${globalState.bulkStockCondition}`
);
}
// 옵션 인라인 수정 표시 (실제 수정된 필드만 보고)
if (isOptionModified) {
if (!globalState.bulkPriceCondition && optModifiedFields.includes('price_adjustment')) {
const priceValue = opt.price_adjustment?.toLocaleString?.() ?? opt.price_adjustment;
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_price_adjustment_inline', {
value: priceValue,
})
|| `Price adjustment: ${priceValue}`
);
}
if (!globalState.bulkPriceCondition && optModifiedFields.includes('selling_price')) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_selling_price', {
price: opt.selling_price?.toLocaleString?.() ?? opt.selling_price,
})
|| `Selling price: ${opt.selling_price}`
);
}
if (!globalState.bulkStockCondition && optModifiedFields.includes('stock_quantity')) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_stock_inline', {
value: opt.stock_quantity,
})
|| `Stock: ${opt.stock_quantity}`
);
}
if (optModifiedFields.includes('option_name')) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_option_name', {
name: localizeValue(opt.option_name),
})
|| `Option name: ${localizeValue(opt.option_name)}`
);
}
if (optModifiedFields.includes('sku')) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_sku', { sku: opt.sku })
|| `SKU: ${opt.sku}`
);
}
if (optModifiedFields.includes('list_price')) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_list_price', {
price: formatAmountInCurrency(Number(opt.list_price ?? 0)),
})
|| `List price: ${opt.list_price}`
);
}
if (optModifiedFields.includes('safe_stock_quantity')) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_safe_stock', {
value: opt.safe_stock_quantity,
})
|| `Safe stock: ${opt.safe_stock_quantity}`
);
}
if (optModifiedFields.includes('is_active')) {
optChanges.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_is_active', {
value: opt.is_active ? 'ON' : 'OFF',
})
|| `Active: ${opt.is_active ? 'ON' : 'OFF'}`
);
}
confirmData.summary.hasInlineChanges = true;
}
return optChanges;
}
if (selectedItems.length > 0) {
products
.filter((p: any) => selectedItems.includes(p.id))
.forEach((p: any) => {
const changes: string[] = [];
const isProductModified = p._modified || modifiedProductIds.includes(p.id);
const productKey = String(p.id);
const pModifiedFields = modifiedProductFields[productKey] || [];
// 일괄 변경 표시
if (globalState.bulkSalesStatus) {
const salesLabel = localizeStatus(G7Core, 'sales_status', globalState.bulkSalesStatus);
changes.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_sales_status', { status: salesLabel })
|| `Sales status: ${salesLabel}`
);
}
if (globalState.bulkDisplayStatus) {
const displayLabel = localizeStatus(G7Core, 'display_status', globalState.bulkDisplayStatus);
changes.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_display_status', { status: displayLabel })
|| `Display status: ${displayLabel}`
);
}
// 인라인 수정 표시 (실제 수정된 필드만 보고)
if (isProductModified) {
if (!globalState.bulkSalesStatus && pModifiedFields.includes('sales_status')) {
const salesLabel = localizeStatus(G7Core, 'sales_status', p.sales_status);
changes.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_sales_status', { status: salesLabel })
|| `Sales status: ${salesLabel}`
);
}
if (!globalState.bulkDisplayStatus && pModifiedFields.includes('display_status')) {
const displayLabel = localizeStatus(G7Core, 'display_status', p.display_status);
changes.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_display_status', { status: displayLabel })
|| `Display status: ${displayLabel}`
);
}
if (pModifiedFields.includes('name')) {
changes.push(G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_name_changed') || 'Name changed');
}
if (pModifiedFields.includes('list_price')) {
changes.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_list_price', { price: formatAmountInCurrency(Number(p.list_price ?? 0)) })
|| `List price: ${p.list_price?.toLocaleString?.() || p.list_price}`
);
}
if (pModifiedFields.includes('selling_price')) {
changes.push(
G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_selling_price', { price: formatAmountInCurrency(Number(p.selling_price ?? 0)) })
|| `Selling price: ${p.selling_price?.toLocaleString?.() || p.selling_price}`
);
}
confirmData.summary.hasInlineChanges = true;
}
if (changes.length > 0 || hasBulkChanges || isProductModified) {
confirmData.products.push({
id: p.id,
name: localizeValue(p.name),
changes: changes.length > 0 ? changes.join(', ') : (isProductModified
? (G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_inline_modified') || 'Inline modified')
: (G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_bulk_applied') || 'Bulk changes applied')),
});
}
// 옵션 변경 사항 수집 (상품 체크 시 모든 옵션 포함)
//
// 목록은 옵션을 기본 적재하지 않으므로, 펼치지 않은 상품은 `options` 가 아예 없다
// (`undefined`). 그렇다고 적용 범위가 줄어드는 것은 아니다 — 서버가 상품 ID 를 받아
// 그 상품의 모든 옵션(비활성 포함)으로 전개하기 때문이다. 그래서 열거는 못 하더라도
// **개수는 반드시 세어** 확인 모달의 수치가 실제 적용 건수와 일치하게 한다.
const optionsApplied = hasBulkChanges
&& !!(globalState.bulkPriceCondition || globalState.bulkStockCondition);
if (Array.isArray(p.options)) {
p.options.forEach((opt: any) => {
const optionKey = `${p.id}-${opt.id}`;
const isOptionModified = opt._modified || modifiedOptionIds.includes(optionKey);
const optChanges = collectOptionChanges(opt, optionKey, isOptionModified);
if (optChanges.length > 0 || optionsApplied || isOptionModified) {
confirmData.options.push({
productId: p.id,
optionId: opt.id,
productName: localizeValue(p.name),
optionName: opt.option_name_localized || localizeValue(opt.option_name) || opt.name || '',
changes: optChanges.length > 0 ? optChanges.join(', ') : (isOptionModified
? (G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_inline_modified') || 'Inline modified')
: (G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_bulk_applied') || 'Bulk changes applied')),
});
}
});
} else if (optionsApplied) {
// 미펼침 상품 — 집계 엔트리 1건으로 대체한다. `options_total_count` 는 비활성을
// 포함한 전체 옵션 수로, 서버가 전개하는 모집단과 같다(활성 수인 `options_count`
// 를 쓰면 미펼침 상품의 요약이 실제보다 적게 나온다).
const aggregateCount = Number(p.options_total_count) || 0;
if (aggregateCount > 0) {
confirmData.options.push({
aggregate: true,
productId: p.id,
optionId: 0,
optionCount: aggregateCount,
productName: localizeValue(p.name),
optionName: '',
changes: collectOptionChanges({}, `${p.id}-*`, false).join(', ')
|| (G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_bulk_applied') || 'Bulk changes applied'),
});
}
}
});
}
// 체크된 옵션 처리 (체크된 상품에 속하지 않은 옵션만 처리)
// 상품이 체크된 경우 해당 상품의 옵션은 위에서 이미 처리됨
if (selectedOptionIds.length > 0) {
products.forEach((p: any) => {
// 이미 체크된 상품의 옵션은 건너뜀 (중복 방지)
if (selectedProductIdSet.has(p.id)) {
return;
}
(p.options || []).forEach((opt: any) => {
const optionKey = `${p.id}-${opt.id}`;
if (selectedOptionIds.includes(optionKey)) {
const isOptionModified = opt._modified || modifiedOptionIds.includes(optionKey);
const optChanges = collectOptionChanges(opt, optionKey, isOptionModified);
confirmData.options.push({
productId: p.id,
optionId: opt.id,
productName: localizeValue(p.name),
optionName: opt.option_name_localized || localizeValue(opt.option_name) || opt.name || '',
changes: optChanges.length > 0 ? optChanges.join(', ') : (isOptionModified
? (G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_inline_modified') || 'Inline modified')
: (G7Core.t('sirsoft-ecommerce.admin.product.messages.bulk_summary_selected') || 'Selected')),
});
}
});
});
}
confirmData.summary.productCount = confirmData.products.length;
// 집계 엔트리는 배열에서 1칸을 쓰지만 실제로는 N건을 대표한다. 그래서 개수는 배열 길이가
// 아니라 "열거분 + 집계분" 으로 센다 — 전부 펼친 경우와 전부 미펼침인 경우의 수치가 같아야 한다.
confirmData.summary.optionCount = confirmData.options.reduce(
(sum, entry) => sum + (entry.aggregate ? (entry.optionCount || 0) : 1),
0
);
// 글로벌 상태에 확인 데이터 저장
G7Core.state.set({
bulkConfirmData: confirmData,
});
logger.log('[buildConfirmData] Built confirm data:', confirmData);
}