-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1773 lines (1491 loc) · 63.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Custom color logger
function colorLog(message, color) {
color = color || "black";
switch (color) {
case "success":
color = "Green";
break;
case "info":
color = "DodgerBlue";
break;
case "error":
color = "Red";
break;
case "warning":
color = "Orange";
break;
default:
color = color;
}
console.log("%c" + message, "color:" + color);
}
const CRUWI_BASE_API_URL = "https://app.cruwi.com";
// Main Script function
(() => {
// Iniciamos el script
colorLog('***** Cruwi Script Init *****', "warning");
// Testeo en local o en la web de test de CRUWI
let isLocalDevelopment = window.document.location.hostname === '127.0.0.1' || window.document.location.hostname === 'cruwishop.myshopify.com';
let isTestNow = false;
// Detectamos lenguaje del usuario
const preferredLanguage = window.navigator.language; // es-ES
colorLog(`Preferred Language: ${preferredLanguage}`, "success");
// Procesamos el script
let currentScriptProcessed;
if(isLocalDevelopment) {
const testScript = document.createElement('script');
testScript.setAttribute('src','https://unpkg.com/cruwi-widget?merchantName=Cruwishop&apiKey=42ce241171fce799168ed5faa01dd3b2&widgetType=checkout');
currentScriptProcessed = testScript;
} else {
currentScriptProcessed = document.currentScript;
}
// Obtenemos los datos del merchant por la url del script
const merchantNameFromScript = new URLSearchParams(new URL(currentScriptProcessed.getAttribute('src')).search).get('merchantName');
const merchantApiKeyFromScript = new URLSearchParams(new URL(currentScriptProcessed.getAttribute('src')).search).get('apiKey');
const widgetTypeFromScript = new URLSearchParams(new URL(currentScriptProcessed.getAttribute('src')).search).get('widgetType');
colorLog(`Merchant: ${merchantNameFromScript}`, "success");
colorLog(`Api Key: ${merchantApiKeyFromScript}`, "success");
colorLog(`Widget Type: ${widgetTypeFromScript}`, "success");
// Comprobamos nombre del merchant según la url
const TLDs = ["ac", "ad", "ae", "aero", "af", "ag", "ai", "al", "am", "an", "ao", "aq", "ar", "arpa", "as", "asia", "at", "au", "aw", "ax", "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "biz", "bj", "bm", "bn", "bo", "br", "bs", "bt", "bv", "bw", "by", "bz", "ca", "cat", "cc", "cd", "cf", "cg", "ch", "ci", "ck", "cl", "cm", "cn", "co", "com", "coop", "cr", "cu", "cv", "cx", "cy", "cz", "de", "dj", "dk", "dm", "do", "dz", "ec", "edu", "ee", "eg", "er", "es", "et", "eu", "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi", "gl", "gm", "gn", "gov", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn", "hr", "ht", "hu", "id", "ie", "il", "im", "in", "info", "int", "io", "iq", "ir", "is", "it", "je", "jm", "jo", "jobs", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "la", "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me", "mg", "mh", "mil", "mk", "ml", "mm", "mn", "mo", "mobi", "mp", "mq", "mr", "ms", "mt", "mu", "museum", "mv", "mw", "mx", "my", "mz", "na", "name", "nc", "ne", "net", "nf", "ng", "ni", "nl", "no", "np", "nr", "nu", "nz", "om", "org", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "pro", "ps", "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb", "sc", "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "st", "su", "sv", "sy", "sz", "tc", "td", "tel", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to", "tp", "tr", "travel", "tt", "tv", "tw", "tz", "ua", "ug", "uk", "us", "uy", "uz", "va", "vc", "ve", "vg", "vi", "vn", "vu", "wf", "ws", "xxx", "ye", "yt", "za", "zm", "zw"].join();
function getDomain(url){
var parts = url.split('.');
if (parts[0] === 'www' && parts[1] !== 'com'){
parts.shift()
}
var ln = parts.length, i = ln, minLength = parts[parts.length-1].length, part
while(part = parts[--i]){
if (i === 0 || i < ln-2 || part.length < minLength || TLDs.indexOf(part) < 0){
return part
}
}
}
// Obtenemos el nombre del merchant oficial
let merchantNameFromUrl = getDomain(isLocalDevelopment ? 'cruwi.com' : window.location.host);
colorLog(`Merchant Name from URL: ${merchantNameFromUrl}`, "success");
// Obtenemos el documento completo (para montar HTML luego)
const body = document.querySelector('body');
// Comprobamos si hay widget y qué tipo de widget se solicita
const widgetElement = document.querySelector('[data-cruwi-widget-type]');
if(widgetElement) {
// Cargamos amplitude
loadAmplitudeSDK();
// Obtenemos el tipo de widget que hay en la página
const widgetType = widgetElement.dataset.cruwiWidgetType;
// Según sea el tipo montamos
if(widgetType === 'pdp') {
buildCruwiModal();
buildCruwiPDPWidget();
} else if(widgetType === 'section') {
buildCruwiSectionWidget();
} else if(widgetType === 'tiktok') {
loadTiktokScript();
buildCruwiTiktokWidget();
} else if(widgetType === 'checkout') {
buildCruwiCheckoutWidget();
} else {
console.error('This widget type is not valid');
}
} else {
console.error('There is no CRUWI widget to display.');
}
// Función que carga el SDK de Amplitude
function loadAmplitudeSDK() {
let projectId = isLocalDevelopment ? '203521c0ed2ec0d7fbe8d1176f8c3503' : 'ae6db858c2fce34e9561b18032893b25';
const scriptAmplitude = document.createElement('script');
var scriptAmplitudeContent = document.createTextNode(`!function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[],_iq:[]};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{var n=function(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}},s=function(e,t,r){return function(n){e._q.push({name:t,args:Array.prototype.slice.call(r,0),resolve:n})}},o=function(e,t,r){e[t]=function(){if(r)return{promise:new Promise(s(e,t,Array.prototype.slice.call(arguments)))}}},i=function(e){for(var t=0;t<g.length;t++)o(e,g[t],!1);for(var r=0;r<m.length;r++)o(e,m[r],!0)};r.invoked=!0;var u=t.createElement("script");u.type="text/javascript",u.integrity="sha384-GHWzi7MsT/TD3t0f+KUaVeuvPUsuVgdUKegrAWlzO4I83+klmUJna8WTuUunlsg6",u.crossOrigin="anonymous",u.async=!0,u.src="https://cdn.amplitude.com/libs/analytics-browser-1.6.6-min.js.gz",u.onload=function(){e.amplitude.runQueuedFunctions||console.log("[Amplitude] Error: could not load SDK")};var a=t.getElementsByTagName("script")[0];a.parentNode.insertBefore(u,a);for(var c=function(){return this._q=[],this},l=["add","append","clearAll","prepend","set","setOnce","unset","preInsert","postInsert","remove","getUserProperties"],p=0;p<l.length;p++)n(c,l[p]);r.Identify=c;for(var d=function(){return this._q=[],this},v=["getEventProperties","setProductId","setQuantity","setPrice","setRevenue","setRevenueType","setEventProperties"],f=0;f<v.length;f++)n(d,v[f]);r.Revenue=d;var g=["getDeviceId","setDeviceId","getSessionId","setSessionId","getUserId","setUserId","setOptOut","setTransport","reset"],m=["init","add","remove","track","logEvent","identify","groupIdentify","setGroup","revenue","flush"];i(r),r.createInstance=function(){var e=r._iq.push({_q:[]})-1;return i(r._iq[e]),r._iq[e]},e.amplitude=r}}(window,document)}(); amplitude.init("${projectId}"); `);
scriptAmplitude.appendChild(scriptAmplitudeContent);
let head = document.getElementsByTagName('head')[0];
head.appendChild(scriptAmplitude);
}
// Función que carga TikTok
function loadTiktokScript() {
const script = document.createElement('link');
script.setAttribute('src', 'https://www.tiktok.com/embed.js');
script.setAttribute('async', true);
let head = document.getElementsByTagName('head')[0];
head.appendChild(script);
}
// Función que monta el PDP Widget
function buildCruwiPDPWidget() {
colorLog('-- Building PDP Widget --', "info");
// Comprobamos que estilo quieren (2 estilos hay)
const widgetTextStyle = widgetElement.dataset.cruwiWidgetStyle ?? '1';
let widgetText = "Gana dinero recomendando nuestros productos";
if(widgetTextStyle === '2') {
widgetText = "Comparte con amig@s para que tod@s ganemos";
}
// Si el idioma no contiene 'es', ponemos en inglés
if(preferredLanguage.indexOf('es') === -1) {
widgetText = "Earn money by recommending our products";
}
// Vemos el tamaño de pantalla para algunos ajustes en el futuro
let windowSize = window.screen.width;
// Creamos el Div con el banner
const cruwiPDPWidget = document.createElement('div');
cruwiPDPWidget.id = "cruwi-pdp-widget";
cruwiPDPWidget.classList.add('cruwi-pdp-widget');
cruwiPDPWidget.innerHTML = `
<div class="cruwi-pdp-widget-wrapper">
<div class="cruwi-pdp-widget-logo-wrapper">
<div class="cruwi-pdp-widget-logo">
<img class="cruwi-pdp-widget-logo-img" src="https://uploads-ssl.webflow.com/62ea5c239bacb85550bf44ea/6328573bad60f760ac2b5fbb_CRUWI%20(3).svg" alt="CRUWI Logo Banner" >
</div>
</div>
<div class="cruwi-pdp-widget-text">
${widgetText}
</div>
</div>
<div class="cruwi-pdp-widget-button">+ Info</div>
`;
widgetElement.appendChild(cruwiPDPWidget);
// Escuchamos el click
cruwiPDPWidget.addEventListener('click', () => {
window.amplitude && amplitude.track('pdp_widget_clicked', {
merchantName: merchantNameFromScript,
});
let event = new CustomEvent("cruwiModalOpen", { bubbles: true });
cruwiPDPWidget.dispatchEvent(event);
});
loadCruwiCustomFont();
injectCruwiStyles();
}
// Función que monta el PDP Widget
async function buildCruwiTiktokWidget() {
colorLog('-- Building Tiktok Widget --', "info");
// Vemos el tamaño de pantalla
let windowSize = window.screen.width;
// Obtenemos los favoritos de ese merchant
const { data } = await fetchGetFavouriteMerchantTiktoks(merchantApiKeyFromScript);
const numberOfFavourites = data.length;
if(numberOfFavourites < 3) {
// Menos de 3 no tiene sentido ponerlo, mostramos error en consola
colorLog('Necesitas al menos 3 tiktoks marcados como favoritos', "warning");
return;
}
const playButtonUrl = 'https://cdn.shopify.com/s/files/1/0582/8408/1175/t/1/assets/play-video-icon_50x.png?v=49291947946775394611663754349';
let tiktoksHtml = '';
for (var i = 0; i < data.length; i++) {
const tiktok = data[i];
tiktoksHtml += `
<div id="cruwi-tiktok-widget-tiktok">
<div id="cruwi-tiktok-widget-tiktok-icon">
<img src="${playButtonUrl}">
</div>
<div class="cruwi-tiktok-widget-tiktok-overlay" id="cruwi-tiktok-widget-tiktok-overlay" data-tiktok-id="${tiktok.tikTokId}"></div>
<img id="cruwi-tiktok-widget-tiktok-image" src="${tiktok.coverImageUrl}">
</div>
`;
}
// Creamos el div principal y su contenido y le inyectamos los tiktoks dinámicos
const cruwiTiktokWidget = document.createElement('div');
cruwiTiktokWidget.id = "cruwi-tiktok-widget";
cruwiTiktokWidget.classList.add('cruwi-tiktok-widget');
cruwiTiktokWidget.innerHTML = `
<h6 id="cruwi-tiktok-widget-title">Nuestros clientes comparten</h6>
<div id="${numberOfFavourites < 4 ? 'cruwi-tiktok-widget-wrapper-short' : 'cruwi-tiktok-widget-wrapper'}">
${tiktoksHtml}
</div>
<div id="cruwi-tiktok-widget-modal"></div>
<div id="cruwi-tiktok-widget-modal-content">
<iframe id="cruwi-tiktok-widget-modal-content-iframe" frameborder="0"></iframe>
<button id="cruwi-tiktok-widget-modal-content-button">Seguir comprando</button>
</div>
<h6 id="cruwi-tiktok-widget-subtitle">Powered by CRUWI</h6>
`;
// Metemos el html para poder poner los eventos en cada elemento
widgetElement.appendChild(cruwiTiktokWidget);
const cruwiTiktokModalOverlay = document.getElementById('cruwi-tiktok-widget-modal');
const cruwiTiktokModalContent = document.getElementById('cruwi-tiktok-widget-modal-content');
const cruwiTiktokModalContentCloseButton = document.getElementById('cruwi-tiktok-widget-modal-content-button');
const cruwiTiktokModalContentIframe = document.getElementById('cruwi-tiktok-widget-modal-content-iframe');
const cruwiTiktoksOverlays = document.querySelectorAll('.cruwi-tiktok-widget-tiktok-overlay');
cruwiTiktoksOverlays.forEach(tiktok => {
tiktok.addEventListener('click', function handleClick(event) {
const tiktokVideoUrl = `https://www.tiktok.com/embed/${event.target.dataset.tiktokId}`;
cruwiTiktokModalContentIframe.src = tiktokVideoUrl;
cruwiTiktokModalOverlay.style.display = 'block';
cruwiTiktokModalContent.style.display = 'flex';
});
});
cruwiTiktokModalOverlay.addEventListener('click', function handleClick(e) {
cruwiTiktokModalContent.style.display = 'none';
cruwiTiktokModalOverlay.style.display = 'none';
});
cruwiTiktokModalContentCloseButton.addEventListener('click', function handleClick(e) {
cruwiTiktokModalContent.style.display = 'none';
cruwiTiktokModalOverlay.style.display = 'none';
});
injectCruwiStyles();
}
// Función que monta la sección completa
function buildCruwiSectionWidget() {
colorLog('-- Building Section Widget --', "info");
// Creamos el modal con un ID
const sectionWidget = document.createElement('div');
sectionWidget.classList.add('cruwi-section');
sectionWidget.id = 'cruwiSection';
sectionWidget.innerHTML = `
<div class="cruwi-section-main">
<h2 class="cruwi-section-title">¡Te devolvemos parte de tu compra cuando tus amigas compren en ${merchantNameFromScript} contigo!</h2>
<div class="cruwi-section-card-container">
<div class="cruwi-section-card">
<div class="cruwi-section-card-bullet">1</div>
<h2>Compra como siempre</h2>
<p>Haz tu compra con normalidad, como lo haces siempre</p>
</div>
<div class="cruwi-section-card">
<div class="cruwi-section-card-bullet">2</div>
<h2>Invita a amigas</h2>
<p>Una vez finalizada tu compra, recibirás un enlace a tu tienda personalizada para que invites a tus amigas</p>
</div>
<div class="cruwi-section-card">
<div class="cruwi-section-card-bullet">3</div>
<h2>Recupera tu dinero</h2>
<p>Cada vez que una amiga compre te reembolsaremos una parte de tu compra en el método de pago que utilices</p>
</div>
</div>
<h2 class="cruwi-section-poweredby">
powered by <img width="40" src="https://uploads-ssl.webflow.com/62ea5c239bacb85550bf44ea/6328573bad60f760ac2b5fbb_CRUWI%20(3).svg" alt="Powered by CRUWI.COM" />
</h2>
</div>
`
// Añadimos la section completo al documento
document.body.appendChild(sectionWidget);
loadCruwiCustomFont();
injectCruwiStyles();
}
// Función que monta el widget del checkout
async function buildCruwiCheckoutWidget() {
colorLog('-- Building Checkout Widget --', "info");
// Montamos el widget entero en desarrollo
if(isLocalDevelopment && isTestNow) {
const cruwiCheckoutMainWidget = document.createElement('div');
cruwiCheckoutMainWidget.id = "cruwi-checkout-main-widget";
cruwiCheckoutMainWidget.classList.add('cruwi-checkout-main-widget');
cruwiCheckoutMainWidget.innerHTML = `
<div class="cruwi-checkout-main-widget-content">
<div class="marquee running js-marquee">
<div class="marquee-inner">
<span>BE AMBASSADOR</span>
</div>
</div>
<h5 class="cruwi-checkout-main-widget-content-title">
Conviértete en embajador/a de Cruwishop
</h5>
<p class="cruwi-checkout-main-widget-content-info">
Consigue descuentos exclusivos para ti y tus amigos, gana dinero por conseguir ventas y muchos más beneficios.
</p>
<p class="cruwi-checkout-main-widget-content-info">
<label for="instagram">
Déjanos tu Instagram para desbloquear todos los beneficios👇🏼
</label>
</p>
<div class="cruwi-checkout-main-widget-content-instagram">
<input placeholder="@tu-instagram" class="cruwi-checkout-main-widget-content-instagram-input" type="text" id="cruwi-checkout-main-widget-input-instagram" name="instagram" required minlength="4" maxlength="40">
<button id="cruwi-checkout-main-widget-button-instagram" class="cruwi-checkout-main-widget-content-instagram-button">
<div class="cruwi-checkout-main-widget-content-instagram-button-content">Desbloquear</div>
</button>
</div>
<div class="cruwi-checkout-main-widget-content-spinner-wrapper">
<div class="cruwi-checkout-main-widget-content-spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
<div class="cruwi-checkout-main-widget-content-spinner-success-wrapper">
<svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52"> <circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/> <path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/></svg>
</div>
<div class="cruwi-checkout-main-widget-content-instagram-success-wrapper">
<a id="cruwi-checkout-main-widget-button" target="_blank" href="https://app.cruwi.com?o=t" class="cruwi-checkout-main-widget-content-button">
Acceder a mi tienda
</a>
<p class="cruwi-checkout-main-widget-content-instagram-success-notification">¡Te hemos enviado un correo con toda la info! :)</p>
</div>
</div>
`;
widgetElement.appendChild(cruwiCheckoutMainWidget);
function cruwiRemoveAtSymbol(text) {
if (text[0] === '@') {
return text.slice(1);
}
return text;
}
async function stall(stallTime = 3000) {
await new Promise(resolve => setTimeout(resolve, stallTime));
}
const cruwiCheckoutMainWidgetButtonInstagram = document.getElementById('cruwi-checkout-main-widget-button-instagram');
const cruwiCheckoutMainWidgetInputInstagram = document.getElementById('cruwi-checkout-main-widget-input-instagram');
cruwiCheckoutMainWidgetButtonInstagram.addEventListener('click', async () => {
if(cruwiCheckoutMainWidgetInputInstagram.value.length === 0) {
alert('El campo instagram no puede estar vacío.')
} else {
// Ponemos el loader principal
const cruwiCheckoutMainWidgetSpinner = document.getElementsByClassName('cruwi-checkout-main-widget-content-spinner-wrapper')[0];
cruwiCheckoutMainWidgetSpinner.style.display = 'flex';
// Hacemos la llamada de instagram
await stall(2500);
// Si todo ok, quitamos el loader y ponemos el check de éxito
cruwiCheckoutMainWidgetSpinner.style.display = 'none';
const cruwiCheckoutMainWidgetSpinnerSuccess = document.getElementsByClassName('cruwi-checkout-main-widget-content-spinner-success-wrapper')[0];
cruwiCheckoutMainWidgetSpinnerSuccess.style.display = 'flex';
// Simulamos 1500 y quitamos el check
await stall(1500);
cruwiCheckoutMainWidgetSpinnerSuccess.style.display = 'none';
// Mostramos los nuevos contenidos (todo: traducciones)
const cruwiCheckoutMainWidgetContentTitle = document.getElementsByClassName('cruwi-checkout-main-widget-content-title')[0];
cruwiCheckoutMainWidgetContentTitle.innerHTML = '❤️🔥 Ya eres parte de nuestro equipo de embajadores ❤️🔥';
const cruwiCheckoutMainWidgetContentInfo = document.getElementsByClassName('cruwi-checkout-main-widget-content-info')[0];
const cruwiCheckoutMainWidgetContentInfo2 = document.getElementsByClassName('cruwi-checkout-main-widget-content-info')[1];
cruwiCheckoutMainWidgetContentInfo2.style.display = 'none';
cruwiCheckoutMainWidgetContentInfo.innerHTML = 'Para que veas que vamos en serio, te hemos creado una tienda con descuentos para ti y tus amigos. Accede a ella para descubrir cómo funciona.';
const cruwiCheckoutMainWidgetContentInstagram = document.getElementsByClassName('cruwi-checkout-main-widget-content-instagram')[0];
cruwiCheckoutMainWidgetContentInstagram.style.display = 'none';
const cruwiCheckoutMainWidgetContentInstagramSuccess = document.getElementsByClassName('cruwi-checkout-main-widget-content-instagram-success-wrapper')[0];
cruwiCheckoutMainWidgetContentInstagramSuccess.style.display = 'block';
}
});
loadCruwiCustomFont();
injectCruwiStyles();
// Marquee logic
document.querySelectorAll('.js-marquee').forEach(function(e) {
var letter = e.querySelector('span');
for (counter = 1; counter <= 3; ++counter) {
var clone = letter.cloneNode(true);
letter.after(clone);
}
});
}
// Comprobamos que exista el objeto Shopify
if(!window.Shopify) return;
// Si no está en españa, no renderiamos (Fooga, Arze, etc)
const customerCountry = Shopify.checkout.billing_address.country_code;
if(customerCountry !== 'ES') return;
// Get main data from shopify checkout
let shopRawUrl = Shopify.shop;
let orderId = Shopify.checkout.order_id;
let discountCode = Shopify.checkout.discount ? Shopify.checkout.discount.code : '';
let lineItems = Shopify.checkout.line_items;
let isCruwiDiscount = Boolean(discountCode && discountCode.slice(0, 3) === 'CCB');
let isCruwiPartnerDiscount = Boolean(discountCode && discountCode.slice(0, 3) === 'CCP');
colorLog(`DISCOUNT: ${isCruwiDiscount}`, "info");
colorLog(`DISCOUNT: ${isCruwiPartnerDiscount}`, "info");
try {
// Pedimos los datos de la tienda y de la campaña que tenga activa
const { data: { brandName, isActive, hasShadowWidget, logoUrl, merchantUrl, campaigns, checkoutWidgetTitle, checkoutWidgetText } } = await fetchGetMerchantAndCampaignData(shopRawUrl);
// Comprobamos que está activo el merchant
if(!isActive) return;
// Comprobamos que haya campaña (por si hay algún error)
if(campaigns.length <= 0) return;
// Textos e idioma del widget
let checkoutWidgetTitleText = checkoutWidgetTitle;
let checkoutWidgetContentText = checkoutWidgetText;
let checkoutWidgetRotatingText1 = "BE AMBASSADOR";
let checkoutWidgetButton = "ACCEDE A TU TIENDA";
let checkoutWidgetInstagramText = "Déjanos tu Instagram para desbloquear todos los beneficios👇🏼";
let checkoutWidgetInstagramButton = "Desbloquear";
let checkoutWidgetInstagramTextSuccess = "Te hemos enviado un correo con toda la info y tus primeros beneficios :)";
let isEnglish = false;
if(preferredLanguage.indexOf('es') === -1) {
isEnglish = true;
checkoutWidgetTitleText = "Earn money sharing your purchase";
checkoutWidgetContentText = `With your purchase you have unlocked your own ${merchantNameFromScript} store. Share it with friends so they can shop with a discount. For every purchase they make you will earn money directly to your account.`;
checkoutWidgetRotatingText1 = "BE AMBASSADOR";
checkoutWidgetButton = "ACCESS YOUR STORE";
checkoutWidgetInstagramText = "Leave us your Instagram to unlock all the benefits👇🏼";
checkoutWidgetInstagramButton = "Unlock";
checkoutWidgetInstagramTextSuccess = "We have sent you an email with all the info and your first benefits :)";
}
// Si son todos los productos, no buscamos matches
let matchesFromLineItems = [];
if(campaigns[0].criteria !== 'all') {
// Comprobamos que el pedido tenga producto de la campaña activa (EL MATCH)
// --> 1º sacar el array de ids de line items
// --> 2º filtrar el array de objetos producto con el array de ids
// --> 3º los productos comprados (line_items) llevan el id sin el prefijo.. lo añadimos para el match
let lineItemsIds = lineItems.map(product => 'gid://shopify/Product/' + product.product_id);
let matches = campaigns[0].products.filter(function (product) {
return lineItemsIds.indexOf(product.id) >= 0;
});
// Cogemos los line items que han tenido match (los datos son mejores para mostrar en la mini tienda)
for (let i = 0; i < lineItems.length; i++) {
const productItem = lineItems[i];
const productItemId = productItem.product_id;
for (let j = 0; j < matches.length; j++) {
const matchItem = matches[j];
if (Number(matchItem.id.replace('gid://shopify/Product/', '')) === productItemId) {
matchesFromLineItems.push(productItem);
}
}
}
console.log('MATCHES: ', matches);
console.log('FINAL MATCHES: ', matchesFromLineItems);
// Comprobamos el nº de matches (si no hay matches, nada.. no es de la campaña)
if(matches.length === 0) return;
} else {
matchesFromLineItems = lineItems;
console.log('TODOS ENTRAN: ', matchesFromLineItems);
}
// Si es es un código de CRUWI (viene de mini tienda), mandamos evento a Amplitude
if(isCruwiDiscount || isCruwiPartnerDiscount) {
window.amplitude && amplitude.track('purchase_completed', {
merchantName: merchantNameFromScript,
cruwiCoupon: discountCode,
purchasedItems: matchesFromLineItems.map(product => product.product_id),
purchaseSize: matchesFromLineItems.length
});
}
// Mandamos los datos del pedido y cliente actuales
const { data: { shopData: { shortUrl, url, orderId } } } = await fetchPostClientData(Shopify.checkout, matchesFromLineItems, isCruwiDiscount, isCruwiPartnerDiscount, shopRawUrl, campaigns);
// Creamos el Div principal del checkout (izquierda)
const cruwiCheckoutMainWidget = document.createElement('div');
cruwiCheckoutMainWidget.id = "cruwi-checkout-main-widget";
cruwiCheckoutMainWidget.classList.add('cruwi-checkout-main-widget');
cruwiCheckoutMainWidget.innerHTML = `
<div class="cruwi-checkout-main-widget-content">
<div class="marquee running js-marquee">
<div class="marquee-inner">
<span>${checkoutWidgetRotatingText1}</span>
</div>
</div>
<h5 class="cruwi-checkout-main-widget-content-title">
${checkoutWidgetTitleText}
</h5>
<p class="cruwi-checkout-main-widget-content-info">
${checkoutWidgetContentText}
</p>
<p class="cruwi-checkout-main-widget-content-info">
<label for="instagram">
${checkoutWidgetInstagramText}
</label>
</p>
<div class="cruwi-checkout-main-widget-content-instagram">
<input placeholder="@tu-instagram" class="cruwi-checkout-main-widget-content-instagram-input" type="text" id="cruwi-checkout-main-widget-input-instagram" name="instagram" required minlength="4" maxlength="40">
<button id="cruwi-checkout-main-widget-button-instagram" class="cruwi-checkout-main-widget-content-instagram-button">
<div class="cruwi-checkout-main-widget-content-instagram-button-content">
${checkoutWidgetInstagramButton}
</div>
</button>
</div>
<div class="cruwi-checkout-main-widget-content-spinner-wrapper">
<div class="cruwi-checkout-main-widget-content-spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>
</div>
<div class="cruwi-checkout-main-widget-content-spinner-success-wrapper">
<svg class="checkmark" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 52 52">
<circle class="checkmark__circle" cx="26" cy="26" r="25" fill="none"/>
<path class="checkmark__check" fill="none" d="M14.1 27.2l7.1 7.2 16.7-16.8"/>
</svg>
</div>
<div class="cruwi-checkout-main-widget-content-instagram-success-wrapper">
<a id="cruwi-checkout-main-widget-button" target="_blank" href="${url}?o=t" class="cruwi-checkout-main-widget-content-button">
Acceder a mi tienda
</a>
<p class="cruwi-checkout-main-widget-content-instagram-success-notification">¡Te hemos enviado un correo con toda la info! :)</p>
</div>
</div>
`;
widgetElement.appendChild(cruwiCheckoutMainWidget);
// No mostramos el widget si la marca no quiere (Ej. GoatedLink)
if(hasShadowWidget) {
cruwiCheckoutMainWidget.style.display = 'none';
}
async function stall(stallTime = 3000) {
await new Promise(resolve => setTimeout(resolve, stallTime));
}
// *** New Instagram feature *** //
function cruwiRemoveAtSymbol(text) {
if (text[0] === '@') {
return text.slice(1);
}
return text;
}
const cruwiCheckoutMainWidgetButtonInstagram = document.getElementById('cruwi-checkout-main-widget-button-instagram');
const cruwiCheckoutMainWidgetInputInstagram = document.getElementById('cruwi-checkout-main-widget-input-instagram');
cruwiCheckoutMainWidgetButtonInstagram.addEventListener('click', async () => {
const userInstagram = cruwiCheckoutMainWidgetInputInstagram.value;
if(userInstagram.length === 0) {
alert('El campo instagram no puede estar vacío.');
} else {
// Ponemos el loader principal
const cruwiCheckoutMainWidgetSpinner = document.getElementsByClassName('cruwi-checkout-main-widget-content-spinner-wrapper')[0];
cruwiCheckoutMainWidgetSpinner.style.display = 'flex';
// Actualizar la shop con el instagram, asociarlo a ella
const { data } = await fetchPostClientInstagram(orderId, cruwiRemoveAtSymbol(userInstagram));
if(data?.savedShop) {
colorLog('Instagram insertado en la tienda correctamente', "info");
// Quitamos el loader y ponemos el check de éxito
cruwiCheckoutMainWidgetSpinner.style.display = 'none';
const cruwiCheckoutMainWidgetSpinnerSuccess = document.getElementsByClassName('cruwi-checkout-main-widget-content-spinner-success-wrapper')[0];
cruwiCheckoutMainWidgetSpinnerSuccess.style.display = 'flex';
// Simulamos 1500 y quitamos el check
await stall(1800);
cruwiCheckoutMainWidgetSpinnerSuccess.style.display = 'none';
// Mostramos los nuevos contenidos
const cruwiCheckoutMainWidgetContentTitle = document.getElementsByClassName('cruwi-checkout-main-widget-content-title')[0];
cruwiCheckoutMainWidgetContentTitle.innerHTML = isEnglish ? '❤️🔥 You are already part of our team of ambassadors ❤️🔥' : '❤️🔥 Ya eres parte de nuestro equipo de embajadores ❤️🔥';
const cruwiCheckoutMainWidgetContentInfo = document.getElementsByClassName('cruwi-checkout-main-widget-content-info')[0];
const cruwiCheckoutMainWidgetContentInfo2 = document.getElementsByClassName('cruwi-checkout-main-widget-content-info')[1];
cruwiCheckoutMainWidgetContentInfo2.style.display = 'none';
cruwiCheckoutMainWidgetContentInfo.innerHTML = isEnglish ? 'Here is your first benefit, we have created a store with discounts for you and your friends. Click the button to find out how it works.' : 'Para que veas que vamos en serio, te hemos creado una tienda con descuentos para ti y tus amigos. Accede a ella para descubrir cómo funciona.';
const cruwiCheckoutMainWidgetContentInstagram = document.getElementsByClassName('cruwi-checkout-main-widget-content-instagram')[0];
cruwiCheckoutMainWidgetContentInstagram.style.display = 'none';
const cruwiCheckoutMainWidgetContentInstagramSuccess = document.getElementsByClassName('cruwi-checkout-main-widget-content-instagram-success-wrapper')[0];
cruwiCheckoutMainWidgetContentInstagramSuccess.style.display = 'block';
}
}
});
const cruwiCheckoutMainWidgetButton = document.getElementById('cruwi-checkout-main-widget-button');
// Click en el botón para enviar evento a Amplitude
cruwiCheckoutMainWidgetButton.addEventListener('click', () => {
window.amplitude && amplitude.track('checkout_widget_clicked', {
merchantName: merchantNameFromScript,
});
});
// Mandamos evento a Amplitude de widget cargado
window.amplitude && amplitude.track('checkout_widget_viewed', {
merchantName: merchantNameFromScript,
});
// Cargamos la tipografía y los estilos
loadCruwiCustomFont();
injectCruwiStyles();
// Marquee logic
document.querySelectorAll('.js-marquee').forEach(function(e) {
var letter = e.querySelector('span');
for (counter = 1; counter <= 3; ++counter) {
var clone = letter.cloneNode(true);
letter.after(clone);
}
});
} catch (error) {
console.log(error);
return;
}
}
// Función que monta el modal
function buildCruwiModal() {
// Comprobamos que estilo quieren (2 estilos hay)
const widgetTextStyle = widgetElement.dataset.cruwiWidgetStyle ?? '1';
// Creamos el modal con un ID
const cruwiModal = document.createElement('div');
cruwiModal.classList.add('cruwi-modal');
cruwiModal.id = 'cruwiModal';
// Creamos el overlay de cruwi
const cruwiModalOverlay = document.createElement('div');
cruwiModalOverlay.id = 'cruwi-modal-overlay';
// Creamos el header del modal
const cruwiModalHeader = document.createElement('div');
cruwiModalHeader.classList.add('cruwi-modal-header');
// Añadimos al header del modal
const cruwiModalTitleDiv = document.createElement('div');
cruwiModalTitleDiv.classList.add('cruwi-modal-title');
// Añadimos el logo de Cruwi al header
const cruwiModalLogo = document.createElement('img');
cruwiModalLogo.classList.add('cruwi-modal-logo');
cruwiModalTitleDiv.appendChild(cruwiModalLogo);
cruwiModalHeader.appendChild(cruwiModalTitleDiv);
// Añadimos el icono de cerrar el modal
const cruwiModalCloseButton = document.createElement('img');
cruwiModalCloseButton.src = 'https://svgshare.com/i/iSG.svg';
cruwiModalCloseButton.classList.add('cruwi-modal-close-button');
cruwiModalTitleDiv.appendChild(cruwiModalCloseButton);
// Metemos el header en el modal
cruwiModal.appendChild(cruwiModalHeader);
// Creamos el cuerpo del modal
const cruwiModalBody = document.createElement('div');
cruwiModalBody.classList.add('cruwi-modal-body');
// Creamos el contenido del cuerpo del modal
const cruwiModalBodyContent = document.createElement('div');
cruwiModalBodyContent.classList.add('cruwi-modal-body-content');
// Textos para poner en el idioma del navegador del usuario
let modalTitleText;
let modalHowItWorksText;
let modalFirstStepText;
let modalSecondStepText;
let modalThirdStepText;
let modalAclarationText;
if(preferredLanguage.indexOf('es') !== -1) {
modalTitleText = "Gana dinero recomendando nuestros productos";
modalHowItWorksText = "¿Cómo funciona?";
modalFirstStepText = "Realiza una compra como siempre";
modalSecondStepText = `Conseguirás un enlace a tu propia tienda de ${merchantNameFromScript} con descuentos exclusivos`;
modalThirdStepText = "Compártelo y gana dinero* cada vez que alguien compre a través de tu enlace";
modalAclarationText = "*El dinero lo recibirás automáticamente en el método de pago que utilices en tu compra";
} else {
modalTitleText = "Earn money by recommending our products";
modalHowItWorksText = "How does it work?";
modalFirstStepText = "Make a purchase as always";
modalSecondStepText = `You will get a link to your own ${merchantNameFromScript} store with exclusive discounts`;
modalThirdStepText = "Share it and earn money* every time someone buys through your link";
modalAclarationText = "*You will automatically receive the money in the payment method you use for your purchase";
}
// TODO: mejorar las opciones
cruwiModalBodyContent.innerHTML = `
<div class="cruwi-modal-body-content-wrapper">
<h4 class="cruwi-modal-body-content-title">
${modalTitleText}
</h4>
<div class="cruwi-modal-body-content-how">
<span class="cruwi-modal-body-content-how-text">
${modalHowItWorksText}
<span>
</div>
<div class="cruwi-modal-body-content-steps">
<div class="cruwi-modal-body-content-step">
<div class="cruwi-modal-body-content-step-icon">
🛍️
</div>
<div class="cruwi-modal-body-content-step-text">
${modalFirstStepText}
</div>
</div>
<div class="cruwi-modal-body-content-step">
<div class="cruwi-modal-body-content-step-icon">
📲
</div>
<div class="cruwi-modal-body-content-step-text">
${modalSecondStepText}
</div>
</div>
<div class="cruwi-modal-body-content-step">
<div class="cruwi-modal-body-content-step-icon">
🤑
</div>
<div class="cruwi-modal-body-content-step-text">
${modalThirdStepText}
</div>
</div>
<div class="cruwi-modal-body-content-disclaimer">
${modalAclarationText}
</div>
</div>
</div>
`;
// Metemos el contenido en el cuerpo
cruwiModalBody.appendChild(cruwiModalBodyContent);
// Metemos el cuerpo en el modal
cruwiModal.appendChild(cruwiModalBody);
// Creamos el footer del modal
const cruwiModalFooter = document.createElement('div');
cruwiModalFooter.classList.add('cruwi-modal-footer');
// Creamos el wrapper y el powered by y el logo de cruwi
const cruwiModalFooterWrapper = document.createElement('div');
cruwiModalFooterWrapper.classList.add('cruwi-modal-footer-wrapper');
cruwiModalFooter.appendChild(cruwiModalFooterWrapper);
const cruwiModalFooterWrapperText = document.createElement('div');
cruwiModalFooterWrapperText.classList.add('cruwi-modal-footer-wrapper-text');
cruwiModalFooterWrapperText.insertAdjacentText('beforeend', 'Powered by CRUWI');
cruwiModalFooterWrapper.appendChild(cruwiModalFooterWrapperText);
// Metemos el footer en el modal
cruwiModal.appendChild(cruwiModalFooter);
// Añadimos el modal completo al documento
document.body.appendChild(cruwiModal);
// Añadimos el overlay al documento también
document.body.appendChild(cruwiModalOverlay);
// Escuchamos el evento de abrir el modal
document.addEventListener("cruwiModalOpen", function(event) {
console.log('Modal opened');
// Mostramos el modal
cruwiModal.classList.add('cruwi-modal-active');
// Mostramos el overlay
cruwiModalOverlay.classList.add('cruwi-modal-overlay-active');
// Prevenimos el scroll en el body de modal con una clase
body.classList.add('cruwi-modal-body-overflow');
});
// Añadimos eventos de click a la capa de overlay para cerrar el modal
cruwiModalOverlay.addEventListener('click', () => {
console.log('Modal closed');
// Cerramos el modal
cruwiModal.classList.remove('cruwi-modal-active');
cruwiModalOverlay.classList.remove('cruwi-modal-overlay-active');
// Devolvemos el overflow de body al default
body.classList.remove('cruwi-modal-body-overflow');
});
// Añadimos el evento de click al botón de cerrar
cruwiModalCloseButton.addEventListener('click', () => {
console.log('Modal closed');
// Cerramos el modal
cruwiModal.classList.remove('cruwi-modal-active');
cruwiModalOverlay.classList.remove('cruwi-modal-overlay-active');
// Devolvemos el overflow de body al default
body.classList.remove('cruwi-modal-body-overflow');
});
}
// Cargamos el font que necesitamos de Google Fonts
function loadCruwiCustomFont() {
const link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', 'http://fonts.cdnfonts.com/css/dm-sans');
document.getElementsByTagName('head')[0].appendChild(link);
}
// Cargamos el CSS de Cruwi
function injectCruwiStyles() {
const cruwiStyleTag = document.createElement('style');
document.head.append(cruwiStyleTag);
cruwiStyleTag.innerHTML = `
:root {
--offset: 20vw;
--move-initial: calc(-25% + var(--offset));
--move-final: calc(-50% + var(--offset));
}
#cruwi-pdp-widget {
position: relative !important;
background-color: white;
transition: 0.3s;
color: #111 !important;
display: inline-block;
font-family: 'DM Sans', sans-serif !important;
border: 1px solid #EBD0FF;
border-radius: 8px;
padding: 8px !important;
cursor: pointer;
margin: 10px 0;
}
#cruwi-pdp-widget:hover {
background-color: #EBD0FF;
}
#cruwi-pdp-widget .cruwi-pdp-widget-wrapper {
display: flex;
justify-content: center;
align-items: center;
}
#cruwi-pdp-widget .cruwi-pdp-widget-button {
position: absolute !important;
bottom: 0;
right: 0;
font-size: 9px !important;
font-weight: bold !important;
letter-spacing: 0px !important;
background: #eeeeee !important;
padding: 2px 10px !important;
border-top-left-radius: 8px !important;
border-bottom-right-radius: 8px !important;
}
#cruwi-pdp-widget .cruwi-pdp-widget-wrapper .cruwi-pdp-widget-logo-wrapper {
background-color: #EBD0FF;
padding: 5px 12px;
border-radius: 8px;
margin-right: 10px;
}
#cruwi-pdp-widget .cruwi-pdp-widget-wrapper .cruwi-pdp-widget-logo-wrapper .cruwi-pdp-widget-logo {
display: flex;
justify-content: center;
align-items: center;
height: 35px;
}
#cruwi-pdp-widget .cruwi-pdp-widget-wrapper .cruwi-pdp-widget-logo-wrapper .cruwi-pdp-widget-logo .cruwi-pdp-widget-logo-img {
margin: 0 !important;
width: 80px !important;
border-radius: 0px !important;
margin-bottom: 0 !important;
max-width: none !important;
}
#cruwi-pdp-widget .cruwi-pdp-widget-wrapper .cruwi-pdp-widget-text {
font-size: 14px !important;
max-width: 260px !important;
letter-spacing: 0px !important;
line-height: normal !important;
}
.cruwi-modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) scale(0);
transition: 10ms ease-in-out;
border-radius: 0px;
width: 90%;
height: 70%;
background-color: white;
box-shadow: 1px 1px 20px #0000001c;
font-family: 'Poppins', sans-serif;
z-index: 21474836;
overflow: auto;
display: flex;
flex-direction: column;
border-radius: 8px;
}
.cruwi-modal.cruwi-modal-active {
transform: translate(-50%, -50%) scale(1);
}
.cruwi-modal-body-overflow {
overflow: hidden;
}
#cruwiModal .cruwi-modal-header {
padding: 10px 15px;
border-bottom: 1px solid #ebe5e5;
}