Files
Gnuboard7/plugins/_bundled/sirsoft-pay_nicepayments/dist/js/plugin.iife.js
T
HeuJung 1e89335258 fix(core,extensions): 동적 스크립트 주입 경로 전부에 출처 게이트 적용
레이아웃 scripts[] 에만 있던 원격 스크립트 차단 게이트가 다른 주입 경로에는
없어, 저장측(SafeLayoutExpressions·NoExternalUrls)이 외부 URL 저장을 422 로
막아도 런타임 디스패치 한 번으로 임의 원격 코드가 로드됐다. 저장 검증이
통째로 무의미해지는 상태였고 오류도 경고도 남지 않았다.

판정식을 support/scriptSrcPolicy.ts 로 분리해 런타임 SSoT 를 하나로 두고,
loadScript 액션 · 확장 핸들러 재로드 · 편집기 프리뷰 · 편집기 자산 매니페스트 ·
G7Core.asset.loadScript · PG 플러그인 SDK 주입이 모두 그것을 경유하게 했다.
사본을 두지 않은 이유는 차집합이 그대로 우회로가 되기 때문이다.

- 게이트는 캐시 검사보다 앞에 둔다 (뒤에 두면 이미 로드된 미신뢰 스크립트가
 캐시 히트로 통과한다)
- NoExternalUrls 순회를 9키로 확대 — 번들 레이아웃 601개 사전 스캔으로
 정당한 외부 URL 0건을 확인한 뒤 넓혔다 (저장 회귀 없음)
- callExternal 은 생성자를 참조 동일성으로 거부하고(별칭 전역 포함),
 프로토타입 경로 세그먼트를 읽기·매핑 키 양쪽에서 차단한다
- PG SDK 는 서비스 SDK 라 자체 호스팅이 불가능하므로 manifest 선언 +
 주입 직전 호스트 확인이 게이트다. tosspayments SDK URL 은 확장자가 없어
 정적 검사에 걸리지 않아 그 런타임 확인이 유일한 게이트다
- 함께 드러난 결함: 동시 loadScript 가 로드 전에 완료 처리되던 문제,
 확장 재로드에서 script 기존재가 CSS 까지 건너뛰던 문제, loadCSS 의
 in-flight 미공유
2026-09-02 21:43:13 +09:00

2 lines
24 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 de(e){return e.trim().slice(0,160)}async function ue(e,t="nicepay-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:de(t)||"nicepay-window-closed"};try{const a=window.G7Core?.api;if(typeof a?.post=="function"){await a.post(e.closeReportUrl,n);return}await fetch(le(e.closeReportUrl),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),keepalive:!0})}catch(a){console.warn("[sirsoft-pay_nicepayments] failed to report payment window close",a)}}const pe=["web.nicepay.co.kr"];function me(e,t){const n=window?.G7Core?.t;if(typeof n!="function")return t;const a=`sirsoft-pay_nicepayments.${e}`,r=n(a);return typeof r=="string"&&r!==a?r:t}function ye(e){let t=null;try{t=new URL(e)}catch{t=null}if(t===null||t.protocol!=="https:"||!pe.includes(t.hostname.toLowerCase()))throw new Error(me("payment.error.sdk_url_untrusted","결제 모듈 주소가 올바르지 않아 결제를 진행할 수 없습니다."))}async function fe(e){if(ye(e),typeof window.goPay=="function")return;document.querySelectorAll(`script[src="${CSS.escape(e)}"]`).forEach(n=>n.remove());const t=window?.G7Core?.asset?.loadScript;if(typeof t=="function"){await t(e,{},{label:"nicepayments SDK"});return}await new Promise((n,a)=>{const r=document.createElement("script");r.src=e,r.onload=()=>n(),r.onerror=()=>a(new Error(`Failed to load script: ${e}`)),document.head.appendChild(r)})}function he(e,t){const n=document.createElement("form");n.id="nicepayForm",n.method="post",n.action=e,n.acceptCharset="utf-8";for(const[a,r]of Object.entries(t)){const o=document.createElement("input");o.type="hidden",o.name=a,o.value=r,n.appendChild(o)}return document.body.appendChild(n),n}const we="/plugins/sirsoft-pay_nicepayments/payment/callback",be="https://web.nicepay.co.kr/v3/v3Payment.jsp";function ge(){if(typeof navigator>"u")return!1;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 _e(e,t){const{pgPaymentData:n,paymentMethod:a}=e.params??{},r=window.__templateApp?.globalState?._local,o=a??n?.payment_method??r?.paymentMethod??"card";if(!n){console.error("[sirsoft-pay_nicepayments] pgPaymentData is required");return}const i=window.G7Core;try{const s=await i.api.get("/modules/sirsoft-ecommerce/payments/client-config/nicepayments");if(!s.data){console.error("[sirsoft-pay_nicepayments] Failed to fetch client config",s);return}const l=s.data,d=ge();if(!d&&(await fe(l.sdk_url),typeof window.goPay!="function")){i?.toast?.error?.("나이스페이먼츠 SDK를 불러올 수 없습니다. 잠시 후 다시 시도해주세요."),i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o});return}const _=window.location.origin+l.sign_data_url,u=typeof localStorage<"u"?localStorage.getItem("auth_token"):null,te={"Content-Type":"application/json","X-Requested-With":"XMLHttpRequest",Accept:"application/json"};u&&(te.Authorization=`Bearer ${u}`);const ne=await fetch(_,{method:"POST",credentials:"include",headers:te,body:JSON.stringify({amt:n.amount,moid:n.order_number,buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??""})});if(!ne.ok)throw new Error("SignData 생성에 실패했습니다.");const I=await ne.json(),ae=window.location.origin+we,M=typeof o=="string"&&o.startsWith("nicepay_"),oe=M?"CARD":{card:"CARD",vbank:"VBANK",bank:"BANK",phone:"CELLPHONE"}[o??"card"]??"CARD",c={PayMethod:oe,GoodsName:n.order_name,Amt:String(n.amount),MID:I.mid,Moid:n.order_number,BuyerName:n.customer_name??"",BuyerEmail:n.customer_email??"",BuyerTel:n.customer_phone??"",ReturnURL:ae,EdiDate:I.ediDate,SignData:I.signData,CharSet:"utf-8",GoodsCl:"1",DirectShowOpt:"",DirectEasyPay:"",NicepayReserved:"",EasyPayMethod:"",MallReserved:"",MallReserved1:""};oe==="CELLPHONE"&&(c.GoodsCl=n.goods_cl??"1");const bt=l.useEscrow&&!M;if(c.TransType=bt?"1":"0",M)switch(c.DirectShowOpt="CARD",c.MallReserved=`nicepay_easy_pay_method=${encodeURIComponent(o)}`,c.MallReserved1=o,o){case"nicepay_naverpay":c.DirectEasyPay="E020",c.EasyPayMethod="E020=CARD";break;case"nicepay_kakaopay":c.NicepayReserved="DirectKakao=Y";break;case"nicepay_samsungpay":c.DirectEasyPay="E021";break;case"nicepay_applepay":c.DirectEasyPay="E025";break;case"nicepay_payco":c.NicepayReserved="DirectPayco=Y";break;case"nicepay_skpay":c.NicepayReserved="DirectPay11=Y";break;case"nicepay_ssgpay":c.DirectEasyPay="E007";break;case"nicepay_lpay":c.DirectEasyPay="E018";break}try{const m=(await i.api.get(`/modules/sirsoft-ecommerce/user/orders/${n.order_number}`))?.data;if(m){const P=Number(m.total_tax_amount??0),h=Number(m.total_vat_amount??0),ce=Number(m.total_tax_free_amount??0);(P>0||h>0||ce>0)&&(c.TaxAmt=String(P),c.VatAmt=String(h),c.TaxFreeAmt=String(ce))}}catch{}const p=he(ae,c);if(d){p.action=be,p.acceptCharset="euc-kr";const f=p.querySelector('input[name="CharSet"]');f&&(f.value="euc-kr"),p.submit();return}window.nicepaySubmit=()=>{p.submit()};let re=!1;const gt=new Set(document.body.children),ie=(f,m)=>{if(re)return;re=!0;const P=[f,m].filter(Boolean).join(": ")||"nicepay-window-closed";ue({closeReportUrl:l.close_report_url,oid:n.order_number,price:Number(n.amount),buyer_email:n.customer_email??"",buyer_phone:n.customer_phone??"",payment_method:o},P),window.removeEventListener("popstate",se),Array.from(document.body.children).forEach(h=>{gt.has(h)||h.remove()}),p.parentNode&&p.parentNode.removeChild(p),window.__sirsoftNicepayPaymentInProgress=!1,i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o}),m&&i?.toast?.error?.(m)};window.nicepayClose=ie;const se=()=>ie("","");window.history.pushState({nicepayOpen:!0},""),window.addEventListener("popstate",se),window.goPay(p)}catch(s){console.error("[sirsoft-pay_nicepayments] requestPayment error",s),window.__sirsoftNicepayPaymentInProgress=!1,i?.state?.setLocal?.({isSubmittingOrder:!1,paymentMethod:o}),i?.toast?.error?.("결제 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.")}}const Pe={nicepay_naverpay:"네이버페이",nicepay_kakaopay:"카카오페이",nicepay_samsungpay:"삼성페이",nicepay_applepay:"애플페이",nicepay_payco:"PAYCO",nicepay_skpay:"11pay",nicepay_ssgpay:"SSG페이",nicepay_lpay:"L.pay"},Ce="0 0 0 2px #ffffff, 0 0 0 5px rgba(0,0,0,0.55)";function D(){const e=document.getElementById("nicepay_checkout_payment_section");if(!e)return null;const t=e.querySelectorAll("p");for(const n of t)if(n.textContent?.includes("간편결제"))return n.nextElementSibling;return null}function R(){const e=D();e&&e.querySelectorAll("button").forEach(t=>{t.style.boxShadow="",t.style.outline=""})}function Se(e){const t=D();if(!t)return;const n=Pe[e];t.querySelectorAll("button").forEach(a=>{a.textContent?.trim()===n?(a.style.boxShadow=Ce,a.style.outline="none"):(a.style.boxShadow="",a.style.outline="")})}function Ee(e){const t=e.params?.paymentMethod;if(!t)return;const n=typeof t=="string"&&t.indexOf("nicepay_")===0;window.G7Core?.state?.setLocal?.({paymentMethod:t}),n?Se(t):R()}function $(){const e=window.__templateApp;typeof e?.onGlobalStateChange=="function"&&e.onGlobalStateChange(t=>{const n=t?._local?.paymentMethod;typeof n=="string"&&(n.startsWith("nicepay_")||R())})}const T={requestPayment:_e,setPaymentMethod:Ee},xe="sirsoft-pay_nicepayments",Ne={info:(...e)=>console.info(`[${xe}]`,...e)};function Ae(){Ne.info("order interceptor is a no-op — payment entry is dispatched via pg_payment_handler")}const C="sirsoft-pay_nicepayments",O="__nicepayOcReceiptInjectorInstalled",B="nicepay-oc-receipt-btn",ke=/^\/shop\/orders\/([^/]+)\/complete$/;function j(){return localStorage.getItem("auth_token")}async function ve(e){const t=j();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 G(e){const t=j();if(!t)return null;try{const n=await fetch(`/api/plugins/${C}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function Le(e){if(!e)return!1;const t=Array.from(document.querySelectorAll("div"));for(const n of t){const a=Array.from(n.children).filter(i=>i instanceof HTMLElement&&i.tagName==="SPAN");if(a.length<2)continue;const r=a[0].textContent?.trim();if(r!=="결제 방법"&&r!=="결제수단"&&r!=="결제 방식")continue;const o=a[a.length-1];return o.textContent?.trim()!==e&&(o.textContent=e,o.dataset.nicepayPaymentMethodPatched="true"),n.dataset.nicepayPaymentMethodRow="true",!0}return!1}async function Ie(e){if(document.getElementById(B))return;const t=await ve(e);if(!t||t.pg_provider!=="nicepayments"||!t.transaction_id||!t.paid_at)return;const n=Array.from(document.querySelectorAll('button[type="button"]')).find(s=>s.className.includes("bg-blue-600"));if(!n?.parentElement)return;const a=await G(e);Le(a?.payment_method_display_label);const r=n.parentElement,o=document.createElement("button");o.id=B,o.type="button",o.className=n.className.replace(/bg-blue-\d+/g,"bg-green-600").replace(/hover:bg-blue-\d+/g,"hover:bg-green-700"),o.textContent="영수증 조회",o.addEventListener("click",async()=>{o.disabled=!0,o.textContent="로딩 중...";const s=await G(e);o.disabled=!1,o.textContent="영수증 조회";const l=s?.receipt_url??null;l&&window.open(l,"nicepay_receipt","width=800,height=600,scrollbars=yes,resizable=yes")});const i=r.lastElementChild;r.insertBefore(o,i),console.info(`[${C}] receipt button injected on order complete page`)}function Me(){const e=location.pathname.match(ke);e&&Ie(e[1])}function De(){if(typeof window>"u")return;const e=window;if(e[O])return;e[O]=!0,console.info(`[${C}] order complete receipt injector installed`);const t=(a=1200)=>setTimeout(Me,a);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...a)=>{n(...a),t()},window.addEventListener("popstate",()=>t(500))}const w="sirsoft-pay_nicepayments",H="__nicepayOrderShowInjectorInstalled",q="nicepay-mp-receipt-row",U="nicepay-mp-vbank-info",Re=/^\/mypage\/orders\/([^/]+)$/;function $e(e){try{const n=window.G7Core?.getState,o=n?.()?.currentDataContext?.order?.data;return!o||o.order_number!==e?null:o}catch{return null}}function Te(){return localStorage.getItem("auth_token")}async function F(e){const t=Te();if(!t)return null;try{const n=await fetch(`/api/plugins/${w}/user/orders/${e}/receipt`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});return n.ok?await n.json():null}catch{return null}}function Oe(e,t){if(!t)return!1;const n=Array.from(e.querySelectorAll("div"));for(const a of n){const r=Array.from(a.children).filter(s=>s instanceof HTMLElement&&s.tagName==="SPAN");if(r.length<2)continue;const o=r[0].textContent?.trim();if(o!=="결제 방법"&&o!=="결제수단"&&o!=="Payment Method")continue;const i=r[r.length-1];return i.textContent?.trim()!==t&&(i.textContent=t,i.dataset.nicepayPaymentMethodPatched="true"),a.dataset.nicepayPaymentMethodRow="true",!0}return!1}function Be(){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(a=>a.textContent?.includes("결제 정보"));if(!t)return null;const n=t.parentElement?.parentElement;return n?Array.from(n.children).find(a=>a.className?.includes("space-y"))??n:null}function je(e){const t=document.createElement("div");t.id=q,t.className="flex items-center justify-between";const n=document.createElement("span");n.className="text-gray-500 dark:text-gray-400 text-sm",n.textContent="영수증";const a=document.createElement("button");return a.type="button",a.className="inline-flex items-center gap-1 text-sm text-blue-600 dark:text-blue-400 hover:underline disabled:opacity-50",a.textContent="영수증 조회",a.addEventListener("click",async()=>{a.disabled=!0,a.textContent="로딩 중...";const r=await F(e);a.disabled=!1,a.textContent="영수증 조회";const o=r?.receipt_url??null;o&&window.open(o,"nicepay_receipt","width=800,height=600,scrollbars=yes,resizable=yes")}),t.appendChild(n),t.appendChild(a),t}function Ge(e){if(!e)return"";try{const t=new Date(e);if(Number.isNaN(t.getTime()))return e;const n=a=>String(a).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())} ${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}catch{return e}}function b(e,t,n="font-medium text-gray-900 dark:text-white"){const a=document.createElement("div");a.className="flex justify-between text-sm";const r=document.createElement("span");r.className="text-gray-600 dark:text-gray-400",r.textContent=e;const o=document.createElement("span");return o.className=n,o.textContent=t,a.appendChild(r),a.appendChild(o),a}function He(e){const t=e.payment??{},n=document.createElement("div");n.id=U,n.className="pt-4 mt-2 border-t border-gray-200 dark:border-gray-700";const a=document.createElement("div");a.className="bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700 rounded-lg p-4";const r=document.createElement("h3");r.className="text-sm font-semibold text-blue-800 dark:text-blue-300 mb-3",r.textContent="가상계좌 입금 안내";const o=document.createElement("div");o.className="space-y-2",o.appendChild(b("은행",t.vbank_name??"")),o.appendChild(b("계좌번호",t.vbank_number??"","font-medium font-mono text-gray-900 dark:text-white")),o.appendChild(b("예금주",t.vbank_holder??"")),o.appendChild(b("입금 금액",e.total_amount_formatted??"","font-bold text-blue-600 dark:text-blue-400"));const i=t.vbank_due_at;if(i){const s=document.createElement("div");s.className="flex justify-between text-sm pt-2 border-t border-blue-200 dark:border-blue-700 mt-2";const l=document.createElement("span");l.className="text-gray-600 dark:text-gray-400",l.textContent="입금 기한";const d=document.createElement("span");d.className="font-medium text-red-600 dark:text-red-400",d.textContent=Ge(i),s.appendChild(l),s.appendChild(d),o.appendChild(s)}if(a.appendChild(r),a.appendChild(o),!t.paid_at){const s=document.createElement("p");s.className="text-xs text-blue-700 dark:text-blue-300 mt-3",s.textContent="입금 기한 내에 입금이 완료되지 않으면 주문이 자동 취소됩니다.",a.appendChild(s)}return n.appendChild(a),n}async function qe(e){const t=$e(e);if(!t)return!1;const{payment:n}=t;if(!n||n.pg_provider!=="nicepayments")return!0;const a=Be();if(!a)return!1;const r=await F(e);return Oe(a,r?.payment_method_display_label),n.payment_method==="vbank"&&n.vbank_number&&!document.getElementById(U)&&(a.appendChild(He(t)),console.info(`[${w}] vbank info injected on mypage order show`)),!n.transaction_id||!n.paid_at||document.getElementById(q)||(a.appendChild(je(e)),console.info(`[${w}] receipt button injected on mypage order show`)),!0}function Ue(e){let t=0;const n=setInterval(()=>{t++,qe(e).then(a=>{(a||t>=30)&&clearInterval(n)})},400)}function Fe(){const e=location.pathname.match(Re);e&&Ue(e[1])}function We(){if(typeof window>"u")return;const e=window;if(e[H])return;e[H]=!0,console.info(`[${w}] mypage order show injector installed`);const t=(a=1500)=>setTimeout(Fe,a);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...a)=>{n(...a),t(600)},window.addEventListener("popstate",()=>t(500))}const Ye="sirsoft-pay_nicepayments",W="__nicepayAdminPaymentMethodBrandInjectorInstalled",Y="__nicepayAdminPaymentMethodBrandSyncListenerAttached",Ke=/^\/admin\/ecommerce\/settings\/?$/,K='[data-nicepay-admin-payment-brand-mark="true"]',ze=200,Ve=120,Je=[{id:"nicepay_naverpay",labels:["네이버페이 (나이스페이먼츠)","네이버페이로 결제 (나이스페이먼츠)","Naver Pay (NicePayments)","Pay with Naver Pay (NicePayments)"],shortLabels:[],markLines:["N"],markClassName:"bg-green-500 text-white"},{id:"nicepay_kakaopay",labels:["카카오페이 (나이스페이먼츠)","카카오페이로 결제 (나이스페이먼츠)","Kakao Pay (NicePayments)","Pay with Kakao Pay (NicePayments)"],shortLabels:[],markLines:["K"],markClassName:"bg-yellow-400 text-gray-950"},{id:"nicepay_samsungpay",labels:["삼성페이 (나이스페이먼츠)","삼성페이로 결제 (나이스페이먼츠)","Samsung Pay (NicePayments)","Pay with Samsung Pay (NicePayments)"],shortLabels:[],markLines:["S"],markClassName:"bg-blue-600 text-white"},{id:"nicepay_applepay",labels:["애플페이 (나이스페이먼츠)","애플페이로 결제 (나이스페이먼츠)","Apple Pay (NicePayments)","Pay with Apple Pay (NicePayments)"],shortLabels:[],markLines:["A"],markClassName:"bg-gray-900 text-white"},{id:"nicepay_payco",labels:["PAYCO (나이스페이먼츠)","PAYCO로 결제 (나이스페이먼츠)","PAYCO (NicePayments)","Pay with PAYCO (NicePayments)"],shortLabels:[],markLines:["P"],markClassName:"bg-red-500 text-white"},{id:"nicepay_skpay",labels:["11pay (나이스페이먼츠)","11pay로 결제 (나이스페이먼츠)","11pay (NicePayments)","Pay with 11pay (NicePayments)"],shortLabels:[],markLines:["11"],markClassName:"bg-orange-500 text-white"},{id:"nicepay_ssgpay",labels:["SSG페이 (나이스페이먼츠)","SSG페이로 결제 (나이스페이먼츠)","SSG Pay (NicePayments)","Pay with SSG Pay (NicePayments)"],shortLabels:[],markLines:["SSG"],markClassName:"bg-red-700 text-white"},{id:"nicepay_lpay",labels:["L.pay (나이스페이먼츠)","L.pay로 결제 (나이스페이먼츠)","L.pay (NicePayments)","Pay with L.pay (NicePayments)"],shortLabels:[],markLines:["L"],markClassName:"bg-purple-600 text-white"}];let z=null,g=null,S=!1;function Xe(){return window}function E(){if(!Ke.test(window.location.pathname))return!1;const e=new URLSearchParams(window.location.search).get("tab");return e===null||e===""||e==="order_settings"}function Qe(e){return e instanceof HTMLElement?e.className:""}function V(e){return(e??"").replace(/\u200B/g,"").replace(/\s+/g," ").trim()}function Ze(e){const t=Qe(e);return t.includes("excel-card")||t.includes("flex-center")&&t.includes("border")&&t.includes("gap-4")}function J(e){return e.querySelector(".font-medium")}function et(e){const t=V(J(e)?.textContent),n=V(e.textContent);return Je.find(a=>a.shortLabels.some(r=>t===r)||a.labels.some(r=>n.includes(r)))??null}function tt(e){return Array.from(e.querySelectorAll("div")).filter(Ze)}function nt(e){return Array.from(e.querySelectorAll("svg, [data-icon], i")).find(n=>!n.closest("[data-drag-handle]")&&!n.closest(K)&&!n.closest('.row-stack, .excel-card-body, button, select, [role="switch"]'))??null}function X(e,t){e.dataset.nicepayAdminPaymentBrandMark="true",e.dataset.nicepayAdminPaymentMethod=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.textContent=t.markLines[0]??"")}function at(e){const t=document.createElement("span");return X(t,e),t}function ot(e,t){const n=e.querySelector(K);if(n instanceof HTMLSpanElement)return e.dataset.nicepayAdminPaymentMethod=t.id,X(n,t),!0;const a=at(t),r=nt(e);if(r&&r.parentElement)return e.dataset.nicepayAdminPaymentMethod=t.id,r.replaceWith(a),!0;const o=J(e);return o&&o.parentElement?(e.dataset.nicepayAdminPaymentMethod=t.id,o.parentElement.insertBefore(a,o),!0):!1}function x(e=document){if(typeof window>"u"||typeof document>"u"||!E())return!1;let t=!1;return tt(e).forEach(n=>{const a=et(n);a&&ot(n,a)&&(t=!0)}),t}function rt(){S||(S=!0,window.setTimeout(()=>{S=!1,x()},0))}function N(){g!==null&&(window.clearInterval(g),g=null)}function A(){if(!E())return;N(),x();let e=0;g=window.setInterval(()=>{e+=1,x(),e>=Ve&&N()},ze);const t=document.body;t[Y]||(t[Y]=!0,z=new MutationObserver(()=>rt()),z.observe(document.body,{childList:!0,subtree:!0,characterData:!0}))}function k(){if(E()){A();return}N()}function it(){if(typeof window>"u"||typeof document>"u")return;const e=Xe();if(e[W])return;e[W]=!0,console.info(`[${Ye}] admin payment method brand sync installed`),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>A()):A();const t=history.pushState.bind(history);history.pushState=(...a)=>{t(...a),window.setTimeout(()=>k(),200)};const n=history.replaceState.bind(history);history.replaceState=(...a)=>{n(...a),window.setTimeout(()=>k(),200)},window.addEventListener("popstate",()=>window.setTimeout(()=>k(),200))}const v="sirsoft-pay_nicepayments",Q="__nicepayAdminPaymentDisplayInjectorInstalled",st=/^\/admin\/ecommerce\/orders\/([^/]+)$/;function ct(){return localStorage.getItem("auth_token")}async function lt(e){const t=ct();if(!t)return null;try{const n=await fetch(`/api/plugins/${v}/admin/orders/${e}/transaction-status`,{headers:{Authorization:`Bearer ${t}`,Accept:"application/json"}});if(!n.ok)return null;const a=await n.json();return("data"in a?a.data:a)??null}catch{return null}}function dt(e){return Array.from(e.children).filter(t=>t instanceof HTMLElement)}function ut(e,t){let n=!1;const a=Array.from(e.querySelectorAll("div"));for(const r of a){const o=dt(r),i=o.findIndex(u=>u.textContent?.trim()==="결제수단");if(i<0)continue;const s=o.slice(i+1).find(u=>u.textContent?.trim()&&u.textContent.trim()!=="결제수단");if(!s)continue;const l=o.slice(i+2).find(u=>/^\(.+\)$/.test(u.textContent?.trim()??"")),d=l?.textContent?.trim().replace(/^\(|\)$/g,"")??"",_=d&&t.endsWith(")")?t.replace(/\)$/,`, ${d})`):t;s.textContent?.trim()!==_&&(s.textContent=_,s.dataset.nicepayPaymentMethodPatched="true"),r.dataset.nicepayPaymentMethodRow="admin-order",l&&d&&(l.textContent="",l.style.display="none",l.dataset.nicepayPaymentInstallmentHidden="true"),n=!0}return n}function pt(e,t,n){const r=Array.from(e.querySelectorAll("span")).filter(o=>o.textContent?.trim()===t).find(o=>{const i=typeof o.className=="string"?o.className:"";return i.includes("rounded-full")||i.includes("font-medium")});return r?(r.textContent=n,r.dataset.nicepayPaymentMethodPatched="true",r.dataset.nicepayPaymentMethodBadge="admin-order",!0):!1}function mt(e,t){const n=t?._pay_method_label,a=t?._embedded_pg_provider_label,r=t?._base_pay_method_label;if(!n||!a)return!1;const o=ut(e,n),i=r?pt(e,r,a):!1;return o||i}async function yt(e){const t=document.getElementById("section_payment_info")??document.getElementById("payment_info_card");if(!t)return!1;const n=await lt(e);return n&&mt(t,n)&&console.info(`[${v}] payment method display patched on admin order detail`),!0}function ft(e){let t=0;const n=setInterval(()=>{t++,yt(e).then(a=>{(a||t>=30)&&clearInterval(n)})},400)}function ht(){const e=location.pathname.match(st);e&&ft(e[1])}function wt(){if(typeof window>"u")return;const e=window;if(e[Q])return;e[Q]=!0,console.info(`[${v}] admin order payment display injector installed`);const t=(a=1500)=>setTimeout(ht,a);document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>t()):t();const n=history.pushState.bind(history);history.pushState=(...a)=>{n(...a),t(600)},window.addEventListener("popstate",()=>t(500))}const y="sirsoft-pay_nicepayments",L={info:(...e)=>console.info(`[${y}]`,...e),warn:(...e)=>console.warn(`[${y}]`,...e),error:(...e)=>console.error(`[${y}]`,...e)};function Z(){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 a=0;for(const[r,o]of Object.entries(T)){const i=`${y}.${r}`;n.registerHandler(i,o,{category:"plugin",source:y}),a++}return a}function ee(){Ae(),De(),We(),it(),wt();const e=()=>{const t=Z();if(t>0){L.info(`${t} handler(s) registered`),$();return}let n=0;const a=50,r=setInterval(()=>{n++;const o=Z();if(o>0){clearInterval(r),L.info(`${o} handler(s) registered (after ${n} retries)`),$();return}n>=a&&(clearInterval(r),L.warn("ActionDispatcher not available after timeout"))},100)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):e()}ee(),window.__SirsoftNicepayments={identifier:y,handlers:Object.keys(T),initPlugin:ee}})();