-
Notifications
You must be signed in to change notification settings - Fork 3
/
content.js
1482 lines (1323 loc) · 54.5 KB
/
content.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
// TODO - popup with simple "קבע לי תור" button. Will open
// with extra hash that will triger the open of Shraga
const STATE_INIT = 'STATE_INIT';
const STATE_INIT_COMPLETE = 'STATE_INIT_COMPLETE';
const STATE_INIT_FAILURE = 'STATE_INIT_FAILURE';
const STATE_LOGGED_OUT = 'STATE_LOGGED_OUT';
const STATE_LOAD_LAST_USER_DATA = 'STATE_LOAD_LAST_USER_DATA';
const STATE_LOAD_LAST_SEARCH_DATA = 'STATE_LOAD_LAST_SEARCH_DATA';
const STATE_ID_INPUT = 'STATE_ID_INPUT';
const STATE_ID_INPUT_VALIDATION = 'STATE_ID_INPUT_VALIDATION';
const STATE_PHONE_INPUT = 'STATE_PHONE_INPUT';
const STATE_PHONE_INPUT_VALIDATION = 'STATE_PHONE_INPUT_VALIDATION';
const STATE_SERVICE_TYPE_INPUT = 'STATE_SERVICE_TYPE_INPUT';
const STATE_LOCATION_INPUT = 'STATE_LOCATION_INPUT';
const STATE_MONTH_INPUT = 'STATE_MONTH_INPUT';
const STATE_TIME_INPUT = 'STATE_TIME_INPUT';
const STATE_SEARCHING = 'STATE_SEARCHING';
const STATE_SEARCH_SUCCESS = 'STATE_SEARCH_SUCCESS';
const STATE_SEARCH_FAILURE = 'STATE_SEARCH_FAILURE';
const STATE_SOMETHING_WENT_WRONG = 'STATE_SOMETHING_WENT_WRONG';
const STATE_ALREADY_HAVE_AN_APPONTMENT = 'STATE_ALREADY_HAVE_AN_APPONTMENT';
const STATE_USER_ALREADY_HAVE_AN_APPONTMENT = 'STATE_USER_ALREADY_HAVE_AN_APPONTMENT';
const STATE_DISCLAIMER = 'DISCLAIMER';
const MIN_MINUTES_FROM_TODAYS_SLOT = 90;
var apiHost = window.location.host === 'piba.myvisit.com'
? 'piba-api.myvisit.com' : 'central.myvisit.com';
var toolTipObject = null;
var allLocations = [];
var hasAppointment = false;
var disclaimerAccepted = false;
var curState = STATE_INIT;
// personal data
var userId;
var userPhone;
// search data
var serviceIdSelection = [];
var serviceTypeSelection;
var timeSelection = [];
var monthSelection = [];
var serviceTypeId;
var isLoggedIn;
var initComplete;
var appointment;
var windowWasOpened = false;
var input;
var onBoardServices;
function handleInput(i) {
// add buuble
const container = $(`<div class="shraga-user-input-bubble">${i}</div>`);
addChatContent(container, false);
input = i;
switch (curState) {
case STATE_ID_INPUT:
runStateMachine(STATE_ID_INPUT_VALIDATION);
break;
case STATE_PHONE_INPUT:
runStateMachine(STATE_PHONE_INPUT_VALIDATION);
break;
default:
console.error('unknown input state', curState);
}
}
function dateAdd(date, interval, units) {
if(!(date instanceof Date))
return undefined;
var ret = new Date(date); //don't change original date
var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
switch(String(interval).toLowerCase()) {
case 'year' : ret.setFullYear(ret.getFullYear() + units); checkRollover(); break;
case 'quarter': ret.setMonth(ret.getMonth() + 3*units); checkRollover(); break;
case 'month' : ret.setMonth(ret.getMonth() + units); checkRollover(); break;
case 'week' : ret.setDate(ret.getDate() + 7*units); break;
case 'day' : ret.setDate(ret.getDate() + units); break;
case 'hour' : ret.setTime(ret.getTime() + units*3600000); break;
case 'minute' : ret.setTime(ret.getTime() + units*60000); break;
case 'second' : ret.setTime(ret.getTime() + units*1000); break;
default : ret = undefined; break;
}
return ret;
}
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
function hideInput() {
$(".jBox-content").animate({
height: '560px'
}, { duration: 200, queue: false });
$(".shraga-user-input-container").animate({
height: '0px'
}, { duration: 200, queue: false });
}
function showInput() {
mainWindowHeight = $(".jBox-content").innerHeight();
$(".jBox-content").animate({
height: '500px',
}, { duration: 200, queue: false });
$(".shraga-user-input-container").animate(
{ height: '60px' },
{
duration: 200,
queue: false,
},
);
const container = $(".shraga-container").parent();
container.animate({ scrollTop: container.prop("scrollHeight")}, {duration:200, queue: false});
}
async function getServiceTypeId() {
const res = await fetch(`https://${apiHost}/CentralAPI/GetServiceTypeList?organizationId=56`, {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "en",
"application-api-key": "8640a12d-52a7-4c2a-afe1-4411e00e3ac4",
"application-name": "myVisit.com v3.5",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"referrer": "https://myvisit.com/",
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
});
const json = await res.json();
return json["Results"].find(service => service.serviceTypeName === 'תיאום פגישה לתיעוד ביומטרי')["serviceTypeId"];
}
async function getOrgId() {
const res = await fetch(`https://${apiHost}/CentralAPI/ProviderSearch?CategoryId=0&CountryId=1&ResultsInPage=20&SearchPhrase=&ViewMode=0¤tPage=1&mostPopular=true&src=mvws`, {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "en",
"application-api-key": "8640a12d-52a7-4c2a-afe1-4411e00e3ac4",
"application-name": "myVisit.com v3.5",
"sec-ch-ua": "\"Not_A Brand\";v=\"99\", \"Google Chrome\";v=\"109\", \"Chromium\";v=\"109\"",
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "\"macOS\"",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"referrer": "https://myvisit.com/",
"referrerPolicy": "no-referrer-when-downgrade",
"body": null,
"method": "GET",
"mode": "cors",
"credentials": "include"
});
}
async function getLoggedInStatus() {
res = await fetch(`https://${apiHost}/CentralAPI/Organization/56/PrepareVisit`, {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "en",
"application-api-key": "8640a12d-52a7-4c2a-afe1-4411e00e3ac4",
"application-name": "myVisit.com v3.5",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"method": "POST",
"mode": "cors",
"credentials": "include"
});
return res.status !== 401;
}
async function getLocations() {
res = await fetch(`https://${apiHost}/CentralAPI/LocationSearch?organizationId=56&resultsInPage=100&serviceTypeId=156`, {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "en",
"application-api-key": "8640a12d-52a7-4c2a-afe1-4411e00e3ac4",
"application-name": "myVisit.com v3.5",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"mode": "cors",
"credentials": "include"
});
if (!res.ok) {
throw new Error(`HTTP error! status: ${res.status}`);
}
const json = await res.json();
return json['Results'].map(res => {
return {
name: res['LocationName'],
id: res['ServiceId']
}
});
}
function playSound(soundToPlay) {
var audio = document.createElement('audio');
audio.src = chrome.runtime.getURL('sound/' + soundToPlay);
audio.autoplay = true;
return audio.play();
}
async function getRelevantTimeSlots(serviceId, calendarInfo) {
const calendarId = calendarInfo['calendarId']
res = await fetch(`https://${apiHost}/CentralAPI/SearchAvailableSlots?CalendarId=${calendarId}&ServiceId=${serviceId}&dayPart=0`, {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "en",
"application-api-key": "8640a12d-52a7-4c2a-afe1-4411e00e3ac4",
"application-name": "myVisit.com v3.5",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"mode": "cors",
"credentials": "include"
});
if (res.status === 401) {
throw new Error('http error');
}
if (!res.ok) {
return;
}
const json = await res.json();
if (!json["Success"] || !json['TotalResults']) {
return;
}
const now = new Date();
const isToday = now.toDateString() === new Date(calendarInfo['calendarDate']).toDateString();
const slots = json['Results'].filter(slot => {
// if the slot is today and less than 90 minutes from now, skip it since
// the user might not have enough time to get there and they won't be able
// to cancel it either due to the restriction of can't cancel an hour before
// the appointment
if (isToday) {
const minutesFromMidnight = now.getHours() * 60 + now.getMinutes();
if (slot['Time'] - minutesFromMidnight < MIN_MINUTES_FROM_TODAYS_SLOT) {
return false;
}
}
if (!timeSelection.length) {
return true;
}
for (const relevantTs of timeSelection) {
parts = relevantTs.split('-')
const from = Number(parts[0]);
const to = Number(parts[1]);
if (slot['Time'] >= from && slot['Time'] <= to) {
return true;
}
}
})
.map(slot => slot['Time']);
if (isToday) {
// since it takes time to get to the appointment, if the free slot is today
// prefer the latest available slot
slots.reverse();
}
return slots;
}
async function getAvailableDates(serviceId) {
var res;
try {
res = await fetch(`https://${apiHost}/CentralAPI/SearchAvailableDates?maxResults=365&serviceId=${serviceId}&startDate=${getTodayDate()}`, {
"headers": {
"accept": "application/json, text/plain, */*",
"accept-language": "en",
"application-api-key": "8640a12d-52a7-4c2a-afe1-4411e00e3ac4",
"application-name": "myVisit.com v3.5",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site"
},
"mode": "cors",
"credentials": "include"
});
} catch {
return [];
}
if (res.status === 401) {
throw new Error('http error');
}
if (!res.ok) {
return [];
}
const json = await res.json();
if (!json["Success"]) {
return [];
}
return (json['Results'] || []).filter(r => {
const appDate = r['calendarDate'].split('T')[0];
const dateParts = appDate.split('-');
if (monthSelection.includes(`${dateParts[0]}-${dateParts[1]}`)) {
return true;
}
const rDate = new Date(r['calendarDate']);
const now = new Date();
// check the options 1-4 next weeks
for (var w = 1 ; w <= 4 ; w++) {
if (!monthSelection.includes(`w${w}`)) {
continue;
}
if (dateAdd(now, 'week', w) >= rDate) {
return true;
}
}
return false;
});
}
function getRelevantDates(res) {
return res.filter(d => {
const appDate = json['Results'][0]['calendarDate'].split('T')[0];
const dateParts = appDate.split('-');
return monthSelection.includes(`${dateParts[0]}-${dateParts[1]}`);
});
}
async function runSearchForServiceId(serviceId) {
const availableDates = await getAvailableDates(serviceId)
if (!availableDates.length) {
return false;
}
for (const availableDate of availableDates) {
const relevantSlots = await getRelevantTimeSlots(serviceId, availableDate);
for (const relevantTimeSlot of relevantSlots) {
const state = await setAnAppointment(onBoardServices.find(s => s["Data"]["ServiceId"] === serviceId), availableDate["calendarDate"], relevantTimeSlot);
if (!state) {
await new Promise(r => setTimeout(r, 2000));
continue;
}
if (state === STATE_ALREADY_HAVE_AN_APPONTMENT) {
return STATE_ALREADY_HAVE_AN_APPONTMENT;
}
const appDate = availableDate['calendarDate'].split('T')[0];
const dateParts = appDate.split('-');
const printDate = `${dateParts[2]}/${dateParts[1]}/${dateParts[0]}`
const timeDate = dateAdd(new Date(2023,1,1), 'minute', relevantTimeSlot);
appointment = {
name: allLocations.find(l => l.id === serviceId).name,
date: printDate,
time: `${pad(timeDate.getHours(),2)}:${pad(timeDate.getMinutes(),2)}`,
}
return STATE_SEARCH_SUCCESS;
}
}
return false;
}
async function runSearch() {
// let's wait for all services to be onboarded
try {
await onboardSelectedServices();
} catch {
runStateMachine(STATE_SOMETHING_WENT_WRONG);
return;
}
try {
while (true) {
for (serviceId of serviceIdSelection) {
const state = await runSearchForServiceId(serviceId);
if (!state) {
await new Promise(r => setTimeout(r, 15000));
continue;
}
runStateMachine(state);
return;
}
}
} catch {
runStateMachine(STATE_SEARCH_FAILURE);
}
}
async function init() {
try {
runStateMachine(STATE_INIT);
[allLocations, isLoggedIn, hasAppointment] = await Promise.all([getLocations(), getLoggedInStatus(), checkIfUserHasAppontments()]);
runStateMachine(STATE_DISCLAIMER);
} catch (err) {
console.log('unable to init system', err);
runStateMachine(STATE_INIT_FAILURE);
}
}
var chatMessagesQueue = [];
function addChatMessage(message, withDotsAnimation, callback) {
const div = $('<div/>');
div.addClass('shraga-message-bubble');
div.html(message);
chatMessagesQueue.push({content: div, animation: withDotsAnimation, callback: callback});
if (chatMessagesQueue.length === 1) {
displayNextChatMessage();
}
}
function addChatContent(content, withDotsAnimation, callback) {
chatMessagesQueue.push({content: $(content), animation: withDotsAnimation, callback: callback});
if (chatMessagesQueue.length === 1) {
displayNextChatMessage();
}
}
var isDotsVisible = false;
function addDots() {
isDotsVisible = true;
const div = $('<div/>');
div.html(`
<span class="shraga-dots-cont">
<span class="shraga-dot shraga-dot-1"></span>
<span class="shraga-dot shraga-dot-2"></span>
<span class="shraga-dot shraga-dot-3"></span>
</span>
`);
addChatItem(div);
}
function replaceDotsWithContent(content) {
isDotsVisible = false;
$('.shraga-container > :last').prev().remove();
addChatItem(content)
}
function addChatItem(content) {
// disable all previous buttons
$('.shraga-chat-button').each(function() {
jQuery(this).addClass('disabled');
jQuery(this).off('click');
jQuery(this).removeAttr('id');
})
content.addClass('shraga-chat-item');
$('.shraga-container > :last').before(content);
document.querySelector('.jBox-content').style.overflowY = 'scroll';
const container = $(".shraga-container").parent();
container.animate({ scrollTop: container.prop("scrollHeight")}, 500);
}
function displayNextChatMessage() {
const msg = chatMessagesQueue[0];
if (isDotsVisible) {
replaceDotsWithContent(msg.content);
msg.callback && msg.callback();
chatMessagesQueue.shift();
if (chatMessagesQueue.length) {
setTimeout(displayNextChatMessage, 0);
}
return;
}
if (!msg.animation) {
addChatItem(msg.content);
msg.callback && msg.callback();
chatMessagesQueue.shift();
if (chatMessagesQueue.length) {
setTimeout(displayNextChatMessage, 0);
}
return;
}
addDots();
setTimeout(
() => {
replaceDotsWithContent(msg.content);
msg.callback && msg.callback();
chatMessagesQueue.shift();
if (chatMessagesQueue.length) {
setTimeout(displayNextChatMessage, 0);
}
},
2000,
);
}
function initServiceTypeSelection(id) {
new lc_select(`#${id}`, {
wrap_width: '100%',
pre_placeh_opt: true,
enable_search: false,
autofocus_search: true,
addit_classes: ['lcslt-rtl'],
on_change: (selections) => {
$('#acceptServiceButton').removeClass('disabled');
serviceTypeSelection = selections[0];
},
});
}
function initLocationSelection(id) {
new lc_select(`#${id}`, {
wrap_width: '100%',
enable_search: true,
min_for_search: 0,
autofocus_search: true,
labels: ['הקלידו את שם הלשכה', '', '', 'לא נמצאה תוצאה'],
addit_classes: ['lcslt-rtl'],
on_change: (selections) => {
if (!selections.length) {
$('#acceptLocationsButton').addClass('disabled');
} else {
$('#acceptLocationsButton').removeClass('disabled');
}
serviceIdSelection = selections.map(id => Number(id));
},
});
}
function initMonthSelection(id) {
new lc_select(`#${id}`, {
wrap_width: '100%',
enable_search: false,
autofocus_search: true,
addit_classes: ['lcslt-rtl'],
on_change: (selections) => {
if (!selections.length) {
$('#acceptMonthsButton').addClass('disabled');
} else {
$('#acceptMonthsButton').removeClass('disabled');
}
monthSelection = selections;
},
});
}
function initTimeSelection(id) {
new lc_select(`#${id}`, {
wrap_width: '100%',
enable_search: false,
autofocus_search: true,
addit_classes: ['lcslt-rtl'],
on_change: (selections) => {
timeSelection = selections;
},
});
}
function isValidId(id) {
id = String(id).trim();
if (id.length > 9 || isNaN(id)) return false;
id = id.length < 9 ? ("00000000" + id).slice(-9) : id;
return Array.from(id, Number).reduce((counter, digit, i) => {
const step = digit * ((i % 2) + 1);
return counter + (step > 9 ? step - 9 : step);
}) % 10 === 0;
}
var uiIdCounter = 0;
function runStateMachine(newState) {
if (curState === newState) {
return;
}
curState = newState || curState;
if (!windowWasOpened) {
return;
}
switch(curState) {
case STATE_INIT: {
addChatMessage('טוען נתונים...', false, addDots);
break;
}
case STATE_DISCLAIMER: {
const onDisclaimerAccept = () => {
disclaimerAccepted = true;
if (hasAppointment) {
runStateMachine(STATE_USER_ALREADY_HAVE_AN_APPONTMENT);
} else if (!isLoggedIn) {
runStateMachine(STATE_LOGGED_OUT);
} else {
runStateMachine(STATE_LOAD_LAST_USER_DATA);
}
};
if (disclaimerAccepted) {
onDisclaimerAccept();
break;
}
addChatMessage('לידיעתכם, השימוש בשרגא הוא בניגוד לתנאי השימוש של האתר ועל אחריותכם בלבד', true, addDots);
addChatContent(`
<div class="shraga-chat-buttons-container">
<div class="shraga-primary-button shraga-chat-button" id="shragaAcceptDisclaimer">אני רוצה להמשיך</div>
<div class="shraga-primary-button shraga-chat-button" id="shragaDeclineDisclaimer">אני רוצה לצאת</div>
</div>
`,
false,
() => {
$('#shragaAcceptDisclaimer').click(() => {
onDisclaimerAccept();
});
$('#shragaDeclineDisclaimer').click(() => {
toolTipObject.close();
});
}
);
break;
}
case STATE_LOGGED_OUT: {
addChatMessage('אינכם מחוברים למערכת. יש להתחבר ורק אז אפשר יהיה להמשיך', true, addDots);
addChatContent(`
<div class="shraga-chat-buttons-container">
<div class="shraga-primary-button shraga-chat-button" id="shragaLoginButton">התחבר למערכת</div>
<div class="shraga-primary-button shraga-chat-button" id="shragaInitButton">המשך אחרי חיבור למערכת</div>
</div>
`,
false,
() => {
$('#shragaLoginButton').click(() => {
window.open("https://myvisit.com/#!/home/signin/", "_blank");
});
$('#shragaInitButton').click(() => {
runStateMachine(STATE_INIT);
void init();
});
}
);
break;
}
case STATE_INIT_FAILURE: {
addChatMessage('ארעה שגיאה באתחול. יש לטעון מחדש את הדף', false);
break;
}
case STATE_LOAD_LAST_USER_DATA: {
chrome.storage.local.get([
"last-user-id",
"last-user-phone",
]
).then((result) => {
if (!result || !result["last-user-id"] || !result["last-user-phone"]) {
runStateMachine(STATE_ID_INPUT);
return;
}
addChatMessage(
`
האם להשתמש בפרטים האישיים מהחיפוש הקודם?
<br>
<br>
מספר זהות: ${result["last-user-id"]}
<br>
טלפון: ${result["last-user-phone"]}
`,
false);
addChatContent(`
<div class="shraga-chat-buttons-container">
<div class="shraga-primary-button shraga-chat-button" id="loadPersonalDataButton">כן</div>
<div class="shraga-primary-button shraga-chat-button" id="declinePersonalDataButton">לא</div>
</div>`,
false,
() => {
$('#loadPersonalDataButton').click(() => {
userId = result["last-user-id"];
userPhone = result["last-user-phone"];
runStateMachine(STATE_LOAD_LAST_SEARCH_DATA);
});
$('#declinePersonalDataButton').click(() => {
runStateMachine(STATE_ID_INPUT);
});
}
);
}).catch(_ => runStateMachine(STATE_ID_INPUT));
break;
}
case STATE_LOAD_LAST_SEARCH_DATA: {
chrome.storage.local.get([
"last-service-type-selection",
"last-service-id-selection",
"last-month-selection",
"last-time-selection",
]
).then((result) => {
if (!result || !result["last-service-type-selection"] || !result["last-service-id-selection"] || !result["last-month-selection"] || !result["last-time-selection"]) {
runStateMachine(STATE_SERVICE_TYPE_INPUT);
return;
}
const locations = result["last-service-id-selection"].map(
lsid => allLocations.find(ll => ll.id === lsid).name
).join(",");
const dates = result[["last-month-selection"]].map(ld => {
switch (ld) {
case "w1":
return "בשבוע הקרוב";
case "w2":
return "בשבועיים הקרובים";
case "w3":
return "בשלושת השבועות הקרובים";
case "w4":
return "בחודש הקרוב";
default:
const parts = ld.split('-');
return parts[1]+'/'+parts[0];
}
}).join(",");
var times;
if (!result["last-time-selection"].length) {
times = 'בכל שעה';
} else {
times = result["last-time-selection"].map(t => {
const parts = t.split('-');
const from = dateAdd(new Date(2023, 1, 1), 'minute', Number(parts[0]));
const to = dateAdd(new Date(2023, 1, 1), 'minute', Number(parts[1]));
return `${pad(from.getHours(),2)}:${pad(from.getMinutes(),2)}-${pad(to.getHours(),2)}:${pad(to.getMinutes(),2)}`
}).join(',');
}
addChatMessage(
`
האם להשתמש בפרטים של החיפוש הקודם?
<br>
<br>
שירות: ${result["last-service-type-selection"]}
<br>
לשכות: ${locations}
<br>
תאריכים: ${dates}
<br>
שעות: ${times}
`,
false);
addChatContent(`
<div class="shraga-chat-buttons-container">
<div class="shraga-primary-button shraga-chat-button" id="loadSearchDataButton">כן</div>
<div class="shraga-primary-button shraga-chat-button" id="declineSearchDataButton">לא</div>
</div>`,
false,
() => {
$('#loadSearchDataButton').click(() => {
serviceIdSelection = result["last-service-id-selection"];
serviceTypeSelection = result["last-service-type-selection"];
timeSelection = result["last-time-selection"];
monthSelection = result["last-month-selection"];
runStateMachine(STATE_SEARCHING);
});
$('#declineSearchDataButton').click(() => {
runStateMachine(STATE_SERVICE_TYPE_INPUT);
});
}
);
}).catch(_ => runStateMachine(STATE_ID_INPUT));
break;
}
case STATE_ID_INPUT: {
addChatMessage('מה מספר תעודת הזהות שלכם?', true, showInput);
break;
}
case STATE_ID_INPUT_VALIDATION: {
if (isValidId(input)) {
userId = input;
runStateMachine(STATE_PHONE_INPUT);
} else {
addChatMessage('מספר זהות אינו תקין', true);
runStateMachine(STATE_ID_INPUT);
}
break;
}
case STATE_PHONE_INPUT: {
addChatMessage('מה מספר הטלפון שלכם? (מתחיל ב 05 ומורכב מספרות בלבד)', true);
break;
}
case STATE_PHONE_INPUT_VALIDATION: {
if (input.startsWith('05') && input.length >= 10 && isNaN(input) === false) {
userPhone = input;
hideInput();
chrome.storage.local.set({
"last-user-id": userId,
"last-user-phone": userPhone,
});
runStateMachine(STATE_SERVICE_TYPE_INPUT);
} else {
addChatMessage('מספר הטלפון אינו תקין', true);
runStateMachine(STATE_PHONE_INPUT);
}
break;
}
case STATE_SERVICE_TYPE_INPUT: {
const id = `serviceSelect_${uiIdCounter++}`;
addChatMessage('בואו נתחיל!', true);
addChatContent(`
<span id="w${id}">
<select id="${id}" name="multiple" data-placeholder="בחרו בשירות הרלוונטי">
<option value="הנפקת ת.ז. ביומטרית">הנפקת ת.ז. ביומטרית</option>
<option value="דרכון ביומטרי- ראשון">דרכון ביומטרי- ראשון</option>
<option value="דרכון ביומטרי- חידוש">דרכון ביומטרי- חידוש</option>
<option value="דרכון ביומטרי- אבדן/גניבה/השחתה">דרכון ביומטרי- אבדן/גניבה/השחתה</option>
<option value="שינוי מצב אישי (עם בחירת שם)">שינוי מצב אישי (עם בחירת שם)</option>
<option value="שינוי שם פרטי/משפחה">שינוי שם פרטי/משפחה</option>
<option value="הצהרה על תאריך לידה (יום וחודש)">הצהרה על תאריך לידה (יום וחודש)</option>
</select>
</span>
`, false, () => initServiceTypeSelection(id));
addChatContent(`
<div class="shraga-chat-buttons-container">
<div class="shraga-primary-button shraga-chat-button disabled" id="acceptServiceButton">המשך</div>
</div>
`,
false,
() => {
$('#acceptServiceButton').click(() => {
$('#acceptServiceButton').off('click');
document.querySelector(`#w${id}`).addEventListener('click', (e) => e.stopPropagation(), true);
runStateMachine(STATE_LOCATION_INPUT);
});
}
);
break;
}
case STATE_LOCATION_INPUT: {
const id = `locationSelect_${uiIdCounter++}`;
addChatMessage('לאילו לשכות תרצו להגיע? ניתן לבחור יותר מלשכה אחת.', false);
options = '';
for (const loc of allLocations) {
options += `<option value="${loc.id}">${loc.name}</option>`
}
addChatContent(`
<span id="w${id}">
<select id="${id}" name="multiple" data-placeholder="בחרו בלשכות רלוונטיות" multiple>
${options}
</select>
</span>
`,
false,
() => initLocationSelection(id),
);
addChatContent(`
<div class="shraga-chat-buttons-container">
<div class="shraga-primary-button shraga-chat-button disabled" id="acceptLocationsButton">המשך</div>
</div>
`,
false,
() => {
$('#acceptLocationsButton').click(() => {
if (!serviceIdSelection.length) {
return;
}
$('#acceptLocationsButton').off('click');
document.querySelector(`#w${id}`).addEventListener('click', (e) => e.stopPropagation(), true);
runStateMachine(STATE_MONTH_INPUT);
});
}
);
break;
}
case STATE_MONTH_INPUT: {
const id = `monthSelect_${uiIdCounter++}`;
addChatMessage('באילו חודשים תרצו לקבוע את התור? ניתן לבחור יותר מאפשרות אחת.', false);
options = `
<option value="w1">בשבוע הקרוב</option>
<option value="w2">בשבועיים הקרובים</option>
<option value="w3">בשלושת השבועות הקרובים</option>
<option value="w4">בחודש הקרוב</option>
`;
const baselineDate = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
for (i = 0 ; i < 12 ; i++) {
const date = dateAdd(baselineDate, 'month', i);
const month = pad(date.getMonth() + 1, 2);
const year = date.getFullYear();
options += `<option value="${year}-${month}">${month}/${year}</option>`;
}
addChatContent(`
<span id="w${id}">
<select id="${id}" name="multiple" data-placeholder="תאריכים רלוונטיים" multiple>
${options}
</select>
</span>
`,
false,
() => initMonthSelection(id),
);
addChatContent(`
<div class="shraga-chat-buttons-container">
<div class="shraga-primary-button shraga-chat-button disabled" id="acceptMonthsButton">המשך</div>
</div>`,
false,
() => {
$('#acceptMonthsButton').click(() => {
if (!monthSelection.length) {
return;
}
$('#acceptMonthsButton').off('click');
document.querySelector(`#w${id}`).addEventListener('click', (e) => e.stopPropagation(), true);
runStateMachine(STATE_TIME_INPUT);
});
}
);
break;
}
case STATE_TIME_INPUT: {
const id = `timeSelect_${uiIdCounter++}`;
addChatMessage('באילו שעות תרצו להגיע? עבור כל שעות היום אין צורך לבחור. ניתן לבחור יותר מטווח שעות אחד.', false);
minutesFromMidnight = (hour) => {
return hour * 60;
}
addChatContent(`
<span id="w${id}">
<select id="${id}" name="multiple" data-placeholder="בחרו בשעות הרלוונטיות" multiple>
<option value="${minutesFromMidnight(8)}-${minutesFromMidnight(10)}">08:00-10:00</option>
<option value="${minutesFromMidnight(10)}-${minutesFromMidnight(12)}">10:00-12:00</option>
<option value="${minutesFromMidnight(12)}-${minutesFromMidnight(14)}">12:00-14:00</option>
<option value="${minutesFromMidnight(14)}-${minutesFromMidnight(16)}">14:00-16:00</option>
<option value="${minutesFromMidnight(16)}-${minutesFromMidnight(18)}">16:00-18:00</option>
<option value="${minutesFromMidnight(18)}-${minutesFromMidnight(20)}">18:00-20:00</option>
</select>