/* 회원 업종별 개인화 (로그인 원장님 전용, 비로그인은 화면 변화 없음) - 상단 카테고리 메뉴(GNB): 대표업종 카테고리를 맨 앞(행사·신상 메뉴 다음)으로 옮긴다(「내 업종」 표시는 하지 않음) - 메인 카테고리 아이콘: 대표업종 아이콘에 「내 업종」 표시 - 메인 「{회원명} 원장님의 다시 구매하기」: 최근 1년 주문 상품 중 판매 중인 것 최근순 최대 6개. 품절·판매종료·미전시 상품은 빼고, 남는 상품이 없으면 영역을 만들지 않는다. - 상품 썸네일 「구매한 상품」 표시: 최근 1년 주문 상품 (메인·상품 목록 등 썸네일 카드가 있는 모든 화면) - 신상 컬렉션·실시간 베스트 탭의 「내 업종」 표시와 실시간 베스트 제목 교체는 각 SPA(main-new-spa.js·main-best-spa.js)가 한다. 업종 판정은 회원 부가정보 대표업종 하나만 쓰고, 카테고리 연결은 메인 신상 SPA 와 같다(매트 2026-08-20). */ (function () { if (window.__gbPersonalizeLoaded) return; window.__gbPersonalizeLoaded = true; const IS_MO = /^m[.-]/.test(location.hostname); const MAX_REBUY = 6; const CHECK_LIMIT = 30; // 판매 여부를 확인할 최대 상품 수 (품절이 많아도 메인이 느려지지 않게) const CACHE_KEY = 'gbPersonalizeOrders'; const CACHE_TTL = 10 * 60 * 1000; const READY_TIMEOUT = 8000; const BOUGHT_STATUSES = 'PAY_DONE,PRODUCT_PREPARE,DELIVERY_PREPARE,DELIVERY_ING,DELIVERY_DONE,BUY_CONFIRM'; // 대표업종 → 카테고리 (네일은 젤네일·네일아트&도구 둘 다) const CATEGORY_BY_UPJONG = { '네일': [915138, 915150], '속눈썹': [915206], '반영구': [915212], '왁싱': [915214], '피부': [915217], '피부관리': [915217], '헤어': [915221], '마사지': [915217], '스킨': [915217], '태닝': [915217], '두피/탈모관리': [915221], '바버': [915221], }; // 대표업종 → 상단 카테고리 메뉴 이름 (CATEGORY_BY_UPJONG 과 같은 연결) const GNB_LABELS_BY_UPJONG = { '네일': ['젤네일', '네일아트&도구'], '속눈썹': ['속눈썹'], '반영구': ['반영구'], '왁싱': ['왁싱'], '헤어': ['헤어'], '피부': ['피부관리'], '피부관리': ['피부관리'], '마사지': ['피부관리'], '스킨': ['피부관리'], '태닝': ['피부관리'], '두피/탈모관리': ['헤어'], '바버': ['헤어'], }; const escapeHtml = (s) => String(s == null ? '' : s) .replace(/&/g, '&').replace(//g, '>') .replace(/"/g, '"').replace(/'/g, '''); const TAG_HTML = '내 업종'; const isSignedIn = () => { try { return Boolean(ShopbySkin.utils.isSignedIn()); } catch (e) { return false; } }; // shop-api.js 를 안 싣는 페이지도 있어서 없으면 불러온다 const ensureApi = () => new Promise((resolve) => { if (window.fetchShopApi) return resolve(true); if (!document.querySelector('script[src="/shop-api.js"]')) { const s = document.createElement('script'); s.src = '/shop-api.js'; document.head.appendChild(s); } const deadline = Date.now() + READY_TIMEOUT; (function check() { if (window.fetchShopApi) resolve(true); else if (Date.now() >= deadline) resolve(false); else setTimeout(check, 50); })(); }); const whenSkinReady = () => new Promise((resolve) => { const deadline = Date.now() + READY_TIMEOUT; (function check() { if (window.ShopbySkin && ShopbySkin.utils) resolve(true); else if (Date.now() >= deadline) resolve(false); else setTimeout(check, 50); })(); }); const ymd = (d) => { const k = new Date(d.getTime() + 9 * 3600000); return k.toISOString().slice(0, 10); }; /* ---------- 데이터 ---------- */ function loadProfile() { return fetchShopApi('/profile').then((p) => { let info = {}; try { info = JSON.parse(p.additionalInfo || '{}') || {}; } catch (e) { info = {}; } return { memberNo: p.memberNo || p.memberId || '', memberName: (p.memberName || '').trim(), upjong: info.대표업종 || '' }; }); } // 최근 1년 주문 → 상품별 최근 주문일·주문 횟수 (최근순). 취소·반품·교환 진행 건, 사은품·추가상품은 뺀다. function loadBought(memberKey) { try { const cached = JSON.parse(sessionStorage.getItem(CACHE_KEY) || 'null'); if (cached && cached.key === memberKey && Date.now() - cached.at < CACHE_TTL) return Promise.resolve(cached.list); } catch (e) { /* 캐시 무시 */ } const now = new Date(); const from = new Date(now.getTime() - 365 * 86400000); const base = `/profile/orders?orderRequestTypes=${BOUGHT_STATUSES}&startYmd=${ymd(from)}&endYmd=${ymd(now)}&pageSize=200`; const fetchPage = (page) => fetchShopApi(`${base}&pageNumber=${page}`).then((d) => d.items || []); return fetchPage(1) .then((items) => (items.length >= 200 ? fetchPage(2).then((more) => items.concat(more)) : items)) .then((orders) => { const map = new Map(); orders.forEach((order) => { const date = String(order.orderYmdt || '').slice(0, 10); const seenInOrder = new Set(); (order.orderOptions || []).forEach((o) => { if (!o.productNo || o.isFreeGift || o.isExtraProduct || o.claimStatusType) return; const no = Number(o.productNo); let entry = map.get(no); if (!entry) { entry = { productNo: no, lastDate: date, count: 0, name: o.productName || '', brand: o.brandName || '', image: o.imageUrl || '' }; map.set(no, entry); } if (date > entry.lastDate) entry.lastDate = date; if (!seenInOrder.has(no)) { entry.count += 1; seenInOrder.add(no); } }); }); const list = Array.from(map.values()).sort((a, b) => (a.lastDate < b.lastDate ? 1 : a.lastDate > b.lastDate ? -1 : 0)); try { sessionStorage.setItem(CACHE_KEY, JSON.stringify({ key: memberKey, at: Date.now(), list })); } catch (e) { /* 저장 실패 무시 */ } return list; }); } function fetchProduct(no) { return fetchShopApi(`/products/search?filter.includeMallProductNo=${no}&filter.saleStatus=ALL_CONDITIONS&filter.soldout=true&pageSize=1&pageNumber=1`) .then((d) => (d.items || [])[0] || null) .catch(() => null); } const isBuyable = (item) => item && !item.isSoldOut && item.saleType !== 'SOLDOUT' && item.saleStatusType !== 'FINISHED' && item.saleStatusType !== 'STOP' && item.saleStatusType !== 'PROHIBITION'; // 최근순으로 판매 중인 상품 최대 6개. 6개씩 묶어 조회하고 다 차면 멈춘다. async function pickRebuy(bought) { const picked = []; const candidates = bought.slice(0, CHECK_LIMIT); for (let i = 0; i < candidates.length && picked.length < MAX_REBUY; i += MAX_REBUY) { const chunk = candidates.slice(i, i + MAX_REBUY); const items = await Promise.all(chunk.map((b) => fetchProduct(b.productNo))); chunk.forEach((b, j) => { if (picked.length < MAX_REBUY && isBuyable(items[j])) picked.push({ b, item: items[j] }); }); } return picked; } /* ---------- 상단 카테고리 메뉴(GNB) ---------- */ // 1차 카테고리 번호는 개발몰과 운영몰이 달라(운영 915xxx) 메뉴 이름으로도 찾는다. 이름은 두 몰이 같다. // 상품 목록의 하위 카테고리 슬라이더와 섞이지 않게 상단 카테고리 메뉴(gb-catbar 가 붙은 슬라이더)만 본다. function applyGnb(cats, labels) { const wrappers = document.querySelectorAll('.nav__slider .swiper-wrapper[data-gbcat-ready], .category-slider .swiper-wrapper[data-gbcat-ready]'); wrappers.forEach((wrapper) => { if (!wrapper.children.length) return; const mine = Array.from(wrapper.children).filter((li) => { if (li.classList.contains('gbcat-pre')) return false; const a = li.querySelector('a[href*="categoryNo="]'); if (!a) return false; const m = (a.getAttribute('href') || '').match(/categoryNo=(\d+)$/); const label = Array.from(a.childNodes).filter((n) => n.nodeType === 3).map((n) => n.textContent).join('').trim(); return (m && cats.includes(Number(m[1]))) || labels.includes(label); }); if (!mine.length || mine.every((li) => li.hasAttribute('data-gbp-mine'))) return; // 행사·신상 메뉴(gb-catbar) 다음, 첫 번째 일반 카테고리 자리로 옮긴다 (메뉴 순서 유지) const firstNormal = Array.from(wrapper.children).find((li) => !li.classList.contains('gbcat-pre') && !mine.includes(li)); mine.forEach((li) => { li.setAttribute('data-gbp-mine', ''); if (firstNormal) wrapper.insertBefore(li, firstNormal); const a = li.querySelector('a'); a.classList.add('gbp-hl'); // 상단 메뉴는 「내 업종」 표시 없이 위치·글자색만 (아이콘·탭엔 표시 유지) }); const sw = wrapper.closest('.swiper'); try { if (sw && sw.swiper) { sw.swiper.update(); sw.swiper.slideTo(0, 0); } } catch (e) { /* noop */ } }); } /* ---------- 메인 카테고리 아이콘 ---------- */ function applyQuickMenu(cats) { cats.forEach((c) => { const a = document.querySelector(`.main-quick-menu a[href$="categoryNo=${c}"]`); const li = a && a.closest('li'); if (!li || li.classList.contains('gbp-hl')) return; li.classList.add('gbp-hl'); li.insertAdjacentHTML('afterbegin', '내 업종'); }); } /* ---------- 신상 컬렉션·실시간 베스트 탭 ---------- */ // 탭은 각 SPA 가 그리므로 그려진 뒤 대표업종 탭을 찾아 표시만 붙인다 (탭 이동·기본 탭 선택은 SPA 가 이미 한다) // 「많이 찾는 상품」 탭은 섹션 제목에 업종 이름이 이미 있어 「내 업종」 표시를 붙이지 않는다 (신상 컬렉션 탭만) function applyTabs(newCat) { const li = newCat && document.querySelector(`#mainNewV2TabList > li[data-category="${newCat}"]`); if (li && !li.querySelector('.gbp-tag')) li.insertAdjacentHTML('beforeend', TAG_HTML); } /* ---------- 구매한 상품 표시 ---------- */ function markBought(set) { document.querySelectorAll('a[href*="productNo="]').forEach((a) => { if (a.closest('.gbp-rebuy')) return; const no = ((a.getAttribute('href') || '').match(/productNo=(\d+)/) || [])[1]; if (!no || !set.has(Number(no))) return; const media = a.matches('.thumb-item__media') ? a : a.querySelector('.thumb-item__media'); if (!media || media.querySelector('.gbp-bought')) return; media.classList.add('gbp-media'); media.insertAdjacentHTML('beforeend', '구매한 상품'); }); } /* ---------- 메인 다시 구매하기 ---------- */ function priceHtml(item) { const discount = (item.immediateDiscountAmt || 0) + (item.additionDiscountAmt || 0); const final = item.salePrice - discount; return `
${final.toLocaleString()}원
`; } function renderRebuy(picked, memberName) { const anchor = document.querySelector('.main-quick-menu'); const host = anchor && anchor.closest('article'); if (!host || document.querySelector('.gbp-rebuy')) return; const title = memberName ? `${escapeHtml(memberName)} 원장님의 다시 구매하기` : '다시 구매하기'; const cards = picked.map(({ b, item }) => { const img = (item.listImageUrls && item.listImageUrls[0]) || (item.imageUrls && item.imageUrls[0]) || b.image || ''; const url = `/pages/product/product-detail.html?productNo=${item.productNo}`; const date = b.lastDate ? b.lastDate.replace(/-/g, '.') : ''; return ``; }).join(''); const row = document.createElement('article'); row.className = 'gbp-rebuy'; row.innerHTML = `최근 1년 동안 구매하신 상품입니다