(async () => {
const { EventManager, utils } = ShopbySkin;
const $introduce = $('introduce'); // 상단 소개글 컴포넌트
const $customArticleFormTerms = $('custom-article-form-terms'); // 하단 약관 컴포넌트
const $inputForm = $('input-form'); // 작성 폼 컴포넌트
let profile; // 회원 프로필 데이터
const searchParams = new URLSearchParams(location.search);
ShopbySkin.EventManager.on('PAGE_LOAD_COMPLETED', (commonData) => {
profile = commonData.profile;
});
const $postList = $('post-list'); // 게시판 리스트 아이템 컴포넌트
const boardNo = 279942; // 게시판 번호
const boardId = 'b2b'; // 게시판 Id
const type = searchParams.get('type'); // 문의 타입
const entryCategoryNo = 3839; // 상품 입점문의 카테고리 번호
const adCategoryNo = 3840; // 광고/제휴문의 카테고리 번호
EventManager.on('PAGE_LOAD_COMPLETED', () => {
const title = type === 'entry' ? '상품입점 문의' : '광고/제휴 문의';
document.querySelector('shopby-header').store.setState({
subTitle: title,
});
});
if (type === 'entry') {
const data = [];
data.title = '상품입점 문의';
data.content =
"
귀사의 경쟁력있는 상품을 기다리고 있습니다.
" +
"" +
'골프 클럽/용품 전문 쇼핑몰의 절대강자 SB골프는 제안해 주시는 귀사의 상품을 소중하게 생각합니다. SB골프와 함께 미래를 이끌 새로운 트랜드를 만들 수 있습니다.
' +
'입점문의 후 담당MD팀에서 제안서 검토 후 10영업일 내에 개별연락을 드리고 있습니다.
' +
'단, 업무폭주로 인해 입점이 불가한 상품에 대해서는 별도 통지가 되지 않으며, 전화문의는 받지 않으니 양해바랍니다.' +
'
';
const introduceHtml = renderHtml($introduce, data);
$introduce.append(introduceHtml);
const field = fnSetField(type);
const formHtml = renderHtml($inputForm, field);
$inputForm.append(formHtml);
} else if (type === 'ad') {
const data = [];
data.title = '광고/제휴 문의';
data.content =
"SB골프와 WIN - WIN 할 파트너를 모십니다.
" +
"" +
'SB골프는 상호협력과 신뢰를 바탕으로 서로 win-win을 위한 최고의 파트너를 기다리고 있습니다.
' +
'다양하고 참신한 제안을 통해 SB골프와 새로운 도약을 함께 하시기 바랍니다.' +
'
';
const introduceHtml = renderHtml($introduce, data);
$introduce.append(introduceHtml);
const field = fnSetField(type);
const formHtml = renderHtml($inputForm, field);
$inputForm.append(formHtml);
}
const isLogin = utils.isSignIn();
// [Jay] 약관 데이터 조회 (개인정보 수집)
const termsTypes = isLogin
? 'PI_COLLECTION_AND_USE_REQUIRED'
: 'PI_COLLECTION_AND_USE_FOR_GUEST_ON_ARTICLE';
const params = {
queryString: {
termsTypes: termsTypes,
},
};
const termsRes = await callShopApi('/terms?', 'GET', params);
const termsData = [];
termsData.isLogin = isLogin;
termsData.data = termsRes.result[termsTypes.toLowerCase()];
const termsHtml = renderHtml($customArticleFormTerms, termsData);
$customArticleFormTerms.append(termsHtml);
// [Jay] velocity 적용
$('.l-content').velocity({ opacity: 1 }, { duration: 500 });
const ACTION_HANDLER_MAP = {};
function fnSetField(type) {
const field = [];
if (!utils.isSignIn()) {
field.push(
{
title: '작성자',
name: 'writerNm',
type: 'inputText',
required: true,
},
{
title: '비밀번호',
name: 'password',
type: 'inputText',
required: true,
},
);
}
field.push(
{
title: '회사명',
name: 'companyNm',
type: 'inputText',
required: true,
},
{
title: '회사주소',
name: 'companyAddress',
type: 'inputText',
required: false,
},
{
title: '홈페이지',
name: 'homepage',
type: 'inputText',
required: false,
},
{
title: '담당자 이름',
name: 'managerNm',
type: 'inputText',
required: true,
},
{
title: '담당부서',
name: 'department',
type: 'inputText',
required: false,
},
{
title: '이메일',
name: 'email',
type: 'inputText',
required: true,
},
{
title: '휴대폰 번호',
name: 'phoneNum',
type: 'inputText',
required: true,
},
{
title: '전화번호',
name: 'officeNum',
type: 'inputText',
required: false,
},
{
title: '회사소개',
name: 'companyIntroduce',
type: 'textArea',
required: false,
},
);
if (type === 'entry') {
field.push(
{
title: '브랜드명',
name: 'brandNm',
type: 'inputText',
required: true,
},
{
title: '상품유형',
name: 'productType',
type: 'inputText',
required: true,
},
);
} else if (type === 'ad') {
field.push({
title: '제안내용',
name: 'suggestContent',
type: 'textArea',
required: true,
});
}
return field;
}
const clickEventListener = (e) => {
if (!e?.target) {
return;
}
const btn =
e?.target?.closest?.('[shopby-action]') ||
e?.target?.parentElement?.closest?.('[shopby-action]');
const action = btn?.getAttribute('shopby-action');
if (!btn) {
return;
}
ACTION_HANDLER_MAP[action]?.({
event: e,
});
};
document.addEventListener('click', clickEventListener);
// [Jay] 게시글 작성 이벤트
document
.getElementById('article')
.addEventListener('submit', async function (event) {
event.preventDefault(); // 폼의 기본 동작(페이지 리로드)을 막음
// [Jay] 개인정보 수집 이용 동의 여부
const termsCheck = $('input[name="check-terms"]').is(':checked');
if (!termsCheck) {
EventManager.fire('MODAL_ALERT_OPEN', {
noticeType: 'WARNING',
message: '개인정보 수집 이용 동의 체크가 필요합니다.',
});
return false;
}
// 로그인 여부
const isLogin = utils.isSignIn();
// 폼 데이터
const formData = $('#article').serializeArray();
// 전화번호 배열 인덱스
const officeNumIdx = formData.findIndex(
(item) => item.name === 'officeNum',
);
if (type === 'entry') {
const companyIntroduce = $('#companyIntroduce').val(); // 회사소개 value값
// [Jay] form에 회사소개 데이터가 없어서 회사소개 객체 만들어줌
const companyIntroduceObj = {
name: 'companyIntroduce',
value: companyIntroduce,
};
// 전화번호 키값 뒤에 회사소개 데이터 추가
formData.splice(officeNumIdx + 1, 0, companyIntroduceObj);
} else if (type === 'ad') {
const companyIntroduce = $('#companyIntroduce').val(); // 회사소개 value값
// [Jay] form에 회사소개 데이터가 없어서 회사소개 객체 만들어줌
const companyIntroduceObj = {
name: 'companyIntroduce',
value: companyIntroduce,
};
// 전화번호 키값 뒤에 회사소개 데이터 추가
formData.splice(officeNumIdx + 1, 0, companyIntroduceObj);
const suggestContent = $('#suggestContent').val(); // 제안내용 value값
// [Jay] form에 제안내용 데이터가 없어서 회사소개 객체 만들어줌
const suggestContentObj = {
name: 'suggestContent',
value: suggestContent,
};
// 전화번호 키값 뒤에 회사소개 데이터 추가
formData.splice(officeNumIdx + 2, 0, suggestContentObj);
}
const imgTarget = $('.article-form__attachment').find('img');
const writerNm = $('#writerNm').val();
const password = $('#password').val();
// [Jay] 첨부파일 이미지 배열 추가
const imgSrcArr = [];
imgTarget.each((index, elem) => {
const srcUrl = $(elem).attr('src');
const imageName = $(elem).attr('alt');
const croppedUrl = srcUrl.match(/.*\.(png|jpg|jpeg|gif|bmp)/i)[0]; // 이미지 사이즈가 URL에 붙어서 확장자까지만 잘라냄.
imgSrcArr.push({
originalFileName: imageName, // 원본 파일명
uploadedFileName: croppedUrl, // 업로드 된 파일 Url
});
});
// 필드 이름을 변경하기 위한 매핑 객체
const nameMap = {
companyNm: '회사명',
companyAddress: '회사주소',
homepage: '홈페이지',
managerNm: '담당자 이름',
department: '담당부서',
email: '이메일',
phoneNum: '휴대폰 번호',
officeNum: '전화번호',
companyIntroduce: '회사소개',
suggestContent: '제안내용',
brandNm: '브랜드명',
productType: '상품유형',
};
// [Jay] 비회원인 경우 작성자, 비밀번호 배열 제거(컨텐츠 내용에 굳이 필요없음)
if (!isLogin) {
delete formData[0];
delete formData[1];
}
// 빈 키값 제거
const filteredFormData = formData.filter(
(item) => item.name.trim() !== '',
);
const content = filteredFormData.map((item) => {
// 필드 이름이 매핑된 경우 그 이름으로, 아니면 기존 이름 사용
const displayName = nameMap[item.name] ?? item.name;
return `${displayName} : ${item.value}`;
});
// [Jay] 게시글 최종 데이터
const finalData = {
images: imgSrcArr,
password: isLogin ? null : password, // 비회원 글쓰기용 비밀번호
articleTitle:
type === 'entry'
? '상품입점 문의 드립니다.'
: '광고/제휴 문의 드립니다.', // 게시글 제목
articleContent: content.join('
'), // 게시글 내용
boardCategoryNo: type === 'entry' ? entryCategoryNo : adCategoryNo, // 카테고리 번호
secreted: true, // 비밀글 여부
guestName: isLogin ? profile.memberName : writerNm, // 작성자. 생략하면 '비회원'으로 노출.
};
const param = {
data: JSON.stringify(finalData), // post body에 보내려면 JSON.stringify 처리
};
// [Jay] 로그인 상태인 경우 accessToken 추가
if (isLogin) {
param.accessTokenType = 'member';
}
const result = await callShopApi(
`/boards/${boardId}/articles`,
'POST',
param,
);
if (result.statusCode === 204) {
EventManager.fire('MODAL_ALERT_OPEN', {
noticeType: 'SUCCESS',
message: '등록되었습니다.',
onClose: () => {
location.href = '/pages/service/main.html';
},
});
} else {
EventManager.fire('MODAL_ALERT_OPEN', {
noticeType: 'CAUTION',
message: `${result.result.message}`,
});
}
});
})();