',this.overrideStyles=null,this.data={},this.i18n={},this.internalAutorization=!0,this.availableAmount=1e8,
this.onCountryChoiced=e=>{},this.onSkuChoiced=(e,t)=>{},this.onQuotation=e=>{},this.onInitialized=()=>{},this.onCompleted=()=>{},this.onError=()=>{},this.onValidation=()=>{},this.onCheckout=()=>{},this.onTermsAccepted=()=>{},e.observedAttributes.forEach((e=>{this.data[e]=this.getAttribute(e)||("skus"==e?[]:"")})),this.initialized=!1,this.observer=new MutationObserver((e=>{e.forEach((e=>{"attributes"===e.type&&(this.data[e.attributeName]=this.getAttribute(e.attributeName)||"",this.refresh())}))}))}static frequencyRecipients={};static denominations={};fetchFrequencyRecipients(t,i){return new Promise(((n,a)=>{void 0!==e.frequencyRecipients[t]&&!1!==e.frequencyRecipients[t]?n(e.frequencyRecipients[t].filter((e=>e.recipientCountry==i))):$.ajax({type:"GET",url:this.createApiUrl(`wallet/frequency-recipients/${t}`),success:a=>{e.frequencyRecipients[t]=a,n(e.frequencyRecipients[t].filter((e=>e.recipientCountry==i)))},error:e=>a(e)})}))}fetchDenominations(e){
return this._denominationsCached||(this._denominationsCached={}),new Promise(((t,i)=>{this._denominationsCached[e]&&t(this._denominationsCached[e]),$.ajax({type:"GET",url:this.createApiUrl(`wallet/payout/${e}/denominations`),success:i=>{this._denominationsCached[e]=i,t(i)},error:e=>i(e)})}))}connectedCallback(){this.observer.observe(this,{attributes:!0}),this.render()}disconnectedCallback(){this.observer.disconnect()}static isomasrkandregexp=null;fetchIsoMaskAndRegexp(t){return new Promise(((i,n)=>{null!=e.isomasrkandregexp?i(e.isomasrkandregexp[t]??null):$.ajax({type:"GET",url:"/assets/isomaskandregesp.json",success:n=>{e.isomasrkandregexp=n,i(e.isomasrkandregexp[t]??null)},error:e=>n(e)})}))}static rates=null;static fetching=!1;static recipientForm={};static get observedAttributes(){return["iso","flag","country","skus"]}attributeChangedCallback(e,t,i){void 0===this.data[e]&&t!=i&&(this.data[e]=i,this.refresh())}trans(e,t){let i=void 0!==this.i18n[e]?(this.i18n[e]??e).trim():e.trim()
;if(void 0!==t)for(var e in t)i=i.replace(e,t[e]).trim();return i.trim()}createApiUrl(e){return`https://${document.querySelector('meta[name="app-env"]')&&"dev"==document.querySelector('meta[name="app-env"]').getAttribute("content")?"dev-api":"api"}.remesita.com/rest/v1/${e}`}loadPayOutRates(t){return new Promise(((i,n)=>{t||null==e.rates?e.fetching||(e.fetching=!0,$.ajax({type:"GET",url:this.createApiUrl("wallet/payout/rates?group=topup,billpay"),success:t=>{i(t),e.rates=t,e.fetching=!1},error:t=>{e.rates=null,e.fetching=!1,n(t)}})):i(e.rates)}))}fetchRecipientForm(t){return new Promise(((i,n)=>{null!=e.recipientForm[t]?i(e?.recipientForm[t]):$.ajax({type:"GET",url:this.createApiUrl(`wallet/${t}/recipient-form`),success:n=>{e.recipientForm[t]=n,i(n)},error:e=>n(e)})}))}getRatesGroupByContry(e){return new Promise(((t,i)=>{this.loadPayOutRates(e).then((e=>{const i={};for(const t in e)e[t].countries.forEach((n=>{i[n.iso]||(i[n.iso]={...n,skus:[]}),i[n.iso].skus.push({...e[t],sku:t})}))
;for(const e in i)i[e].skus.sort(((e,t)=>e.enabled-t.enabled));const n={};Object.keys(i).sort().forEach((function(e){n[e]=i[e]})),t(n)})).catch((e=>i(e)))}))}refresh(){this.overrideStyles&&(this.initialized=!1),this.render()}render(){let e="";if(this.overrideStyles)for(let t in this.overrideStyles){let i=[];for(let e in this.overrideStyles[t])i.push(`${e}:${this.overrideStyles[t][e]};`);e+=`.${this.uniqueSuffix} ${t} {${i.join("")}}`}this.initialized||(this.innerHTML=`\n \n \n \n `,this.container=this.querySelector("div"));const t=[],i=[];this.getRatesGroupByContry().then((e=>{if(this._countryChoices=e,!this.initialized){for(var n in e){
const a=e[n],o=`
${this.trans("Consultemos con _INSTITUTION_ para veer si tienes algún adeudo.",{
_INSTITUTION_:(e.institution??this.trans("la institución")).replace("UNKNOWN",this.trans("la institución"))
})}
\n
\n ${this.trans("Número de la factura")}\n
\n \n
\n \n \n \n
\n
\n
\n
\n
\n ${this.trans("La factura no tienes adeudos en estos momentos.")}\n
\n
\n ${this.trans(" Espere mientras conectamos con _INSTITUTION_ para verificar si tienes algún adeudo, este proceso puede tardar, no te desesepres.",{
_INSTITUTION_:(e.institution??this.trans("la institución")).replace("UNKNOWN",this.trans("la institución"))})}\n
\n
\n
\n
\n \n
\n
`,this.querySelector("#invoice-number").addEventListener("input",(t=>{const i=(this.querySelector("#invoice-number").value??"").replace(/\s/g,"").trim();let n=8;"UNE_INVOICE"===e.sku&&(n=13),
i.length>=n?this.querySelector("button").removeAttribute("disabled"):this.querySelector("button").setAttribute("disabled",!0)})),this.querySelector("button").addEventListener("click",(async n=>{this.querySelector("button").setAttribute("disabled",!0),this.querySelector("button").innerHTML=` ${this.trans("CONSULTANDO")}...`;const a=(this.querySelector("#invoice-number").value??"").replace(/\s/g,"").trim();this.querySelector(".invoice-error").style.display="none",this.querySelector(".invoice-loading").style.display="",$.ajax({type:"GET",url:this.createApiUrl(`bill/${a}/${e.sku}/check`),success:n=>{if(this.querySelector(".invoice-loading").style.display="none",n.error)this.querySelector(".invoice-error").style.display="",this.querySelector(".invoice-error").innerHTML=n.error??this.trans("La factura no tienes adeudos en estos momentos.");else{const o=parseFloat(n.balance)/e.currencies[0].exchangeRate,r=o*e.percent+e.fix,s=o+r;this.data.isValid=!0,
this.data.quotation={sku:e.sku,label:e.label,country:t,sourceValue:o,targetValue:parseFloat(n.balance),targetChoiced:null,currency:n.currency,totalFees:r},this.data.recipientData=[{slug:"recipientAccount",mapto:"recipientAccount",value:a},{slug:"recipientPhone",mapto:"recipientPhone",value:window.auth.user.phone},{slug:"recipientEmail",mapto:"recipientEmail",value:window.auth.user.email},{slug:"recipientName",mapto:"recipientName",value:window.auth.user.fullName},{slug:"invoiceHolder",mapto:"metaItem",value:n.holder??this.trans("Desconocido")}],
this.container.innerHTML=`\n ${i} \n
`,this.querySelector("#invoice-authorize-slider").addEventListener("change",(e=>{if(this.querySelector("#invoice-authorize-slider").value>=99)this.querySelector("#invoice-authorize-slider").setAttribute("disabled",!0),this.querySelector("#invoice-authorize-slider-container").classList.add("authorized"),this.authorize();else{const e=setInterval((()=>{if(!this.querySelector("#invoice-authorize-slider"))return clearInterval(e)
;this.querySelector("#invoice-authorize-slider").value=Math.max(this.querySelector("#invoice-authorize-slider").value-10),0==this.querySelector("#invoice-authorize-slider").value&&clearInterval(e)}),24)}}))}},error:()=>{this.querySelector(".invoice-loading").style.display="none",this.querySelector("button").removeAttribute("disabled"),this.querySelector("button").innerHTML=`${this.trans("SIGUIENTE")} `,this.querySelector(".invoice-error").style.display="",this.querySelector(".invoice-error").innerHTML=this.trans("La factura no tienes adeudos en estos momentos.")}})}));else{
this.container.innerHTML=`\n ${i}\n \n
\n ${this.trans("No tienes suficiente balance para realizar esta operación.")}\n
\n
\n
\n \n
\n
`;const n={
"Enter _CURRENCY_":this.trans("Introduce los _CURRENCY_"),"Source amount on _CURRENCY_":this.trans("Lo que se debitará de tu Wallet."),"Target amount on _CURRENCY_":this.trans("Lo que recibe el Destinatario."),"Exchange Rate _RATE_":this.trans("Tipo de cambio _RATE_"),"Percentage Fee _RATE_":this.trans("Comisión Remesita _RATE_"),"Percentage Fee":this.trans("Comisión Remesita"),"Fixed Fee":this.trans("Tarifa de operación"),"Conversion before taxes":this.trans("Conversión antes de impuestos"),"Conversion after taxes":this.trans("Conversión después de impuestos"),"Value must be between _MIN_ and _MAX_ _CURRENCY_":this.trans("El valor debe estar entre _MIN_ y _MAX_ _CURRENCY_"),"Total commissions":this.trans("Costo operacional"),"View more":"Ver detalle completo","View less":"Ocultar detalle","Total conversion":"Cantidad convertida","Recipient amount":"Cantidad a recibir","Discount applied":"Descuento aplicado",
"The amount exceed the established limits":"Los datos introducidos no son válidos."};$("#airtime-billpay-quotation").setupDQ({showFlag:!1,exchangeRate:e.denominations&&e.denominations.length?e.denominations[0]?.exchangeRate:e.currencies[0].exchangeRate,targetChoice:!(!e.denominations||!e.denominations.length)&&e.denominations,fixedFees:{"Fixed Fee":e.fix??0},percentageFees:{"Percentage Fee":(e.percent??0)/100},minSource:Math.max(1,e.minAmount),maxSource:e.denominations&&e.denominations.length?e.denominations[0].amount:1e5,minTarget:e.denominations&&e.denominations.length?e.denominations[0].value:Math.max(1,e.minAmount),maxTarget:e.denominations&&e.denominations.length?e.denominations[e.denominations.length-1].value:1e4,sourceCurrency:"SRM",targetCurrency:e.currencies[0].symbol,target:e.denominations&&e.denominations.length?e.denominations[0].value:null,source:e.denominations&&e.denominations.length?null:parseInt(Math.min(100,this.availableAmount).toFixed(0)),
backendQuotationEndpoint:e.quotationEndpoint??!1,feeApplyTo:"source",components:e.denominations&&e.denominations.length?["target","source","details"]:["source","details","target"],i18n:n,detailsCls:"animate fadeIn",styles:this.getQuotationStyles(),onValidation:i=>{this.data.quotation={sku:e.sku,label:e.label,country:t,sourceValue:i.sourceValue,targetValue:i.targetValue,targetChoiced:i.targetChoiced??null,currency:e.currencies[0].symbol,totalFees:i.totalFees},i.success&&i.sourceValue<=this.availableAmount?this.querySelector("button").removeAttribute("disabled"):this.querySelector("button").setAttribute("disabled",!0),this.container.querySelector(".insuficiente-amount").style.display=i.sourceValue>this.availableAmount?"block":"none"},onInitialized:()=>{this.fetchFrequencyRecipients(e.sku,t.iso).then((()=>{}))}}),this.querySelector("button").addEventListener("click",(i=>{setTimeout((()=>{this.onQuotation(this.data.quotation),this.dispatchEvent(new CustomEvent("quotation",{
detail:this.data.quotation}))}),100),this.renderFrequencyRecipients(e.sku,t.iso)}))}this.dispatchEvent(new CustomEvent("skuCoiced",{detail:e})),this.onSkuChoiced(e)}_header(){return`
${this.trans("¿Quién será el destinatario?")} `;this.container.innerHTML=`${i}${this.loadingHtml}`,this.fetchFrequencyRecipients(e,t).then((t=>{
t.length?(this.container.innerHTML=`${i} \n
\n
\n
\n
${this.trans("Nuevo Destinatario")}
\n
\n ${t.map((e=>`
\n \n
${e.recipientName}
\n
`)).join("")}\n
`,
this.container.querySelector(".airtime-billpay-recipient-add").addEventListener("click",(t=>this.renderRecipientForm(e))),this.container.querySelectorAll(".airtime-billpay-recipient-choice").forEach((t=>{t.addEventListener("click",(i=>this.renderRecipientForm(e,JSON.parse(atob(t.getAttribute("data"))),!0)))}))):this.renderRecipientForm(e)})).catch((t=>this.renderRecipientForm(e))),this.fetchRecipientForm(e).then((e=>{}))}renderRecipientForm(t,i,n){this.fetchRecipientForm(t).then((t=>{if(this.data.recipientForm=t,t&&0!=t.length||(t=[]),!t.find((e=>"recipientAccount"==e.mapto))){if(e.isomasrkandregexp[this.data.quotation.country.iso])var a=e.isomasrkandregexp[this.data.quotation.country.iso].mask,o=e.isomasrkandregexp[this.data.quotation.country.iso].regexp;t.push({mapto:"recipientAccount",label:this.trans("Número de celular"),type:"text",slug:"recipientAccount",requirement:"required",mask:a,regexp:o})}t.find((e=>"recipientName"==e.mapto))||t.push({
label:this.trans("Nombre del destinatario"),help:this.trans("Te pedimos este dato para almacenar el beneficiario y puedas reutilizarlo en el futuro."),type:"text",mapto:"recipientName",slug:"recipientName",requirement:"required",regexp:"^[a-zA-Z ]+$"}),this.data.recipientForm=t;const r=t.map((e=>(e.value=null,i&&null!=(i[e.slug]??null)&&(e.value=i[e.slug]),e)))
;this.container.innerHTML=`${this._header()}\n
${this.trans("Por favor, lee cuidadosamente los siguientes términos y condiciones:")}
\n
\n
${this.trans("Entiendo que si el beneficiario o el remitente aparecen en listas negras, la operación podría ser cancelada y reembolsada, y mi cuenta de Remesita podría estar en riesgo de ser cerrada.")}
\n
${this.trans("Entiendo que soy responsable de ingresar correctamente los datos del beneficiario y que, en caso de error, acepto que puedo perder los fondos.")}
\n
${this.trans("Entiendo que los fondos serán debitados de mi wallet de forma inmediata, pero la operación en el destino final dependerá del operador en el otro extremo, pudiendo tardar entre 30 segundos y 72 horas.")}
\n
${this.trans("Entiendo que solo aplican devoluciones para las operaciones rechazadas por nuestro proveedor, y no para aquellas que no llegan a su destino por problemas internos del país o errores en los datos ingresados.")}
\n
${this.trans("Entiendo que Remesita no conecta directamente al proveedor de servicio de mi destinatario sino que instruye la operación por medaicion de su socio comercial Reloadly Networks, LLC.")}
\n
${this.trans("Declaro que he revisado mi cotización y entiendo que se debitarán de mi wallet en total _DBT_ SRM.",{
_DBT_:this.data.quotation.sourceValue.toFixed(2)
})}
\n
${this.trans("Declaro bajo juramento y bajo pena de perjurio que el beneficiario NO ES una persona políticamente expuesta (PEP)-")}
\n
${this.trans("Declaro bajo juramento y bajo pena de perjurio que estos fondos NO SON para financiar temas migratorios-")}
\n
${this.trans("Declaro bajo juramento y bajo pena de perjurio que estos fondos NO SON para financiar actividades políticas-")}
\n
${this.trans("Libero a Remesita de toda responsabilidad por cualquier tarifa que el banco o entidad receptora aplique a la cuenta del beneficiario por la recepción de los fondos.")}
\n
\n
${this.trans("Esta operación será procesada por nuestro sponsor, Lemargo Inc., una compañía registrada en Ontario, Canadá, bajo el número 1078188 y MSB Fintrac M08130624. Remesita solo instruye y monitorea el estatus, sin custodiar los fondos en el destino final.")}
\n
\n
\n ${this.trans("Lée hasta el final para que puedas autorizar la operación.")}\n
\n
\n ${this.internalAutorization?`
\n
\n \n
\n
`:""}`,
this.container.querySelector(".disclaimer").addEventListener("scroll",(e=>{const t=e.target.scrollHeight;e.target.scrollTop+e.target.clientHeight>=t-30&&(this.internalAutorization&&this.container.querySelector(".btn-authorization").removeAttribute("disabled"),this.container.querySelector(".disclaimer-reed-force-message").innerHTML=` ${this.trans("Ahora aque has leído los términos y condiciones, ahora puedes autorizar la operación.")}`,this.onTermsAccepted())}));const e={};this.data.recipientForm.forEach((t=>e[t.slug]=t.value??null)),this.container.querySelector(".edit-recipient").addEventListener("click",(t=>this.renderRecipientForm(this.data.quotation.sku,e,!1))),this.onCheckout()}authorize(){const t=e=>{
this.container.innerHTML=`
\n ${this.trans("La operación fue instruida al proveedor.")} ${this.trans("Recibirás una notificación cuando sea completada.")}\n ${i.reference??"----"}\n
`,this.onCompleted(i)):t(i.error)},error:e=>{t(this.trans("Ha ocurrido un error al procesar la transacción"))}})):t(this.trans("Los datos des destinatario no son válidos"))}validateForm(e){let t=!0,i=[]
;this.data.recipientData=this.data.recipientForm.map((e=>{if(!this.container.querySelector(`#${this.uniqueSuffix+e.slug}`))return{slug:e.slug,mapto:e.mapto,value:e.value,valid:!0};if(e.value="switch"==e.type?this.container.querySelector(`#${this.uniqueSuffix+e.slug}`).checked??!1:this.container.querySelector(`#${this.uniqueSuffix+e.slug}`).value,e.valid=!0,this.container.querySelector(`#${this.uniqueSuffix+e.slug}caption`).style.display="block",this.container.querySelector(`#${this.uniqueSuffix+e.slug}error`).innerHTML="","required"==e.requirement&&("switch"==e.type&&!e.value||"switch"!=e.type&&!e.value.length)&&(e.valid=!1,e.valid||i.push(this.trans("El campo *_LABEL_* es requerido",{_LABEL_:e.label}))),"switch"!=e.type&&e.valid&&void 0!==e.regexp&&(e.regexp??"").length){const t=new RegExp(e.regexp.replace("_ISO_",this.data.quotation.country.iso),"i"),n="recipientAccount"==e.mapto?e.value.replace(/\s/g,"").trim():e.value.trim();e.valid=t.test(n),
e.valid||i.push((e.regexerr??"").length?e.regexerr:this.trans("Este valor no parece ser válido"))}e.valid||(this.container.querySelector(`#${this.uniqueSuffix+e.slug}error`).innerHTML=(e.regexerr??"").length?e.regexerr:this.trans("Este valor no parece ser válido"),this.container.querySelector(`#${this.uniqueSuffix+e.slug}caption`).style.display="none",t=!1);var n=/recipientAccount|recipientName|recipientCountry/.test(e.mapto)?(e.value??"").toUpperCase():e.value??"";return/recipientAccount|recipientPhone/.test(e.mapto)&&(n=n.replace(/\s|-|\(|\)/g,"")),{slug:e.slug,mapto:e.mapto,value:n.trim(),valid:e.valid}}));const n={success:t,error:i.join(". ")};this.data.isValid=t,this.internalAutorization&&this.container.querySelector("button.btn-authorization")&&(this.container.querySelector("button.btn-authorization").disabled=!t),this.onValidation(n),this.dispatchEvent(new CustomEvent("validation",{detail:n})),
e&&t?this.checkout():t?this.container.querySelector("button.btn-next-resume").removeAttribute("disabled"):this.container.querySelector("button.btn-next-resume").setAttribute("disabled",!0)}setupAirtimeBillpay(t){this.initialized=!1,e.rates=null,void 0!==t.overrideStyles&&(this.overrideStyles=t.overrideStyles),void 0!==t.internalAutorization&&(this.internalAutorization=t.internalAutorization),void 0!==t.onCountryChoiced&&(this.onCountryChoiced=t.onCountryChoiced),void 0!==t.onInitialized&&(this.onInitialized=t.onInitialized),void 0!==t.onSkuChoiced&&(this.onSkuChoiced=t.onSkuChoiced),void 0!==t.onError&&(this.onError=t.onError),void 0!==t.onValidation&&(this.onValidation=t.onValidation),void 0!==t.onCompleted&&(this.onCompleted=t.onCompleted),void 0!==t.onTermsAccepted&&(this.onTermsAccepted=t.onTermsAccepted),void 0!==t.onCheckout&&(this.onCheckout=t.onCheckout),void 0!==t.availableAmount&&(this.availableAmount=t.availableAmount),void 0!==t.shortcut&&(this.shortcut=t.shortcut),
this.refresh()}}customElements.define("remex-airtime-billpay",e),"undefined"!=typeof jQuery&&function(e){e.fn.setupAirtimeBillpay=function(e){return this.each((function(){"remex-airtime-billpay"===this.tagName.toLowerCase()&&this.setupAirtimeBillpay(e)}))},e.fn.authorizeAirtimeBillpay=function(){return this.each((function(){"remex-airtime-billpay"===this.tagName.toLowerCase()&&this.authorize()}))}}(jQuery);const t="dev"!=document.querySelector('meta[name="app-env"]')?.getAttribute("content"),i=document.querySelector('meta[name="x-cpl"]')?.getAttribute("content")||"1.0.0";var script;customElements.get("dynamic-quotation")||((script=document.createElement("script")).src=`/cdn/${i}/microfronts/dynamic-quotation/index${t?".min":""}.js`,script.async=!0,document.head.appendChild(script)),customElements.get("remex-select")||((script=document.createElement("script")).src=`/cdn/${i}/microfronts/remex-select/index${t?".min":""}.js`,script.async=!0,document.head.appendChild(script)),
void 0===$.fn.mask&&((script=document.createElement("script")).src="/assets/js/jquery.mask.min.js",script.async=!0,document.head.appendChild(script))}