PageSourceSearch

https://www.rus.com.ar/assets/js/cupones.js?v=1790855574

js rus.com.ar collected 2026-10-09 04:42:47 UTC 6,491 bytes, 175 lines download raw bytes

1/* ================================================================
2   CUPONES — toast flotante y módulo del carrito.
3
4   El toast replica el comportamiento de cupones_ejemplos/2-producto-toast.html:
5   arranca chico con Trofi hablando, se abre al tocarlo y al aplicar muestra el
6   estado "aplicado". A diferencia del ejemplo no se abre solo: molestaba al que
7   estaba mirando el producto.
8
9   Diferencia con el ejemplo: el ejemplo cambiaba el precio a mano en el HTML.
10   Acá los precios los arma PHP en un montón de lugares (ficha, planes, modales,
11   carrito, totales), así que después de aplicar o quitar un cupón se recarga la
12   página: es lo único que garantiza que TODOS los precios queden coherentes.
13   ================================================================ */
14(function () {
15  'use strict';
16
17  var RECARGA_MS = 1600;
18
19  function $(id) { return document.getElementById(id); }
20  function mostrar(el, visible) { if (el) el.classList.toggle('cpn-hidden', !visible); }
21
22  function postear(url, datos) {
23    var cuerpo = Object.keys(datos).map(function (k) {
24      return encodeURIComponent(k) + '=' + encodeURIComponent(datos[k]);
25    }).join('&');
26    return fetch(url, {
27      method: 'POST',
28      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
29      credentials: 'same-origin',
30      body: cuerpo
31    }).then(function (r) { return r.json(); });
32  }
33
34  // Quitar el cupón de la sesión y recargar: lo usan el toast y el carrito
35  function bindQuitar(boton) {
36    if (!boton) return;
37    boton.addEventListener('click', function () {
38      boton.disabled = true;
39      postear('ajax/cupon_quitar.php', {})
40        .then(function () { window.location.reload(); })
41        .catch(function () { boton.disabled = false; });
42    });
43  }
44
45  /* ══════════════════════════════ TOAST ══════════════════════════════ */
46  function initToast() {
47    var mini = $('cpn-mini-toast');
48    var full = $('cpn-full-toast');
49    if (!mini || !full) return;
50
51    var input = $('cpn-toast-input');
52    var boton = $('cpn-toast-aplicar');
53    var error = $('cpn-toast-error');
54    var errorTexto = $('cpn-toast-error-text');
55    var estadoInput = $('cpn-toast-input-state');
56    var estadoOk = $('cpn-toast-applied-state');
57    var okTexto = $('cpn-toast-ok-text');
58    var trofi = $('cpn-full-toast-trofi');
59
60    function abrir() {
61      mini.style.display = 'none';
62      full.classList.add('cpn-visible');
63      if (input && !estadoInput.classList.contains('cpn-hidden')) {
64        setTimeout(function () { input.focus(); }, 450);
65      }
66    }
67
68    function cerrar() {
69      full.classList.remove('cpn-visible');
70      setTimeout(function () { mini.style.display = 'flex'; }, 400);
71    }
72
73    mini.addEventListener('click', abrir);
74    mini.addEventListener('keydown', function (e) {
75      if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); abrir(); }
76    });
77    var cerrarBtn = $('cpn-full-toast-cerrar');
78    if (cerrarBtn) cerrarBtn.addEventListener('click', cerrar);
79
80    function aplicar() {
81      var codigo = (input.value || '').trim();
82      if (!codigo) { input.focus(); return; }
83
84      boton.disabled = true;
85      mostrar(error, false);
86
87      postear('ajax/cupon_aplicar.php', { codigo: codigo })
88        .then(function (data) {
89          if (data && data.ok) {
90            mostrar(estadoInput, false);
91            mostrar(estadoOk, true);
92            if (okTexto) okTexto.textContent = data.mensaje;
93            if (trofi && trofi.dataset.srcOk) trofi.src = trofi.dataset.srcOk;
94            // Se recarga para que todos los precios de la página tomen el cupón
95            setTimeout(function () { window.location.reload(); }, RECARGA_MS);
96          } else {
97            boton.disabled = false;
98            if (errorTexto) errorTexto.textContent = (data && data.mensaje) ? data.mensaje : 'No se pudo aplicar el cupón.';
99            mostrar(error, true);
100          }
101        })
102        .catch(function () {
103          boton.disabled = false;
104          if (errorTexto) errorTexto.textContent = 'No se pudo conectar. Probá de nuevo en un momento.';
105          mostrar(error, true);
106        });
107    }
108
109    if (boton) boton.addEventListener('click', aplicar);
110    if (input) {
111      input.addEventListener('keydown', function (e) {
112        if (e.key === 'Enter') { e.preventDefault(); aplicar(); }
113      });
114      input.addEventListener('input', function () { mostrar(error, false); });
115    }
116
117    bindQuitar($('cpn-toast-quitar'));
118  }
119
120  /* ══════════════════════════ MÓDULO DEL CARRITO ══════════════════════════ */
121  function initCarrito() {
122    var mod = $('cpn-carrito');
123    if (!mod) return;
124
125    var input = $('cpn-carrito-input');
126    var boton = $('cpn-carrito-aplicar');
127    var error = $('cpn-carrito-error');
128    var errorTexto = $('cpn-carrito-error-text');
129    var quitar = $('cpn-carrito-quitar');
130
131    // El botón Aplicar recién aparece cuando hay algo escrito, como en la referencia
132    if (input && boton) {
133      input.addEventListener('input', function () {
134        boton.classList.toggle('cpn-show', this.value.trim().length > 0);
135        mostrar(error, false);
136      });
137      input.addEventListener('keydown', function (e) {
138        if (e.key === 'Enter') { e.preventDefault(); aplicar(); }
139      });
140    }
141
142    function aplicar() {
143      var codigo = (input.value || '').trim();
144      if (!codigo) return;
145
146      boton.disabled = true;
147      mostrar(error, false);
148
149      postear('ajax/cupon_aplicar.php', { codigo: codigo })
150        .then(function (data) {
151          if (data && data.ok) {
152            window.location.reload();
153          } else {
154            boton.disabled = false;
155            if (errorTexto) errorTexto.textContent = (data && data.mensaje) ? data.mensaje : 'No se pudo aplicar el cupón.';
156            mostrar(error, true);
157          }
158        })
159        .catch(function () {
160          boton.disabled = false;
161          if (errorTexto) errorTexto.textContent = 'No se pudo conectar. Probá de nuevo en un momento.';
162          mostrar(error, true);
163        });
164    }
165
166    if (boton) boton.addEventListener('click', aplicar);
167
168    bindQuitar(quitar);
169  }
170
171  document.addEventListener('DOMContentLoaded', function () {
172    initToast();
173    initCarrito();
174  });
175})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.