결제 플러그인 3종(pay_kginicis/nhnkcp/nicepayments)과 sirsoft-basic 템플릿의
배포 JS 에 //# sourceMappingURL 주석과 .map 파일이 남아 있어, 공개 배포판에
원본 TS/TSX 전문(sourcesContent)이 노출될 수 있었다(NoSourcemapArtifactsTest 2건 실패).
각 확장을 --production(G7_BUILD_SOURCEMAP=0) 으로 재빌드해 소스맵 주석·.map 을
제거하고 {plugin|template}:update 로 활성 디렉토리에 반영. 기능 코드는 바이트 동일,
소스맵 주석만 제거된다. nhnkcp/nicepayments 의 components.json 파생 버전도 매니페스트
SSoT(1.0.0)로 재동기화. 매니페스트 버전은 무변경(동작 변화 없는 배포본 위생 수정).
NoSourcemapArtifactsTest 4/4 green.
18 lines
34 KiB
JavaScript
18 lines
34 KiB
JavaScript
(function(){"use strict";function Le(e){return/^https?:\/\//i.test(e)||e.startsWith("/api/")?e:e.startsWith("/plugins/")?`/api${e}`:e.startsWith("plugins/")?`/api/${e}`:e}function Oe(e){return e.trim().slice(0,160)}function Ke(e){if(e)return e.replace(/\/payment\/close-report$/,"/payment/retry")}async function ee(e,t,n=!1){const o=window.G7Core?.api;if(typeof o?.post=="function"){await o.post(e,t);return}const r=await fetch(Le(e),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),keepalive:n});if(!r.ok){let a=`NHN KCP payment request failed (${r.status})`;try{const s=await r.json(),i=Array.isArray(s?.errors?.message)?s.errors.message[0]:s?.error??s?.message;typeof i=="string"&&i.trim()!==""&&(a=i)}catch{}throw new Error(a)}}async function je(e){const t=Ke(e.closeReportUrl);t&&await ee(t,{oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??""})}async function Be(e,t="kcp-window-closed"){if(!e.closeReportUrl)return;const n={oid:e.oid,price:Number(e.price),buyer_email:e.buyer_email??"",buyer_phone:e.buyer_phone??"",payment_method:e.payment_method??"",reason:Oe(t)||"kcp-window-closed"};try{await ee(e.closeReportUrl,n,!0)}catch(o){console.warn("[sirsoft-pay_nhnkcp] failed to report payment window close",o)}}const De="nhnkcp_applepay";function S(e){return e===De}function x(){if(typeof navigator>"u")return!1;const e=navigator,t=(e.userAgent||"").toLowerCase(),n=((e.userAgentData?.platform??e.platform)||"").toLowerCase(),o=e.maxTouchPoints??0;return/iphone|ipad|ipod/.test(t)||/iphone|ipad|ipod|ios/.test(n)?!0:/macintosh|mac os x/.test(t)&&o>1}function M(){return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?"애플페이는 IOS 기기에 모바일결제만 가능합니다.":"Apple Pay is available only for mobile payments on iOS devices."}function T(e){return(e??"KRW").trim().toUpperCase()||"KRW"}function He(e){return T(e)==="KRW"}function Fe(e){const t=T(e);return((typeof document<"u"?document.documentElement.lang:"")||"").toLowerCase().startsWith("ko")?`NHN KCP는 KRW 결제만 지원합니다. (${t})`:`NHN KCP supports KRW payments only. (${t})`}function qe(e){const t=Math.max(0,Math.round(Number(e.amount??0))),n=Math.min(Math.max(0,Math.round(Number(e.tax_free_amount??0))),t);if(n<=0)return{};const o=Math.max(0,Math.round(Number(e.tax_amount??0))),r=Math.max(0,Math.round(Number(e.vat_amount??0))),a=Math.max(0,t-n),s=a>0&&o>0&&r>0?Math.min(a,Math.round(a*(r/o))):0,i=a-s;return{tax_flag:"TG03",comm_tax_mny:String(i),comm_vat_mny:String(s),comm_free_mny:String(n)}}class R extends Error{constructor(t){super(t??"결제가 취소되었습니다."),this.name="KcpCancelledError"}}const Ue={card:"100000000000",bank_transfer:"010000000000",virtual_account:"001000000000",mobile:"000010000000",bank:"010000000000",vbank:"001000000000",phone:"000010000000"},te={nhnkcp_payco:{payco_direct:"Y"},nhnkcp_naverpay:{naverpay_direct:"Y"},nhnkcp_naverpay_point:{naverpay_direct:"Y",naverpay_point_direct:"Y"},nhnkcp_kakaopay:{kakaopay_direct:"Y"},nhnkcp_applepay:{applepay_direct:"Y"}};function Ye(e,t){const n=e.toLowerCase();return!t||!Object.prototype.hasOwnProperty.call(te,n)?{}:{param_opt_1:n,nhnkcp_easy_pay_method:n}}function Ge(e){if(!e.isConnected)return!0;const t=window.getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!0;const n=e.getBoundingClientRect();return n.width<=0||n.height<=0}function We(e,t){let n=!1,o,r;const a=()=>{n=!0,r&&(r.disconnect(),r=void 0),o!==void 0&&(window.clearInterval(o),o=void 0)},s=()=>{n||!Ge(e)||(a(),t())},i=document.body??document.documentElement;return i&&typeof MutationObserver<"u"&&(r=new MutationObserver(s),r.observe(i,{attributes:!0,attributeFilter:["class","hidden","style"],childList:!0,subtree:!0})),o=window.setInterval(s,300),a}function ze(){if(typeof navigator>"u")return!1;if(x())return!0;const e=navigator;if(e.userAgentData?.mobile!==void 0)return e.userAgentData.mobile;const t=(navigator.userAgent||"").toLowerCase();return!!(/android|iphone|ipod|windows phone|iemobile|blackberry|opera mini|mobile safari/.test(t)||(navigator.maxTouchPoints??0)>1&&!t.includes("windows")&&!t.includes("macintosh"))}async function Je(e,t){const{pgPaymentData:n,paymentMethod:o}=e.params||{};if(!n){console.error("[sirsoft-pay_nhnkcp] pgPaymentData is required");return}const r=o??n.payment_method??n.pay_method??"card",a=typeof r=="string"&&r.startsWith("nhnkcp_"),s=window.G7Core;let i=null;try{if(!He(n.currency)){const u=Fe(n.currency);s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}if(S(r)&&!x()){const u=M();s?.state?.setLocal?.({paymentErrorMessage:u,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal");return}const c=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/nhnkcp");if(!c.data){console.error("[sirsoft-pay_nhnkcp] Failed to fetch client config",c);return}const d=c.data;i={closeReportUrl:d.callback_urls.close_report,oid:n.order_number,price:Number(n.amount),buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??"",payment_method:r};const l=window.location.origin+d.callback_urls.callback;await je(i),ze()?await Ve(s,n,r,a,l):await Qe(d,n,r,a,l)}catch(c){if(c instanceof R){i&&await Be(i,c.message||"kcp-window-closed"),s?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:r});return}console.error("[sirsoft-pay_nhnkcp] requestPayment error",c);const l=c?.response?.data,u=l?.errors?Object.values(l.errors)[0]?.[0]:void 0,p=l?.error??l?.message??u??(c instanceof Error?c.message:"Unknown error");s?.state?.setLocal?.({paymentErrorMessage:p,isSubmittingOrder:!1,paymentMethod:r}),s?.modal?.open?.("nhnkcp_payment_error_modal")}}async function Ve(e,t,n,o,r){const a=await e.api.post("/plugins/sirsoft-pay_nhnkcp/mobile/approval-key",{order_number:t.order_number,amount:t.amount,good_name:t.order_name,pay_method:n,buyr_name:t.customer_name??"",buyr_mail:t.customer_email??"",buyr_tel1:t.customer_phone??"",ret_url:r,currency:T(t.currency)});if(!a.success||!a.data){const d=a.errors,l=d?Object.values(d)[0]?.[0]:void 0;throw new Error(a.error??a.message??l??"KCP 모바일 승인키 획득 실패")}const{pay_url:s,fields:i}=a.data,c=document.createElement("form");c.method="POST",c.action=s,c.acceptCharset="euc-kr",c.style.display="none";for(const[d,l]of Object.entries(i)){const u=document.createElement("input");u.type="hidden",u.name=d,u.value=String(l),c.appendChild(u)}document.body.appendChild(c),c.submit(),await new Promise(()=>{})}async function Qe(e,t,n,o,r){const a=o?"100000000000":Ue[t.pay_method??"card"]??"100000000000",i={site_cd:n==="nhnkcp_payco"?e.easy_pay_client_id??e.client_id:e.use_escrow&&!o?e.escrow_client_id??e.client_id:e.client_id,ordr_idxx:t.order_number,good_name:t.order_name,good_mny:String(t.amount),buyr_name:t.customer_name??"",buyr_mail:t.customer_email??"",buyr_tel1:t.customer_phone??"",pay_method:a,Ret_URL:r};if(Object.assign(i,qe(t)),Object.assign(i,Ye(n,o)),a==="001000000000"&&(i.vcnt_expire_term=String(e.vbank_expire_days??3),i.disp_tax_yn="N"),e.use_escrow&&!o&&(i.escw_used="Y",i.pay_mod="O"),o){i.payco_direct="",i.naverpay_direct="A",i.kakaopay_direct="A",i.applepay_direct="A";const d=te[n];d&&Object.assign(i,d)}const c=Object.entries(i).map(([d,l])=>`<input type="hidden" name="${d}" value="${l.replace(/"/g,""")}">`).join("");await new Promise((d,l)=>{document.getElementById("kcp-sdk-iframe")?.remove(),document.getElementById("kcp-dim-overlay")?.remove();const u=document.createElement("div");u.id="kcp-dim-overlay",u.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.6);z-index:99998;",document.body.appendChild(u);const p=document.createElement("iframe");p.id="kcp-sdk-iframe",p.setAttribute("allowtransparency","true"),p.style.cssText="position:fixed;top:0;left:0;width:100%;height:100%;border:0;z-index:99999;background:transparent;",document.body.appendChild(p);const f=p.contentWindow;let V=!1,y,k;const cn=()=>{k?.(),k=void 0,y!==void 0&&(clearTimeout(y),y=void 0),p.remove(),u.remove()},N=m=>{V||(V=!0,cn(),l(m))},dn=()=>{V=!0,k?.(),k=void 0,y!==void 0&&(clearTimeout(y),y=void 0)};k=We(p,()=>{N(new R("kcp-payment-frame-closed"))}),f.m_Completepayment=function(m){const A=m.elements.res_cd?.value??"",X=m.elements.res_msg?.value??"";if(A==="0000"){dn();const h=f.document.forms.namedItem("order_info"),C=h&&h!==m?h:m;if(h&&h!==m)for(let Z=0;Z<m.elements.length;Z++){const I=m.elements[Z];if(!I.name)continue;let g=h.elements.namedItem(I.name);g||(g=f.document.createElement("input"),g.type="hidden",g.name=I.name,h.appendChild(g)),g.value=I.value}C.action=r,C.method="POST",C.target="_top",f.document.body.appendChild(C),C.submit()}else{const h=A===""||A==="7777"||X.includes("취소");N(h?new R(X):new Error(`KCP 오류 [${A}]: ${X}`))}},f.__kcpFail=m=>{N(m)};const Q=p.contentDocument||f.document;Q.open(),Q.write(`<!DOCTYPE html><html><head>
|
|
<script src="${e.sdk_url}"><\/script>
|
|
</head><body style="margin:0;padding:0;background:transparent;">
|
|
<form name="order_info">${c}</form>
|
|
<script>
|
|
try {
|
|
if (typeof KCP_Pay_Execute === 'function') {
|
|
KCP_Pay_Execute(document.forms['order_info']);
|
|
window.__kcpReady && window.__kcpReady();
|
|
} else {
|
|
window.__kcpFail && window.__kcpFail(new Error('KCP_Pay_Execute not defined'));
|
|
}
|
|
} catch(e) {
|
|
window.__kcpFail && window.__kcpFail(e);
|
|
}
|
|
<\/script>
|
|
</body></html>`),Q.close(),y=window.setTimeout(()=>{N(new Error("KCP SDK load timeout"))},15e3),f.__kcpReady=()=>{y!==void 0&&(clearTimeout(y),y=void 0)}})}const Xe={nhnkcp_payco:"PAYCO",nhnkcp_naverpay:"네이버페이",nhnkcp_naverpay_point:"네이버페이 포인트",nhnkcp_kakaopay:"카카오페이",nhnkcp_applepay:"Apple Pay"},Ze="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function ne(){return document.querySelector(".nhnkcp-easy-pay-btns")??null}function oe(){const e=ne();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function et(e){const t=ne();if(!t)return;const n=Xe[e];t.querySelectorAll("button").forEach(o=>{o.textContent?.trim()===n?(o.style.boxShadow=Ze,o.style.outline="none"):(o.style.boxShadow="",o.style.outline="")})}function tt(e){const t=e.params?.paymentMethod;if(!t)return;const n=window.G7Core;if(S(t)&&!x()){const r=M();n?.state?.setLocal?.({paymentErrorMessage:r,isSubmittingOrder:!1}),n?.modal?.open?.("nhnkcp_payment_error_modal"),oe();return}const o=typeof t=="string"&&t.startsWith("nhnkcp_");n?.state?.setLocal?.({paymentMethod:t}),o?et(t):oe()}function nt(e){const t=document.createElement("textarea");t.value=e,t.setAttribute("readonly","readonly"),t.style.position="fixed",t.style.left="-9999px",t.style.top="0",document.body.appendChild(t),t.select();try{document.execCommand("copy")}finally{t.remove()}}async function ot(e){const t=String(e.params?.text??"");if(t!==""){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(t);return}nt(t)}}const re={requestPayment:Je,setPaymentMethod:tt,copyToClipboard:ot},ae="/api/modules/sirsoft-ecommerce/user/orders",$="sirsoft-pay_nhnkcp",se={info:(...e)=>console.info(`[${$}]`,...e),warn:(...e)=>console.warn(`[${$}]`,...e),error:(...e)=>console.error(`[${$}]`,...e)};function rt(e){return typeof e=="string"?e:e instanceof URL?e.toString():typeof Request<"u"&&e instanceof Request?e.url:String(e)}function at(e,t){return t?.method?t.method.toUpperCase():typeof Request<"u"&&e instanceof Request?e.method.toUpperCase():"GET"}function st(e,t){if(t!=="POST")return!1;const n=e.split("?")[0].split("#")[0];return n===ae||n.endsWith(ae)}function it(e){try{return JSON.parse(e).payment_method}catch{return}}function ct(e){return new Response(JSON.stringify({success:!1,message:e,error:e,errors:{payment_method:[e]}}),{status:422,statusText:"Unprocessable Content",headers:{"Content-Type":"application/json"}})}function dt(){if(typeof window>"u"||typeof window.fetch!="function")return;const e="__sirsoftNhnkcpInterceptorInstalled",t=window;if(t[e])return;t[e]=!0;const n=window.fetch.bind(window);window.fetch=async function(r,a){const s=rt(r),i=at(r,a);if(!st(s,i))return n(r,a);let c;if(a?.body&&typeof a.body=="string"&&(c=it(a.body)),S(c)&&!x()){const d=M();return se.warn(d),ct(d)}return n(r,a)},se.info("order request interceptor installed (Apple Pay device guard)")}const L="sirsoft-pay_nhnkcp",ie="__kcpOcReceiptInjectorInstalled",ce="kcp-oc-receipt-btn",lt=/^\/shop\/orders\/([^/]+)\/complete$/;function de(){return localStorage.getItem("auth_token")}async function ut(e){const t=de();if(!t)return null;try{const n=await fetch(`/api/modules/sirsoft-ecommerce/user/orders/${e}`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?(await n.json())?.data?.payment??null:null}catch{return null}}async function O(e){const t=de();if(!t)return null;try{const n=await fetch(`/api/plugins/${L}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function le(e,t,n){const o=document.createElement("button");return o.type="button",o.className=t,o.textContent=e,o.addEventListener("click",()=>n(o)),o}function pt(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const o=Array.from(n.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(o.length<2)continue;const r=o[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const a=o[o.length-1];return a.textContent?.trim()===e?(n.dataset.nhnkcpPaymentMethodRow="true",!0):(a.textContent=e,a.dataset.nhnkcpPaymentMethodPatched="true",n.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}async function mt(e){if(document.getElementById(ce))return;const t=await ut(e);if(!t||t.pg_provider!=="nhnkcp"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(c=>c.className.includes("bg-blue-600"));if(!n?.parentElement)return;const o=await O(e);pt(o?.payment_method_display_label);const r=n.parentElement,a=le("영수증 조회",n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),async c=>{c.disabled=!0,c.textContent="로딩 중...";const d=await O(e);if(c.disabled=!1,c.textContent="영수증 조회",d){const l=window.KcpReceiptPopup;l&&new l({url:d.receipt_url??void 0})}});a.id=ce;const s=r.lastElementChild;r.insertBefore(a,s);const i="kcp-oc-cash-receipt-btn";if(!document.getElementById(i)&&(t.payment_method==="vbank"||t.payment_method==="bank_transfer")){const c=le("현금영수증 조회",a.className.replace(/bg-green-\d+/g,"bg-teal-600").replace(/hover:bg-green-\d+/g,"hover:bg-teal-700"),async d=>{d.disabled=!0,d.textContent="로딩 중...";const l=await O(e);if(d.disabled=!1,d.textContent="현금영수증 조회",l){const u=window.KcpReceiptPopup;u&&new u({cash_url:l.cash_receipt_url??void 0})}});c.id=i,r.insertBefore(c,s)}console.info(`[${L}] receipt button injected on order complete page`)}function ft(){const t=location.pathname.match(lt);t&&mt(t[1])}function yt(){if(typeof window>"u")return;const e=window;if(e[ie])return;e[ie]=!0,console.info(`[${L}] order complete receipt injector installed`);const t=(o=1200)=>setTimeout(ft,o);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...o)=>{n(...o),t()},window.addEventListener("popstate",()=>t(500))}const _="sirsoft-pay_nhnkcp",ue="__kcpMpShowInjectorInstalled",K="kcp-mp-vbank-row",j="kcp-mp-receipt-row",v="kcp-mp-mock-deposit",ht=/^\/mypage\/orders\/([^/]+)$/;function _t(e){try{const n=window.G7Core?.getState,a=n?.()?.currentDataContext?.order?.data;return!a||a.order_number!==e?null:a}catch{return null}}function pe(){return localStorage.getItem("auth_token")}async function me(e){const t=pe();if(!t)return null;try{const n=await fetch(`/api/plugins/${_}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}async function fe(e){const t=pe();if(!t)return null;try{const n=await fetch(`/api/plugins/${_}/user/orders/${e}/vbank-mock-deposit-info`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function ye(e){const t=document.createElement("div");t.id=v,t.className="pt-4 mt-2 border-t border-dashed border-orange-300 dark:border-orange-700";const n=document.createElement("div");n.className="flex items-center gap-2 mb-3";const o=document.createElement("span");o.className="inline-flex items-center px-2 py-0.5 rounded text-xs font-bold bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300 border border-orange-300 dark:border-orange-700",o.textContent="TEST";const r=document.createElement("p");r.className="text-sm font-semibold text-orange-700 dark:text-orange-300",r.textContent="모의입금처리",n.appendChild(o),n.appendChild(r);const a=document.createElement("form");a.method="POST",a.action=e.mock_url??"",a.target="_blank",a.className="space-y-2";const s=[{label:"KCP 거래번호",name:"e_trade_no",value:e.trade_no??""},{label:"입금계좌",name:"deposit_no",value:e.account_no??""},{label:"입금자명",name:"req_name",value:"NHN KCP",editable:!0},{label:"입금통보 URL",name:"noti_url",value:e.notify_url??""}];for(const d of s){const l=document.createElement("div");l.className="flex items-center gap-2 text-sm";const u=document.createElement("span");u.className="w-28 flex-shrink-0 text-gray-500 dark:text-gray-400 text-xs",u.textContent=d.label;const p=document.createElement("input");p.type="text",p.name=d.name,p.value=d.value,p.readOnly=!d.editable,p.className=d.editable?"flex-1 px-2 py-1 text-xs border border-gray-300 dark:border-gray-600 rounded bg-white dark:bg-gray-700 text-gray-900 dark:text-white font-mono":"flex-1 px-2 py-1 text-xs border border-gray-200 dark:border-gray-700 rounded bg-gray-50 dark:bg-gray-800 text-gray-700 dark:text-gray-300 font-mono",l.appendChild(u),l.appendChild(p),a.appendChild(l)}const i=document.createElement("div");i.className="pt-1";const c=document.createElement("button");if(c.type="submit",c.className="w-full py-1.5 text-xs font-semibold rounded border border-orange-400 dark:border-orange-600 bg-orange-50 dark:bg-orange-900/30 text-orange-700 dark:text-orange-300 hover:bg-orange-100 dark:hover:bg-orange-900/50 transition-colors",c.textContent="입금통보 테스트",i.appendChild(c),a.appendChild(i),t.appendChild(n),t.appendChild(a),e.is_admin_view){const d=document.createElement("p");d.className="mt-2 text-xs text-center text-orange-500 dark:text-orange-400 font-medium",d.textContent="관리자에게만 출력되는 내용",t.appendChild(d)}return t}function he(){const e=document.getElementById("order_payment_info_panel");if(e)return Array.from(e.children).find(a=>a.className?.includes("space-y"))??e;const t=Array.from(document.querySelectorAll("h3")).find(r=>r.textContent?.includes("결제 정보"));if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(r=>r.className?.includes("space-y"))??n:null}function w(e,t,n="font-medium text-gray-900 dark:text-white"){const o=document.createElement("div");o.className="flex items-center justify-between text-sm";const r=document.createElement("span");r.className="text-gray-500 dark:text-gray-400",r.textContent=e;const a=document.createElement("span");return a.className=n,a.textContent=t,o.appendChild(r),o.appendChild(a),o}function bt(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const o of n){const r=Array.from(o.children).filter(i=>i instanceof HTMLElement&&i.tagName==="SPAN");if(r.length<2)continue;const a=r[0].textContent?.trim();if(a!=="결제 방법"&&a!=="결제수단"&&a!=="Payment Method")continue;const s=r[r.length-1];return s.textContent?.trim()===t?(o.dataset.nhnkcpPaymentMethodRow="true",!0):(s.textContent=t,s.dataset.nhnkcpPaymentMethodPatched="true",o.dataset.nhnkcpPaymentMethodRow="true",!0)}return!1}function gt(e,t){const n=document.createElement("div");n.id=K,n.className="pt-4 mt-2 border-t border-gray-200 dark:border-gray-700 space-y-3";const o=document.createElement("p");o.className="text-sm font-semibold text-gray-800 dark:text-gray-200",o.textContent="가상계좌 입금 안내";const r=document.createElement("div");r.className="space-y-1.5",r.appendChild(w("은행",e.vbank_name??"")),r.appendChild(w("계좌번호",e.vbank_number??"","font-medium text-gray-900 dark:text-white font-mono tracking-wide")),r.appendChild(w("예금주",e.vbank_holder??"")),r.appendChild(w("입금 금액",t)),e.due_date_formatted&&r.appendChild(w("입금 기한",e.due_date_formatted));const a=document.createElement("p");return a.className="text-xs text-amber-600 dark:text-amber-400",a.textContent="입금 기한 내에 입금하지 않으시면 주문이 자동 취소됩니다.",n.appendChild(o),n.appendChild(r),n.appendChild(a),n}function wt(e){const t=document.createElement("div");t.id=j,t.className="pt-4 mt-2 border-t border-gray-200 dark:border-gray-700";const n=document.createElement("div");n.className="flex items-center justify-between";const o=document.createElement("span");o.className="text-gray-500 dark:text-gray-400 text-sm",o.textContent="영수증";const r=document.createElement("button");return r.type="button",r.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",r.textContent="영수증 조회",r.addEventListener("click",async()=>{r.disabled=!0,r.textContent="로딩 중...";const a=await me(e);if(r.disabled=!1,r.textContent="영수증 조회",a){const s=window.KcpReceiptPopup;s&&new s({url:a.receipt_url,cash_url:a.cash_receipt_url})}}),n.appendChild(o),n.appendChild(r),t.appendChild(n),t}async function kt(e){const t=_t(e);if(!t){if(!document.getElementById(v)){const p=he();if(!p)return!1;const f=await fe(e);f?.available&&(p.appendChild(ye(f)),console.info(`[${_}] mock deposit form injected on mypage order show`))}return!0}const{payment:n}=t;if(!n||n.pg_provider!=="nhnkcp")return!0;const o=n.payment_method==="vbank"&&!!n.vbank_name,r=!!n.transaction_id&&!!n.paid_at,a=n.payment_method==="vbank"&&!!n.vbank_number,s=!o||!!document.getElementById(K),i=!r||!!document.getElementById(j),c=!a||!!document.getElementById(v);if(s&&i&&c)return!0;const d=he();if(!d)return!1;const l=r?await me(e):null,u=bt(d,l?.payment_method_display_label);if(!document.getElementById(K)&&o)return d.appendChild(gt(n,t.total_amount_formatted??"")),console.info(`[${_}] vbank info injected on mypage order show`),!1;if(!document.getElementById(j)&&r)return d.appendChild(wt(e)),console.info(`[${_}] receipt button injected on mypage order show`),!1;if(u&&console.info(`[${_}] payment method display patched on mypage order show`),!document.getElementById(v)&&a){const p=await fe(e);if(p?.available)d.appendChild(ye(p)),console.info(`[${_}] mock deposit form injected on mypage order show`);else return!0}return!0}function Ct(e){let t=0;const n=setInterval(()=>{t++,kt(e).then(o=>{(o||t>=30)&&clearInterval(n)})},400)}function xt(){const e=location.pathname.match(ht);e&&Ct(e[1])}function vt(){if(typeof window>"u")return;const e=window;if(e[ue])return;e[ue]=!0,console.info(`[${_}] mypage order show injector installed`);const t=(o=1500)=>setTimeout(xt,o);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...o)=>{n(...o),t(600)},window.addEventListener("popstate",()=>t(500))}const Pt="sirsoft-pay_nhnkcp",_e="__kcpAdminApplePayNoticeInjectorInstalled",Et=/^\/admin\/ecommerce\/settings\/?$/,be="__kcpAdminApplePayNoticeListenerAttached",Nt="애플페이는 IOS 기기에 모바일결제만 가능합니다.",At="Apple Pay is available only for mobile payments on iOS devices.";let ge=null,P=null,B=!1;function It(){return window}function D(){if(!Et.test(window.location.pathname))return!1;const e=new URLSearchParams(window.location.search).get("tab");return e===null||e==="order_settings"}function we(){return(document.documentElement.lang||navigator.language||"").toLowerCase().startsWith("ko")?Nt:At}function ke(e){return(e??"").replace(/\s+/g," ").trim()}function St(e){const t=ke(e.textContent);return t==="애플페이"||t==="Apple Pay"}function Mt(){const e=document.createElement("span");return e.dataset.nhnkcpAdminApplePayNotice="true",e.className="text-label-subtle",e.style.display="block",e.style.width="100%",e.style.flexBasis="100%",e.style.marginTop="2px",e.style.fontSize="12px",e.style.lineHeight="1rem",e.textContent=we(),e}function H(e=document){if(typeof window>"u"||typeof document>"u"||!D()||ke(document.body?.innerText??document.body?.textContent).includes(we()))return!1;const n=Array.from(e.querySelectorAll("span, p, div")).find(St);return n?(n.insertAdjacentElement("afterend",Mt()),!0):!1}function Tt(){B||(B=!0,window.setTimeout(()=>{B=!1,H()},0))}function Ce(){P!==null&&(window.clearInterval(P),P=null)}function F(){if(!D())return;Ce(),H();let e=0;P=window.setInterval(()=>{e+=1,(H()||e>=50)&&Ce()},200);const t=document.body;t[be]||(t[be]=!0,ge=new MutationObserver(()=>Tt()),ge.observe(document.body,{childList:!0,subtree:!0,characterData:!0}))}function xe(){D()&&F()}function Rt(){if(typeof window>"u"||typeof document>"u")return;const e=It();if(e[_e])return;e[_e]=!0,console.info(`[${Pt}] admin Apple Pay notice injector installed`),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>F()):F();const t=history.pushState.bind(history);history.pushState=(...n)=>{t(...n),window.setTimeout(()=>xe(),200)},window.addEventListener("popstate",()=>window.setTimeout(()=>xe(),200))}const $t="sirsoft-pay_nhnkcp",ve="__nhnkcpAdminPaymentMethodBrandInjectorInstalled",Pe="__nhnkcpAdminPaymentMethodBrandSyncListenerAttached",Lt=/^\/admin\/ecommerce\/settings\/?$/,Ee='[data-nhnkcp-admin-payment-brand-mark="true"]',Ot=200,Kt=120,jt=[{id:"nhnkcp_payco",labels:["PAYCO (NHN KCP)","PAYCO로 결제 (NHN KCP)","Pay with PAYCO (NHN KCP)"],shortLabels:["PAYCO"],markLines:["P"],markClassName:"bg-red-500 text-white"},{id:"nhnkcp_naverpay",labels:["네이버페이 (NHN KCP)","네이버페이 신용카드로 결제 (NHN KCP)","Naver Pay (NHN KCP)","Pay by Naver Pay credit card (NHN KCP)"],shortLabels:["네이버페이 (카드)","Naver Pay (Card)"],markLines:["N"],markClassName:"bg-green-500 text-white"},{id:"nhnkcp_naverpay_point",labels:["네이버페이 포인트 (NHN KCP)","네이버페이 머니/포인트로 결제 (NHN KCP)","Naver Pay Point (NHN KCP)","Pay with Naver Pay Money/Points (NHN KCP)"],shortLabels:["네이버페이 (포인트)","Naver Pay (Point)"],markLines:["NP"],markClassName:"bg-green-600 text-white"},{id:"nhnkcp_kakaopay",labels:["카카오페이 (NHN KCP)","카카오페이로 결제 (NHN KCP)","Kakao Pay (NHN KCP)","Pay with Kakao Pay (NHN KCP)"],shortLabels:["카카오페이","Kakao Pay"],markLines:["K"],markClassName:"bg-yellow-400 text-gray-950"},{id:"nhnkcp_applepay",labels:["애플페이 (NHN KCP)","애플페이로 결제 (NHN KCP)","Apple Pay (NHN KCP)","Pay with Apple Pay (NHN KCP)"],shortLabels:["애플페이","Apple Pay"],markLines:["A"],markClassName:"bg-gray-900 text-white"}];let Ne=null,E=null,q=!1;function Bt(){return window}function U(){if(!Lt.test(window.location.pathname))return!1;const e=new URLSearchParams(window.location.search).get("tab");return e===null||e===""||e==="order_settings"}function Dt(e){return e instanceof HTMLElement?e.className:""}function Ae(e){return(e??"").replace(/\u200B/g,"").replace(/\s+/g," ").trim()}function Ht(e){const t=Dt(e);return t.includes("excel-card")||t.includes("flex-center")&&t.includes("border")&&t.includes("gap-4")}function Ie(e){return e.querySelector(".font-medium")}function Ft(e){const t=Ae(Ie(e)?.textContent),n=Ae(e.textContent);return jt.find(o=>o.shortLabels.some(r=>t===r)||o.labels.some(r=>n.includes(r)))??null}function qt(e){return Array.from(e.querySelectorAll("div")).filter(Ht)}function Ut(e){return Array.from(e.querySelectorAll("svg, [data-icon], i")).find(n=>!n.closest("[data-drag-handle]")&&!n.closest(Ee)&&!n.closest('.row-stack, .excel-card-body, button, select, [role="switch"]'))??null}function Se(e,t){e.dataset.nhnkcpAdminPaymentBrandMark="true",e.dataset.nhnkcpAdminPaymentMethod=t.id,e.setAttribute("aria-hidden","true"),e.className=`inline-flex items-center justify-center rounded-lg font-bold ${t.markClassName}`,e.style.width="32px",e.style.height="32px",e.style.flex="0 0 32px",e.style.lineHeight="1",e.style.fontSize=t.markLines.join("").length>2?"9px":"12px";const n=t.markLines.join("");e.textContent!==n&&(e.replaceChildren(),t.markLines.length>1?(e.style.flexDirection="column",t.markLines.forEach(o=>{const r=document.createElement("span");r.style.lineHeight="1",r.textContent=o,e.appendChild(r)})):(e.style.removeProperty("flex-direction"),e.textContent=t.markLines[0]??""))}function Yt(e){const t=document.createElement("span");return Se(t,e),t}function Gt(e,t){const n=e.querySelector(Ee);if(n instanceof HTMLSpanElement)return e.dataset.nhnkcpAdminPaymentMethod=t.id,Se(n,t),!0;const o=Yt(t),r=Ut(e);if(r&&r.parentElement)return e.dataset.nhnkcpAdminPaymentMethod=t.id,r.replaceWith(o),!0;const a=Ie(e);return a&&a.parentElement?(e.dataset.nhnkcpAdminPaymentMethod=t.id,a.parentElement.insertBefore(o,a),!0):!1}function Y(e=document){if(typeof window>"u"||typeof document>"u"||!U())return!1;let t=!1;return qt(e).forEach(n=>{const o=Ft(n);o&&Gt(n,o)&&(t=!0)}),t}function Wt(){q||(q=!0,window.setTimeout(()=>{q=!1,Y()},0))}function G(){E!==null&&(window.clearInterval(E),E=null)}function W(){if(!U())return;G(),Y();let e=0;E=window.setInterval(()=>{e+=1,Y(),e>=Kt&&G()},Ot);const t=document.body;t[Pe]||(t[Pe]=!0,Ne=new MutationObserver(()=>Wt()),Ne.observe(document.body,{childList:!0,subtree:!0,characterData:!0}))}function Me(){if(U()){W();return}G()}function zt(){if(typeof window>"u"||typeof document>"u")return;const e=Bt();if(e[ve])return;e[ve]=!0,console.info(`[${$t}] admin payment method brand sync installed`),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>W()):W();const t=history.pushState.bind(history);history.pushState=(...n)=>{t(...n),window.setTimeout(()=>Me(),200)},window.addEventListener("popstate",()=>window.setTimeout(()=>Me(),200))}const z="sirsoft-pay_nhnkcp",Te="__nhnkcpAdminPaymentDisplayInjectorInstalled",Jt=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function Vt(){return localStorage.getItem("auth_token")}async function Qt(e){const t=Vt();if(!t)return null;try{const n=await fetch(`/api/plugins/${z}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const o=await n.json();return("data"in o?o.data:o)??null}catch{return null}}function Xt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function Zt(e,t){let n=!1;const o=Array.from(e.querySelectorAll("div"));for(const r of o){const a=Xt(r),s=a.findIndex(u=>u.textContent?.trim()==="결제수단");if(s<0)continue;const i=a.slice(s+1).find(u=>u.textContent?.trim()&&u.textContent.trim()!=="결제수단");if(!i)continue;const c=a.slice(s+2).find(u=>/^\(.+\)$/.test(u.textContent?.trim()??"")),d=c?.textContent?.trim().replace(/^\(|\)$/g,"")??"",l=d&&t.endsWith(")")?t.replace(/\)$/,`, ${d})`):t;i.textContent?.trim()!==l&&(i.textContent=l,i.dataset.nhnkcpPaymentMethodPatched="true"),r.dataset.nhnkcpPaymentMethodRow="admin-order",c&&d&&(c.textContent="",c.style.display="none",c.dataset.nhnkcpPaymentInstallmentHidden="true"),n=!0}return n}function en(e,t,n){const r=Array.from(e.querySelectorAll("span")).filter(a=>a.textContent?.trim()===t).find(a=>{const s=typeof a.className=="string"?a.className:"";return s.includes("rounded-full")||s.includes("font-medium")});return r?(r.textContent=n,r.dataset.nhnkcpPaymentMethodPatched="true",r.dataset.nhnkcpPaymentMethodBadge="admin-order",!0):!1}function tn(e,t){const n=t?._pay_method_label,o=t?._embedded_pg_provider_label,r=t?._base_pay_method_label;if(!n||!o)return!1;const a=Zt(e,n),s=r?en(e,r,o):!1;return a||s}async function nn(e){const t=document.getElementById("section_payment_info")??document.getElementById("payment_info_card");if(!t)return!1;const n=await Qt(e);return n&&tn(t,n)&&console.info(`[${z}] payment method display patched on admin order detail`),!0}function on(e){let t=0;const n=setInterval(()=>{t++,nn(e).then(o=>{(o||t>=30)&&clearInterval(n)})},400)}function rn(){const e=location.pathname.match(Jt);e&&on(e[1])}function an(){if(typeof window>"u")return;const e=window;if(e[Te])return;e[Te]=!0,console.info(`[${z}] admin order payment display injector installed`);const t=(o=1500)=>setTimeout(rn,o);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...o)=>{n(...o),t(600)},window.addEventListener("popstate",()=>t(500))}class sn{constructor(t){const n="width=800,height=600,scrollbars=yes,resizable=yes,toolbar=no,menubar=no";t.url&&window.open(t.url,"kcp_receipt",n),t.cash_url&&window.open(t.cash_url,"kcp_cash_receipt",n)}}window.KcpReceiptPopup=sn;const b="sirsoft-pay_nhnkcp",J={info:(...e)=>console.info(`[${b}]`,...e),warn:(...e)=>console.warn(`[${b}]`,...e),error:(...e)=>console.error(`[${b}]`,...e)};function Re(){const e=window.G7Core;if(!e)return 0;const t=e.getActionDispatcher;if(typeof t!="function")return 0;const n=t();if(!n||typeof n.registerHandler!="function")return 0;let o=0;for(const[r,a]of Object.entries(re)){const s=`${b}.${r}`;n.registerHandler(s,a,{category:"plugin",source:b}),o++}return o}function $e(){const e=()=>{const t=Re();if(t>0){J.info(`${t} handler(s) registered`);return}let n=0;const o=50,r=setInterval(()=>{n++;const a=Re();if(a>0){clearInterval(r),J.info(`${a} handler(s) registered (after ${n} retries)`);return}n>=o&&(clearInterval(r),J.warn("ActionDispatcher not available after timeout"))},100)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):e()}dt(),yt(),vt(),Rt(),zt(),an(),$e(),window.__SirsoftNhnkcp={identifier:b,handlers:Object.keys(re),initPlugin:$e}})();
|